From f8086457ef28a9956c7fd7d13afa85d221bed2e0 Mon Sep 17 00:00:00 2001 From: James Siri Date: Thu, 13 Dec 2018 11:53:02 -0800 Subject: [PATCH 001/655] Initial commit --- README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..64a45c9c --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# aws-cdk-user-guide +User guide for the AWS Cloud Development Kit (CDK). From bf557457ae02a154e30b86b9c306f4b76d269c2e Mon Sep 17 00:00:00 2001 From: James Siri Date: Thu, 13 Dec 2018 11:53:03 -0800 Subject: [PATCH 002/655] Creating initial file from template --- .github/PULL_REQUEST_TEMPLATE.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..6bdaa999 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,6 @@ +*Issue #, if available:* + +*Description of changes:* + + +By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. From a844de21ee70ff3ac351cca1beed0deec131b03a Mon Sep 17 00:00:00 2001 From: James Siri Date: Thu, 13 Dec 2018 11:53:03 -0800 Subject: [PATCH 003/655] Creating initial file from template --- CONTRIBUTING.md | 56 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..18841707 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,56 @@ +# Guidelines for contributing + +Thank you for your interest in contributing to AWS documentation! 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. + +## 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. + +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 look forward to receiving your pull requests for: + +* 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 + +**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 + +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: + +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. + +Before you send us a pull request, please be sure that: + +1. You're working from the latest source on the **master** branch. +2. You check [existing open](https://github.com/awsdocs/aws-cdk-user-guide/pulls), and [recently closed](https://github.com/awsdocs/aws-cdk-user-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-cdk-user-guide/issues/new) before working on a contribution that will take a significant amount of your time. + +For contributions that will take a significant amount of time, [open a new issue](https://github.com/awsdocs/aws-cdk-user-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-cdk-user-guide/issues) in this repository for some ideas. Any issues with the [help wanted](https://github.com/awsdocs/aws-cdk-user-guide/labels/help%20wanted) or [enhancement](https://github.com/awsdocs/aws-cdk-user-guide/labels/enhancement) labels are 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 + +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. + +## Licensing + +See the [LICENSE](https://github.com/awsdocs/aws-cdk-user-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. From 4b99416e73aa4e208f5d508f248e718abbbc4eee Mon Sep 17 00:00:00 2001 From: James Siri Date: Thu, 13 Dec 2018 11:53:04 -0800 Subject: [PATCH 004/655] Creating initial file from template --- LICENSE | 152 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..7785b904 --- /dev/null +++ b/LICENSE @@ -0,0 +1,152 @@ +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. From 74175b8e20f23f9a15119f0b6677eae0137329cf Mon Sep 17 00:00:00 2001 From: James Siri Date: Thu, 13 Dec 2018 11:53:05 -0800 Subject: [PATCH 005/655] Creating initial file from template --- LICENSE-SAMPLECODE | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 LICENSE-SAMPLECODE diff --git a/LICENSE-SAMPLECODE b/LICENSE-SAMPLECODE new file mode 100644 index 00000000..14aabc34 --- /dev/null +++ b/LICENSE-SAMPLECODE @@ -0,0 +1,14 @@ +Copyright 2018 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. From e7fb585022e5a713dd978732cea8766c85521aee Mon Sep 17 00:00:00 2001 From: James Siri Date: Thu, 13 Dec 2018 11:53:06 -0800 Subject: [PATCH 006/655] Creating initial file from template --- LICENSE-SUMMARY | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 LICENSE-SUMMARY diff --git a/LICENSE-SUMMARY b/LICENSE-SUMMARY new file mode 100644 index 00000000..56888df1 --- /dev/null +++ b/LICENSE-SUMMARY @@ -0,0 +1,5 @@ +Copyright 2018 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. From 45204ac273b8b17a9bcb39b05c44882d083aaa01 Mon Sep 17 00:00:00 2001 From: James Siri Date: Thu, 13 Dec 2018 11:53:07 -0800 Subject: [PATCH 007/655] Updating initial README.md from template --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 64a45c9c..75d04678 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,9 @@ -# aws-cdk-user-guide +## AWS Cdk User Guide + User guide for the AWS Cloud Development Kit (CDK). + +## License Summary + +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. From 0f3bf0f7dcc37f669084e862da4c040dd1cfa5b9 Mon Sep 17 00:00:00 2001 From: James Siri Date: Thu, 13 Dec 2018 11:53:07 -0800 Subject: [PATCH 008/655] Creating initial file from template --- CODE_OF_CONDUCT.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 CODE_OF_CONDUCT.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..3b644668 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,4 @@ +## 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. From f1dc14b290adf435fdcbb6e0a941f1af51d1878f Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Mon, 7 Jan 2019 12:33:56 -0800 Subject: [PATCH 009/655] Added initial MD files --- doc_source/cdk_applets.md | 64 ++++ doc_source/cdk_apps.md | 66 ++++ doc_source/cdk_assets.md | 11 + doc_source/cdk_aws_construct_lib.md | 41 +++ doc_source/cdk_cloudformation.md | 119 ++++++++ doc_source/cdk_concepts.md | 15 + doc_source/cdk_constructs.md | 104 +++++++ doc_source/cdk_context.md | 104 +++++++ doc_source/cdk_ecs_example.md | 123 ++++++++ doc_source/cdk_environments.md | 28 ++ doc_source/cdk_examples.md | 11 + doc_source/cdk_install_config.md | 48 +++ doc_source/cdk_logical_ids.md | 75 +++++ doc_source/cdk_passing_in_data.md | 215 +++++++++++++ doc_source/cdk_serverless_example.md | 385 +++++++++++++++++++++++ doc_source/cdk_stacks.md | 38 +++ doc_source/cdk_tools.md | 286 +++++++++++++++++ doc_source/cdk_tutorial.md | 440 +++++++++++++++++++++++++++ doc_source/cdk_writing_constructs.md | 90 ++++++ doc_source/doc-history.md | 15 + doc_source/glossary.md | 9 + doc_source/index.md | 38 +++ doc_source/what-is-CDK.md | 143 +++++++++ 23 files changed, 2468 insertions(+) create mode 100644 doc_source/cdk_applets.md create mode 100644 doc_source/cdk_apps.md create mode 100644 doc_source/cdk_assets.md create mode 100644 doc_source/cdk_aws_construct_lib.md create mode 100644 doc_source/cdk_cloudformation.md create mode 100644 doc_source/cdk_concepts.md create mode 100644 doc_source/cdk_constructs.md create mode 100644 doc_source/cdk_context.md create mode 100644 doc_source/cdk_ecs_example.md create mode 100644 doc_source/cdk_environments.md create mode 100644 doc_source/cdk_examples.md create mode 100644 doc_source/cdk_install_config.md create mode 100644 doc_source/cdk_logical_ids.md create mode 100644 doc_source/cdk_passing_in_data.md create mode 100644 doc_source/cdk_serverless_example.md create mode 100644 doc_source/cdk_stacks.md create mode 100644 doc_source/cdk_tools.md create mode 100644 doc_source/cdk_tutorial.md create mode 100644 doc_source/cdk_writing_constructs.md create mode 100644 doc_source/doc-history.md create mode 100644 doc_source/glossary.md create mode 100644 doc_source/index.md create mode 100644 doc_source/what-is-CDK.md diff --git a/doc_source/cdk_applets.md b/doc_source/cdk_applets.md new file mode 100644 index 00000000..fdfbdc16 --- /dev/null +++ b/doc_source/cdk_applets.md @@ -0,0 +1,64 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Applets + +**Note** +The AWS CDK only supports applets published as JavaScript modules\. + +Applets are YAML files that directly instantiate constructs, without writing any code\. The structure of an applet file looks like the following: + +``` +applets: + Applet1: + type: MODULE[:CLASS] + properties: + property1: value1 + property2: value2 + ... + Applet2: + type: MODULE[:CLASS] + properties: + ... +``` + +Every applet will be synthesized to its own stack, named after the key used in the applet definition\. + +## Specifying the Applet to Load + +An applet `type` specification looks like the following: + +``` +applet: MODULE[:CLASS] +``` + +**MODULE** can be used to indicate: ++ A local file, such as `./my-module` \(expects `my-module.js` in the same directory\)\. ++ A local module such as `my-dependency` \(expects an NPM package at `node_modules/my-dependency`\)\. ++ A global module, such as `@aws-cdk/aws-s3` \(expects the package to have been globally installed using NPM\)\. ++ An NPM package, such as `npm://some-package@1.2.3` \(the version specifier may be omitted to refer to the latest version of the package\)\. + +**CLASS** should reference the name of a class exported by the indicated module\. If the class name is omitted, `Applet` is used as the default class name\. + +## Properties + +Pass properties to the applet by specifying them in the `properties` object\. The properties will be passed to the instantiation of the class in the `type` parameter\. + +## Running + +To run an applet, pass its YAML file directly as the `--app` argument to a `cdk` invocation: + +``` +cdk --app ./my-applet.yaml deploy +``` + +To avoid needing to specify `--app` for every invocation, make a `cdk.json` file and add in the application in the config as usual: + +``` +{ + "app": "./my-applet.yaml" +} +``` \ No newline at end of file diff --git a/doc_source/cdk_apps.md b/doc_source/cdk_apps.md new file mode 100644 index 00000000..ce5976a3 --- /dev/null +++ b/doc_source/cdk_apps.md @@ -0,0 +1,66 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Apps + +The main artifact of an AWS CDK program is called a *CDK App*\. This is an executable program that can be used to synthesize deployment artifacts that can be deployed by supporting tools like the AWS CDK Toolkit, which are described in [Command\-line Toolkit \(cdk\)](cdk_tools.md)\. + +Tools interact with apps through the program's **argv**/**stdout** interface, which can be easily implemented using the **App** class, as shown in the following example\. + +``` +import { App } from '@aws-cdk/cdk' + +const app = new App(); // input: ARGV + +// + +app.run(); +``` + +An [App](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app) is a collection of [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) objects, as shown in the following example\. + +``` +import { App } from '@aws-cdk/cdk' +import { MyStack } from './my-stack' + +const app = new App(); + +const dev = new MyStack(app, { name: 'Dev', region: 'us-west-2', dev: true }) +const preProd = new MyStack(app, { name: 'PreProd', region: 'us-west-2', preProd: true }) +const prod = [ + new MyStack(app, { name: 'NAEast', region: 'us-east-1' }), + new MyStack(app, { name: 'NAWest', region: 'us-west-2' }), + new MyStack(app, { name: 'EU', region: 'eu-west-1', encryptedStorage: true }) +] + +new DeploymentPipeline(app, { + region: 'us-east-1', + strategy: DeploymentStrategy.Waved, + preProdStages: [ preProd ], + prodStages: prod +}); + +app.run(); +``` + +Use the cdk list command to list the stacks in this executable, as shown in the following example\. + +``` +[ + { name: "Dev", region: "us-west-2" } + { name: "PreProd", region: "us-west-2" }, + { name: "NAEast", region: "us-east-1" }, + { name: "NAWest", region: "us-west-2" }, + { name: "EU", region: "eu-west-1" }, + { name: "DeploymentPipeline", region: 'us-east-1' } +] +``` + +Use the cdk deploy command to deploy an individual stack: + +``` +cdk deploy Dev +``` \ No newline at end of file diff --git a/doc_source/cdk_assets.md b/doc_source/cdk_assets.md new file mode 100644 index 00000000..75f7475d --- /dev/null +++ b/doc_source/cdk_assets.md @@ -0,0 +1,11 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Assets + +Assets are local files, directories, or Docker images which can be bundled into CDK constructs and apps\. A common example is a directory which contains the handler code for a Lambda function, but assets can represent any artifact that is needed for the app’s operation\. + +When deploying an AWS CDK app that includes constructs with assets, the toolkit first prepares and publishes them to Amazon S3 or Amazon ECR, and only then deploy the stacks\. The locations of the published assets are passed in as AWS CloudFormation parameters to the relevant stacks\. \ No newline at end of file diff --git a/doc_source/cdk_aws_construct_lib.md b/doc_source/cdk_aws_construct_lib.md new file mode 100644 index 00000000..1daabbd0 --- /dev/null +++ b/doc_source/cdk_aws_construct_lib.md @@ -0,0 +1,41 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# AWS Construct Library + +The AWS Construct Library is a set of modules which expose APIs for defining AWS resources in AWS CDK apps\. The AWS Construct Library is organized in modules based on the AWS service to which the resource belongs\. For example, the [@aws\-cdk/aws\-ec2](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#module-@aws-cdk/aws-ec2) module includes the [@aws\-cdk/aws\-ec2\.VpcNetwork](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#@aws-cdk/aws-ec2.VpcNetwork) construct which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your AWS CDK app\. + +The AWS Construct Library includes many common patterns and capabilities which are designed to allow developers to focus on their application\-specific architectures and reduces the boilerplate and glue logic needed when working with AWS\. + +## Least\-Privilege IAM Policies + +IAM policies are automatically defined based on intent\. For example, when subscribing an Amazon SNS [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) to a Lambda [Function](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.Function) the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. + +Furthermore, most AWS Constructs expose `grant*` methods which allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct has a [grantRead\(principal\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.grantRead) method, which accepts an IAM [Principal](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#iprincipal-interface) such as a [User](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#user) or a [Role](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#role) which modifies the policy to allow the principal to read objects from the bucket\. + +## Event\-Driven APIs + +Many AWS constructs include `on*` methods, which can be used to react to events emitted by the construct\. For example, the AWS CodeCommit [Repository](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#Repository) construct has an [onCommit](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#@aws-cdk/aws-codecommit.RepositoryRef.onCommit) method\. AWS Constructs that can be used as targets for various event providers implement interfaces such as [IEventRuleTarget](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html#ieventruletarget-interface) \(for CloudWatch Event Rule target\), [IAlarmAction](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#ialarmaction-interface) \(for AWS CloudWatch Alarm actions\), etc\. + +For more information see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html) and [@aws\-cdk/aws\-events](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html)\. + +## Security Groups + +Amazon EC2 network entities such as the [Elastic Load Balancing](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-elasticloadbalancingv2.html) and [Auto Scaling Group](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-autoscaling.html#auto-scaling-group) instances can connect to each other based on definitions of security groups\. + +The AWS CDK provides APIs for defining security group connections\. For more information, see [Allowing Connections](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#allowing-connections)\. + +## Metrics + +Many AWS resources emit AWS CloudWatch metrics as part of their normal operation\. Metrics can be used to setup an [Alarm](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Alarm) or included in a [Dashboard](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Dashboard)\. + +[Metric](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Metric) objects for AWS Constructs can be obtained using `metricXxx()` methods\. For example, the [metricDuration\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.FunctionRef.metricDuration) method reports the execution time of an AWS Lambda function\. + +For more information see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html)\. + +## Imports + +If you need to reference a resource, such as an Amazon S3 bucket or VPC, which is defined outside of your AWS CDK app, you can use the `Xxxx.import(...)` static methods that are available on AWS Constructs\. For example, the [Bucket\.import\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.import) method can be used to obtain a [BucketRef](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef) object, which can be used in most places where a bucket is required\. This patterns allows treating resources defined outside your app as if they were part of your app\. \ No newline at end of file diff --git a/doc_source/cdk_cloudformation.md b/doc_source/cdk_cloudformation.md new file mode 100644 index 00000000..fa22c6b6 --- /dev/null +++ b/doc_source/cdk_cloudformation.md @@ -0,0 +1,119 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# AWS AWS CloudFormation Library + +The [AWS Construct Library](cdk_aws_construct_lib.md) includes constructs with APIs for defining AWS infrastructure\. For example, the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct can be used to define Amazon S3 Buckets and the [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) construct can be used to define Amazon SNS Topics\. + +Under the hood, these constructs are implemented using AWS CloudFormation resources, which are available in the `CfnXxx` classes in each library\. For example, the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct uses the [@aws\-cdk/aws\-s3\.cloudformation\.BucketResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.cloudformation.BucketResource) resource \(as well as other resources, depending on what bucket APIs are used\)\. + +**Important** +Generally, when building AWS CDK apps, you shouldn't need to interact with AWS CloudFormation directly\. However, there might be advanced use cases and migration scenarios where this might be required\. We are also aware that there might be gaps in capabilities in the AWS Construct Library over time\. + +## Resources + +AWS CloudFormation resource classes are automatically generated from the [AWS AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) and available under the `CfnXxx` classes of each AWS library\. Their API matches 1:1 with how you would use these resources in AWS CloudFormation\. + +When defining AWS CloudFormation resource, the `props` argument of the class initializer will match 1:1 to the resource's properties in AWS CloudFormation\. + +For example, to define an [AWS::SQS::Queue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html) resource encrypted with an AWS managed key you can directly specify the [KmsMasterKeyId](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-kmsmasterkeyid) property\. + +``` +import sqs = require('@aws-cdk/aws-sqs'); + +new sqs.CfnQueue(this, 'MyQueueResource', { + kmsMasterKeyId: 'alias/aws/sqs' +}); +``` + +For reference, if you use the [Queue](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sqs.html#@aws-cdk/aws-sqs.Queue) construct, you can define managed queue encryption as follows: + +``` +import sqs = require('@aws-cdk/aws-sqs'); + +new sqs.Queue(this, 'MyQueue', { + encryption: sqs.QueueEncryption.KmsManaged +}); +``` + +## Resource Options + +To reference the runtime attributes of AWS CloudFormation resources, use one of the properties available on the resource object\. + +The following example configures a Lambda function's dead letter queue to use the ARN of an Amazon SQS queue resource\. + +``` +import sqs = require('@aws-cdk/aws-sqs'); +import lambda = require('@aws-cdk/aws-lambda'); + +const dlq = new sqs.CfnQueue(this, { name: 'DLQ' }); + +new lambda.CfnFunction(this, { + deadLetterConfig: { + targetArn: dlq.queueArn + } +}); +``` + +The [cdk\.Resource\.ref](@cdk-class-url;#@aws-cdk/cdk.Resource.ref) attribute represents the AWS CloudFormation resource's intrinsic reference \(or *Return Value*\)\. For example, *dlq\.ref* also [refers](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-properties-sqs-queues-ref) to the queue's ARN\. When possible, it is preferrable to use an explicitly named attribute instead of *ref*\. + +## Resource Options + +The [cdk\.Resource\.options](@cdk-class-url;#@aws-cdk/cdk.Resource.options) object includes AWS CloudFormation options, such as `condition`, `updatePolicy`, `createPolicy` and `metadata`, for a resource\. + +## Parameters + +``` +import sns = require('@aws-cdk/aws-sns'); +import cdk = require('@aws-cdk/cdk'); + +const p = new cdk.Parameter(this, 'MyParam', { type: 'String' }); +new sns.CfnTopic(this, 'MyTopic', { displayName: p.ref }); +``` + +## Outputs + +``` +import sqs = require('@aws-cdk/aws-sqs'); +import cdk = require('@aws-cdk/cdk'); + +const queue = new sqs.CfnQueue(this, 'MyQueue'); +const out = new cdk.Output(this, 'MyQueueArn', { value: queue.queueArn }); + +const import = out.makeImportValue(); +assert(import === { "Fn::ImportValue": out.exportName } +``` + +## Conditions + +``` +import sqs = require('@aws-cdk/aws-sqs'); +import cdk = require('@aws-cdk/cdk'); +const cond = new cdk.Condition(this, 'MyCondition', { + expression: new cdk.FnIf(...) +}); + +const queue = new sqs.CfnQueue(this, 'MyQueue'); +queue.options.condition = cond; +``` + +## Intrinsic Functions + +``` +import { Fn } from'@aws-cdk/cdk'; +Fn.join(",", [...]) +``` + +## Pseudo Parameters + +``` +import cdk = require('@aws-cdk/cdk'); +new cdk.AwsRegion() + + +cdk synch > mytemplate +into a CI/CD pipeline +``` \ No newline at end of file diff --git a/doc_source/cdk_concepts.md b/doc_source/cdk_concepts.md new file mode 100644 index 00000000..5df4f8d2 --- /dev/null +++ b/doc_source/cdk_concepts.md @@ -0,0 +1,15 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# AWS CDK Concepts + +This topic describes some of the concepts \(the why and how\) behind the AWS CDK\. It also discusses the advantages of a AWS Construct Library over a low\-level CloudFormation Resource\. + +AWS CDK apps are represented as a hierarchal structure we call the *construct tree*\. Every node in the tree is a [Construct](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#construct) object\. The root of an AWS CDK app is typically an [App](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app) construct\. Apps contain one or more [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) constructs, which are deployable units of your app\. + +This composition of constructs gives you the flexibility to architect your app, such as having a stack deployed in multiple regions\. Stacks represent a collection of AWS resources, either directly or indirectly through a child construct that itself represents an AWS resource, such as an Amazon SQS queue, an Amazon SNS topic, a Lambda function, or a DynamoDB table\. + +This composition of constructs also means you can easily create sharable constructs, and make changes to any construct and have those changes available to consumers as shared class libraries\. \ No newline at end of file diff --git a/doc_source/cdk_constructs.md b/doc_source/cdk_constructs.md new file mode 100644 index 00000000..15a3a046 --- /dev/null +++ b/doc_source/cdk_constructs.md @@ -0,0 +1,104 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Constructs + +Constructs are the building blocks of AWS CDK applications\. Constructs can have child constructs, which in turn can have child constructs, forming a hierarchical tree structure\. + +The AWS CDK includes two different levels of constructs: + +CloudFormation Resource +These constructs are low\-level constructs that provide a direct, one\-to\-one, mapping to an AWS CloudFormation resource, as listed in the AWS CloudFormation topic [ AWS Resource Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. +All CloudFormation Resource members are found in the `@aws-cdk/resources` package\. + +AWS Construct Library +These constructs have been handwritten by AWS and come with convenient defaults and additional knowledge about the inner workings of the AWS resources they represent\. In general, you will be able to express your intent without worrying about the details too much, and the correct resources will automatically be defined for you\. +AWS Construct Library members are found in the `@aws-cdk/aws-NAMESPACE` packages, where NAMESPACE is the short name for the associated service, such as SQS for the AWS Construct Library for the Amazon SQS service\. See the [Reference](https://awslabs.github.io/aws-cdk/reference.html#reference) section for descriptions of the AWS CDK packages and constructs\. + +## Construct Structure + +The construct tree structure is a powerful design pattern for composing high\-level abstractions\. For example, you can define a `StorageLayer` construct that represents your application's storage layer and include all the AWS resources, such as DynamoDB tables and Amazon S3 buckets, needed to implement your storage layer in this construct\. When your higher\-level code uses this construct, it only needs to instantiate the `StorageLayer` construct\. + +When you initialize a construct, add the construct to the construct tree by specifying the parent construct as the first initializer parameter, an identifier for the construct as the second parameter, and a set of properties for the final parameter, as shown in the following example\. + +``` +new SomeConstruct(parent, name[, props]); +``` + +In almost all cases, you should pass the keyword `this` for the `parent` argument, because you will generally initialize new constructs in the context of the parent construct\. Any descriptive string will do for the `name` argument, and an in\-line object for the set of properties\. + +``` +new BeautifulConstruct(this, 'Foo', { + applicationName: 'myApp', + timeout: 300 +}); +``` + +**Note** +Associating the construct to its parent as part of initialization is necessary because the construct occasionally needs contextual information from its parent, such as to which the region the stack is deployed\. + +Use the following operations to inspect the construct tree\. + + aws\-cdk\.Construct\.parent +Gets the path of this construct from the root of the tree\. + + aws\-cdk\.Construct\.getChildren +Gets an array of all of the contruct's children\. + + aws\-cdk\.Construct\.getChild +Gets the child construct with the specified ID\. + + aws\-cdk\.Construct\.toTreeString\(\) +Gets a string representing the construct's tree\. + +## Construct Names + +Every construct in a CDK app must have a **name** unique among its siblings\. Names are used to track constructs in the construct hierarchy, and to allocate logical IDs so that AWS CloudFormation can keep track of the generated resources\. + +When a construct is created, its name is specified as the second initializer argument: + +``` +const c1 = new MyBeautifulConstruct(this, 'OneBeautiful'); +const c2 = new MyBeautifulConstruct(this, 'TwoBeautiful'); +assert(c1.name === 'OneBeautiful'); +assert(c2.name === 'TwoBeautiful'); +``` + +Use the `aws-cdk.Construct.path` property to get the path of this construct from the root of the tree\. + +Note that the name of a construct does not directly map onto the physical name of the resource when it is created\. If you want to give a physical name to a bucket or table, specify the physical name using use the appropriate property, such as `bucketName` or `tableName`, as shown in the following example: + +``` +new Bucket(this, 'MyBucket', { + bucketName: 'physical-bucket-name' +}); +``` + +Avoid specifying physical names\. Instead, let AWS CloudFormation generate names for you\. Use attributes, such as `bucket.bucketName`, to discover the generated names\. + +When you synthesize an AWS CDK tree into an AWS CloudFormation template, the AWS CloudFormation logical ID for each resource in the template is allocated according to the path of that resource in the construct tree\. For more information, see [Logical IDs](cdk_logical_ids.md)\. + +## Construct Properties + +Customize constructs by passing a property object as the third parameter \(*props*\)\. Every construct has its own set of parameters, defined as an interface\. You can pass a property object to your construct in two ways: + +``` +// Inline (recommended) +new Queue(this, 'MyQueue', { + visibilityTimeout: 300 +}); + +// Instantiate separate property object +const props: QueueProps = { + visibilityTimeout: 300 +}; + +new Queue(this, 'MyQueue', props); +``` + +## Construct Metadata + +You can attach metadata to a construct using the `aws-cdk.Construct.addMetadata` operation\. Metadata entries automatically include the stack trace from which the metadata entry was added\. Therefore, at any level of a construct you can find the code location, even if metadata was created by a lower\-level library that you don't own\. \ No newline at end of file diff --git a/doc_source/cdk_context.md b/doc_source/cdk_context.md new file mode 100644 index 00000000..596597dd --- /dev/null +++ b/doc_source/cdk_context.md @@ -0,0 +1,104 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Environmental Context + +When you synthesize a stack to create a AWS CloudFormation template, the AWS CDK might need information based on the environment \(account and Region\), such as the availability zones or AMIs available in the Region\. To enable this feature, the AWS CDK Toolkit uses *context providers*, and saves the context information into `cdk.json` the first time you call `cdk synth`\. + +The AWS CDK currently supports the following context providers\. + +[AvailabilityZoneProvider](@cdk-class-url;#@aws-cdk/cdk.AvailabilityZoneProvider) +Use this provider to get the list of all supported availability zones in this environment\. For example, the following code iterates over all of the AZs in the current environment\. + +``` +// "this" refers to a parent Construct +const zones: string[] = new AvailabilityZoneProvider(this).availabilityZones; + +for (let zone of zones) { + // do somethning for each zone! +} +``` + +[SSMParameterProvider](@cdk-class-url;#@aws-cdk/cdk.SSMParameterProvider) +Use this provider to read values from the current Region's SSM parameter store\. For example, the follow code returns the value of the *my\-awesome\-parameter* key: + +``` +const ami: string = new SSMParameterProvider(this, { + parameterName: 'my-awesome-parameter' +).parameterValue(); +``` +This is only for reading plain strings, and not recommended for secrets\. For reading secure strings from SSM Parmeter store, see [Getting a Value from an SSM Store Variable](cdk_passing_in_data.md#cdk_passing_ssm_value)\.\. + +[HostedZoneProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-route53.html#@aws-cdk/aws-route53.HostedZoneProvider) +Use this provider to discover existing hosted zones in your account\. For example, the following code imports an existing hosted zone into your CDK app so you can add records to it: + +``` +const zone: HostedZoneRef = new HostedZoneProvider(this, { + domainName: 'test.com' +}).findAndImport(this, 'HostedZone'); +``` + +[VpcNetworkProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#@aws-cdk/aws-ec2.VpcNetworkProvider) +Use this provider to look up and reference existing VPC in your accounts\. For example, the follow code imports a VPC by tag name: + +``` +const provider = new VpcNetworkProvider(this, { + tags: { + Purpose: 'WebServices' + } +}); + +const vpc = VpcNetworkRef.import(this, 'VPC', provider.vpcProps); +``` + +## Viewing and managing context + +Context is used to retrieve information such as the Availability Zones in your account or AMI IDs used to start your instances\. To avoid unexpected changes to your deployments, such as when you add a `Queue` to your application, but a new Amazon Linux AMI was released, thus changing your AutoScalingGroup, the AWS CDK stores the context values in `cdk.json`\. This ensures that the AWS CDK retrieves the same value on the next synthesis\. + +Use the cdk context to see context values stored for your application\. The output should be something like the following: + +``` +Context found in cdk.json: + +┌───┬────────────────────────────────────────────────────┬────────────────────────────────────────────────────┐ +│ # │ Key │ Value │ +├───┼────────────────────────────────────────────────────┼────────────────────────────────────────────────────┤ +│ 1 │ availability-zones:account=123456789012:region=us- │ [ "us-east-1a", "us-east-1b", "us-east-1c", │ +│ │ east-1 │ "us-east-1d", "us-east-1e", "us-east-1f" ] │ +├───┼────────────────────────────────────────────────────┼────────────────────────────────────────────────────┤ +│ 2 │ ssm:account=123456789012:parameterName=/aws/ │ "ami-013be31976ca2c322" │ +│ │ service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_ │ │ +│ │ 64-gp2:region=us-east-1 │ │ +└───┴────────────────────────────────────────────────────┴────────────────────────────────────────────────────┘ + +Run cdk context --reset KEY_OR_NUMBER to remove a context key. It will be refreshed on the next CDK synthesis run. +``` + +If at some point you want to update to the latest version of the Amazon Linux AMI, do a controlled update of the context value, reset it, and synthesize again: + +``` +$ cdk context --reset 2 +``` + +``` +Context value +ssm:account=123456789012:parameterName=/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2:region=us-east-1 +reset. It will be refreshed on the next SDK synthesis run. +``` + +``` +cdk synth +``` + +``` +... +``` + +To clear all context values, run cdk context \-\-clear: + +``` +cdk context --clear +``` \ No newline at end of file diff --git a/doc_source/cdk_ecs_example.md b/doc_source/cdk_ecs_example.md new file mode 100644 index 00000000..92de2d45 --- /dev/null +++ b/doc_source/cdk_ecs_example.md @@ -0,0 +1,123 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Creating an Amazon ECS Fargate Service Using the AWS CDK + +This example walks you through creating a Fargate service running on an ECS cluster fronted by an internet\-facing application load balancer\. + +Amazon ECS is a highly scalable, fast, container management service that makes it easy to run, stop, and manage Docker containers on a cluster\. You can host your cluster on a serverless infrastructure that is managed by Amazon ECS by launching your services or tasks using the Fargate launch type\. For more control you can host your tasks on a cluster of Amazon Elastic Compute Cloud \(Amazon EC2\) instances that you manage by using the Amazon EC2 launch type\. + +This example shows you how to launch some services using the Fargate launch type\. If you've ever used the console to create a Fargate service, you know that there are many steps you must follow to accomplish that task\. AWS has a number of tutorials and documentation topics that walk you through creating a Fargate service, including: ++ [How to Deploy Docker Containers \- AWS](https://aws.amazon.com/getting-started/tutorials/deploy-docker-containers) ++ [Setting up with Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/get-set-up-for-amazon-ecs.html) ++ [Getting Started with Amazon ECS using Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_GetStarted.html) + +This example creates a similar Fargate service in AWS CDK code\. + +Since Amazon ECS can be used with a number of AWS services, you should understand how the Amazon ECS construct that we use in this example gives you a leg up on using AWS services by providing the following benefits: ++ Automatically configures a load balancer\. ++ Automatic security group opening for load balancers, which enables load balancers to communicate with instances without you explictly creating a security group\. ++ Automatic ordering dependency between service and load balancer attaching to a target group, where the AWS CDK enforces the correct order of creating the listener before an instance is created ++ Automatic userdata configuration on auto\-scaling group, which creates the correct configuration to associate a cluster to AMI\(s\)\. ++ Early validation of parameter combinations, which exposes AWS CloudFormation issues earlier, thus saving you deployment time\. For example, depending upon the task, it is easy to mis\-configure the memory settings\. Previously you would not encounter an error until you deployed your app, but now the AWS CDK can detect a misconfiguration and emit an error when you synthesize your app\. ++ Automatically adds permissions for Amazon ECR if you use an image from Amazon ECR When you use an image from Amazon ECR, the AWS CDK adds the correct permissions\. ++ Automatic autoscaling\. The AWS CDK supplies a method so you can autoscaling instances when you use an Amazon EC2 cluster; this functionality is done automatically when you use an instance in a Fargate cluster\. + + In addition, the AWS CDK prevents instances from being deleted when autoscaling tries to kill an instance, but either a task is running or is scheduled on that instance\. + + Previously, you had to create a Lambda function to have this functionality\. ++ Asset support, so that you can deploy source from your machine to Amazon ECS in one step Previously, to use application source you had to perform a number of manual steps, such as upload to Amazon ECR and create a Docker image\. + +## Creating the Directory and Initializing the AWS CDK + +Let's start with creating a new directory to hold our AWS CDK code and create a new app in that directory\. + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language typescript +``` + +Build the app and confirm that it creates an empty stack\. + +``` +npm run build +cdk synth +``` + +You should see a stack like the following, where *CDK\-VERSION* is the version of the CDK\. + +``` +Resources: + CDKMetadata: + Type: 'AWS::CDK::Metadata' + Properties: + Modules: @aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_ecs_construct=0.1.0 +``` + +## Add the Amazon EC2 and Amazon ECS Packages + +Install support for Amazon EC2 and Amazon ECS\. + +``` +npm install @aws-cdk/aws-ec2 @aws-cdk/aws-ecs +``` + +## Create a Fargate Service + +There are two different ways of running your container tasks with Amazon ECS\. ++ Using the `Fargate` launch type, where Amazon ECS manages the physical machines that your containers are running on for you\. ++ Using the `EC2` launch type, where you do the managing, such as specifying autoscaling\. + +The following example creates a Fargate service running on an ECS cluster fronted by an internet\-facing application load balancer\. + +Add the following `import` statements to `lib/my_ecs_construct-stack.ts`\. + +``` +import ec2 = require('@aws-cdk/aws-ec2'); +import ecs = require('@aws-cdk/aws-ecs'); +``` + +Replace the comment at the end of the constructor with the following code\. + +``` +const vpc = new ec2.VpcNetwork(this, 'MyVpc', { + maxAZs: 3 // Default is all AZs in region +}); + +const cluster = new ecs.Cluster(this, 'MyCluster', { + vpc: vpc +}); + +// Create a load-balanced Fargate service and make it public +new ecs.LoadBalancedFargateService(this, 'MyFargateService', { + cluster: cluster, // Required + cpu: '512', // Default is 256 + desiredCount: 6, // Default is 1 + image: ecs.ContainerImage.fromDockerHub('amazon/amazon-ecs-sample'), // Required + memoryMiB: '2048', // Default is 512 + publicLoadBalancer: true // Default is false +}); +``` + +Save it and make sure it builds and creates a stack\. + +``` +npm run build +cdk synth +``` + +The stack is hundreds of lines, so we won't show it here\. The stack should contain one default instance, a private subnet and a public subnet for the three availability zones, and a security group\. + +Deploy the stack\. + +``` +cdk deploy +``` + +AWS CloudFormation displays information about the dozens of steps that it takes as it deploys your app\. + +That's how easy it is to create a Fargate service to run a Docker image\. \ No newline at end of file diff --git a/doc_source/cdk_environments.md b/doc_source/cdk_environments.md new file mode 100644 index 00000000..18b5a9b8 --- /dev/null +++ b/doc_source/cdk_environments.md @@ -0,0 +1,28 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Environments and Authentication + +The AWS CDK refers to the combination of an account ID and a Region as an *environment*\. The simplest environment is the one you get by default, which is the one you get when you have set up your credentials and a default Region as described in [Configuring the AWS CDK Toolkit](cdk_install_config.md#cdk_credentials)\. + +When you create a [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) instance, you can supply the target deployment environment for the stack using the `env` property, as shown in the following example, where REGION is the Region in which you want to create the stack and ACCOUNT is your account ID\. + +``` +new MyStack(app, { env: { region: 'REGION', account: 'ACCOUNT' } }); +``` + +For each of the two arguments, **region** and **account**, the AWS CDK uses the following lookup procedure: ++ If **region** or **account** are provided directly as an property to the Stack, use that\. ++ Otherwise, read **default\-account** and **default\-region** from the application's context\. These can be set in the AWS CDK Toolkit in either the local `cdk.json` file or the global version in *$HOME/\.cdk* on Linux or MacOS or *%USERPROFILE%\\\\\.cdk* on Windows\. ++ If these are not defined, it will determine them as follows: + + **account**: use account from default SDK credentials\. Environment variables are tried first \(`AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`\), followed by credentials in *$HOME/\.aws/credentials* on Linux or MacOS or *%USERPROFILE%\\\\\.aws\\\\credentials* on Windows\. + + **region**: use the default region configured in *$HOME/\.aws/config* on Linux or MacOS or *%USERPROFILE%\\\\\.aws\\\\config* on Windows\. + + You can set these defaults manually, but we recommend you use `aws configure`, as described in [Installing and Configuring the AWS CDK](cdk_install_config.md) + +We recommend that you use the default environment for development stacks, and explicitly specify accounts and Regions for production stacks\. + +**Note** +Note that even though the region and account might explicitly be set on your Stack, if you run `cdk deploy`, the AWS CDK will still use the currently\-configured SDK credentials, as provided via the `AWS_` environment variables or `aws configure`\. This means that if you want to deploy stacks to multiple accounts, you will have to set the correct credentials for each invocation to `cdk deploy STACK`\. \ No newline at end of file diff --git a/doc_source/cdk_examples.md b/doc_source/cdk_examples.md new file mode 100644 index 00000000..d0d03aa7 --- /dev/null +++ b/doc_source/cdk_examples.md @@ -0,0 +1,11 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# AWS CDK Examples + +This topic contains examples to help you get started using some of the advanced constructs offered by the AWS CDK\. ++ [Creating a Serverless Application Using the AWS CDK](cdk_serverless_example.md) Creates a serverless application to dispense widgets\. ++ [Creating an Amazon ECS Fargate Service Using the AWS CDK](cdk_ecs_example.md) Creates an Amazon ECS Fargate service\. \ No newline at end of file diff --git a/doc_source/cdk_install_config.md b/doc_source/cdk_install_config.md new file mode 100644 index 00000000..43187b69 --- /dev/null +++ b/doc_source/cdk_install_config.md @@ -0,0 +1,48 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Installing and Configuring the AWS CDK + +This topic describes how to install and configure the AWS CDK\. + +## Prerequisites + +You must install [Node\.js \(>= 8\.11\.x\)](https://nodejs.org/en/download) to use the command\-line toolkit and language bindings\. + +If you use Java, you must set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine to build an AWS CDK app in Java\. + +Specify your credentials and region with the [AWS CLI](https://aws.amazon.com/cli)\. You must specify both your credentials and a region to use the toolkit\. See [Configuring the AWS CDK Toolkit](#cdk_credentials) for information on using the AWS CLI to specify your credentials\. + +## Installing the AWS CDK + +Install the AWS CDK using the following command: + +``` +npm install -g aws-cdk +``` + +Run the following command to see the currently installed version of the AWS CDK: + +``` +cdk --version +``` + +## Configuring the AWS CDK Toolkit + +Use the AWS CDK toolkit to view the contents of an app\. + +**Note** +You must specify your default credentials and region to use the toolkit\. +Use the AWS Command Line Interface aws configure command to specify your default credentials and region\. +You can also set environment variables for your default credentials and region\. Environment variables take precedence over settings in the credentials or config file\. +`AWS_ACCESS_KEY_ID` specifies your access key +`AWS_SECRET_ACCESS_KEY` specifies your secret access key +`AWS_DEFAULT_REGION` specifies your default region +See [Environment Variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-environment.html) in the CLI User Guide for details\. + +**Note** +The China regions \(cn\-north\-1 and cn\-northwest\-1\) do not support version reporting\. +See [Version Reporting](cdk_tools.md#cdk_version_reporting) for details, including how to [opt\-out](cdk_tools.md#cdk_version_reporting_opt_out)\. \ No newline at end of file diff --git a/doc_source/cdk_logical_ids.md b/doc_source/cdk_logical_ids.md new file mode 100644 index 00000000..60ef3b15 --- /dev/null +++ b/doc_source/cdk_logical_ids.md @@ -0,0 +1,75 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Logical IDs + +When you synthesize a stack into an AWS CloudFormation template, the AWS CDK assigns a [ logical ID](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html), which must be unique within the template, to each resource in the stack\. + +**Important** +When you update the template, AWS CloudFormation uses these logical IDs to plan the update and apply changes\. Therefore, logical IDs must remain "stable" across updates\. If you make a modification in your code that results in a change to a logical ID of a resource, AWS CloudFormation deletes the resource and creates a new resource when it updates the stack\. + +Each resource in the construct tree has a unique path that represents its location within the tree\. Since logical IDs can only use alphanumeric characters and cannot exceed 255 characters, the CDK is unable to simply use a delimited path as the logical ID\. Instead, logical IDs are allocated by concatenating a human\-friendly rendition from the path \(concatenation, de\-duplicate, trim\) with an eight\-character MD5 hash of the delimited path\. This final component is necessary since AWS CloudFormation logical IDs cannot include the delimiting slash character \(/\), so simply concatenating the component values does not work\. For example, concatenating the components of the path */a/b/c* produces **abc**, which is the same as concatenating the components of the path */ab/c*\. + +``` +VPCPrivateSubnet2RouteTable0A19E10E +<-----------human---------><-hash-> +``` + +Low\-level CloudFormation resources \(from `@aws-cdk/resources`\) that are direct children of the [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) class use their name as their logical ID without modification\. This makes it easier to port existing templates into a CDK app\. + +This scheme ensures that: + +Logical IDs have a human\-friendly portion +This is useful when interacting directly with the synthesized AWS CloudFormation template during development and deployment\. + +Logical IDs are unique within the stack +This is ensured by the MD5 component, which is based on the absolute path to the resource, which is unique within a stack\. + +Logical IDs remain unchanged across updates +This is true as long as their location within the construct tree doesn't change\. + +The AWS CDK applies some heuristics to improve the human\-friendliness of the prefix: ++ If a path component is **Default**, it is hidden completely from the logical ID computation\. You will generally want to use this if you create a new construct that wraps an existing one\. By naming the inner construct **Default**, you ensure that the logical identifiers of resources in already\-deployed copy of that construct do not change\. ++ If a path component is **Resource**, it is omitted from the human readable portion of the logical ID\. This postfix does not normally contribute any additional useful information to the ID\. ++ If two subsequent names in the path are the same, only one is retained\. ++ If the prefix exceeds 240 characters, it is trimmed to 240 characters\. This ensures that the total length of the logical ID does not exceed the 255 character AWS CloudFormation limit for logical IDs\. + +## Renaming Logical IDs + +The `aws-cdk.Stack.renameLogical` method can be used to explicitly assign logical IDs to certain resources\. + +``` +class MyStack extends Stack { + constructor(parent: App, name: string, props: StackProps) { + super(parent, name); + + // note that renameLogical must be called /before/ defining the construct. + // a good practice would be to always put these at the top of your stack initializer. + this.renameLogical('MyTableCD117FA1', 'MyTable'); + this.renameLogical('MyQueueAB4432A3', 'MyAwesomeQueue'); + + new Table(this, 'MyTable'); + new Queue(this, 'MyQueue'); + } +} +``` + +In some cases changing a resource results in a structural change, which results in a different path, thus changing the logical ID of the resource\. + +When a resource's logical ID changes, AWS CloudFormation eventually deletes the old resource and create a new resource, as it cannot determine that the two resources are the same\. Depending on the nature of the resource, this can be disastrous in production, such as when deleting a DynamoDB table\. + +You could use [AWS CloudFormation Stack Policies](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html) to protect critical resources in your stack from accidental deletion\. Although this AWS CloudFormation feature is not supported in the AWS CDK and AWS CDK Toolkit, the AWS CDK does provide a few other mechanisms to help deal with logical ID changes\. + +If you have CDK stacks deployed with persistent resources such as S3 buckets or DynamoDB tables, you might want to explicitly "rename" the new logical IDs to match your existing resources\. + +First, make sure you compare the newly synthesized template with any deployed stacks\. `cdk diff` will tell you which resources are about to be destroyed: + +``` +[-] ☢️ Destroying MyTable (type: AWS::DynamoDB::Table) +[+] 🆕 Creating MyTableCD117FA1 (type: AWS::DynamoDB::Table) +``` + +Now, you can add a `aws-cdk.Stack.renameLogical` call before the table is defined to rename **MyTableCD117FA1** to **MyTable**\. \ No newline at end of file diff --git a/doc_source/cdk_passing_in_data.md b/doc_source/cdk_passing_in_data.md new file mode 100644 index 00000000..a018d449 --- /dev/null +++ b/doc_source/cdk_passing_in_data.md @@ -0,0 +1,215 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Passing in External Values to Your AWS CDK App + +There may be cases where you want to parameterize one or more of your stack resources\. Therefore, you want to be able to pass values into your app from outside your app\. Currently, you can get values into your app from outside your app through any of the following\. ++ Using a context variable ++ Using an environment variable ++ Using an SSM Parameter Store variable ++ Using a Secrets manager value ++ Using a value from another stack ++ Using a AWS CloudFormation parameter ++ Using a resource in an existing AWS CloudFormation template + +Each of these techniques is described in the following sections\. + +## Getting a Value from a Context Variable + +You can specify a context variable either as part of a AWS CDK Toolkit command, or in a **context** section of `cdk.json`\. + +To create a command\-line context variable, use the **\-\-context** \(**\-c**\) option of a AWS CDK Toolkit command, as shown in the following example\. + +``` +cdk synth -c bucket_name=mygroovybucket +``` + +To specify the same context variable and value in *cdk\.json*: + +``` +{ + "context": { + "bucket_name": "myotherbucket" + } +} +``` + +To get the value of a context variable in your app, use code like the following, which gets the value of the context variable **bucket\_name**\. + +``` +const bucket_name string = this.getContext("bucket_name"); +``` + +## Getting a Value from an Environment Variable + +To get the value of an environment variable, use code like the following, which gets the value of the environment variable `MYBUCKET`\. + +``` +const bucket_name = process.env.MYBUCKET; +``` + +## Getting a Value from an SSM Store Variable + +There are three ways to get the value of an SSM parameter store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It is not possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from SecretsManager \(see [Getting a Value from AWS Secrets Manager](#cdk_passing_secrets_manager)\)\. + +The first two are not recommended for values that are supposed to be secrets, such as passwords\. + +To retrieve the latest value once \(as a context value, see [Environmental Context](cdk_context.md)\), and keep on using the same value until the context value manually refreshed, use a [SSMParameterProvider](@cdk-class-url;#@aws-cdk/cdk.SSMParameterProvider): + +``` +import cdk = require('@amp;aws-cdk/cdk'); + +const myvalue = new cdk.SSMParameterProvider(this).getString("my-parameter-name"); +``` + +To read a particular version of an SSM Parameter Store plain string value at CloudFormation deployment time, use [ssm\.ParameterStoreString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstorestring): + +``` +import ssm = require('@amp;aws-cdk/aws-ssm'); + +const parameterString = new ssm.ParameterStoreString(this, 'MyParameter', { + parameterName: 'my-parameter-name', + version: 1, +}); + +const myvalue = parameterString.value; +``` + +To read a particular version of an SSM Parameter Store SecureString value at CloudFormation deployment time, use [ssm\.ParameterStoreSecureString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstoresecurestring): + +``` +import ssm = require('@amp;aws-cdk/aws-ssm'); + +const secureString = new ssm.ParameterStoreSecureString(this, 'MySecretParameter', { + parameterName: 'my-secret-parameter-name', + version: 1, +}); + +const myvalue = secureString.value; +``` + +## Getting a Value from AWS Secrets Manager + +To use values from AWS Secrets Manager in your CDK app, create an instance of [SecretsManager](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-secretsmanager.html/_aws-cdk_aws-secretsmanager.html#aws-cdk-aws-secretsmanager)\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. + +``` +import secretsmanager = require('@amp;aws-cdk/aws-secretsmanager'); + +const loginSecret = new secretsmanager.SecretString(stack, 'Secret', { + secretId: 'MyLogin' + + // By default, the latest version is retrieved. It's possible to + // use a specific version instead. + // versionStage: 'AWSCURRENT' +}); + +// Retrieve a value from the secret's JSON +const username = loginSecret.jsonFieldValue('username'); +const password = loginSecret.jsonFieldValue('password'); + +// Retrieve the whole secret's string value +const fullValue = loginSecret.value; +``` + +## Passing in a Value From Another Stack + +You can pass a value from one stack to another stack in the same app by using the `export` method in one stack and the `import` method in the other stack\. + +The following example creates a bucket on one stack and passes a reference to that bucket to the other stack through an interface\. + +First create a stack with a bucket\. The stack includes a property we use to pass the bucket's properties to the other stack\. Note how we use the `export` method on the bucket to get its properties and save them in the stack property\. + +``` +class HelloCdkStack extends cdk.Stack { + // Property that defines the stack you are exporting from + public readonly myBucketRefProps: s3.BucketRefProps; + + constructor(parent: cdk.App, name: string, props?: cdk.StackProps) { + super(parent, name, props); + + const mybucket = new s3.Bucket(this, "MyFirstBucket"); + + // Save bucket's BucketRefProps + this.myBucketRefProps = mybucket.export(); + } +} +``` + +Create an interface for the second stack's properties\. We use this interface to pass the bucket properties between the two stacks\. + +``` +// Interface we'll use to pass the bucket's properties to another stack +interface MyCdkStackProps { + theBucketRefProps: s3.BucketRefProps; +} +``` + +Create the second stack that gets a reference to the other bucket from the properties passed in through the constructor\. + +``` +// The class for the other stack +class MyCdkStack extends cdk.Stack { + constructor(parent: cdk.App, name: string, props: MyCdkStackProps) { + super(parent, name); + + const myOtherBucket = s3.Bucket.import(this, "MyOtherBucket", props.theBucketRefProps); + + // Do something with myOtherBucket + } +} +``` + +Finally, connect the dots in your app\. + +``` +const app = new cdk.App(); + +const myStack = new HelloCdkStack(app, "HelloCdkStack"); + +new MyCdkStack(app, "MyCdkStack", { + theBucketRefProps: myStack.myBucketRefProps +}); + +app.run(); +``` + +## Using an AWS CloudFormation Parameter + +See [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for information about using the optional *Parameters* section to customize your AWS CloudFormation templates\. + +You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [AWS CDK Concepts](cdk_concepts.md)\. + +## Using an Existing AWS CloudFormation Template + +The AWS CDK provides a mechanism that you can use to incorporate resources from an existing AWS CloudFormation template into your AWS CDK app\. For example, suppose you have a template, `my-template.json`, with the following resource, where **S3Bucket** is the logical ID of the bucket in your template: + +``` +{ + "S3Bucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "prop1": "value1" + } + } +} +``` + +You can include this bucket in your AWS CDK app, as shown in the following example \(note that you cannot use this method in an AWS Construct Library construct\): + +``` +import cdk = require("@amp;aws-cdk/cdk"); +import fs = require("fs"); + +new cdk.Include(this, "ExistingInfrastructure", { + template: JSON.parse(fs.readFileSync("my-template.json").toString()) +}); +``` + +Then to access an attribute of the resource, such as the bucket's ARN: + +``` +const bucketArn = new cdk.FnGetAtt("S3Bucket", "Arn"); +``` \ No newline at end of file diff --git a/doc_source/cdk_serverless_example.md b/doc_source/cdk_serverless_example.md new file mode 100644 index 00000000..83f7649c --- /dev/null +++ b/doc_source/cdk_serverless_example.md @@ -0,0 +1,385 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Creating a Serverless Application Using the AWS CDK + +This example walks you through creating the resources for a simple widget dispensing service\. It includes: ++ An AWS Lambda function ++ An API Gateway API to call our Lambda function ++ An Amazon S3 bucket that contains our Lambda function code + +## Overview + +This example contains the following steps\. + +1. Create a AWS CDK app + +1. Create a Lambda function that gets a list of widgets with: GET / + +1. Create the service that calls the Lambda function + +1. Add the service to the AWS CDK app + +1. Test the app + +1. Add Lambda functions to: + + create an widget based with: POST /\{name\} + + get an widget by name with: GET /\{name\} + + delete an widget by name with: DELETE /\{name\} + +## Create an AWS CDK App + +Create the TypeScript app **MyWidgetService** in in the current folder\. + +``` +mkdir MyWidgetService +cd MyWidgetService +cdk init --language typescript +``` + +This creates `my_widget_service.ts` in the `bin` directory and `my_widget_service-stack.ts` in the `lib` directory\. + +Build it and note that it creates an empty stack\. + +``` +npm run build +cdk synth +``` + +You should see a stack like the following, where *CDK\-VERSION* is the version of the CDK\. + +``` +Resources: + CDKMetadata: + Type: AWS::CDK::Metadata + Properties: + Modules: "@aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_widget_service=0.1.0" +``` + +## Create a Lambda Function to List all Widgets + +The next step is to create a Lambda function to list all of the widgets in our Amazon S3 bucket\. + +Create the directory `resources` at the same level as the bin directory\. + +``` +mkdir resources +``` + +Create the following Javascript file, `widgets.js`, in the `resources` directory\. + +``` +const AWS = require('aws-sdk'); +const S3 = new AWS.S3(); + +const bucketName = process.env.BUCKET; + +exports.main = async function(event, context) { + try { + var method = event.httpMethod; + + if (method === "GET") { + if (event.path === "/") { + const data = await S3.listObjectsV2({ Bucket: bucketName }).promise(); + var body = { + widgets: data.Contents.map(function(e) { return e.Key }) + }; + return { + statusCode: 200, + headers: {}, + body: JSON.stringify(body) + }; + } + } + + // We only accept GET for now + return { + statusCode: 400, + headers: {}, + body: "We only accept GET /" + }; + } catch(error) { + var body = error.stack || JSON.stringify(error, null, 2); + return { + statusCode: 400, + headers: {}, + body: JSON.stringify(body) + } + } +} +``` + +Save it and make sure it builds and creates an empty stack\. Note that since we haven't wired the function to our app, the Lambda file does not appear in the output\. + +``` +npm run build +cdk synth +``` + +## Creating a Widget Service + +Add the API Gateway, Lambda, and Amazon S3 packages to our app\. + +``` +npm install @aws-cdk/aws-apigateway @aws-cdk/aws-lambda @aws-cdk/aws-s3 +``` + +Create the Typescript file `widget_service.ts` in the `lib` directory\. + +``` +import cdk = require('@aws-cdk/cdk'); +import apigateway = require('@aws-cdk/aws-apigateway'); +import lambda = require('@aws-cdk/aws-lambda'); +import s3 = require('@aws-cdk/aws-s3'); + +export class WidgetService extends cdk.Construct { + constructor(parent: cdk.Construct, name: string) { + super(parent, name); + + // Use S3 bucket to store our widgets + const bucket = new s3.Bucket(this, 'WidgetStore'); + + // Create a handler that calls the function main + // in the source file widgets(.js) in the resources directory + // to handle requests through API Gateway + const handler = new lambda.Function(this, 'WidgetHandler', { + runtime: lambda.Runtime.NodeJS810, + code: lambda.Code.directory('resources'), + handler: 'widgets.main', + environment: { + BUCKET: bucket.bucketName // So runtime has the bucket name + } + }); + + bucket.grantReadWrite(handler.role); + + // Create an API Gateway REST API + const api = new apigateway.RestApi(this, 'widgets-api', { + restApiName: 'Widget Service', + description: 'This service serves widgets.' + }); + + // Pass the request to the handler + const getWidgetsIntegration = new apigateway.LambdaIntegration(handler); + + // Use the getWidgetsIntegration when there is a GET request + api.root.addMethod('GET', getWidgetsIntegration); // GET / + } +} +``` + +Save it and make sure it builds and creates a \(still empty\) stack\. + +``` +npm run build +cdk synth +``` + +## Add the Service to the App + +To add the service to our app, we need to first modify `my_widget_service-stack.ts`\. Add the following line of code after the existing **import** statement\. + +``` +import widget_service = require('../lib/widget_service'); +``` + +Replace the comment in the constructor with the following line of code\. + +``` +new widget_service.WidgetService(this, 'Widgets'); +``` + +Make sure it builds and creates a stack \(we don't show the stack as it's over 250 lines\)\. + +``` +npm run build +cdk synth +``` + +## Deploy and Test the App + +Before you can deploy your first AWS CDK app, you must bootstrap your deployment, which creates some AWS infracture that the AWS CDK needs\. See the **bootstrap** section of [Command\-line Toolkit \(cdk\)](cdk_tools.md) for details \(you'll get a warning and nothing changes if you have already bootstrapped an AWS CDK app\)\. + +``` +cdk bootstrap +``` + +Deploy your app: + +``` +cdk deploy +``` + +If the deployment is successfull, save the URL for your server, which appears in one of the last lines in the window, where *GUID* is an alpha\-numeric GUID and *REGION* is your region\. + +``` +https://GUID.execute-REGION.amazonaws.com/prod/ +``` + +You can test your app by getting the list of widgets \(currently empty\) by navigating to this URL in a browser or use the following command\. + +``` +curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' +``` + +You can also test the app by: ++ Opening the AWS Management Console ++ Navigating to the API Gateway service ++ Finding **Widget Service** in the list ++ Selecting **GET** and **Test** to test the function\. + +Since we haven't stored any widgets yet, the output should be similar to the following\. + +``` +{ "widgets": [] } +``` + +## Add the Individual Widget Functions + +The next step is to create Lambda functions to create, show, and delete individual widgets\. Replace the existing `exports.main` function in `widgets.js` with the following code\. + +``` +exports.main = async function(event, context) { + try { + var method = event.httpMethod; + // Get name, if present + var widgetName = event.path.startsWith('/') ? event.path.substring(1) : event.path; + + if (method === "GET") { + // GET / to get the names of all widgets + if (event.path === "/") { + const data = await S3.listObjectsV2({ Bucket: bucketName }).promise(); + var body = { + widgets: data.Contents.map(function(e) { return e.Key }) + }; + return { + statusCode: 200, + headers: {}, + body: JSON.stringify(body) + }; + } + + if (widgetName) { + // GET /name to get info on widget name + const data = await S3.getObject({ Bucket: bucketName, Key: widgetName}).promise(); + var body = data.Body.toString('utf-8'); + + return { + statusCode: 200, + headers: {}, + body: JSON.stringify(body) + }; + } + } + + if (method === "POST") { + // POST /name + // Return error if we do not have a name + if (!widgetName) { + return { + statusCode: 400, + headers: {}, + body: "Widget name missing" + }; + } + + // Create some dummy data to populate object + const now = new Date(); + var data = widgetName + " created: " + now; + + var base64data = new Buffer(data, 'binary'); + + await S3.putObject({ + Bucket: bucketName, + Key: widgetName, + Body: base64data, + ContentType: 'application/json' + }).promise(); + + return { + statusCode: 200, + headers: {}, + body: JSON.stringify(event.widgets) + }; + } + + if (method === "DELETE") { + // DELETE /name + // Return an error if we do not have a name + if (!widgetName) { + return { + statusCode: 400, + headers: {}, + body: "Widget name missing" + }; + } + + await S3.deleteObject({ + Bucket: bucketName, Key: widgetName + }).promise(); + + return { + statusCode: 200, + headers: {}, + body: "Successfully deleted widget " + widgetName + }; + } + + // We got something besides a GET, POST, or DELETE + return { + statusCode: 400, + headers: {}, + body: "We only accept GET, POST, and DELETE, not " + method + }; + } catch(error) { + var body = error.stack || JSON.stringify(error, null, 2); + return { + statusCode: 400, + headers: {}, + body: body + } + } +} +``` + +Wire these functions up to our API Gateway code in `widget_service.ts` by adding the following code at the end of the constructor\. + +``` +const widget = api.root.addResource('{name}'); + +// Add new widget to bucket with: POST /{name} +const postWidgetIntegration = new apigateway.LambdaIntegration(handler); + +// Get a specific widget from bucket with: GET /{name} +const getWidgetIntegration = new apigateway.LambdaIntegration(handler); + +// Remove a specific widget from the bucket with: DELETE /{name} +const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); + +widget.addMethod('POST', postWidgetIntegration); // POST /{name} +widget.addMethod('GET', getWidgetIntegration); // GET /{name} +widget.addMethod('DELETE', deleteWidgetIntegration); // DELETE /{name} +``` + +Save, build, and deploy the app\. + +``` +npm run build +cdk deploy +``` + +We can now store, show, or delete an individual widget\. Use the following commands to list the widgets, create the widget **dummy**, list all of the widgets, show the contents of **dummy** \(it should show today's date\), and delete **dummy**, and again show the list of widgets\. + +``` +curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' +curl -X POST 'https://GUID.execute-REGION.amazonaws.com/prod/dummy' +curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' +curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod/dummy' +curl -X DELETE 'https://GUID.execute-REGION.amazonaws.com/prod/dummy' +curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' +``` + +You can also use the API Gateway console to test these functions\. You'll have to set the **name** entry to the name of an widget, such as **dummy**\. \ No newline at end of file diff --git a/doc_source/cdk_stacks.md b/doc_source/cdk_stacks.md new file mode 100644 index 00000000..58eb33d9 --- /dev/null +++ b/doc_source/cdk_stacks.md @@ -0,0 +1,38 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Stacks + +A [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) is an AWS CDK construct that can be deployed into an AWS environment\. The combination of region and account becomes the stack's *environment*, as described in [Environments and Authentication](cdk_environments.md)\. Most production apps consist of multiple stacks of resources that are deployed as a single transaction using a resource provisioning service like AWS CloudFormation\. Any resources added directly or indirectly as children of a stack are included in the stack's template as it is synthesized by your AWS CDK program\. + +Define an application stack by extending the [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) class, as shown in the following example\. + +``` +import { Stack, StackProps } from '@aws-cdk/cdk' + +interface MyStackProps extends StackProps { + encryptedStorage: boolean; +} + +class MyStack extends Stack { + constructor(parent: Construct, name: string, props?: MyStackProps) { + super(parent, name, props); + + new MyStorageLayer(this, 'Storage', { encryptedStorage: props.encryptedStorage }); + new MyControlPlane(this, 'CPlane'); + new MyDataPlane(this, 'DPlane'); + } +} +``` + +And then, add instances of this class to your app: + +``` +const app = new App(); + +new MyStack(app, 'NorthAmerica', { env: { region: 'us-east-1' } }); +new MyStack(app, 'Europe', { env: { region: 'us-west-2' } }); +``` \ No newline at end of file diff --git a/doc_source/cdk_tools.md b/doc_source/cdk_tools.md new file mode 100644 index 00000000..db07d2b9 --- /dev/null +++ b/doc_source/cdk_tools.md @@ -0,0 +1,286 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Command\-line Toolkit \(cdk\) + +cdk \(the AWS CDK Toolkit\) is the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you have written and compiled, interrogates the application model you have defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. + +There are two ways that you can tell cdk what command to use to run your AWS CDK app\. The first way is to include an explicit \-\-app option whenever you use a cdk command: + +``` +cdk --app 'node bin/main.js' synth +``` + +The second way is to add the following entry to the file `cdk.json`: + +``` +{ + "app": "node bin/main.js" +} +``` + +Here are the actions you can take on your CDK app \(this is the output of the cdk \-\-help command\): + +``` +Usage: cdk -a COMMAND + +Commands: + list Lists all stacks in the app [aliases: ls] + synthesize [STACKS..] Synthesizes and prints the CloudFormation template + for this stack [aliases: synth] + bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS + environment + deploy [STACKS..] Deploys the stack(s) named STACKS into your AWS + account + destroy [STACKS..] Destroy the stack(s) named STACKS + diff [STACK] Compares the specified stack with the deployed + stack or a local template file + metadata [STACK] Returns all metadata associated with this stack + init [TEMPLATE] Create a new, empty CDK project from a template. + Invoked without TEMPLATE, the app template will be + used. + context Manage cached context values + docs Opens the documentation in a browser[aliases: doc] + doctor Check your set-up for potential problems + +Options: + --app, -a REQUIRED: Command-line for executing your CDK app (e.g. + "node bin/my-app.js") [string] + --context, -c Add contextual string parameter. [array] + --plugin, -p Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] + --rename Rename stack name if different then the one defined in + the cloud executable [string] + --trace Print trace for stack warnings [boolean] + --strict Do not construct stacks with warnings [boolean] + --ignore-errors Ignores synthesis errors, which will likely produce an + invalid output [boolean] [default: false] + --json, -j Use JSON output instead of YAML [boolean] + --verbose, -v Show debug logs [boolean] + --profile Use the indicated AWS profile as the default environment + [string] + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified. [string] + --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: + guess EC2 instance status. [boolean] + --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized + templates (enabled by default) [boolean] + --path-metadata Include "aws:cdk:path" CloudFormation metadata for each + resource (enabled by default) [boolean] [default: true] + --role-arn, -r ARN of Role to use when invoking CloudFormation [string] + --version Show version number [boolean] + -h, --help Show help [boolean] + +If your app has a single stack, there is no need to specify the stack name + +If one of cdk.json or ~/.cdk.json exists, options specified there will be used +as defaults. Settings in cdk.json take precedence. +``` + +If your app has a single stack, there is no need to specify the stack name\. + +If one of `cdk.json` or `~/.cdk.json` exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. + +## Security\-related changes + +In order to protect you against unintended changes that affect your security posture, the CDK toolkit will prompt you to approve security\-related changes before deploying them\. + +You change the level of changes that requires approval by specifying: + +``` +cdk deploy --require-approval LEVEL +``` + +Where *LEVEL* can be one of: + +never +Approval is never required\. + +any\-change +Requires approval on any IAM or security\-group related change\. + +broadening +\(default\) Requires approval when IAM statements or traffic rules are added\. Removals do not require approval\. + +The setting also be configured in `cdk.json`: + +``` +{ + "app": "...", + "requireApproval": "never" +} +``` + +## Version Reporting + +In order to gain insights in how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported using a resource identified as `AWS::CDK::Metadata` that is added to AWS CloudFormation templates, and can easily be reviewed\. This information may also be used to identify stacks using a package with known serious security or reliability issues and contact their users with important information\. + +The AWS CDK reports the name and version of npm modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. + +The `AWS::CDK::Metadata` resource looks like the following: + +``` +CDKMetadata: + Type: "AWS::CDK::Metadata" + Properties: + Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,lodash=4.17.10" +``` + +## Opting\-out from Version Reporting + +To out\-out, use one of the following methods: ++ Use the cdk command with the the `--no-version-reporting` argument: + + ``` + cdk --no-version-reporting synth + ``` ++ Set `versionReporting` to **false** in `./cdk.json` or `~/cdk.json`: + + ``` + { + "app": "...", + "versionReporting": false + } + ``` + +## Plugins + +The AWS CDK toolkit provides extension points that enable users to augment the features provided by the toolkit\. There is currently only one extension point, allowing users to define custom AWS credential providers, but other extension points may be added in the future as the needs arise\. + +### Loading Plugins + +Plugins can be loaded by providing the Node module name \(or path\) to the AWS CDK toolkit: ++ Using the `--plugin` command line option, which can be specified multiple times: + + ``` + cdk list --plugin=module + cdk deploy --plugin=module_1 --plugin=module_2 + ``` ++ Adding entries to the `~/.cdk.json` or `cdk.json` file: + + ``` + { + // ... + "plugin": [ + "module_1", + "module_2" + ], + // ... + } + ``` + +### Authoring Plugins + +Plugins must be authored in TypeScript or Javascript, and are defined by implementing a Node module that implements the following protocol, and using [PluginHost\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost) methods: + +------ +#### [ TypeScript ] + +``` +import cdk = require('aws-cdk'); + +export = { + version: '1', // Version of the plugin infrastructure (currently always '1') + init(host: cdk.PluginHost): void { + // Your plugin initialization hook. + // Use methods of host to register custom code with the CDK toolkit + } +}; +``` + +------ +#### [ JavaScript ] + +``` +export = { + version: '1', // Version of the plugin infrastructure (currently always '1') + init(host) { + // Your plugin initialization hook. + // Use methods of host to register custom code with the CDK toolkit + } +}; +``` + +------ + +### Credential Provider Plugins + +Custom credential providers are classes implementing the [CredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.CredentialProviderSource) interface, and registered to the toolkit using the [registerCredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost.registerCredentialProviderSource) method\. + +------ +#### [ TypeScript ] + +``` +import cdk = require('aws-cdk'); +import aws = require('aws-sdk'); + +class CustomCredentialProviderSource implements cdk.CredentialProviderSource { + public async isAvailable(): Promise { + // Return false if the plugin could determine it cannot be used (for example, + // if it depends on files that are not present on this host). + return true; + } + + public async canProvideCredentials(accountId: string): Promise { + // Return false if the plugin is unable to provide credentials for the + // requested account (for example if it's not managed by the credentials + // system that this plugin adds support for). + return true; + } + + public async getProvider(accountId: string, mode: cdk.Mode): Promise { + let credentials: aws.Credentials; + // Somehow obtain credentials in credentials, and return those. + return credentials; + } +} + +export = { + version = '1', + init(host: cdk.PluginHost): void { + // Register the credential provider to the PluginHost. + host.registerCredentialProviderSource(new CustomCredentialProviderSource()); + } +}; +``` + +------ +#### [ JavaScript ] + +``` +class CustomCredentialProviderSource { + async isAvailable() { + // Return false if the plugin could determine it cannot be used (for example, + // if it depends on files that are not present on this host). + return true; + } + + async canProvideCredentials(accountId) { + // Return false if the plugin is unable to provide credentials for the + // requested account (for example if it's not managed by the credentials + // system that this plugin adds support for). + return true; + } + + async getProvider(accountId, mode) { + let credentials; + // Somehow obtain credentials in credentials, and return those. + return credentials; + } +} + +export = { + version = '1', + init(host) { + // Register the credential provider to the PluginHost. + host.registerCredentialProviderSource(new CustomCredentialProviderSource()); + } +}; +``` + +------ + +Note that the credentials obtained from the providers for a given account and mode will be cached, and as a consequence it is strongly advised that the credentials objects returned are self\-refreshing, as descibed in the [AWS SDK for Javascript](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html) documentation\. \ No newline at end of file diff --git a/doc_source/cdk_tutorial.md b/doc_source/cdk_tutorial.md new file mode 100644 index 00000000..0ec2eb4f --- /dev/null +++ b/doc_source/cdk_tutorial.md @@ -0,0 +1,440 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# AWS CDK Tutorial + +This topic walks you through creating and deploying an AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. + +## Creating the Project + +Create a directory for your project with an empty Git repository\. + +``` +mkdir hello-cdk +cd hello-cdk +``` + +## Initializing the Project + +Initialize an empty project, where *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), or **typescript** \(TypeScript\)\. + +``` +cdk init --language LANGUAGE +``` + +## Compiling the Project + +Compile your program: + +------ +#### [ C\# ] + +Since configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command: + +``` +cdk +``` + +------ +#### [ JavaScript ] + +Nothing to compile\. + +------ +#### [ TypeScript ] + +``` +npm run build +``` + +------ +#### [ Java ] + +``` +mvn compile +``` + +------ + +## Listing the Stacks in the App + +List the stacks in the app\. + +``` +cdk ls +``` + +The result is just the name of the stack: + +``` +HelloCdkStack +``` + +**Note** +There is a known issue on Windows with the AWS CDK \.NET environment\. Whenever you use a cdk command, it issues a node warning similar to the following: + +``` +(node:27508) UnhandledPromiseRejectionWarning: Unhandled promise rejection +(rejection id: 1): Error: EPIPE: broken pipe, write +(node:27508) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. +In the future, promise rejections that are not handled will terminate the +Node.js process with a non-zero exit code. +``` + +You can safely ignore this warning\. + +## Adding an Amazon S3 Bucket + +What can you do with this app? Nothing\. Since the stack is empty, there's nothing to deploy\. Let's define an Amazon S3 bucket\. + +Install the `@aws-cdk/aws-s3` package: + +------ +#### [ C\# ] + +``` +dotnet add package Amazon.CDK.AWS.S3 +``` + +------ +#### [ JavaScript ] + +``` +npm install @aws-cdk/aws-s3 +``` + +------ +#### [ TypeScript ] + +``` +npm install @aws-cdk/aws-s3 +``` + +------ +#### [ Java ] + +Add the following to `pom.xml`, where *CDK\-VERSION* is the version of the AWS CDK: + +``` + + software.amazon.awscdk + s3 + CDK-VERSION + +``` + +------ + +Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represented by the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.Bucket) class: + +------ +#### [ C\# ] + +Create `MyStack.cs`: + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +namespace HelloCdk +{ + public class MyStack : Stack + { + public MyStack(App parent, string name) : base(parent, name, null) + { + new Bucket(this, "MyFirstBucket", new BucketProps + { + Versioned = true + }); + } + } +} +``` + +------ +#### [ JavaScript ] + +In `index.js`: + +``` +const cdk = require('@aws-cdk/cdk'); +const s3 = require('@aws-cdk/aws-s3'); + +class MyStack extends cdk.Stack { + constructor(parent, id, props) { + super(parent, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} +``` + +------ +#### [ TypeScript ] + +In `lib/hello-cdk-stack.ts`: + +``` +import cdk = require('@aws-cdk/cdk'); +import s3 = require('@aws-cdk/aws-s3'); + +export class HelloCdkStack extends cdk.Stack { + constructor(parent: cdk.App, id: string, props?: cdk.StackProps) { + super(parent, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} +``` + +------ +#### [ Java ] + +In `src/main/java/com/acme/MyStack.java`: + +``` +package com.acme; + +import software.amazon.awscdk.App; +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.services.s3.Bucket; +import software.amazon.awscdk.services.s3.BucketProps; + +public class MyStack extends Stack { + public MyStack(final App parent, final String name) { + this(parent, name, null); + } + + public MyStack(final App parent, final String name, final StackProps props) { + super(parent, name, props); + + new Bucket(this, "MyFirstBucket", BucketProps.builder() + .withVersioned(true) + .build()); + } +} +``` + +------ + +A few things to notice: ++ [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.Bucket) is a construct\. This means it's initialization signature has **parent**, **id**, and **props**\. In this case, the bucket is an immediate child of **MyStack**\. ++ `MyFirstBucket` is the **logical id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. See [Logical IDs](cdk_logical_ids.md) for information on logical IDs\. To specify a physical name for your bucket, set the [bucketName](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketProps.bucketName) property when you define your bucket\. ++ Since the bucket's [versioned](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. + +Compile your program: + +------ +#### [ C\# ] + +Since configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command: + +``` +cdk +``` + +------ +#### [ JavaScript ] + +Nothing to compile\. + +------ +#### [ TypeScript ] + +``` +npm run build +``` + +------ +#### [ Java ] + +``` +mvn compile +``` + +------ + +## Synthesizing an AWS CloudFormation Template + +Synthesize a AWS CloudFormation template for the stack: + +``` +cdk synth HelloCdkStack +``` + +**Note** +Since the AWS CDK app only contains a single stack, you can omit `HelloCdkStack`\. + +This command executes the AWS CDK app and synthesize an AWS CloudFormation template for the **HelloCdkStack** stack\. You should see something similar to the following, where *VERSION* is the version of the AWS CDK\. + +``` +Resources: + MyFirstBucketB8884501: + Type: AWS::S3::Bucket + Properties: + VersioningConfiguration: + Status: Enabled + Metadata: + aws:cdk:path: HelloCdkStack/MyFirstBucket/Resource + CDKMetadata: + Type: AWS::CDK::Metadata + Properties: + Modules: "@aws-cdk/aws-codepipeline-api=VERSION,@aws-cdk/aws-events=VERSION,@aws-c\ + dk/aws-iam=VERSION,@aws-cdk/aws-kms=VERSION,@aws-cdk/aws-s3=VERSION,@aws-c\ + dk/aws-s3-notifications=VERSION,@aws-cdk/cdk=VERSION,@aws-cdk/cx-api=VERSION\ + .0,hello-cdk=0.1.0" +``` + +You can see that the stack contains an **AWS::S3::Bucket** resource with the desired versioning configuration\. + +**Note** +The **AWS::CDK::Metadata** resource was automatically added to your template by the toolkit\. This allows us to learn which libraries were used in your stack\. See [Version Reporting](cdk_tools.md#cdk_version_reporting) for details, including how to [opt out](cdk_tools.md#cdk_version_reporting_opt_out)\. + +## Deploying the Stack + +Deploy the stack: + +``` +cdk deploy +``` + +The deploy command synthesizes an AWS CloudFormation template from the stack and then invokes the AWS CloudFormation create/update API to deploy it into your AWS account\. The command displays information as it progresses\. + +## Modifying the Code + +Configure the bucket to use KMS managed encryption: + +------ +#### [ C\# ] + +Update `MyStack.cs`: + +``` +new Bucket(this, "MyFirstBucket", new BucketProps +{ + Versioned = true, + Encryption = BucketEncryption.KmsManaged +}); +``` + +------ +#### [ JavaScript ] + +Update `index.js`: + +``` +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true, + encryption: s3.BucketEncryption.KmsManaged +}); +``` + +------ +#### [ TypeScript ] + +Update `lib/hello-cdk-stack.ts` + +``` +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true, + encryption: s3.BucketEncryption.KmsManaged +}); +``` + +------ +#### [ Java ] + +Update `src/main/java/com/acme/MyStack.java` + +``` +new Bucket(this, "MyFirstBucket", BucketProps.builder() + .withVersioned(true) + .withEncryption(BucketEncryption.KmsManaged) + .build()); +``` + +------ + +Compile your program: + +------ +#### [ C\# ] + +Since configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command: + +``` +cdk +``` + +------ +#### [ JavaScript ] + +Nothing to compile\. + +------ +#### [ TypeScript ] + +``` +npm run build +``` + +------ +#### [ Java ] + +``` +mvn compile +``` + +------ + +## Preparing for Deployment + +Before you deploy the updated stack, evaluate the difference between the AWS CDK app and the deployed stack: + +``` +cdk diff +``` + +The toolkit queries your AWS account for the current AWS CloudFormation template for the **hello\-cdk** stack, and compares the result with the template synthesized from the app\. The output should look like the following: + +``` +[~] 🛠 Updating MyFirstBucketB8884501 (type: AWS::S3::Bucket) +└─ [+] .BucketEncryption: + └─ New value: {"ServerSideEncryptionConfiguration":[{"ServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms"}}]} +``` + +As you can see, the diff indicates that the `ServerSideEncryptionConfiguration` property of the bucket is now set to enable server\-side encryption\. + +You can also see that the bucket is not going to be replaced but rather updated \(**Updating MyFirstBucketB8884501**\)\. + +Update the stack: + +``` +cdk deploy +``` + +The toolkit updates the bucket configuration to enable server\-side KMS encryption for the bucket: + +``` +⏳ Starting deployment of stack hello-cdk... + [ 0/2 ] UPDATE_IN_PROGRESS [AWS::S3::Bucket ] MyFirstBucketB8884501 + [ 1/2 ] UPDATE_COMPLETE [AWS::S3::Bucket ] MyFirstBucketB8884501 + [ 1/2 ] UPDATE_COMPLETE_CLEANUP_IN_PROGRESS [AWS::CloudFormation::Stack ] hello-cdk + [ 2/2 ] UPDATE_COMPLETE [AWS::CloudFormation::Stack ] hello-cdk +✅ Deployment of stack hello-cdk completed successfully +``` + +## What Next? ++ Learn more about [AWS CDK Concepts](cdk_concepts.md) ++ Check out the [examples directory](https://github.com/awslabs/aws-cdk/tree/master/examples) in your GitHub repository ++ Learn about the rich APIs offered by the [AWS Construct Library](cdk_aws_construct_lib.md) ++ Work directly with CloudFormation using the [AWS AWS CloudFormation Library](cdk_cloudformation.md) ++ Come talk to us on [Gitter](https://gitter.im/awslabs/aws-cdk) \ No newline at end of file diff --git a/doc_source/cdk_writing_constructs.md b/doc_source/cdk_writing_constructs.md new file mode 100644 index 00000000..4d741669 --- /dev/null +++ b/doc_source/cdk_writing_constructs.md @@ -0,0 +1,90 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Writing AWS CDK Constructs + +This topic provides some tips writing idiomatic new constructs for the AWS CDK\. The tips here apply equally to constructs written for inclusion in the AWS Construct Library, purpose\-built constructs to achieve a well\-defined goal, or constructs that serve as building blocks for assembling your cloud applications\. + +## General Design Priciples ++ Favor composition over inheritance; most of the constructs should directly extend the `Construct` class instead of some other construct\. Inheritance should mainly be used to allow polymorphism\. Typically, you'll add a child construct and expose any of its APIs and properties in the parent construct\. ++ Provide defaults for everything that a reasonable guess can be made for; ideally, props should be optional and `new MyAwesomeConstruct(this, "Foo")` should be enough to set up a reasonable variant of the construct\. This does not mean that the user should not have the opportunity to customize\! Rather, it means that the specific parameter should be optional and set to a reasonable value if not supplied\. This may involve creating other resources as part of initializing this construct\. For example, all resources that require a role allow passing in a `Role` object \(specifically, a `RoleRef` object\), but if the user does not supply one an appropriate `Role` object is defined in\-place\. ++ Use contextual defaulting between properties; the value of one property may affect sensible defaults for other properties\. For example: `enableDnsHostnames` and `enableDnsSupport`\. `dnsHostnames` requires `dnsSupport`, only throw an error if the user has explicitly disabled DNS Support, but tried to enable DNS Hostnames\. A user expects things to just work\. ++ Make the user think about intent, not implementation detail; for example, if establishing an association between two resources \(such as a `Topic` and a `Queue`\) requires multiple steps \(in this case, creating a `Subscription` but also setting appropriate IAM permissions\), make both things happen in a single call \(to `subscribeQueue()`\)\. ++ Do not rename concepts or terminology\. For example don't Amazon SQS's `dataKeyReusePeriod` with `keyRotation` because it will be hard for people to diagnose problems\. They won't be able to search for *sqs dataKeyReuse* and find topics on it\. It is permissable to introduce a concept if a counterpart does not exist in AWS CloudFormation, especially if it directly maps onto the mental model that users already have about a service\. ++ Optimize for the common case\. For example, `AutoScalingGroup` accepts a `VPC` and deploys in the private subnet by default because that's the common case, but has an option to `placementOptions` for special cases\. ++ If a class can have multiple modes/behaviors: prefer values over polymorphism\. Try switching behavior on property values first\. Switch to multiple classes with a shared base class/interface only if there value to be had from having multiple classes \(type safety, maybe one mode has different features/required parameters\)\. + +## Implementation Details ++ Every construct consists of an exported class \(`MyConstruct`\) and an exported interface \(`MyConstructProps`\) that defines the parameters for these classes\. The props argument is the 3rd to the construct \(after the mandatory `parent` and `id` arguments\), and the entire parameter should be optional if all of the properties on the props object are optional\. ++ Most of the logic happens in the constructor; the constructor will build up the state of the construct \(what children it has, which ones are always there and which ones are optional, etc\.\)\. ++ Validate as early as possible; throw an `Error` in the constructor if the parameters don't make sense\. Only if you want to validate mutations that can occur after construction time, override the `validate()` method\. The hierarchy of validation: + + Best: Incorrect code won't compile, because of type safety guarantees\. + + Good: Runtime check everything the type checker can't enforce and fail early \(error in the constructor\)\. + + Okay: Synth\-time validate everything that can't be checked at construction time \(error in `validate()`\)\. + + Not great: Fail with an error in AWS CloudFormation \(bad because the AWS CloudFormation deploy operation may take a long while, and the error may take several minutes to surface\)\. + + Very bad: Fail with a timeout during AWS CloudFormation deployment \(it may take up to an hour for resource stabilization to timeout\!\) + + Worst: Don't fail the deployment at all, but fail at runtime\. ++ Avoid unneeded hierarchy in props; try to keep the props interface flat to help discoverability\. ++ Constructs are classes that have a set of invariants they maintain over their lifetime \(such as which members are initialized and relationships between properties as members are mutated\)\. ++ Constructs mostly have write\-only scalar properties that are passed in the constructor, but mutating functions for collections \(for example, there will be `construct.addElement()` or `construct.onEvent()`\) functions, but not `construct.setProperty()`\. It is perfectly fine to deviate from this convention as it makes sense for your own constructs\. ++ Don't expose `Tokens` to your consumers; tokens are an implementation mechanism for one of two purpose: representing AWS CloudFormation intrinsic values, or representing lazily evaluated values\. They can be used for implementation purposes, but use more specific types as part of your public API\. ++ `Tokens` are \(mostly\) only used in the implementation of an AWS Construct Library to pass lazy values to other constructs\. For example, if you have an array that can be mutated during the lifetime of your class, you pass it to an CloudFormation Resource construct like so: `new cdk.Token(() => this.myList)`\. ++ Be aware that you might not be able to usefully inspect all strings\. Any string passed into your construct may contain special markers that represent values that will only be known at deploy time \(for example, the ARN of a resource that will be created during deployment\)\. Those are *stringified Tokens* and they look like `"${TOKEN[Token.123]}"`\. You will not be able to validate those against a regular expression, for example, as their real values are not known yet\. To figure out if your string contains a special marker, use `cdk.unresolved(string)`\. ++ Indicate units of measurement in property names that don't use a strong type\. For example, use **milli**, **sec**, **min**, **hr**, **Bytes**, **KiB**, **MiB**, and **GiB**\. ++ Be sure to define an `IMyResource` interface for your resources which defines the API area that other constructs are going to use\. Typical capabilities on this interface are querying for a resource ARN and adding resource permissions\. ++ Accept objects instead of ARNs or names; when accepting other resources as parameters, declare your property as `resource: IMyResource` instead of `resourceArn: string`\. This makes snapping objects together feel natural to consumers, and allows you to query/modify the incoming resource as well\. The latter is particularly useful if something about IAM permissions need to be set, for example\. ++ Implement `export()` and `import()` functions for your resource; these make it possible to interoperate with resources that are not defined in the same AWS CDK app \(they may be manually created, created using raw AWS CloudFormation, or created in a completely unrelated AWS CDK app\)\. ++ If your construct wraps a single \(or most prominent\) other construct, give it an id of either **"Resource"** or **"Default"**; The main resource that an AWS Construct represents should use the ID **"Resource"**, for higher\-level wrapping resources you will generally use **"Default"** \(resources named **"Default"** will inherit their parent's logical ID, while resources named **"Resource"** will have a distinct logical ID but the human\-readable part of it will not show the **"Resource"** part\)\. + +## Implementation Language + +In order for construct libraries to be reusable across programming languages, they need to be authored in a language that can compile to a jsii assembly\. + +At the moment, the only supported language is TypeScript, so prefer TypeScript unless you are planning to specifically isolate your constructs to a single developer base\. + +## Code Organization + +Your package should look like the following\. + +``` +your-package +├── package.json +├── README.md +├── lib +│   ├── index.ts +│   ├── some-resource.ts +│   └── some-other-resource.ts +└── test +  ├── integ.everything.lit.ts +   ├── test.some-resource.ts +   └── test.some-other-resource.ts +``` ++ Your package is named `@aws-cdk/aws-xxx` if it represents the canonical AWS Construct Library for this service; otherwise we recommend starting with `cdk-`, but you are to choose the name\. ++ Code goes under `lib/`, tests go under `test/`\. ++ Entry point should be `lib/index.ts` and should only contain `export`s for other files\. ++ No need to put every class in a separate file\. Try to think of a reader\-friendly organization of your source files\. ++ If you want to make package\-private utility functions, put them in a file that is not exported from `index.ts` and use that file as normal\. ++ Free\-floating functions \(functions that are not part of a class definition\) cannot be accessed through jsii \(i\.e\., from languages other than TypeScript and JavaScript\)\. Don't use them for public features of your construct library\. ++ Document all public APIs with doc comments \(JSdoc syntax\)\. Document defaults using the **@default** marker in doc comments\. + +## Testing ++ Add unit tests for every construct \(`test.xxx.ts`\), relating the construct's properties to the AWS CloudFormation that gets generated\. Use the `@aws-cdk/assert` library to make it easier to write assertions on the AWS CloudFormation output\. ++ Try to test one concern per unit test\. Even if you could test more than one feature of the construct per test, it's better to write multiple tests, one for each feature\. A test should have one reason to break\. ++ Add integration tests \(`integ.xxx.ts`\) that are AWS CDK apps which exercise the features of the construct, then load your shell with credentials and run npm run integ to exercise them\. You will also have to run this if the AWS CloudFormation output of the construct changes\. ++ If there are packages that you only depend on for testing, add them to `devDependencies` \(instead of regular `dependencies`\)\. You're still not allowed to create dependency cycles this way \(from the root, run scripts/find\-cycles\.sh to figure out if you have created any cycles\)\. ++ Try to make your integ test literate \(`integ.xxx.lit.ts`\) if possible and link to it from the `README`\. + +## README ++ Header should include maturity level\. ++ Header should start at H2, not H1\. ++ Include some example code for the simple use case near the very top\. ++ If there are multiple common use cases, provide an example for each one and describe what happens under the hood at a high level \(e\.g\. which resources are created\)\. ++ Reference docs are not needed\. ++ Use literate \(\.lit\.ts\) integration tests into README file\. + +## Construct IDs + +All children's construct IDs are part of your public contract; those IDs are used to generate AWS CloudFormation logical names for resources\. If they change, AWS CloudFormation will replace the resource\. This technically means that if you change any ID of a child construct you will have to major\-version\-bump your library\. \ No newline at end of file diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md new file mode 100644 index 00000000..5df1a2bb --- /dev/null +++ b/doc_source/doc-history.md @@ -0,0 +1,15 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# Document History for the AWS Cloud Development Kit User Guide + +The following table describes the documentation for this release of the AWS Cloud Development Kit \(AWS CDK\)\. + +See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the AWS CDK releases\. ++ **API version: 0\.21\.0** ++ **Latest documentation update:** December 27, 2018 +| Change | Description | Date | +| --- |--- |--- | \ No newline at end of file diff --git a/doc_source/glossary.md b/doc_source/glossary.md new file mode 100644 index 00000000..c8e126f0 --- /dev/null +++ b/doc_source/glossary.md @@ -0,0 +1,9 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# 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/index.md b/doc_source/index.md new file mode 100644 index 00000000..c0caf118 --- /dev/null +++ b/doc_source/index.md @@ -0,0 +1,38 @@ +# AWS Cloud Development Kit User Guide + +----- +*****Copyright © 2019 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 the AWS Cloud Development Kit?](what-is-CDK.md) ++ [Installing and Configuring the AWS CDK](cdk_install_config.md) ++ [AWS CDK Tutorial](cdk_tutorial.md) ++ [AWS CDK Examples](cdk_examples.md) + + [Creating a Serverless Application Using the AWS CDK](cdk_serverless_example.md) + + [Creating an Amazon ECS Fargate Service Using the AWS CDK](cdk_ecs_example.md) ++ [Command-line Toolkit (cdk)](cdk_tools.md) ++ [AWS CDK Concepts](cdk_concepts.md) + + [Constructs](cdk_constructs.md) + + [Stacks](cdk_stacks.md) + + [Logical IDs](cdk_logical_ids.md) + + [Environments and Authentication](cdk_environments.md) + + [Apps](cdk_apps.md) + + [Passing in External Values to Your AWS CDK App](cdk_passing_in_data.md) + + [Environmental Context](cdk_context.md) + + [Assets](cdk_assets.md) + + [Applets](cdk_applets.md) ++ [AWS Construct Library](cdk_aws_construct_lib.md) ++ [AWS AWS CloudFormation Library](cdk_cloudformation.md) ++ [Writing AWS CDK Constructs](cdk_writing_constructs.md) ++ [Document History for the AWS Cloud Development Kit User Guide](doc-history.md) ++ [AWS Glossary](glossary.md) \ No newline at end of file diff --git a/doc_source/what-is-CDK.md b/doc_source/what-is-CDK.md new file mode 100644 index 00000000..dadde215 --- /dev/null +++ b/doc_source/what-is-CDK.md @@ -0,0 +1,143 @@ +-------- + + This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. + +-------- + +# What Is the AWS Cloud Development Kit? + +Welcome to the AWS Cloud Development Kit \(AWS CDK\) User Guide\. + +The AWS CDK is an infrastructure modeling framework that allows you to define your cloud resources using an imperative programming interface\. *The AWS CDK is currently in developer preview\. We look forward to community feedback and collaboration*\. + +## Why Should you use the AWS CDK? + +Perhaps the best reason is shown graphically\. Here is the TypeScript code in an AWS CDK project to create a Fargate service \(this is the code we use in the [Creating an Amazon ECS Fargate Service Using the AWS CDK](cdk_ecs_example.md)\): + +``` +export class MyEcsConstructStack extends cdk.Stack { + constructor(parent: cdk.App, name: string, props?: cdk.StackProps) { + super(parent, name, props); + + const vpc = new ec2.VpcNetwork(this, 'MyVpc', { + maxAZs: 3 // Default is all AZs in region + }); + + const cluster = new ecs.Cluster(this, 'MyCluster', { + vpc: vpc + }); + + // Create a load-balanced Fargate service and make it public + new ecs.LoadBalancedFargateService(this, 'MyFargateService', { + cluster: cluster, // Required + cpu: '512', // Default is 256 + desiredCount: 6, // Default is 1 + image: ecs.ContainerImage.fromDockerHub('amazon/amazon-ecs-sample'), // Required + memoryMiB: '2048', // Default is 512 + publicLoadBalancer: true // Default is false + }); + } +} +``` + +This produces a AWS CloudFormation template of over 600 lines\. We'll show the first and last 25: + +``` +Resources: + MyVpcF9F0CA6F: + Type: AWS::EC2::VPC + Properties: + CidrBlock: 10.0.0.0/16 + EnableDnsHostnames: true + EnableDnsSupport: true + InstanceTenancy: default + Tags: + - Key: Name + Value: MyEcsConstructStack/MyVpc + Metadata: + aws:cdk:path: MyEcsConstructStack/MyVpc/Resource + MyVpcPublicSubnet1SubnetF6608456: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: 10.0.0.0/19 + VpcId: + Ref: MyVpcF9F0CA6F + AvailabilityZone: us-east-2a + MapPublicIpOnLaunch: true + Tags: + - Key: Name + Value: MyEcsConstructStack/MyVpc/PublicSubnet1 + - Key: aws-cdk:subnet-name +... + Metadata: + aws:cdk:path: MyEcsConstructStack/MyFargateService/LB/PublicListener/ECSGroup/Resource + CDKMetadata: + Type: AWS::CDK::Metadata + Properties: + Modules: "@aws-cdk/assets=0.19.0,@aws-cdk/assets-docker=0.19.0,@aws-cdk/aws-appl\ + icationautoscaling=0.19.0,@aws-cdk/aws-autoscaling=0.19.0,@aws-cdk/aws-\ + autoscaling-common=0.19.0,@aws-cdk/aws-certificatemanager=0.19.0,@aws-c\ + dk/aws-cloudformation=0.19.0,@aws-cdk/aws-cloudwatch=0.19.0,@aws-cdk/aw\ + s-codedeploy-api=0.19.0,@aws-cdk/aws-codepipeline-api=0.19.0,@aws-cdk/a\ + ws-ec2=0.19.0,@aws-cdk/aws-ecr=0.19.0,@aws-cdk/aws-ecs=0.19.0,@aws-cdk/\ + aws-elasticloadbalancingv2=0.19.0,@aws-cdk/aws-events=0.19.0,@aws-cdk/a\ + ws-iam=0.19.0,@aws-cdk/aws-kms=0.19.0,@aws-cdk/aws-lambda=0.19.0,@aws-c\ + dk/aws-logs=0.19.0,@aws-cdk/aws-route53=0.19.0,@aws-cdk/aws-s3=0.19.0,@\ + aws-cdk/aws-s3-notifications=0.19.0,@aws-cdk/aws-sns=0.19.0,@aws-cdk/aw\ + s-sqs=0.19.0,@aws-cdk/cdk=0.19.0,@aws-cdk/cx-api=0.19.0,my_ecs_construc\ + t=0.1.0" +Outputs: + MyFargateServiceLoadBalancerDNS704F6391: + Value: + Fn::GetAtt: + - MyFargateServiceLBDE830E97 + - DNSName + Export: + Name: MyEcsConstructStack:MyFargateServiceLoadBalancerDNS704F6391 +``` + +Which creates the following AWS resources\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/MyEcsConstruct.png) + +## The Developer Experience + +To get started see [Installing and Configuring the AWS CDK](cdk_install_config.md)\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/screencast.gif) + +Developers can use one of the supported programming languages to define reusable cloud components called [Constructs](cdk_constructs.md), which are composed together into [Stacks](cdk_stacks.md) and [Apps](cdk_apps.md)\. + +**Note** +Unless otherwise indicated, the code examples in this guide are in TypeScript\. +To aid you in porting a TypeScript example to a supported programming language, take a look at the example code for your language in the [Reference](https://awslabs.github.io/aws-cdk/reference.html)\. + +The [Command\-line Toolkit \(cdk\)](cdk_tools.md) is a command\-line tool for interacting with CDK apps\. It allows developers to synthesize artifacts such as AWS CloudFormation Templates, deploy stacks to development AWS accounts and diff against a deployed stack to understand the impact of a code change\. + +The [AWS Construct Library](cdk_aws_construct_lib.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to use AWS\. The AWS Construct Library aims to reduce the complexity and glue\-logic required when integrating various AWS services to achieve your goals on AWS\. + +**Note** +There is no charge for using the AWS CDK, however you may incur AWS charges for creating or using AWS [chargeable resources](http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Simple Monthly Calculator](http://calculator.s3.amazonaws.com/index.html) to estimate charges for the use of various AWS resources\. + +## Additional Documentation and Resources + +In addition to this guide, the following are other resources available to AWS CDK users: ++ [CDK Reference](https://awslabs.github.io/aws-cdk/) ++ [AWS Developer blog](https://aws.amazon.com/blogs/developer) ++ [Gitter Channel](https://gitter.im/awslabs/aws-cdk) ++ [Stack Overflow](https://stackoverflow.com/questions/tagged/aws-cdk) ++ [GitHub repository](https://github.com/awslabs/aws-cdk) + + [Examples](https://github.com/awslabs/aws-cdk/tree/master/examples) + + [Documentation source](https://github.com/awslabs/aws-cdk/docs_src) + + [Issues](https://github.com/awslabs/aws-cdk/issues) + + [License](https://github.com/awslabs/aws-cdk/blob/master/LICENSE) ++ [AWS CDK Sample for Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/sample-cdk.html) ++ [AWS CloudFormation Concepts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html) + +## About Amazon Web Services + +Amazon Web Services \(AWS\) is a collection of digital infrastructure services that developers can leverage when developing their applications\. The services include computing, storage, database, and application synchronization \(messaging and queuing\)\. + +AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. + +To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com) and click **Create an AWS Account**\. \ No newline at end of file From 42285b6ca98b69a89bbb1b3ffa499ee6a3a0ecf5 Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Mon, 7 Jan 2019 14:33:40 -0800 Subject: [PATCH 010/655] Removed cdk_ from MD filenames --- doc_source/{cdk_applets.md => applets.md} | 8 ++-- doc_source/{cdk_apps.md => apps.md} | 4 +- doc_source/{cdk_assets.md => assets.md} | 2 +- ..._construct_lib.md => aws_construct_lib.md} | 12 +++--- ...dk_cloudformation.md => cloudformation.md} | 20 +++++----- doc_source/{cdk_concepts.md => concepts.md} | 2 +- .../{cdk_constructs.md => constructs.md} | 12 +++--- doc_source/{cdk_context.md => context.md} | 6 +-- .../{cdk_ecs_example.md => ecs_example.md} | 8 ++-- .../{cdk_environments.md => environments.md} | 6 +-- doc_source/{cdk_examples.md => examples.md} | 6 +-- doc_source/index.md | 40 +++++++++---------- ...dk_install_config.md => install_config.md} | 12 +++--- .../{cdk_logical_ids.md => logical_ids.md} | 4 +- ..._passing_in_data.md => passing_in_data.md} | 22 +++++----- ...rless_example.md => serverless_example.md} | 18 ++++----- doc_source/{cdk_stacks.md => stacks.md} | 4 +- doc_source/{cdk_tools.md => tools.md} | 16 ++++---- doc_source/{cdk_tutorial.md => tutorial.md} | 32 +++++++-------- doc_source/{what-is-CDK.md => what-is.md} | 20 +++++----- ...ng_constructs.md => writing_constructs.md} | 16 ++++---- 21 files changed, 135 insertions(+), 135 deletions(-) rename doc_source/{cdk_applets.md => applets.md} (90%) rename doc_source/{cdk_apps.md => apps.md} (97%) rename doc_source/{cdk_assets.md => assets.md} (95%) rename doc_source/{cdk_aws_construct_lib.md => aws_construct_lib.md} (93%) rename doc_source/{cdk_cloudformation.md => cloudformation.md} (82%) rename doc_source/{cdk_concepts.md => concepts.md} (96%) rename doc_source/{cdk_constructs.md => constructs.md} (94%) rename doc_source/{cdk_context.md => context.md} (96%) rename doc_source/{cdk_ecs_example.md => ecs_example.md} (95%) rename doc_source/{cdk_environments.md => environments.md} (93%) rename doc_source/{cdk_examples.md => examples.md} (52%) rename doc_source/{cdk_install_config.md => install_config.md} (78%) rename doc_source/{cdk_logical_ids.md => logical_ids.md} (98%) rename doc_source/{cdk_passing_in_data.md => passing_in_data.md} (87%) rename doc_source/{cdk_serverless_example.md => serverless_example.md} (92%) rename doc_source/{cdk_stacks.md => stacks.md} (76%) rename doc_source/{cdk_tools.md => tools.md} (95%) rename doc_source/{cdk_tutorial.md => tutorial.md} (88%) rename doc_source/{what-is-CDK.md => what-is.md} (83%) rename doc_source/{cdk_writing_constructs.md => writing_constructs.md} (95%) diff --git a/doc_source/cdk_applets.md b/doc_source/applets.md similarity index 90% rename from doc_source/cdk_applets.md rename to doc_source/applets.md index fdfbdc16..7c28e752 100644 --- a/doc_source/cdk_applets.md +++ b/doc_source/applets.md @@ -4,7 +4,7 @@ -------- -# Applets +# Applets **Note** The AWS CDK only supports applets published as JavaScript modules\. @@ -27,7 +27,7 @@ applets: Every applet will be synthesized to its own stack, named after the key used in the applet definition\. -## Specifying the Applet to Load +## Specifying the Applet to Load An applet `type` specification looks like the following: @@ -43,11 +43,11 @@ applet: MODULE[:CLASS] **CLASS** should reference the name of a class exported by the indicated module\. If the class name is omitted, `Applet` is used as the default class name\. -## Properties +## Properties Pass properties to the applet by specifying them in the `properties` object\. The properties will be passed to the instantiation of the class in the `type` parameter\. -## Running +## Running To run an applet, pass its YAML file directly as the `--app` argument to a `cdk` invocation: diff --git a/doc_source/cdk_apps.md b/doc_source/apps.md similarity index 97% rename from doc_source/cdk_apps.md rename to doc_source/apps.md index ce5976a3..0c8af0b1 100644 --- a/doc_source/cdk_apps.md +++ b/doc_source/apps.md @@ -4,9 +4,9 @@ -------- -# Apps +# Apps -The main artifact of an AWS CDK program is called a *CDK App*\. This is an executable program that can be used to synthesize deployment artifacts that can be deployed by supporting tools like the AWS CDK Toolkit, which are described in [Command\-line Toolkit \(cdk\)](cdk_tools.md)\. +The main artifact of an AWS CDK program is called a *CDK App*\. This is an executable program that can be used to synthesize deployment artifacts that can be deployed by supporting tools like the AWS CDK Toolkit, which are described in [Command\-line Toolkit \(cdk\)](tools.md)\. Tools interact with apps through the program's **argv**/**stdout** interface, which can be easily implemented using the **App** class, as shown in the following example\. diff --git a/doc_source/cdk_assets.md b/doc_source/assets.md similarity index 95% rename from doc_source/cdk_assets.md rename to doc_source/assets.md index 75f7475d..95690526 100644 --- a/doc_source/cdk_assets.md +++ b/doc_source/assets.md @@ -4,7 +4,7 @@ -------- -# Assets +# Assets Assets are local files, directories, or Docker images which can be bundled into CDK constructs and apps\. A common example is a directory which contains the handler code for a Lambda function, but assets can represent any artifact that is needed for the app’s operation\. diff --git a/doc_source/cdk_aws_construct_lib.md b/doc_source/aws_construct_lib.md similarity index 93% rename from doc_source/cdk_aws_construct_lib.md rename to doc_source/aws_construct_lib.md index 1daabbd0..39391c0a 100644 --- a/doc_source/cdk_aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -4,31 +4,31 @@ -------- -# AWS Construct Library +# AWS Construct Library The AWS Construct Library is a set of modules which expose APIs for defining AWS resources in AWS CDK apps\. The AWS Construct Library is organized in modules based on the AWS service to which the resource belongs\. For example, the [@aws\-cdk/aws\-ec2](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#module-@aws-cdk/aws-ec2) module includes the [@aws\-cdk/aws\-ec2\.VpcNetwork](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#@aws-cdk/aws-ec2.VpcNetwork) construct which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your AWS CDK app\. The AWS Construct Library includes many common patterns and capabilities which are designed to allow developers to focus on their application\-specific architectures and reduces the boilerplate and glue logic needed when working with AWS\. -## Least\-Privilege IAM Policies +## Least\-Privilege IAM Policies IAM policies are automatically defined based on intent\. For example, when subscribing an Amazon SNS [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) to a Lambda [Function](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.Function) the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. Furthermore, most AWS Constructs expose `grant*` methods which allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct has a [grantRead\(principal\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.grantRead) method, which accepts an IAM [Principal](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#iprincipal-interface) such as a [User](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#user) or a [Role](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#role) which modifies the policy to allow the principal to read objects from the bucket\. -## Event\-Driven APIs +## Event\-Driven APIs Many AWS constructs include `on*` methods, which can be used to react to events emitted by the construct\. For example, the AWS CodeCommit [Repository](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#Repository) construct has an [onCommit](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#@aws-cdk/aws-codecommit.RepositoryRef.onCommit) method\. AWS Constructs that can be used as targets for various event providers implement interfaces such as [IEventRuleTarget](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html#ieventruletarget-interface) \(for CloudWatch Event Rule target\), [IAlarmAction](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#ialarmaction-interface) \(for AWS CloudWatch Alarm actions\), etc\. For more information see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html) and [@aws\-cdk/aws\-events](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html)\. -## Security Groups +## Security Groups Amazon EC2 network entities such as the [Elastic Load Balancing](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-elasticloadbalancingv2.html) and [Auto Scaling Group](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-autoscaling.html#auto-scaling-group) instances can connect to each other based on definitions of security groups\. The AWS CDK provides APIs for defining security group connections\. For more information, see [Allowing Connections](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#allowing-connections)\. -## Metrics +## Metrics Many AWS resources emit AWS CloudWatch metrics as part of their normal operation\. Metrics can be used to setup an [Alarm](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Alarm) or included in a [Dashboard](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Dashboard)\. @@ -36,6 +36,6 @@ Many AWS resources emit AWS CloudWatch metrics as part of their normal operation For more information see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html)\. -## Imports +## Imports If you need to reference a resource, such as an Amazon S3 bucket or VPC, which is defined outside of your AWS CDK app, you can use the `Xxxx.import(...)` static methods that are available on AWS Constructs\. For example, the [Bucket\.import\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.import) method can be used to obtain a [BucketRef](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef) object, which can be used in most places where a bucket is required\. This patterns allows treating resources defined outside your app as if they were part of your app\. \ No newline at end of file diff --git a/doc_source/cdk_cloudformation.md b/doc_source/cloudformation.md similarity index 82% rename from doc_source/cdk_cloudformation.md rename to doc_source/cloudformation.md index fa22c6b6..8a024062 100644 --- a/doc_source/cdk_cloudformation.md +++ b/doc_source/cloudformation.md @@ -4,16 +4,16 @@ -------- -# AWS AWS CloudFormation Library +# AWS AWS CloudFormation Library -The [AWS Construct Library](cdk_aws_construct_lib.md) includes constructs with APIs for defining AWS infrastructure\. For example, the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct can be used to define Amazon S3 Buckets and the [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) construct can be used to define Amazon SNS Topics\. +The [AWS Construct Library](aws_construct_lib.md) includes constructs with APIs for defining AWS infrastructure\. For example, the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct can be used to define Amazon S3 Buckets and the [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) construct can be used to define Amazon SNS Topics\. Under the hood, these constructs are implemented using AWS CloudFormation resources, which are available in the `CfnXxx` classes in each library\. For example, the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct uses the [@aws\-cdk/aws\-s3\.cloudformation\.BucketResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.cloudformation.BucketResource) resource \(as well as other resources, depending on what bucket APIs are used\)\. **Important** Generally, when building AWS CDK apps, you shouldn't need to interact with AWS CloudFormation directly\. However, there might be advanced use cases and migration scenarios where this might be required\. We are also aware that there might be gaps in capabilities in the AWS Construct Library over time\. -## Resources +## Resources AWS CloudFormation resource classes are automatically generated from the [AWS AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) and available under the `CfnXxx` classes of each AWS library\. Their API matches 1:1 with how you would use these resources in AWS CloudFormation\. @@ -39,7 +39,7 @@ new sqs.Queue(this, 'MyQueue', { }); ``` -## Resource Options +## Resource Options To reference the runtime attributes of AWS CloudFormation resources, use one of the properties available on the resource object\. @@ -60,11 +60,11 @@ new lambda.CfnFunction(this, { The [cdk\.Resource\.ref](@cdk-class-url;#@aws-cdk/cdk.Resource.ref) attribute represents the AWS CloudFormation resource's intrinsic reference \(or *Return Value*\)\. For example, *dlq\.ref* also [refers](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-properties-sqs-queues-ref) to the queue's ARN\. When possible, it is preferrable to use an explicitly named attribute instead of *ref*\. -## Resource Options +## Resource Options The [cdk\.Resource\.options](@cdk-class-url;#@aws-cdk/cdk.Resource.options) object includes AWS CloudFormation options, such as `condition`, `updatePolicy`, `createPolicy` and `metadata`, for a resource\. -## Parameters +## Parameters ``` import sns = require('@aws-cdk/aws-sns'); @@ -74,7 +74,7 @@ const p = new cdk.Parameter(this, 'MyParam', { type: 'String' }); new sns.CfnTopic(this, 'MyTopic', { displayName: p.ref }); ``` -## Outputs +## Outputs ``` import sqs = require('@aws-cdk/aws-sqs'); @@ -87,7 +87,7 @@ const import = out.makeImportValue(); assert(import === { "Fn::ImportValue": out.exportName } ``` -## Conditions +## Conditions ``` import sqs = require('@aws-cdk/aws-sqs'); @@ -100,14 +100,14 @@ const queue = new sqs.CfnQueue(this, 'MyQueue'); queue.options.condition = cond; ``` -## Intrinsic Functions +## Intrinsic Functions ``` import { Fn } from'@aws-cdk/cdk'; Fn.join(",", [...]) ``` -## Pseudo Parameters +## Pseudo Parameters ``` import cdk = require('@aws-cdk/cdk'); diff --git a/doc_source/cdk_concepts.md b/doc_source/concepts.md similarity index 96% rename from doc_source/cdk_concepts.md rename to doc_source/concepts.md index 5df4f8d2..04cd5685 100644 --- a/doc_source/cdk_concepts.md +++ b/doc_source/concepts.md @@ -4,7 +4,7 @@ -------- -# AWS CDK Concepts +# AWS CDK Concepts This topic describes some of the concepts \(the why and how\) behind the AWS CDK\. It also discusses the advantages of a AWS Construct Library over a low\-level CloudFormation Resource\. diff --git a/doc_source/cdk_constructs.md b/doc_source/constructs.md similarity index 94% rename from doc_source/cdk_constructs.md rename to doc_source/constructs.md index 15a3a046..8dc3713c 100644 --- a/doc_source/cdk_constructs.md +++ b/doc_source/constructs.md @@ -4,7 +4,7 @@ -------- -# Constructs +# Constructs Constructs are the building blocks of AWS CDK applications\. Constructs can have child constructs, which in turn can have child constructs, forming a hierarchical tree structure\. @@ -18,7 +18,7 @@ AWS Construct Library These constructs have been handwritten by AWS and come with convenient defaults and additional knowledge about the inner workings of the AWS resources they represent\. In general, you will be able to express your intent without worrying about the details too much, and the correct resources will automatically be defined for you\. AWS Construct Library members are found in the `@aws-cdk/aws-NAMESPACE` packages, where NAMESPACE is the short name for the associated service, such as SQS for the AWS Construct Library for the Amazon SQS service\. See the [Reference](https://awslabs.github.io/aws-cdk/reference.html#reference) section for descriptions of the AWS CDK packages and constructs\. -## Construct Structure +## Construct Structure The construct tree structure is a powerful design pattern for composing high\-level abstractions\. For example, you can define a `StorageLayer` construct that represents your application's storage layer and include all the AWS resources, such as DynamoDB tables and Amazon S3 buckets, needed to implement your storage layer in this construct\. When your higher\-level code uses this construct, it only needs to instantiate the `StorageLayer` construct\. @@ -54,7 +54,7 @@ Gets the child construct with the specified ID\. aws\-cdk\.Construct\.toTreeString\(\) Gets a string representing the construct's tree\. -## Construct Names +## Construct Names Every construct in a CDK app must have a **name** unique among its siblings\. Names are used to track constructs in the construct hierarchy, and to allocate logical IDs so that AWS CloudFormation can keep track of the generated resources\. @@ -79,9 +79,9 @@ new Bucket(this, 'MyBucket', { Avoid specifying physical names\. Instead, let AWS CloudFormation generate names for you\. Use attributes, such as `bucket.bucketName`, to discover the generated names\. -When you synthesize an AWS CDK tree into an AWS CloudFormation template, the AWS CloudFormation logical ID for each resource in the template is allocated according to the path of that resource in the construct tree\. For more information, see [Logical IDs](cdk_logical_ids.md)\. +When you synthesize an AWS CDK tree into an AWS CloudFormation template, the AWS CloudFormation logical ID for each resource in the template is allocated according to the path of that resource in the construct tree\. For more information, see [Logical IDs](logical_ids.md)\. -## Construct Properties +## Construct Properties Customize constructs by passing a property object as the third parameter \(*props*\)\. Every construct has its own set of parameters, defined as an interface\. You can pass a property object to your construct in two ways: @@ -99,6 +99,6 @@ const props: QueueProps = { new Queue(this, 'MyQueue', props); ``` -## Construct Metadata +## Construct Metadata You can attach metadata to a construct using the `aws-cdk.Construct.addMetadata` operation\. Metadata entries automatically include the stack trace from which the metadata entry was added\. Therefore, at any level of a construct you can find the code location, even if metadata was created by a lower\-level library that you don't own\. \ No newline at end of file diff --git a/doc_source/cdk_context.md b/doc_source/context.md similarity index 96% rename from doc_source/cdk_context.md rename to doc_source/context.md index 596597dd..52e9c200 100644 --- a/doc_source/cdk_context.md +++ b/doc_source/context.md @@ -4,7 +4,7 @@ -------- -# Environmental Context +# Environmental Context When you synthesize a stack to create a AWS CloudFormation template, the AWS CDK might need information based on the environment \(account and Region\), such as the availability zones or AMIs available in the Region\. To enable this feature, the AWS CDK Toolkit uses *context providers*, and saves the context information into `cdk.json` the first time you call `cdk synth`\. @@ -30,7 +30,7 @@ const ami: string = new SSMParameterProvider(this, { parameterName: 'my-awesome-parameter' ).parameterValue(); ``` -This is only for reading plain strings, and not recommended for secrets\. For reading secure strings from SSM Parmeter store, see [Getting a Value from an SSM Store Variable](cdk_passing_in_data.md#cdk_passing_ssm_value)\.\. +This is only for reading plain strings, and not recommended for secrets\. For reading secure strings from SSM Parmeter store, see [Getting a Value from an SSM Store Variable](passing_in_data.md#passing_ssm_value)\.\. [HostedZoneProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-route53.html#@aws-cdk/aws-route53.HostedZoneProvider) Use this provider to discover existing hosted zones in your account\. For example, the following code imports an existing hosted zone into your CDK app so you can add records to it: @@ -54,7 +54,7 @@ const provider = new VpcNetworkProvider(this, { const vpc = VpcNetworkRef.import(this, 'VPC', provider.vpcProps); ``` -## Viewing and managing context +## Viewing and managing context Context is used to retrieve information such as the Availability Zones in your account or AMI IDs used to start your instances\. To avoid unexpected changes to your deployments, such as when you add a `Queue` to your application, but a new Amazon Linux AMI was released, thus changing your AutoScalingGroup, the AWS CDK stores the context values in `cdk.json`\. This ensures that the AWS CDK retrieves the same value on the next synthesis\. diff --git a/doc_source/cdk_ecs_example.md b/doc_source/ecs_example.md similarity index 95% rename from doc_source/cdk_ecs_example.md rename to doc_source/ecs_example.md index 92de2d45..801e4f13 100644 --- a/doc_source/cdk_ecs_example.md +++ b/doc_source/ecs_example.md @@ -4,7 +4,7 @@ -------- -# Creating an Amazon ECS Fargate Service Using the AWS CDK +# Creating an Amazon ECS Fargate Service Using the AWS CDK This example walks you through creating a Fargate service running on an ECS cluster fronted by an internet\-facing application load balancer\. @@ -31,7 +31,7 @@ Since Amazon ECS can be used with a number of AWS services, you should understan Previously, you had to create a Lambda function to have this functionality\. + Asset support, so that you can deploy source from your machine to Amazon ECS in one step Previously, to use application source you had to perform a number of manual steps, such as upload to Amazon ECR and create a Docker image\. -## Creating the Directory and Initializing the AWS CDK +## Creating the Directory and Initializing the AWS CDK Let's start with creating a new directory to hold our AWS CDK code and create a new app in that directory\. @@ -58,7 +58,7 @@ Resources: Modules: @aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_ecs_construct=0.1.0 ``` -## Add the Amazon EC2 and Amazon ECS Packages +## Add the Amazon EC2 and Amazon ECS Packages Install support for Amazon EC2 and Amazon ECS\. @@ -66,7 +66,7 @@ Install support for Amazon EC2 and Amazon ECS\. npm install @aws-cdk/aws-ec2 @aws-cdk/aws-ecs ``` -## Create a Fargate Service +## Create a Fargate Service There are two different ways of running your container tasks with Amazon ECS\. + Using the `Fargate` launch type, where Amazon ECS manages the physical machines that your containers are running on for you\. diff --git a/doc_source/cdk_environments.md b/doc_source/environments.md similarity index 93% rename from doc_source/cdk_environments.md rename to doc_source/environments.md index 18b5a9b8..7d1c4e20 100644 --- a/doc_source/cdk_environments.md +++ b/doc_source/environments.md @@ -4,9 +4,9 @@ -------- -# Environments and Authentication +# Environments and Authentication -The AWS CDK refers to the combination of an account ID and a Region as an *environment*\. The simplest environment is the one you get by default, which is the one you get when you have set up your credentials and a default Region as described in [Configuring the AWS CDK Toolkit](cdk_install_config.md#cdk_credentials)\. +The AWS CDK refers to the combination of an account ID and a Region as an *environment*\. The simplest environment is the one you get by default, which is the one you get when you have set up your credentials and a default Region as described in [Configuring the AWS CDK Toolkit](install_config.md#credentials)\. When you create a [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) instance, you can supply the target deployment environment for the stack using the `env` property, as shown in the following example, where REGION is the Region in which you want to create the stack and ACCOUNT is your account ID\. @@ -20,7 +20,7 @@ For each of the two arguments, **region** and **account**, the AWS CDK uses the + If these are not defined, it will determine them as follows: + **account**: use account from default SDK credentials\. Environment variables are tried first \(`AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`\), followed by credentials in *$HOME/\.aws/credentials* on Linux or MacOS or *%USERPROFILE%\\\\\.aws\\\\credentials* on Windows\. + **region**: use the default region configured in *$HOME/\.aws/config* on Linux or MacOS or *%USERPROFILE%\\\\\.aws\\\\config* on Windows\. - + You can set these defaults manually, but we recommend you use `aws configure`, as described in [Installing and Configuring the AWS CDK](cdk_install_config.md) + + You can set these defaults manually, but we recommend you use `aws configure`, as described in [Installing and Configuring the AWS CDK](install_config.md) We recommend that you use the default environment for development stacks, and explicitly specify accounts and Regions for production stacks\. diff --git a/doc_source/cdk_examples.md b/doc_source/examples.md similarity index 52% rename from doc_source/cdk_examples.md rename to doc_source/examples.md index d0d03aa7..e5612175 100644 --- a/doc_source/cdk_examples.md +++ b/doc_source/examples.md @@ -4,8 +4,8 @@ -------- -# AWS CDK Examples +# AWS CDK Examples This topic contains examples to help you get started using some of the advanced constructs offered by the AWS CDK\. -+ [Creating a Serverless Application Using the AWS CDK](cdk_serverless_example.md) Creates a serverless application to dispense widgets\. -+ [Creating an Amazon ECS Fargate Service Using the AWS CDK](cdk_ecs_example.md) Creates an Amazon ECS Fargate service\. \ No newline at end of file ++ [Creating a Serverless Application Using the AWS CDK](serverless_example.md) Creates a serverless application to dispense widgets\. ++ [Creating an Amazon ECS Fargate Service Using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service\. \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index c0caf118..70353b76 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -14,25 +14,25 @@ Amazon's trademarks and trade dress may not be used in ----- ## Contents -+ [What Is the AWS Cloud Development Kit?](what-is-CDK.md) -+ [Installing and Configuring the AWS CDK](cdk_install_config.md) -+ [AWS CDK Tutorial](cdk_tutorial.md) -+ [AWS CDK Examples](cdk_examples.md) - + [Creating a Serverless Application Using the AWS CDK](cdk_serverless_example.md) - + [Creating an Amazon ECS Fargate Service Using the AWS CDK](cdk_ecs_example.md) -+ [Command-line Toolkit (cdk)](cdk_tools.md) -+ [AWS CDK Concepts](cdk_concepts.md) - + [Constructs](cdk_constructs.md) - + [Stacks](cdk_stacks.md) - + [Logical IDs](cdk_logical_ids.md) - + [Environments and Authentication](cdk_environments.md) - + [Apps](cdk_apps.md) - + [Passing in External Values to Your AWS CDK App](cdk_passing_in_data.md) - + [Environmental Context](cdk_context.md) - + [Assets](cdk_assets.md) - + [Applets](cdk_applets.md) -+ [AWS Construct Library](cdk_aws_construct_lib.md) -+ [AWS AWS CloudFormation Library](cdk_cloudformation.md) -+ [Writing AWS CDK Constructs](cdk_writing_constructs.md) ++ [What Is the AWS Cloud Development Kit?](what-is.md) ++ [Installing and Configuring the AWS CDK](install_config.md) ++ [AWS CDK Tutorial](tutorial.md) ++ [AWS CDK Examples](examples.md) + + [Creating a Serverless Application Using the AWS CDK](serverless_example.md) + + [Creating an Amazon ECS Fargate Service Using the AWS CDK](ecs_example.md) ++ [Command-line Toolkit (cdk)](tools.md) ++ [AWS CDK Concepts](concepts.md) + + [Constructs](constructs.md) + + [Stacks](stacks.md) + + [Logical IDs](logical_ids.md) + + [Environments and Authentication](environments.md) + + [Apps](apps.md) + + [Passing in External Values to Your AWS CDK App](passing_in_data.md) + + [Environmental Context](context.md) + + [Assets](assets.md) + + [Applets](applets.md) ++ [AWS Construct Library](aws_construct_lib.md) ++ [AWS AWS CloudFormation Library](cloudformation.md) ++ [Writing AWS CDK Constructs](writing_constructs.md) + [Document History for the AWS Cloud Development Kit User Guide](doc-history.md) + [AWS Glossary](glossary.md) \ No newline at end of file diff --git a/doc_source/cdk_install_config.md b/doc_source/install_config.md similarity index 78% rename from doc_source/cdk_install_config.md rename to doc_source/install_config.md index 43187b69..b823b29f 100644 --- a/doc_source/cdk_install_config.md +++ b/doc_source/install_config.md @@ -4,19 +4,19 @@ -------- -# Installing and Configuring the AWS CDK +# Installing and Configuring the AWS CDK This topic describes how to install and configure the AWS CDK\. -## Prerequisites +## Prerequisites You must install [Node\.js \(>= 8\.11\.x\)](https://nodejs.org/en/download) to use the command\-line toolkit and language bindings\. If you use Java, you must set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine to build an AWS CDK app in Java\. -Specify your credentials and region with the [AWS CLI](https://aws.amazon.com/cli)\. You must specify both your credentials and a region to use the toolkit\. See [Configuring the AWS CDK Toolkit](#cdk_credentials) for information on using the AWS CLI to specify your credentials\. +Specify your credentials and region with the [AWS CLI](https://aws.amazon.com/cli)\. You must specify both your credentials and a region to use the toolkit\. See [Configuring the AWS CDK Toolkit](#credentials) for information on using the AWS CLI to specify your credentials\. -## Installing the AWS CDK +## Installing the AWS CDK Install the AWS CDK using the following command: @@ -30,7 +30,7 @@ Run the following command to see the currently installed version of the AWS CDK: cdk --version ``` -## Configuring the AWS CDK Toolkit +## Configuring the AWS CDK Toolkit Use the AWS CDK toolkit to view the contents of an app\. @@ -45,4 +45,4 @@ See [Environment Variables](https://docs.aws.amazon.com/cli/latest/userguide/cli **Note** The China regions \(cn\-north\-1 and cn\-northwest\-1\) do not support version reporting\. -See [Version Reporting](cdk_tools.md#cdk_version_reporting) for details, including how to [opt\-out](cdk_tools.md#cdk_version_reporting_opt_out)\. \ No newline at end of file +See [Version Reporting](tools.md#version_reporting) for details, including how to [opt\-out](tools.md#version_reporting_opt_out)\. \ No newline at end of file diff --git a/doc_source/cdk_logical_ids.md b/doc_source/logical_ids.md similarity index 98% rename from doc_source/cdk_logical_ids.md rename to doc_source/logical_ids.md index 60ef3b15..2724d958 100644 --- a/doc_source/cdk_logical_ids.md +++ b/doc_source/logical_ids.md @@ -4,7 +4,7 @@ -------- -# Logical IDs +# Logical IDs When you synthesize a stack into an AWS CloudFormation template, the AWS CDK assigns a [ logical ID](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html), which must be unique within the template, to each resource in the stack\. @@ -37,7 +37,7 @@ The AWS CDK applies some heuristics to improve the human\-friendliness of the pr + If two subsequent names in the path are the same, only one is retained\. + If the prefix exceeds 240 characters, it is trimmed to 240 characters\. This ensures that the total length of the logical ID does not exceed the 255 character AWS CloudFormation limit for logical IDs\. -## Renaming Logical IDs +## Renaming Logical IDs The `aws-cdk.Stack.renameLogical` method can be used to explicitly assign logical IDs to certain resources\. diff --git a/doc_source/cdk_passing_in_data.md b/doc_source/passing_in_data.md similarity index 87% rename from doc_source/cdk_passing_in_data.md rename to doc_source/passing_in_data.md index a018d449..523a8c5d 100644 --- a/doc_source/cdk_passing_in_data.md +++ b/doc_source/passing_in_data.md @@ -4,7 +4,7 @@ -------- -# Passing in External Values to Your AWS CDK App +# Passing in External Values to Your AWS CDK App There may be cases where you want to parameterize one or more of your stack resources\. Therefore, you want to be able to pass values into your app from outside your app\. Currently, you can get values into your app from outside your app through any of the following\. + Using a context variable @@ -17,7 +17,7 @@ There may be cases where you want to parameterize one or more of your stack reso Each of these techniques is described in the following sections\. -## Getting a Value from a Context Variable +## Getting a Value from a Context Variable You can specify a context variable either as part of a AWS CDK Toolkit command, or in a **context** section of `cdk.json`\. @@ -43,7 +43,7 @@ To get the value of a context variable in your app, use code like the following, const bucket_name string = this.getContext("bucket_name"); ``` -## Getting a Value from an Environment Variable +## Getting a Value from an Environment Variable To get the value of an environment variable, use code like the following, which gets the value of the environment variable `MYBUCKET`\. @@ -51,13 +51,13 @@ To get the value of an environment variable, use code like the following, which const bucket_name = process.env.MYBUCKET; ``` -## Getting a Value from an SSM Store Variable +## Getting a Value from an SSM Store Variable -There are three ways to get the value of an SSM parameter store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It is not possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from SecretsManager \(see [Getting a Value from AWS Secrets Manager](#cdk_passing_secrets_manager)\)\. +There are three ways to get the value of an SSM parameter store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It is not possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from SecretsManager \(see [Getting a Value from AWS Secrets Manager](#passing_secrets_manager)\)\. The first two are not recommended for values that are supposed to be secrets, such as passwords\. -To retrieve the latest value once \(as a context value, see [Environmental Context](cdk_context.md)\), and keep on using the same value until the context value manually refreshed, use a [SSMParameterProvider](@cdk-class-url;#@aws-cdk/cdk.SSMParameterProvider): +To retrieve the latest value once \(as a context value, see [Environmental Context](context.md)\), and keep on using the same value until the context value manually refreshed, use a [SSMParameterProvider](@cdk-class-url;#@aws-cdk/cdk.SSMParameterProvider): ``` import cdk = require('@amp;aws-cdk/cdk'); @@ -91,7 +91,7 @@ const secureString = new ssm.ParameterStoreSecureString(this, 'MySecretParameter const myvalue = secureString.value; ``` -## Getting a Value from AWS Secrets Manager +## Getting a Value from AWS Secrets Manager To use values from AWS Secrets Manager in your CDK app, create an instance of [SecretsManager](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-secretsmanager.html/_aws-cdk_aws-secretsmanager.html#aws-cdk-aws-secretsmanager)\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. @@ -114,7 +114,7 @@ const password = loginSecret.jsonFieldValue('password'); const fullValue = loginSecret.value; ``` -## Passing in a Value From Another Stack +## Passing in a Value From Another Stack You can pass a value from one stack to another stack in the same app by using the `export` method in one stack and the `import` method in the other stack\. @@ -176,13 +176,13 @@ new MyCdkStack(app, "MyCdkStack", { app.run(); ``` -## Using an AWS CloudFormation Parameter +## Using an AWS CloudFormation Parameter See [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for information about using the optional *Parameters* section to customize your AWS CloudFormation templates\. -You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [AWS CDK Concepts](cdk_concepts.md)\. +You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [AWS CDK Concepts](concepts.md)\. -## Using an Existing AWS CloudFormation Template +## Using an Existing AWS CloudFormation Template The AWS CDK provides a mechanism that you can use to incorporate resources from an existing AWS CloudFormation template into your AWS CDK app\. For example, suppose you have a template, `my-template.json`, with the following resource, where **S3Bucket** is the logical ID of the bucket in your template: diff --git a/doc_source/cdk_serverless_example.md b/doc_source/serverless_example.md similarity index 92% rename from doc_source/cdk_serverless_example.md rename to doc_source/serverless_example.md index 83f7649c..cd1ee778 100644 --- a/doc_source/cdk_serverless_example.md +++ b/doc_source/serverless_example.md @@ -4,14 +4,14 @@ -------- -# Creating a Serverless Application Using the AWS CDK +# Creating a Serverless Application Using the AWS CDK This example walks you through creating the resources for a simple widget dispensing service\. It includes: + An AWS Lambda function + An API Gateway API to call our Lambda function + An Amazon S3 bucket that contains our Lambda function code -## Overview +## Overview This example contains the following steps\. @@ -30,7 +30,7 @@ This example contains the following steps\. + get an widget by name with: GET /\{name\} + delete an widget by name with: DELETE /\{name\} -## Create an AWS CDK App +## Create an AWS CDK App Create the TypeScript app **MyWidgetService** in in the current folder\. @@ -59,7 +59,7 @@ Resources: Modules: "@aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_widget_service=0.1.0" ``` -## Create a Lambda Function to List all Widgets +## Create a Lambda Function to List all Widgets The next step is to create a Lambda function to list all of the widgets in our Amazon S3 bucket\. @@ -119,7 +119,7 @@ npm run build cdk synth ``` -## Creating a Widget Service +## Creating a Widget Service Add the API Gateway, Lambda, and Amazon S3 packages to our app\. @@ -178,7 +178,7 @@ npm run build cdk synth ``` -## Add the Service to the App +## Add the Service to the App To add the service to our app, we need to first modify `my_widget_service-stack.ts`\. Add the following line of code after the existing **import** statement\. @@ -199,9 +199,9 @@ npm run build cdk synth ``` -## Deploy and Test the App +## Deploy and Test the App -Before you can deploy your first AWS CDK app, you must bootstrap your deployment, which creates some AWS infracture that the AWS CDK needs\. See the **bootstrap** section of [Command\-line Toolkit \(cdk\)](cdk_tools.md) for details \(you'll get a warning and nothing changes if you have already bootstrapped an AWS CDK app\)\. +Before you can deploy your first AWS CDK app, you must bootstrap your deployment, which creates some AWS infracture that the AWS CDK needs\. See the **bootstrap** section of [Command\-line Toolkit \(cdk\)](tools.md) for details \(you'll get a warning and nothing changes if you have already bootstrapped an AWS CDK app\)\. ``` cdk bootstrap @@ -237,7 +237,7 @@ Since we haven't stored any widgets yet, the output should be similar to the fol { "widgets": [] } ``` -## Add the Individual Widget Functions +## Add the Individual Widget Functions The next step is to create Lambda functions to create, show, and delete individual widgets\. Replace the existing `exports.main` function in `widgets.js` with the following code\. diff --git a/doc_source/cdk_stacks.md b/doc_source/stacks.md similarity index 76% rename from doc_source/cdk_stacks.md rename to doc_source/stacks.md index 58eb33d9..e8de6bbe 100644 --- a/doc_source/cdk_stacks.md +++ b/doc_source/stacks.md @@ -4,9 +4,9 @@ -------- -# Stacks +# Stacks -A [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) is an AWS CDK construct that can be deployed into an AWS environment\. The combination of region and account becomes the stack's *environment*, as described in [Environments and Authentication](cdk_environments.md)\. Most production apps consist of multiple stacks of resources that are deployed as a single transaction using a resource provisioning service like AWS CloudFormation\. Any resources added directly or indirectly as children of a stack are included in the stack's template as it is synthesized by your AWS CDK program\. +A [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) is an AWS CDK construct that can be deployed into an AWS environment\. The combination of region and account becomes the stack's *environment*, as described in [Environments and Authentication](environments.md)\. Most production apps consist of multiple stacks of resources that are deployed as a single transaction using a resource provisioning service like AWS CloudFormation\. Any resources added directly or indirectly as children of a stack are included in the stack's template as it is synthesized by your AWS CDK program\. Define an application stack by extending the [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) class, as shown in the following example\. diff --git a/doc_source/cdk_tools.md b/doc_source/tools.md similarity index 95% rename from doc_source/cdk_tools.md rename to doc_source/tools.md index db07d2b9..e96f7c93 100644 --- a/doc_source/cdk_tools.md +++ b/doc_source/tools.md @@ -4,7 +4,7 @@ -------- -# Command\-line Toolkit \(cdk\) +# Command\-line Toolkit \(cdk\) cdk \(the AWS CDK Toolkit\) is the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you have written and compiled, interrogates the application model you have defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. @@ -84,7 +84,7 @@ If your app has a single stack, there is no need to specify the stack name\. If one of `cdk.json` or `~/.cdk.json` exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. -## Security\-related changes +## Security\-related changes In order to protect you against unintended changes that affect your security posture, the CDK toolkit will prompt you to approve security\-related changes before deploying them\. @@ -114,7 +114,7 @@ The setting also be configured in `cdk.json`: } ``` -## Version Reporting +## Version Reporting In order to gain insights in how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported using a resource identified as `AWS::CDK::Metadata` that is added to AWS CloudFormation templates, and can easily be reviewed\. This information may also be used to identify stacks using a package with known serious security or reliability issues and contact their users with important information\. @@ -129,7 +129,7 @@ CDKMetadata: Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,lodash=4.17.10" ``` -## Opting\-out from Version Reporting +## Opting\-out from Version Reporting To out\-out, use one of the following methods: + Use the cdk command with the the `--no-version-reporting` argument: @@ -146,11 +146,11 @@ To out\-out, use one of the following methods: } ``` -## Plugins +## Plugins The AWS CDK toolkit provides extension points that enable users to augment the features provided by the toolkit\. There is currently only one extension point, allowing users to define custom AWS credential providers, but other extension points may be added in the future as the needs arise\. -### Loading Plugins +### Loading Plugins Plugins can be loaded by providing the Node module name \(or path\) to the AWS CDK toolkit: + Using the `--plugin` command line option, which can be specified multiple times: @@ -172,7 +172,7 @@ Plugins can be loaded by providing the Node module name \(or path\) to the AWS C } ``` -### Authoring Plugins +### Authoring Plugins Plugins must be authored in TypeScript or Javascript, and are defined by implementing a Node module that implements the following protocol, and using [PluginHost\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost) methods: @@ -206,7 +206,7 @@ export = { ------ -### Credential Provider Plugins +### Credential Provider Plugins Custom credential providers are classes implementing the [CredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.CredentialProviderSource) interface, and registered to the toolkit using the [registerCredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost.registerCredentialProviderSource) method\. diff --git a/doc_source/cdk_tutorial.md b/doc_source/tutorial.md similarity index 88% rename from doc_source/cdk_tutorial.md rename to doc_source/tutorial.md index 0ec2eb4f..0e3a3479 100644 --- a/doc_source/cdk_tutorial.md +++ b/doc_source/tutorial.md @@ -4,11 +4,11 @@ -------- -# AWS CDK Tutorial +# AWS CDK Tutorial This topic walks you through creating and deploying an AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. -## Creating the Project +## Creating the Project Create a directory for your project with an empty Git repository\. @@ -17,7 +17,7 @@ mkdir hello-cdk cd hello-cdk ``` -## Initializing the Project +## Initializing the Project Initialize an empty project, where *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), or **typescript** \(TypeScript\)\. @@ -25,7 +25,7 @@ Initialize an empty project, where *LANGUAGE* is one of the supported programmin cdk init --language LANGUAGE ``` -## Compiling the Project +## Compiling the Project Compile your program: @@ -59,7 +59,7 @@ mvn compile ------ -## Listing the Stacks in the App +## Listing the Stacks in the App List the stacks in the app\. @@ -86,7 +86,7 @@ Node.js process with a non-zero exit code. You can safely ignore this warning\. -## Adding an Amazon S3 Bucket +## Adding an Amazon S3 Bucket What can you do with this app? Nothing\. Since the stack is empty, there's nothing to deploy\. Let's define an Amazon S3 bucket\. @@ -227,7 +227,7 @@ public class MyStack extends Stack { A few things to notice: + [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.Bucket) is a construct\. This means it's initialization signature has **parent**, **id**, and **props**\. In this case, the bucket is an immediate child of **MyStack**\. -+ `MyFirstBucket` is the **logical id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. See [Logical IDs](cdk_logical_ids.md) for information on logical IDs\. To specify a physical name for your bucket, set the [bucketName](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketProps.bucketName) property when you define your bucket\. ++ `MyFirstBucket` is the **logical id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. See [Logical IDs](logical_ids.md) for information on logical IDs\. To specify a physical name for your bucket, set the [bucketName](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketProps.bucketName) property when you define your bucket\. + Since the bucket's [versioned](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. Compile your program: @@ -262,7 +262,7 @@ mvn compile ------ -## Synthesizing an AWS CloudFormation Template +## Synthesizing an AWS CloudFormation Template Synthesize a AWS CloudFormation template for the stack: @@ -296,9 +296,9 @@ Resources: You can see that the stack contains an **AWS::S3::Bucket** resource with the desired versioning configuration\. **Note** -The **AWS::CDK::Metadata** resource was automatically added to your template by the toolkit\. This allows us to learn which libraries were used in your stack\. See [Version Reporting](cdk_tools.md#cdk_version_reporting) for details, including how to [opt out](cdk_tools.md#cdk_version_reporting_opt_out)\. +The **AWS::CDK::Metadata** resource was automatically added to your template by the toolkit\. This allows us to learn which libraries were used in your stack\. See [Version Reporting](tools.md#version_reporting) for details, including how to [opt out](tools.md#version_reporting_opt_out)\. -## Deploying the Stack +## Deploying the Stack Deploy the stack: @@ -308,7 +308,7 @@ cdk deploy The deploy command synthesizes an AWS CloudFormation template from the stack and then invokes the AWS CloudFormation create/update API to deploy it into your AWS account\. The command displays information as it progresses\. -## Modifying the Code +## Modifying the Code Configure the bucket to use KMS managed encryption: @@ -395,7 +395,7 @@ mvn compile ------ -## Preparing for Deployment +## Preparing for Deployment Before you deploy the updated stack, evaluate the difference between the AWS CDK app and the deployed stack: @@ -432,9 +432,9 @@ The toolkit updates the bucket configuration to enable server\-side KMS encrypti ✅ Deployment of stack hello-cdk completed successfully ``` -## What Next? -+ Learn more about [AWS CDK Concepts](cdk_concepts.md) +## What Next? ++ Learn more about [AWS CDK Concepts](concepts.md) + Check out the [examples directory](https://github.com/awslabs/aws-cdk/tree/master/examples) in your GitHub repository -+ Learn about the rich APIs offered by the [AWS Construct Library](cdk_aws_construct_lib.md) -+ Work directly with CloudFormation using the [AWS AWS CloudFormation Library](cdk_cloudformation.md) ++ Learn about the rich APIs offered by the [AWS Construct Library](aws_construct_lib.md) ++ Work directly with CloudFormation using the [AWS AWS CloudFormation Library](cloudformation.md) + Come talk to us on [Gitter](https://gitter.im/awslabs/aws-cdk) \ No newline at end of file diff --git a/doc_source/what-is-CDK.md b/doc_source/what-is.md similarity index 83% rename from doc_source/what-is-CDK.md rename to doc_source/what-is.md index dadde215..517f808d 100644 --- a/doc_source/what-is-CDK.md +++ b/doc_source/what-is.md @@ -4,15 +4,15 @@ -------- -# What Is the AWS Cloud Development Kit? +# What Is the AWS Cloud Development Kit? -Welcome to the AWS Cloud Development Kit \(AWS CDK\) User Guide\. +Welcome to the AWS Cloud Development Kit \(AWS CDK\) User's Guide\. The AWS CDK is an infrastructure modeling framework that allows you to define your cloud resources using an imperative programming interface\. *The AWS CDK is currently in developer preview\. We look forward to community feedback and collaboration*\. ## Why Should you use the AWS CDK? -Perhaps the best reason is shown graphically\. Here is the TypeScript code in an AWS CDK project to create a Fargate service \(this is the code we use in the [Creating an Amazon ECS Fargate Service Using the AWS CDK](cdk_ecs_example.md)\): +Perhaps the best reason is shown graphically\. Here is the TypeScript code in an AWS CDK project to create a Fargate service \(this is the code we use in the [Creating an Amazon ECS Fargate Service Using the AWS CDK](ecs_example.md)\): ``` export class MyEcsConstructStack extends cdk.Stack { @@ -100,26 +100,26 @@ Which creates the following AWS resources\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/MyEcsConstruct.png) -## The Developer Experience +## The Developer Experience -To get started see [Installing and Configuring the AWS CDK](cdk_install_config.md)\. +To get started see [Installing and Configuring the AWS CDK](install_config.md)\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/screencast.gif) -Developers can use one of the supported programming languages to define reusable cloud components called [Constructs](cdk_constructs.md), which are composed together into [Stacks](cdk_stacks.md) and [Apps](cdk_apps.md)\. +Developers can use one of the supported programming languages to define reusable cloud components called [Constructs](constructs.md), which are composed together into [Stacks](stacks.md) and [Apps](apps.md)\. **Note** Unless otherwise indicated, the code examples in this guide are in TypeScript\. To aid you in porting a TypeScript example to a supported programming language, take a look at the example code for your language in the [Reference](https://awslabs.github.io/aws-cdk/reference.html)\. -The [Command\-line Toolkit \(cdk\)](cdk_tools.md) is a command\-line tool for interacting with CDK apps\. It allows developers to synthesize artifacts such as AWS CloudFormation Templates, deploy stacks to development AWS accounts and diff against a deployed stack to understand the impact of a code change\. +The [Command\-line Toolkit \(cdk\)](tools.md) is a command\-line tool for interacting with CDK apps\. It allows developers to synthesize artifacts such as AWS CloudFormation Templates, deploy stacks to development AWS accounts and diff against a deployed stack to understand the impact of a code change\. -The [AWS Construct Library](cdk_aws_construct_lib.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to use AWS\. The AWS Construct Library aims to reduce the complexity and glue\-logic required when integrating various AWS services to achieve your goals on AWS\. +The [AWS Construct Library](aws_construct_lib.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to use AWS\. The AWS Construct Library aims to reduce the complexity and glue\-logic required when integrating various AWS services to achieve your goals on AWS\. **Note** There is no charge for using the AWS CDK, however you may incur AWS charges for creating or using AWS [chargeable resources](http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Simple Monthly Calculator](http://calculator.s3.amazonaws.com/index.html) to estimate charges for the use of various AWS resources\. -## Additional Documentation and Resources +## Additional Documentation and Resources In addition to this guide, the following are other resources available to AWS CDK users: + [CDK Reference](https://awslabs.github.io/aws-cdk/) @@ -134,7 +134,7 @@ In addition to this guide, the following are other resources available to AWS CD + [AWS CDK Sample for Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/sample-cdk.html) + [AWS CloudFormation Concepts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html) -## About Amazon Web Services +## About Amazon Web Services Amazon Web Services \(AWS\) is a collection of digital infrastructure services that developers can leverage when developing their applications\. The services include computing, storage, database, and application synchronization \(messaging and queuing\)\. diff --git a/doc_source/cdk_writing_constructs.md b/doc_source/writing_constructs.md similarity index 95% rename from doc_source/cdk_writing_constructs.md rename to doc_source/writing_constructs.md index 4d741669..db60adc5 100644 --- a/doc_source/cdk_writing_constructs.md +++ b/doc_source/writing_constructs.md @@ -4,11 +4,11 @@ -------- -# Writing AWS CDK Constructs +# Writing AWS CDK Constructs This topic provides some tips writing idiomatic new constructs for the AWS CDK\. The tips here apply equally to constructs written for inclusion in the AWS Construct Library, purpose\-built constructs to achieve a well\-defined goal, or constructs that serve as building blocks for assembling your cloud applications\. -## General Design Priciples +## General Design Priciples + Favor composition over inheritance; most of the constructs should directly extend the `Construct` class instead of some other construct\. Inheritance should mainly be used to allow polymorphism\. Typically, you'll add a child construct and expose any of its APIs and properties in the parent construct\. + Provide defaults for everything that a reasonable guess can be made for; ideally, props should be optional and `new MyAwesomeConstruct(this, "Foo")` should be enough to set up a reasonable variant of the construct\. This does not mean that the user should not have the opportunity to customize\! Rather, it means that the specific parameter should be optional and set to a reasonable value if not supplied\. This may involve creating other resources as part of initializing this construct\. For example, all resources that require a role allow passing in a `Role` object \(specifically, a `RoleRef` object\), but if the user does not supply one an appropriate `Role` object is defined in\-place\. + Use contextual defaulting between properties; the value of one property may affect sensible defaults for other properties\. For example: `enableDnsHostnames` and `enableDnsSupport`\. `dnsHostnames` requires `dnsSupport`, only throw an error if the user has explicitly disabled DNS Support, but tried to enable DNS Hostnames\. A user expects things to just work\. @@ -17,7 +17,7 @@ This topic provides some tips writing idiomatic new constructs for the AWS CDK\. + Optimize for the common case\. For example, `AutoScalingGroup` accepts a `VPC` and deploys in the private subnet by default because that's the common case, but has an option to `placementOptions` for special cases\. + If a class can have multiple modes/behaviors: prefer values over polymorphism\. Try switching behavior on property values first\. Switch to multiple classes with a shared base class/interface only if there value to be had from having multiple classes \(type safety, maybe one mode has different features/required parameters\)\. -## Implementation Details +## Implementation Details + Every construct consists of an exported class \(`MyConstruct`\) and an exported interface \(`MyConstructProps`\) that defines the parameters for these classes\. The props argument is the 3rd to the construct \(after the mandatory `parent` and `id` arguments\), and the entire parameter should be optional if all of the properties on the props object are optional\. + Most of the logic happens in the constructor; the constructor will build up the state of the construct \(what children it has, which ones are always there and which ones are optional, etc\.\)\. + Validate as early as possible; throw an `Error` in the constructor if the parameters don't make sense\. Only if you want to validate mutations that can occur after construction time, override the `validate()` method\. The hierarchy of validation: @@ -39,13 +39,13 @@ This topic provides some tips writing idiomatic new constructs for the AWS CDK\. + Implement `export()` and `import()` functions for your resource; these make it possible to interoperate with resources that are not defined in the same AWS CDK app \(they may be manually created, created using raw AWS CloudFormation, or created in a completely unrelated AWS CDK app\)\. + If your construct wraps a single \(or most prominent\) other construct, give it an id of either **"Resource"** or **"Default"**; The main resource that an AWS Construct represents should use the ID **"Resource"**, for higher\-level wrapping resources you will generally use **"Default"** \(resources named **"Default"** will inherit their parent's logical ID, while resources named **"Resource"** will have a distinct logical ID but the human\-readable part of it will not show the **"Resource"** part\)\. -## Implementation Language +## Implementation Language In order for construct libraries to be reusable across programming languages, they need to be authored in a language that can compile to a jsii assembly\. At the moment, the only supported language is TypeScript, so prefer TypeScript unless you are planning to specifically isolate your constructs to a single developer base\. -## Code Organization +## Code Organization Your package should look like the following\. @@ -70,14 +70,14 @@ your-package + Free\-floating functions \(functions that are not part of a class definition\) cannot be accessed through jsii \(i\.e\., from languages other than TypeScript and JavaScript\)\. Don't use them for public features of your construct library\. + Document all public APIs with doc comments \(JSdoc syntax\)\. Document defaults using the **@default** marker in doc comments\. -## Testing +## Testing + Add unit tests for every construct \(`test.xxx.ts`\), relating the construct's properties to the AWS CloudFormation that gets generated\. Use the `@aws-cdk/assert` library to make it easier to write assertions on the AWS CloudFormation output\. + Try to test one concern per unit test\. Even if you could test more than one feature of the construct per test, it's better to write multiple tests, one for each feature\. A test should have one reason to break\. + Add integration tests \(`integ.xxx.ts`\) that are AWS CDK apps which exercise the features of the construct, then load your shell with credentials and run npm run integ to exercise them\. You will also have to run this if the AWS CloudFormation output of the construct changes\. + If there are packages that you only depend on for testing, add them to `devDependencies` \(instead of regular `dependencies`\)\. You're still not allowed to create dependency cycles this way \(from the root, run scripts/find\-cycles\.sh to figure out if you have created any cycles\)\. + Try to make your integ test literate \(`integ.xxx.lit.ts`\) if possible and link to it from the `README`\. -## README +## README + Header should include maturity level\. + Header should start at H2, not H1\. + Include some example code for the simple use case near the very top\. @@ -85,6 +85,6 @@ your-package + Reference docs are not needed\. + Use literate \(\.lit\.ts\) integration tests into README file\. -## Construct IDs +## Construct IDs All children's construct IDs are part of your public contract; those IDs are used to generate AWS CloudFormation logical names for resources\. If they change, AWS CloudFormation will replace the resource\. This technically means that if you change any ID of a child construct you will have to major\-version\-bump your library\. \ No newline at end of file From 6978dcbdcacdf398fec1adb5796f51fee55ed615 Mon Sep 17 00:00:00 2001 From: Doug Date: Wed, 9 Jan 2019 05:37:29 -0800 Subject: [PATCH 011/655] Update README.md Added link to AWS docs. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75d04678..563defe1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ ## AWS Cdk User Guide -User guide for the AWS Cloud Development Kit (CDK). +The markdown (MD) source for the [AWS Cloud Development Kit (CDK) User Guide](https://docs.aws.amazon.com/CDK/latest/userguide). ## License Summary From 8605883942f56c98a6c6b6c1ec04300bd9b1d4b7 Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Wed, 6 Mar 2019 12:22:27 -0800 Subject: [PATCH 012/655] Updated user guide with latest build --- doc_source/advanced_tutorials.md | 11 + doc_source/applets.md | 64 --- doc_source/apps.md | 66 --- doc_source/apps_and_stacks.md | 91 ++++ doc_source/assets.md | 6 +- doc_source/aws_construct_lib.md | 38 +- doc_source/cfn_layer.md | 218 +++++++++ doc_source/cloudformation.md | 80 +-- doc_source/concepts.md | 10 +- doc_source/constructs.md | 149 ++++-- doc_source/context.md | 104 ---- doc_source/core_concepts.md | 11 + doc_source/doc-history.md | 8 +- doc_source/ecs_example.md | 123 ----- doc_source/ecs_tutorial.md | 132 +++++ doc_source/environments.md | 28 -- doc_source/environments_and_context.md | 137 ++++++ doc_source/examples.md | 11 - doc_source/get_cfn_param.md | 11 + doc_source/get_context_var.md | 31 ++ doc_source/get_env_var.md | 13 + doc_source/get_ssm_value.md | 43 ++ doc_source/glossary.md | 9 - doc_source/hello_world_tutorial.md | 455 ++++++++++++++++++ doc_source/how_to_get_ext_values.md | 9 + doc_source/how_to_set_cw_alarm.md | 41 ++ doc_source/how_tos.md | 9 + doc_source/index.md | 48 +- doc_source/install_config.md | 135 +++++- doc_source/logical_ids.md | 48 +- doc_source/passing_in_data.md | 215 --------- doc_source/passing_secrets_manager.md | 28 ++ doc_source/passing_stack_value.md | 67 +++ ...less_example.md => serverless_tutorial.md} | 142 +++--- doc_source/stack_how_to.md | 76 +++ doc_source/stacks.md | 38 -- doc_source/tools.md | 130 ++--- doc_source/tutorial.md | 440 ----------------- doc_source/use_cfn_template.md | 37 ++ doc_source/what-is.md | 96 ++-- doc_source/writing_constructs.md | 122 +++-- 41 files changed, 1996 insertions(+), 1534 deletions(-) create mode 100644 doc_source/advanced_tutorials.md delete mode 100644 doc_source/applets.md delete mode 100644 doc_source/apps.md create mode 100644 doc_source/apps_and_stacks.md create mode 100644 doc_source/cfn_layer.md delete mode 100644 doc_source/context.md create mode 100644 doc_source/core_concepts.md delete mode 100644 doc_source/ecs_example.md create mode 100644 doc_source/ecs_tutorial.md delete mode 100644 doc_source/environments.md create mode 100644 doc_source/environments_and_context.md delete mode 100644 doc_source/examples.md create mode 100644 doc_source/get_cfn_param.md create mode 100644 doc_source/get_context_var.md create mode 100644 doc_source/get_env_var.md create mode 100644 doc_source/get_ssm_value.md delete mode 100644 doc_source/glossary.md create mode 100644 doc_source/hello_world_tutorial.md create mode 100644 doc_source/how_to_get_ext_values.md create mode 100644 doc_source/how_to_set_cw_alarm.md create mode 100644 doc_source/how_tos.md delete mode 100644 doc_source/passing_in_data.md create mode 100644 doc_source/passing_secrets_manager.md create mode 100644 doc_source/passing_stack_value.md rename doc_source/{serverless_example.md => serverless_tutorial.md} (56%) create mode 100644 doc_source/stack_how_to.md delete mode 100644 doc_source/stacks.md delete mode 100644 doc_source/tutorial.md create mode 100644 doc_source/use_cfn_template.md diff --git a/doc_source/advanced_tutorials.md b/doc_source/advanced_tutorials.md new file mode 100644 index 00000000..37a49ebd --- /dev/null +++ b/doc_source/advanced_tutorials.md @@ -0,0 +1,11 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Advanced Tutorials + +This topic contains the following tutorials: ++ [Creating a Serverless Application Using the AWS CDK](serverless_tutorial.md)Creates a serverless application using Lambda, API Gateway, and Amazon S3\. ++ [Creating an AWS Fargate Service Using the AWS CDK](ecs_tutorial.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. \ No newline at end of file diff --git a/doc_source/applets.md b/doc_source/applets.md deleted file mode 100644 index 7c28e752..00000000 --- a/doc_source/applets.md +++ /dev/null @@ -1,64 +0,0 @@ --------- - - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. - --------- - -# Applets - -**Note** -The AWS CDK only supports applets published as JavaScript modules\. - -Applets are YAML files that directly instantiate constructs, without writing any code\. The structure of an applet file looks like the following: - -``` -applets: - Applet1: - type: MODULE[:CLASS] - properties: - property1: value1 - property2: value2 - ... - Applet2: - type: MODULE[:CLASS] - properties: - ... -``` - -Every applet will be synthesized to its own stack, named after the key used in the applet definition\. - -## Specifying the Applet to Load - -An applet `type` specification looks like the following: - -``` -applet: MODULE[:CLASS] -``` - -**MODULE** can be used to indicate: -+ A local file, such as `./my-module` \(expects `my-module.js` in the same directory\)\. -+ A local module such as `my-dependency` \(expects an NPM package at `node_modules/my-dependency`\)\. -+ A global module, such as `@aws-cdk/aws-s3` \(expects the package to have been globally installed using NPM\)\. -+ An NPM package, such as `npm://some-package@1.2.3` \(the version specifier may be omitted to refer to the latest version of the package\)\. - -**CLASS** should reference the name of a class exported by the indicated module\. If the class name is omitted, `Applet` is used as the default class name\. - -## Properties - -Pass properties to the applet by specifying them in the `properties` object\. The properties will be passed to the instantiation of the class in the `type` parameter\. - -## Running - -To run an applet, pass its YAML file directly as the `--app` argument to a `cdk` invocation: - -``` -cdk --app ./my-applet.yaml deploy -``` - -To avoid needing to specify `--app` for every invocation, make a `cdk.json` file and add in the application in the config as usual: - -``` -{ - "app": "./my-applet.yaml" -} -``` \ No newline at end of file diff --git a/doc_source/apps.md b/doc_source/apps.md deleted file mode 100644 index 0c8af0b1..00000000 --- a/doc_source/apps.md +++ /dev/null @@ -1,66 +0,0 @@ --------- - - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. - --------- - -# Apps - -The main artifact of an AWS CDK program is called a *CDK App*\. This is an executable program that can be used to synthesize deployment artifacts that can be deployed by supporting tools like the AWS CDK Toolkit, which are described in [Command\-line Toolkit \(cdk\)](tools.md)\. - -Tools interact with apps through the program's **argv**/**stdout** interface, which can be easily implemented using the **App** class, as shown in the following example\. - -``` -import { App } from '@aws-cdk/cdk' - -const app = new App(); // input: ARGV - -// - -app.run(); -``` - -An [App](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app) is a collection of [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) objects, as shown in the following example\. - -``` -import { App } from '@aws-cdk/cdk' -import { MyStack } from './my-stack' - -const app = new App(); - -const dev = new MyStack(app, { name: 'Dev', region: 'us-west-2', dev: true }) -const preProd = new MyStack(app, { name: 'PreProd', region: 'us-west-2', preProd: true }) -const prod = [ - new MyStack(app, { name: 'NAEast', region: 'us-east-1' }), - new MyStack(app, { name: 'NAWest', region: 'us-west-2' }), - new MyStack(app, { name: 'EU', region: 'eu-west-1', encryptedStorage: true }) -] - -new DeploymentPipeline(app, { - region: 'us-east-1', - strategy: DeploymentStrategy.Waved, - preProdStages: [ preProd ], - prodStages: prod -}); - -app.run(); -``` - -Use the cdk list command to list the stacks in this executable, as shown in the following example\. - -``` -[ - { name: "Dev", region: "us-west-2" } - { name: "PreProd", region: "us-west-2" }, - { name: "NAEast", region: "us-east-1" }, - { name: "NAWest", region: "us-west-2" }, - { name: "EU", region: "eu-west-1" }, - { name: "DeploymentPipeline", region: 'us-east-1' } -] -``` - -Use the cdk deploy command to deploy an individual stack: - -``` -cdk deploy Dev -``` \ No newline at end of file diff --git a/doc_source/apps_and_stacks.md b/doc_source/apps_and_stacks.md new file mode 100644 index 00000000..843d6bd5 --- /dev/null +++ b/doc_source/apps_and_stacks.md @@ -0,0 +1,91 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Apps and Stacks + +The main artifact of a CDK program known as a *CDK app*\. This is an executable program that you can use to synthesize deployment artifacts that supporting tools, such as the CDK Toolkit, can deploy, as described in [AWS CDK Command Line Toolkit \(cdk\)](tools.md)\. + +Stacks are CDK constructs that you can deploy into an AWS environment\. The combination of AWS Region and account becomes the stack's *environment*, as described in [Environments and Authentication](environments_and_context.md#environments)\. Most production apps consist of multiple stacks of resources that are deployed as a single transaction using a resource provisioning service such as AWS CloudFormation\. Any resources added directly or indirectly as children of a stack are included in the stack's template when it is synthesized by your CDK program\. + +## Apps + +An [app](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app) is a collection of [stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) objects, as shown in the following example\. + +``` +import { App } from '@aws-cdk/cdk' +import { MyStack } from './my-stack' + +const app = new App(); + +const dev = new MyStack(app, { name: 'Dev', region: 'us-west-2', dev: true }) +const preProd = new MyStack(app, { name: 'PreProd', region: 'us-west-2', preProd: true }) +const prod = [ + new MyStack(app, { name: 'NAEast', region: 'us-east-1' }), + new MyStack(app, { name: 'NAWest', region: 'us-west-2' }), + new MyStack(app, { name: 'EU', region: 'eu-west-1', encryptedStorage: true }) +] + +new DeploymentPipeline(app, { + region: 'us-east-1', + strategy: DeploymentStrategy.Waved, + preProdStages: [ preProd ], + prodStages: prod +}); + +app.run(); +``` + +Use the cdk list command to list the stacks in this executable, as shown in the following example\. + +``` +[ + { name: "Dev", region: "us-west-2" } + { name: "PreProd", region: "us-west-2" }, + { name: "NAEast", region: "us-east-1" }, + { name: "NAWest", region: "us-west-2" }, + { name: "EU", region: "eu-west-1" }, + { name: "DeploymentPipeline", region: 'us-east-1' } +] +``` + +Use the cdk deploy command to deploy an individual stack\. + +``` +cdk deploy Dev +``` + +## Stacks + +Define an application stack by extending the [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) class, as shown in the following example\. + +``` +import { Stack, StackProps } from '@aws-cdk/cdk' + +interface MyStackProps extends StackProps { + encryptedStorage: boolean; +} + +class MyStack extends Stack { + constructor(scope: Construct, id: string, props?: MyStackProps) { + super(scope, id, props); + + new MyStorageLayer(this, 'Storage', { encryptedStorage: props.encryptedStorage }); + new MyControlPlane(this, 'CPlane'); + new MyDataPlane(this, 'DPlane'); + } +} +``` + +And then, add instances of this class to your app\. + +``` +const app = new App(); + +new MyStack(app, 'NorthAmerica', { env: { region: 'us-east-1' } }); +new MyStack(app, 'Europe', { env: { region: 'us-west-2' } }); +``` + +See [Stack How\-Tos](stack_how_to.md) for additional information about using stacks\. \ No newline at end of file diff --git a/doc_source/assets.md b/doc_source/assets.md index 95690526..dcb53e83 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -1,11 +1,11 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- # Assets -Assets are local files, directories, or Docker images which can be bundled into CDK constructs and apps\. A common example is a directory which contains the handler code for a Lambda function, but assets can represent any artifact that is needed for the app’s operation\. +Assets are local files, directories, or Docker images that can be bundled into CDK constructs and apps\. A common example is a directory that contains the handler code for an AWS Lambda function, however, assets can represent any artifact that the app needs to operate\. -When deploying an AWS CDK app that includes constructs with assets, the toolkit first prepares and publishes them to Amazon S3 or Amazon ECR, and only then deploy the stacks\. The locations of the published assets are passed in as AWS CloudFormation parameters to the relevant stacks\. \ No newline at end of file +When deploying a CDK app that includes constructs with assets, the CDK Toolkit first prepares and publishes them to Amazon Simple Storage Service \(Amazon S3\) or Amazon Elastic Container Registry \(Amazon ECR\), and only then deploys the stacks\. The locations of the published assets are passed in as AWS CloudFormation parameters to the relevant stacks\. \ No newline at end of file diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md index 39391c0a..ce6a2198 100644 --- a/doc_source/aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -1,41 +1,43 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- # AWS Construct Library -The AWS Construct Library is a set of modules which expose APIs for defining AWS resources in AWS CDK apps\. The AWS Construct Library is organized in modules based on the AWS service to which the resource belongs\. For example, the [@aws\-cdk/aws\-ec2](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#module-@aws-cdk/aws-ec2) module includes the [@aws\-cdk/aws\-ec2\.VpcNetwork](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#@aws-cdk/aws-ec2.VpcNetwork) construct which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your AWS CDK app\. +The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, the [@aws\-cdk/aws\-ec2](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#module-@aws-cdk/aws-ec2) module includes the [@aws\-cdk/aws\-ec2\.VpcNetwork](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#@aws-cdk/aws-ec2.VpcNetwork) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your CDK app\. -The AWS Construct Library includes many common patterns and capabilities which are designed to allow developers to focus on their application\-specific architectures and reduces the boilerplate and glue logic needed when working with AWS\. +The AWS Construct Library modules are described in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. -## Least\-Privilege IAM Policies +The AWS Construct Library includes many common patterns and capabilities that are designed to enable developers to focus on their application\-specific architectures and reduce the boilerplate and glue logic needed when working with AWS services\. -IAM policies are automatically defined based on intent\. For example, when subscribing an Amazon SNS [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) to a Lambda [Function](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.Function) the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. +## Grants -Furthermore, most AWS Constructs expose `grant*` methods which allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct has a [grantRead\(principal\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.grantRead) method, which accepts an IAM [Principal](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#iprincipal-interface) such as a [User](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#user) or a [Role](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#role) which modifies the policy to allow the principal to read objects from the bucket\. +AWS Identity and Access Management \(IAM\) policies are automatically defined based on intent\. For example, when subscribing an Amazon Simple Notification Service \(Amazon SNS\) [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) to an AWS Lambda [Function](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.Function), the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. -## Event\-Driven APIs - -Many AWS constructs include `on*` methods, which can be used to react to events emitted by the construct\. For example, the AWS CodeCommit [Repository](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#Repository) construct has an [onCommit](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#@aws-cdk/aws-codecommit.RepositoryRef.onCommit) method\. AWS Constructs that can be used as targets for various event providers implement interfaces such as [IEventRuleTarget](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html#ieventruletarget-interface) \(for CloudWatch Event Rule target\), [IAlarmAction](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#ialarmaction-interface) \(for AWS CloudWatch Alarm actions\), etc\. - -For more information see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html) and [@aws\-cdk/aws\-events](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html)\. +Also, most AWS constructs expose `grant*` methods that allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct has a [grantRead\(principal\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.grantRead) method\. This method accepts an IAM [Principal](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#iprincipal-interface) such as a [User](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#user) or a [Role](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#role), which modifies the policy to allow the principal to read objects from the bucket\. ## Security Groups -Amazon EC2 network entities such as the [Elastic Load Balancing](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-elasticloadbalancingv2.html) and [Auto Scaling Group](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-autoscaling.html#auto-scaling-group) instances can connect to each other based on definitions of security groups\. +Amazon Elastic Compute Cloud \(Amazon EC2\) network entities, such as the [Elastic Load Balancing](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-elasticloadbalancingv2.html) and [Auto Scaling Group](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-autoscaling.html#auto-scaling-group) instances, can connect to each other based on definitions of security groups\. -The AWS CDK provides APIs for defining security group connections\. For more information, see [Allowing Connections](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#allowing-connections)\. +The CDK provides APIs for defining security group connections\. For more information, see [Allowing Connections](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#allowing-connections)\. ## Metrics -Many AWS resources emit AWS CloudWatch metrics as part of their normal operation\. Metrics can be used to setup an [Alarm](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Alarm) or included in a [Dashboard](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Dashboard)\. +Many AWS resources emit [Amazon CloudWatch metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html) as part of their normal operation\. Metrics can be used to set up an [Alarm](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Alarm) or can be included in a [Dashboard](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Dashboard)\. + +You can obtain [Metric](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Metric) objects for AWS constructs by using `metricXxx()` methods\. For example, the [metricDuration\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.FunctionRef.metricDuration) method reports the execution time of an AWS Lambda function\. -[Metric](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Metric) objects for AWS Constructs can be obtained using `metricXxx()` methods\. For example, the [metricDuration\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.FunctionRef.metricDuration) method reports the execution time of an AWS Lambda function\. +For more information, see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html)\. -For more information see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html)\. +## Exports and Imports + +If you need to reference a resource, such as an Amazon S3 bucket or VPC, that's defined outside of your CDK app, you can use the `Xxxx.import(...)` static methods that are available on AWS constructs\. For example, you can use the [Bucket\.import\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.import) method to obtain a [BucketRef](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef) object, which can be used in most places where a bucket is required\. This pattern enables treating resources defined outside of your app as if they are part of your app\. + +## Event\-Driven APIs -## Imports +Many AWS constructs include `on*` methods, which can be used to react to events emitted by the construct\. For example, the CodeCommit [Repository](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#Repository) construct has an [onCommit](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#@aws-cdk/aws-codecommit.RepositoryRef.onCommit) method\. You can use AWS constructs as targets for various event provider interfaces, such as [IEventRuleTarget](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html#ieventruletarget-interface) \(for the CloudWatch event rule target\), [IAlarmAction](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#ialarmaction-interface) \(for Amazon CloudWatch alarm actions\), and so on\. -If you need to reference a resource, such as an Amazon S3 bucket or VPC, which is defined outside of your AWS CDK app, you can use the `Xxxx.import(...)` static methods that are available on AWS Constructs\. For example, the [Bucket\.import\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.import) method can be used to obtain a [BucketRef](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef) object, which can be used in most places where a bucket is required\. This patterns allows treating resources defined outside your app as if they were part of your app\. \ No newline at end of file +For more information, see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html) and [@aws\-cdk/aws\-events](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html)\. \ No newline at end of file diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md new file mode 100644 index 00000000..4691ca43 --- /dev/null +++ b/doc_source/cfn_layer.md @@ -0,0 +1,218 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Accessing the AWS CloudFormation Layer + +This topic describes how to modify the underlying AWS CloudFormation resources in the AWS Construct Library\. We also call this technique an "escape hatch" because it allows users to "escape" from the abstraction boundary defined by the AWS construct, and patch the underlying resources\. + +**Important** +We don't recommend this method because it breaks the abstraction layer and might produce unexpected results\. +If you modify an AWS construct in this way, we can't ensure that your code will be compatible with subsequent releases\. + +AWS constructs, such as [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic), encapsulate one or more AWS CloudFormation resources behind their APIs\. These resources are also represented as `CfnXxx` constructs in each library\. For example, the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct encapsulates the [@aws\-cdk/aws\-s3\.cloudformation\.BucketResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.cloudformation.BucketResource)\. When a stack that includes an AWS construct is synthesized, the AWS CloudFormation definitions of the underlying resources are included in the resulting template\. + +Eventually, we expect the APIs provided by AWS constructs to support all of the services and capabilities offered by AWS\. But we're aware that the library still has many gaps, both at the service level \(some services don't have any constructs yet\) and at the resource level \(an AWS construct exists, but some features are missing\)\. + +**Note** +If you encounter a missing capability in the AWS Construct Library, whether it's an entire library, a specific resource, or a feature, create an [issue](https://github.com/awslabs/aws-cdk/issues/new) on GitHub and let us know\. + +This section describes the following use cases: ++ How to access the low\-level AWS CloudFormation resources encapsulated by an AWS construct ++ How to specify resource options, such as metadata, and dependencies on resources ++ How to add overrides to AWS CloudFormation resources and property definitions ++ How to directly define low\-level AWS CloudFormation resources without an AWS construct + +You can also find more information about how to work directly with the AWS CloudFormation layer in [AWS Construct Library](aws_construct_lib.md)\. + +## Accessing Low\-Level Resources + +Use [construct\.findChild\(\)](@cdk-class-url;#@aws-cdk/cdk.Construct.findChild) to access any child of a construct by its construct ID\. By convention, the main resource of any AWS construct is named **Resource**\. + +The following example shows how to access the underlying Amazon Simple Storage Service \(Amazon S3\) bucket resource, given a [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct\. + +``` +// Create an AWS bucket construct +const bucket = new s3.Bucket(this, 'MyBucket'); + +// The main construct is named "Resource" and +// its type is s3.CfnBucket; const +const bucketResource = bucket.node.findChild('Resource') as s3.CfnBucket; +``` + +The `bucketResource` represents the low\-level AWS CloudFormation resource of type [@aws\-cdk/aws\-s3\.cloudformation\.BucketResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.cloudformation.BucketResource) that's encapsulated by the bucket\. + +If the child can't be located, [construct\.findChildren\(id\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/cdk.Construct.findChild) fails\. This means that if the underlying AWS Construct Library changes the IDs or structure for some reason, synthesis fails\. + +You can also use[construct\.children](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/cdk.Construct.children) for more advanced queries\. For example, you can look for a child that has a certain AWS CloudFormation resource type\. + +``` +const bucketResource = + bucket.children.find(c => (c as cdk.Resource).resourceType === 'AWS::S3::Bucket') + as s3.CfnBucket; +``` + +Once you have a AWS CloudFormation resource, you are interacting with AWS CloudFormation resource classes, which extend [cdk\.Resource](@cdk-class-url;#@aws-cdk/cdk.Resource)\. + +## Resource Options + +Set resource options using [cdk\.Resource](@cdk-class-url;#@aws-cdk/cdk.Resource) properties such as *Metadata* and *DependsOn*\. + +For example, the following code: + +``` +const bucketResource = bucket.node.findChild('Resource') as s3.CfnBucket; + +bucketResource.options.metadata = { MetadataKey: 'MetadataValue' }; +bucketResource.options.updatePolicy = { + autoScalingRollingUpdate: { + pauseTime: '390' + } +}; + +bucketResource.addDependency(otherBucket.node.findChild('Resource') as cdk.Resource); +``` + +Synthesizes into the following template\. + +``` +{ + "Type": "AWS::S3::Bucket", + "DependsOn": [ "Other34654A52" ], + "UpdatePolicy": { + "AutoScalingRollingUpdate": { + "PauseTime": "390" + } + }, + "Metadata": { + "MetadataKey": "MetadataValue" + } +} +``` + +## Overriding Resource Properties + +Each low\-level resource in the CDK has a strongly typed property named `propertyOverrides`\. It enables users to apply overrides that adhere to the AWS CloudFormation schema of the resource, and use code completion and type checking\. + +Use this mechanism when a certain feature is available at the AWS CloudFormation layer but isn't exposed by the AWS construct\. + +The following example sets a bucket's analytics configuration\. + +``` +bucketResource.propertyOverrides.analyticsConfigurations = [ + { + id: 'config1', + storageClassAnalysis: { + dataExport: { + outputSchemaVersion: '1', + destination: { + format: 'html', + bucketArn: otherBucket.bucketArn // use tokens freely + } + } + } + } +]; +``` + +## Raw Overrides + +If the strongly typed overrides aren't sufficient or, for example, if the schema defined in AWS CloudFormation is not up to date, use the [cdk\.Resource\.addOverride\(path, value\)](@cdk-class-url;#@aws-cdk/cdk.Resource.addOverride) method to define an override that is applied to the resource definition during synthesis\. This is shown in the following example\. + +``` +// Define an override at the resource definition root, you can even modify the "Type" +// of the resource if needed. +bucketResource.addOverride('Type', 'AWS::S3::SpecialBucket'); + +// fine an override for a property (both are equivalent operations): +bucketResource.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); +bucketResource.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); + +// se dot-notation to define overrides in complex structures which will be merged +// with the values set by the higher-level construct +bucketResource.addPropertyOverride('LoggingConfiguration.DestinationBucketName', otherBucket.bucketName); + +// It's also possible to assign a null value +bucketResource.addPropertyOverride('Foo.Bar', null); +``` + +This synthesizes to the following\. + +``` +{ + "Type": "AWS::S3::SpecialBucket", + "Properties": { + "Foo": { + "Bar": null + }, + "VersioningConfiguration": { + "Status": "NewStatus" + }, + "LoggingConfiguration": { + "DestinationBucketName": { + "Ref": "Other34654A52" + } + } + } +} +``` + +Use `undefined`, [cdk\.Resource\.addDeletionOverride](@cdk-class-url;#@aws-cdk/cdk.Resource.addDeletionOverride), or [cdk\.Resource\.addPropertyDeletionOverride](@cdk-class-url;#@aws-cdk/cdk.Resource.addPropertyDeletionOverride) to delete values\. + +``` +const bucket = new s3.Bucket(this, 'MyBucket', { + versioned: true, + encryption: s3.BucketEncryption.KmsManaged +}); + +const bucketResource = bucket.node.findChild('Resource') as s3.CfnBucket; +bucketResource.addPropertyOverride('BucketEncryption.ServerSideEncryptionConfiguration.0.EncryptEverythingAndAlways', true); +bucketResource.addPropertyDeletionOverride('BucketEncryption.ServerSideEncryptionConfiguration.0.ServerSideEncryptionByDefault'); +``` + +This synthesizes to the following\. + +``` +{ + "MyBucketF68F3FF0": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketEncryption": { + "ServerSideEncryptionConfiguration": [ + { + "EncryptEverythingAndAlways": true + } + ] + }, + "VersioningConfiguration": { + "Status": "Enabled" + } + } + } +} +``` + +## Directly Defining AWS CloudFormation Resources + +You can also explicitly define AWS CloudFormation resources in your stack\. To do this, instantiate one of the `CfnXxx` constructs of the dedicated library\. + +``` +new s3.CfnBucket(this, 'MyBucket', { + analyticsConfigurations: [ + // ... + ] +}); +``` + +In the rare case where you want to define a resource that doesn't have a corresponding `CfnXxx` class \(such as a new resource that wasn't published yet in the AWS CloudFormation resource specification\), you can instantiate the [cdk\.Resource](@cdk-class-url;#@aws-cdk/cdk.Resource)\. + +``` +new cdk.Resource(this, 'MyBucket', { + type: 'AWS::S3::Bucket', + properties: { + AnalyticsConfiguration: [ /* ... */ ] // note the PascalCase here + } +}); +``` \ No newline at end of file diff --git a/doc_source/cloudformation.md b/doc_source/cloudformation.md index 8a024062..a34ed002 100644 --- a/doc_source/cloudformation.md +++ b/doc_source/cloudformation.md @@ -1,25 +1,25 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- -# AWS AWS CloudFormation Library +# AWS CloudFormation Library -The [AWS Construct Library](aws_construct_lib.md) includes constructs with APIs for defining AWS infrastructure\. For example, the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct can be used to define Amazon S3 Buckets and the [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) construct can be used to define Amazon SNS Topics\. +The [AWS Construct Library](aws_construct_lib.md)includes constructs with APIs for defining AWS infrastructure\. For example, you can use the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct to define Amazon Simple Storage Service \(Amazon S3\) buckets, and the [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) construct to define Amazon Simple Notification Service \(Amazon SNS\) topics\. Under the hood, these constructs are implemented using AWS CloudFormation resources, which are available in the `CfnXxx` classes in each library\. For example, the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct uses the [@aws\-cdk/aws\-s3\.cloudformation\.BucketResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.cloudformation.BucketResource) resource \(as well as other resources, depending on what bucket APIs are used\)\. **Important** -Generally, when building AWS CDK apps, you shouldn't need to interact with AWS CloudFormation directly\. However, there might be advanced use cases and migration scenarios where this might be required\. We are also aware that there might be gaps in capabilities in the AWS Construct Library over time\. +Generally, when building CDK apps, you shouldn't need to interact with AWS CloudFormation directly\. However, there might be advanced use cases and migration scenarios where this might be required\. We are also aware that there might be gaps in capabilities in the AWS Construct Library over time\. ## Resources -AWS CloudFormation resource classes are automatically generated from the [AWS AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) and available under the `CfnXxx` classes of each AWS library\. Their API matches 1:1 with how you would use these resources in AWS CloudFormation\. +The CDK creates the low\-level resources from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) on a regular basis\. The classes are available under the `CfnXxx` classes of each AWS library\. Their API matches 1:1 with how you would use these resources in AWS CloudFormation\. -When defining AWS CloudFormation resource, the `props` argument of the class initializer will match 1:1 to the resource's properties in AWS CloudFormation\. +When defining AWS CloudFormation resources, the `props` argument of the class initializer matches 1:1 to the resource's properties in AWS CloudFormation\. -For example, to define an [AWS::SQS::Queue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html) resource encrypted with an AWS managed key you can directly specify the [KmsMasterKeyId](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-kmsmasterkeyid) property\. +For example, to define an [AWS::SQS::Queue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html) resource encrypted with an AWS managed key, you can directly specify the [KmsMasterKeyId](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-kmsmasterkeyid) property\. ``` import sqs = require('@aws-cdk/aws-sqs'); @@ -29,7 +29,7 @@ new sqs.CfnQueue(this, 'MyQueueResource', { }); ``` -For reference, if you use the [Queue](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sqs.html#@aws-cdk/aws-sqs.Queue) construct, you can define managed queue encryption as follows: +For reference, if you use the [Queue](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sqs.html#@aws-cdk/aws-sqs.Queue) construct, you can define managed queue encryption as follows\. ``` import sqs = require('@aws-cdk/aws-sqs'); @@ -39,11 +39,11 @@ new sqs.Queue(this, 'MyQueue', { }); ``` -## Resource Options +## Resource Object Properties -To reference the runtime attributes of AWS CloudFormation resources, use one of the properties available on the resource object\. +Use resource object properties to get a runtime attribute of an AWS CloudFormation resource\. -The following example configures a Lambda function's dead letter queue to use the ARN of an Amazon SQS queue resource\. +The following example configures the dead letter queue of an AWS Lambda function to use the Amazon Resource Name \(ARN\) of an Amazon SQS queue resource\. ``` import sqs = require('@aws-cdk/aws-sqs'); @@ -58,62 +58,8 @@ new lambda.CfnFunction(this, { }); ``` -The [cdk\.Resource\.ref](@cdk-class-url;#@aws-cdk/cdk.Resource.ref) attribute represents the AWS CloudFormation resource's intrinsic reference \(or *Return Value*\)\. For example, *dlq\.ref* also [refers](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-properties-sqs-queues-ref) to the queue's ARN\. When possible, it is preferrable to use an explicitly named attribute instead of *ref*\. +The [cdk\.Resource\.ref](@cdk-class-url;#@aws-cdk/cdk.Resource.ref) attribute represents the AWS CloudFormation resource's intrinsic reference \(or *return value*\)\. For example, *dlq\.ref* also [refers](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-properties-sqs-queues-ref) to the queue's ARN\. When possible, use an explicitly named attribute instead of *ref*\. ## Resource Options -The [cdk\.Resource\.options](@cdk-class-url;#@aws-cdk/cdk.Resource.options) object includes AWS CloudFormation options, such as `condition`, `updatePolicy`, `createPolicy` and `metadata`, for a resource\. - -## Parameters - -``` -import sns = require('@aws-cdk/aws-sns'); -import cdk = require('@aws-cdk/cdk'); - -const p = new cdk.Parameter(this, 'MyParam', { type: 'String' }); -new sns.CfnTopic(this, 'MyTopic', { displayName: p.ref }); -``` - -## Outputs - -``` -import sqs = require('@aws-cdk/aws-sqs'); -import cdk = require('@aws-cdk/cdk'); - -const queue = new sqs.CfnQueue(this, 'MyQueue'); -const out = new cdk.Output(this, 'MyQueueArn', { value: queue.queueArn }); - -const import = out.makeImportValue(); -assert(import === { "Fn::ImportValue": out.exportName } -``` - -## Conditions - -``` -import sqs = require('@aws-cdk/aws-sqs'); -import cdk = require('@aws-cdk/cdk'); -const cond = new cdk.Condition(this, 'MyCondition', { - expression: new cdk.FnIf(...) -}); - -const queue = new sqs.CfnQueue(this, 'MyQueue'); -queue.options.condition = cond; -``` - -## Intrinsic Functions - -``` -import { Fn } from'@aws-cdk/cdk'; -Fn.join(",", [...]) -``` - -## Pseudo Parameters - -``` -import cdk = require('@aws-cdk/cdk'); -new cdk.AwsRegion() - - -cdk synch > mytemplate -into a CI/CD pipeline -``` \ No newline at end of file +For resources, the [cdk\.Resource\.options](@cdk-class-url;#@aws-cdk/cdk.Resource.options) object includes AWS CloudFormation options, such as `condition`, `updatePolicy`, `createPolicy`, and `metadata`\. \ No newline at end of file diff --git a/doc_source/concepts.md b/doc_source/concepts.md index 04cd5685..33c92728 100644 --- a/doc_source/concepts.md +++ b/doc_source/concepts.md @@ -1,15 +1,11 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- # AWS CDK Concepts -This topic describes some of the concepts \(the why and how\) behind the AWS CDK\. It also discusses the advantages of a AWS Construct Library over a low\-level CloudFormation Resource\. +This topic describes some of the concepts \(the why and how\) behind the CDK\. It also discusses the advantages of the AWS Construct Library over a low\-level AWS CloudFormation Resource\. -AWS CDK apps are represented as a hierarchal structure we call the *construct tree*\. Every node in the tree is a [Construct](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#construct) object\. The root of an AWS CDK app is typically an [App](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app) construct\. Apps contain one or more [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) constructs, which are deployable units of your app\. - -This composition of constructs gives you the flexibility to architect your app, such as having a stack deployed in multiple regions\. Stacks represent a collection of AWS resources, either directly or indirectly through a child construct that itself represents an AWS resource, such as an Amazon SQS queue, an Amazon SNS topic, a Lambda function, or a DynamoDB table\. - -This composition of constructs also means you can easily create sharable constructs, and make changes to any construct and have those changes available to consumers as shared class libraries\. \ No newline at end of file +CDK apps are composed of building blocks known as [Constructs](constructs.md), which are used to create [stacks](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) and [apps](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app)\. \ No newline at end of file diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 8dc3713c..b06c025d 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -1,93 +1,100 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- # Constructs -Constructs are the building blocks of AWS CDK applications\. Constructs can have child constructs, which in turn can have child constructs, forming a hierarchical tree structure\. +You can think of constructs as *cloud components*\. They can represent architectures of any complexity\. They can represent a single resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket or an Amazon Simple Notification Service \(Amazon SNS\) topic\. They can represent reusable components, such as a static website, a part of a specific application, or complex, multistack applications that span multiple accounts and AWS Regions\. Constructs can also include other constructs\. Everything in the AWS CDK is a construct\. -The AWS CDK includes two different levels of constructs: +This composition of constructs means that you can create sharable constructs\. For example, if construct A and construct B use construct C and you make changes to construct C, then and both construct A and construct B get those changes\. -CloudFormation Resource -These constructs are low\-level constructs that provide a direct, one\-to\-one, mapping to an AWS CloudFormation resource, as listed in the AWS CloudFormation topic [ AWS Resource Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. -All CloudFormation Resource members are found in the `@aws-cdk/resources` package\. +## The AWS CloudFormation Resource Library -AWS Construct Library -These constructs have been handwritten by AWS and come with convenient defaults and additional knowledge about the inner workings of the AWS resources they represent\. In general, you will be able to express your intent without worrying about the details too much, and the correct resources will automatically be defined for you\. -AWS Construct Library members are found in the `@aws-cdk/aws-NAMESPACE` packages, where NAMESPACE is the short name for the associated service, such as SQS for the AWS Construct Library for the Amazon SQS service\. See the [Reference](https://awslabs.github.io/aws-cdk/reference.html#reference) section for descriptions of the AWS CDK packages and constructs\. +The AWS CDK provides a class library of constructs called the **AWS CloudFormation Resource Library**\. This library consists of constructs that represent all the resources available on AWS\. + +Each module in the AWS Construct Library includes two types of constructs for each resource: low\-level constructs known as an AWS CloudFormation Resource constructs and high\-level constructs known as an AWS Construct Library constructs\. + +The CDK creates the low\-level resources from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) on a regular basis\. Low\-level constructs are named **Cfn***Xyz*, where *Xyz* represents the name of the resource\. These constructs provide direct, one\-to\-one access to how a resource is synthesized in the AWS CloudFormation template produced by your CDK app\. Using low\-level resources requires you to explicitly configure all resource properties, IAM policies, and have a deep understanding of the details\. + +High\-level resource constructs are authored by AWS and offer an intent\-based API for using AWS services\. They provide the same functionality as the low\-level resources, but encode much of the details, boilerplate, and glue logic required to use AWS\. High\-level resources offer convenient defaults and additional knowledge about the inner workings of the AWS resources they represent\. + +Similarly to the AWS SDKs and AWS CloudFormation, the AWS Construct Library is organized into modules, one for each AWS service\. For example, the `@aws-cdk/aws-ec2` module includes resources for Amazon EC2 instances and networking\. The `aws-sns` module includes resources such as `Topic` and `Subscription`\. See the [Reference](https://awslabs.github.io/aws-cdk/reference.html) for descriptions of the CDK packages and constructs\. + +AWS Construct Library members are found in the `@aws-cdk/aws-NAMESPACE` packages, where `NAMESPACE` is the short name for the associated service, such as `SQS` for the AWS Construct Library for the Amazon Simple Queue Service \(Amazon SQS\) service\. ## Construct Structure -The construct tree structure is a powerful design pattern for composing high\-level abstractions\. For example, you can define a `StorageLayer` construct that represents your application's storage layer and include all the AWS resources, such as DynamoDB tables and Amazon S3 buckets, needed to implement your storage layer in this construct\. When your higher\-level code uses this construct, it only needs to instantiate the `StorageLayer` construct\. +Constructs are represented as normal classes in your code and are defined by instantiating an object of that class\. + +When constructs are initialized, they are always defined within the *scope* of another construct, and always have an *id* that must be unique within the same scope\. -When you initialize a construct, add the construct to the construct tree by specifying the parent construct as the first initializer parameter, an identifier for the construct as the second parameter, and a set of properties for the final parameter, as shown in the following example\. +For example, here's how you would define an Amazon SNS `topic` in your stack with default configuration\. ``` -new SomeConstruct(parent, name[, props]); +new sns.Topic(this, 'MyTopic'); ``` -In almost all cases, you should pass the keyword `this` for the `parent` argument, because you will generally initialize new constructs in the context of the parent construct\. Any descriptive string will do for the `name` argument, and an in\-line object for the set of properties\. +The first argument to every construct is always the scope in which it's created, and is almost always `this`, because most constructs are defined within the current scope\. + +Scopes enable constructs to be composed together to form higher\-level abstractions\. This is done by enabling the framework to group them together into logical units, allocate globally unique identifiers, and allow them to consult context information, such as the AWS Region in which it's going to be deployed and which availability Zones are available for your account\. + +In most cases, the construct initializer has a third `props` argument that can be used to define the construct's initial configuration\. For example: ``` -new BeautifulConstruct(this, 'Foo', { - applicationName: 'myApp', - timeout: 300 +new MyConstruct(this, 'Foo', { + favoriteColor: 'green', + timeout: 300 }); ``` -**Note** -Associating the construct to its parent as part of initialization is necessary because the construct occasionally needs contextual information from its parent, such as to which the region the stack is deployed\. +Use the `construct.node` property to get the following information about the construct\. -Use the following operations to inspect the construct tree\. + construct\.node\.scope +Gets the scope in which the construct was defined\. - aws\-cdk\.Construct\.parent -Gets the path of this construct from the root of the tree\. + construct\.node\.id +Gets the `id` of the construct\. - aws\-cdk\.Construct\.getChildren -Gets an array of all of the contruct's children\. + construct\.node\.uniqueId +Gets the app\-wide unique, safe ID of the construct\. This ID encodes the construct's path into a human\-readable portion and a hash of the full path to ensure global uniqueness\. - aws\-cdk\.Construct\.getChild -Gets the child construct with the specified ID\. + construct\.node\.path +Gets the full path of this construct from the root of the scope \(the `App`\)\. - aws\-cdk\.Construct\.toTreeString\(\) -Gets a string representing the construct's tree\. +## Construct IDs -## Construct Names +Every construct in a CDK app must have an `id` that's unique within the scope in which the construct is defined\. The CDK uses IDs to find constructs in the construct hierarchy\. It also uses IDs to allocate logical IDs so that AWS CloudFormation can keep track of the generated resources\. -Every construct in a CDK app must have a **name** unique among its siblings\. Names are used to track constructs in the construct hierarchy, and to allocate logical IDs so that AWS CloudFormation can keep track of the generated resources\. - -When a construct is created, its name is specified as the second initializer argument: +When a construct is created, its ID is specified as the second initializer argument\. ``` -const c1 = new MyBeautifulConstruct(this, 'OneBeautiful'); -const c2 = new MyBeautifulConstruct(this, 'TwoBeautiful'); -assert(c1.name === 'OneBeautiful'); -assert(c2.name === 'TwoBeautiful'); +const c1 = new MyConstruct(this, 'OneConstruct'); +const c2 = new MyConstruct(this, 'TwoConstruct'); +assert(c1.node.id === 'OneConstruct'); +assert(c2.node.id === 'TwoConstruct'); ``` -Use the `aws-cdk.Construct.path` property to get the path of this construct from the root of the tree\. - -Note that the name of a construct does not directly map onto the physical name of the resource when it is created\. If you want to give a physical name to a bucket or table, specify the physical name using use the appropriate property, such as `bucketName` or `tableName`, as shown in the following example: +Notice that the ID of a construct doesn't directly map to the physical name of the resource when it's created\. To give a physical name to a bucket or table, specify the physical name using the appropriate property, such as `bucketName` or `tableName`, as shown in the following example\. ``` -new Bucket(this, 'MyBucket', { - bucketName: 'physical-bucket-name' +new s3.Bucket(this, 'MyBucket', { + bucketName: 'physical-bucket-name' }); ``` -Avoid specifying physical names\. Instead, let AWS CloudFormation generate names for you\. Use attributes, such as `bucket.bucketName`, to discover the generated names\. +We recommend that you avoid specifying physical names\. Instead, let AWS CloudFormation generate names for you\. Use attributes, such as `bucket.bucketName`, to discover the generated names\. -When you synthesize an AWS CDK tree into an AWS CloudFormation template, the AWS CloudFormation logical ID for each resource in the template is allocated according to the path of that resource in the construct tree\. For more information, see [Logical IDs](logical_ids.md)\. +When you synthesize a CDK app into an AWS CloudFormation template, the AWS CloudFormation logical ID for each resource in the template is allocated according to the path of that resource in the scope hierarchy\. For more information, see [Logical IDs](logical_ids.md)\. ## Construct Properties -Customize constructs by passing a property object as the third parameter \(*props*\)\. Every construct has its own set of parameters, defined as an interface\. You can pass a property object to your construct in two ways: +Customize constructs by passing a property object as the third parameter \(*props*\)\. Every construct has its own set of properties, defined as an interface\. You can pass a property object to your construct in two ways: inline, or instantiated as a separate property object\. ``` // Inline (recommended) -new Queue(this, 'MyQueue', { +new sqs.Queue(this, 'MyQueue', { visibilityTimeout: 300 }); @@ -101,4 +108,56 @@ new Queue(this, 'MyQueue', props); ## Construct Metadata -You can attach metadata to a construct using the `aws-cdk.Construct.addMetadata` operation\. Metadata entries automatically include the stack trace from which the metadata entry was added\. Therefore, at any level of a construct you can find the code location, even if metadata was created by a lower\-level library that you don't own\. \ No newline at end of file +Attach metadata to a construct using the `addMetadata` method\. Metadata is an AWS CDK\-level annotation, and as such, does not appear in the deployed resources\. Metadata entries automatically include the stack trace from which the metadata entry was added to allow tracing back to your code, even if the entry was defined by a lower\-level library that you don't own\. + +Use the `addWarning()` method to emit a message when you you synthesis a stack; use the `addError()` method to not only emit a message when you you synthesis a stack, but to also block the deployment of a stack\. + +The following example blocks the deployment of `myStack` if it is not in `us-west-2`: + +``` +if (myStack.region !== 'us-west-2') { + myStack.node.addError('myStack is not in us-west-2'); +} +``` + +## Tagging Constructs + +You can add a tag to any construct to identify the resources you create\. Tags can be applied to any construct\. Tags are inherited, and are based on scope\. If you tag construct `A`, and construct `A` contains construct `B`, construct `B` inherits the tag\. + +There are two tag operations\. + +Tag +Adds \(or applies\) a tag to a set of resources, or to all but a set of resources\. + +RemoveTag +Removes a tag from a set of resources, or from all but a set of resources\. + +The following example adds the tag key\-value pair *StackType*\-*TheBest* to any resource created within the **theBestStack** stack labeled *MarketingSystem*\. + +``` +import cdk = require('@aws-cdk/cdk'); + +const app = new cdk.App(); +const theBestStack = new cdk.Stack(app, 'MarketingSystem'); +theBestStack.node.apply(new cdk.Tag('StackType', 'TheBest')); + +// To remove the tag: +theBestStack.node.apply(new cdk.RemoveTag('TheBest')); + +// To remove the tag from all EXCEPT the subnets: +theBestStack.node.apply(new cdk.RemoveTag('TheBest'), {exludeResourceTypes: ['AWS::EC2::Subnet']})); +``` + +The tag operations include some properties to fine\-tune how tags are applied to or removed from the resources that the construct creates\. + +applyToLaunchedInstances +Use this Boolean property to set `PropagateAtLaunch` for any Auto Scaling group resource the construct creates\. The default is `true`\. + +includeResourceTypes +Use this array of strings to apply a tag only to those AWS CloudFormation resource types\. The default is an empty array, which means the tag applies to all AWS CloudFormation resource types\. + +excludeResourceTypes +Use this array of strings to exclude a tag from those AWS CloudFormation resource types\. The default is an empty array, which means the tag applies to all AWS CloudFormation resource types\. This property takes precedence over the `includeResourceTypes` property\. + +priority +Set this integer value to control the precedence of tags\. The default is 0 \(zero\) for `Tag` and 1 for `RemoveTag`\. Higher values take precedence over lower values\. \ No newline at end of file diff --git a/doc_source/context.md b/doc_source/context.md deleted file mode 100644 index 52e9c200..00000000 --- a/doc_source/context.md +++ /dev/null @@ -1,104 +0,0 @@ --------- - - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. - --------- - -# Environmental Context - -When you synthesize a stack to create a AWS CloudFormation template, the AWS CDK might need information based on the environment \(account and Region\), such as the availability zones or AMIs available in the Region\. To enable this feature, the AWS CDK Toolkit uses *context providers*, and saves the context information into `cdk.json` the first time you call `cdk synth`\. - -The AWS CDK currently supports the following context providers\. - -[AvailabilityZoneProvider](@cdk-class-url;#@aws-cdk/cdk.AvailabilityZoneProvider) -Use this provider to get the list of all supported availability zones in this environment\. For example, the following code iterates over all of the AZs in the current environment\. - -``` -// "this" refers to a parent Construct -const zones: string[] = new AvailabilityZoneProvider(this).availabilityZones; - -for (let zone of zones) { - // do somethning for each zone! -} -``` - -[SSMParameterProvider](@cdk-class-url;#@aws-cdk/cdk.SSMParameterProvider) -Use this provider to read values from the current Region's SSM parameter store\. For example, the follow code returns the value of the *my\-awesome\-parameter* key: - -``` -const ami: string = new SSMParameterProvider(this, { - parameterName: 'my-awesome-parameter' -).parameterValue(); -``` -This is only for reading plain strings, and not recommended for secrets\. For reading secure strings from SSM Parmeter store, see [Getting a Value from an SSM Store Variable](passing_in_data.md#passing_ssm_value)\.\. - -[HostedZoneProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-route53.html#@aws-cdk/aws-route53.HostedZoneProvider) -Use this provider to discover existing hosted zones in your account\. For example, the following code imports an existing hosted zone into your CDK app so you can add records to it: - -``` -const zone: HostedZoneRef = new HostedZoneProvider(this, { - domainName: 'test.com' -}).findAndImport(this, 'HostedZone'); -``` - -[VpcNetworkProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#@aws-cdk/aws-ec2.VpcNetworkProvider) -Use this provider to look up and reference existing VPC in your accounts\. For example, the follow code imports a VPC by tag name: - -``` -const provider = new VpcNetworkProvider(this, { - tags: { - Purpose: 'WebServices' - } -}); - -const vpc = VpcNetworkRef.import(this, 'VPC', provider.vpcProps); -``` - -## Viewing and managing context - -Context is used to retrieve information such as the Availability Zones in your account or AMI IDs used to start your instances\. To avoid unexpected changes to your deployments, such as when you add a `Queue` to your application, but a new Amazon Linux AMI was released, thus changing your AutoScalingGroup, the AWS CDK stores the context values in `cdk.json`\. This ensures that the AWS CDK retrieves the same value on the next synthesis\. - -Use the cdk context to see context values stored for your application\. The output should be something like the following: - -``` -Context found in cdk.json: - -┌───┬────────────────────────────────────────────────────┬────────────────────────────────────────────────────┐ -│ # │ Key │ Value │ -├───┼────────────────────────────────────────────────────┼────────────────────────────────────────────────────┤ -│ 1 │ availability-zones:account=123456789012:region=us- │ [ "us-east-1a", "us-east-1b", "us-east-1c", │ -│ │ east-1 │ "us-east-1d", "us-east-1e", "us-east-1f" ] │ -├───┼────────────────────────────────────────────────────┼────────────────────────────────────────────────────┤ -│ 2 │ ssm:account=123456789012:parameterName=/aws/ │ "ami-013be31976ca2c322" │ -│ │ service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_ │ │ -│ │ 64-gp2:region=us-east-1 │ │ -└───┴────────────────────────────────────────────────────┴────────────────────────────────────────────────────┘ - -Run cdk context --reset KEY_OR_NUMBER to remove a context key. It will be refreshed on the next CDK synthesis run. -``` - -If at some point you want to update to the latest version of the Amazon Linux AMI, do a controlled update of the context value, reset it, and synthesize again: - -``` -$ cdk context --reset 2 -``` - -``` -Context value -ssm:account=123456789012:parameterName=/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2:region=us-east-1 -reset. It will be refreshed on the next SDK synthesis run. -``` - -``` -cdk synth -``` - -``` -... -``` - -To clear all context values, run cdk context \-\-clear: - -``` -cdk context --clear -``` \ No newline at end of file diff --git a/doc_source/core_concepts.md b/doc_source/core_concepts.md new file mode 100644 index 00000000..dec605d8 --- /dev/null +++ b/doc_source/core_concepts.md @@ -0,0 +1,11 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# CDK Core + +This topic describes some of the core concepts \(the why and how\) behind the CDK\. It also discusses the advantages of using the AWS Construct Library instead of a low\-level AWS CloudFormation Resource\. + +CDK apps are composed of building blocks known as [Constructs](constructs.md), which are composed together to form [stacks](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) and [apps](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app)\. \ No newline at end of file diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 5df1a2bb..36d198e9 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -1,14 +1,14 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- -# Document History for the AWS Cloud Development Kit User Guide +# Document History for the AWS CDK User Guide -The following table describes the documentation for this release of the AWS Cloud Development Kit \(AWS CDK\)\. +The following table describes the documentation for this release of the AWS Cloud Development Kit \(CDK\) \(CDK\)\. -See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the AWS CDK releases\. +See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the CDK releases\. + **API version: 0\.21\.0** + **Latest documentation update:** December 27, 2018 | Change | Description | Date | diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md deleted file mode 100644 index 801e4f13..00000000 --- a/doc_source/ecs_example.md +++ /dev/null @@ -1,123 +0,0 @@ --------- - - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. - --------- - -# Creating an Amazon ECS Fargate Service Using the AWS CDK - -This example walks you through creating a Fargate service running on an ECS cluster fronted by an internet\-facing application load balancer\. - -Amazon ECS is a highly scalable, fast, container management service that makes it easy to run, stop, and manage Docker containers on a cluster\. You can host your cluster on a serverless infrastructure that is managed by Amazon ECS by launching your services or tasks using the Fargate launch type\. For more control you can host your tasks on a cluster of Amazon Elastic Compute Cloud \(Amazon EC2\) instances that you manage by using the Amazon EC2 launch type\. - -This example shows you how to launch some services using the Fargate launch type\. If you've ever used the console to create a Fargate service, you know that there are many steps you must follow to accomplish that task\. AWS has a number of tutorials and documentation topics that walk you through creating a Fargate service, including: -+ [How to Deploy Docker Containers \- AWS](https://aws.amazon.com/getting-started/tutorials/deploy-docker-containers) -+ [Setting up with Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/get-set-up-for-amazon-ecs.html) -+ [Getting Started with Amazon ECS using Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_GetStarted.html) - -This example creates a similar Fargate service in AWS CDK code\. - -Since Amazon ECS can be used with a number of AWS services, you should understand how the Amazon ECS construct that we use in this example gives you a leg up on using AWS services by providing the following benefits: -+ Automatically configures a load balancer\. -+ Automatic security group opening for load balancers, which enables load balancers to communicate with instances without you explictly creating a security group\. -+ Automatic ordering dependency between service and load balancer attaching to a target group, where the AWS CDK enforces the correct order of creating the listener before an instance is created -+ Automatic userdata configuration on auto\-scaling group, which creates the correct configuration to associate a cluster to AMI\(s\)\. -+ Early validation of parameter combinations, which exposes AWS CloudFormation issues earlier, thus saving you deployment time\. For example, depending upon the task, it is easy to mis\-configure the memory settings\. Previously you would not encounter an error until you deployed your app, but now the AWS CDK can detect a misconfiguration and emit an error when you synthesize your app\. -+ Automatically adds permissions for Amazon ECR if you use an image from Amazon ECR When you use an image from Amazon ECR, the AWS CDK adds the correct permissions\. -+ Automatic autoscaling\. The AWS CDK supplies a method so you can autoscaling instances when you use an Amazon EC2 cluster; this functionality is done automatically when you use an instance in a Fargate cluster\. - - In addition, the AWS CDK prevents instances from being deleted when autoscaling tries to kill an instance, but either a task is running or is scheduled on that instance\. - - Previously, you had to create a Lambda function to have this functionality\. -+ Asset support, so that you can deploy source from your machine to Amazon ECS in one step Previously, to use application source you had to perform a number of manual steps, such as upload to Amazon ECR and create a Docker image\. - -## Creating the Directory and Initializing the AWS CDK - -Let's start with creating a new directory to hold our AWS CDK code and create a new app in that directory\. - -``` -mkdir MyEcsConstruct -cd MyEcsConstruct -cdk init --language typescript -``` - -Build the app and confirm that it creates an empty stack\. - -``` -npm run build -cdk synth -``` - -You should see a stack like the following, where *CDK\-VERSION* is the version of the CDK\. - -``` -Resources: - CDKMetadata: - Type: 'AWS::CDK::Metadata' - Properties: - Modules: @aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_ecs_construct=0.1.0 -``` - -## Add the Amazon EC2 and Amazon ECS Packages - -Install support for Amazon EC2 and Amazon ECS\. - -``` -npm install @aws-cdk/aws-ec2 @aws-cdk/aws-ecs -``` - -## Create a Fargate Service - -There are two different ways of running your container tasks with Amazon ECS\. -+ Using the `Fargate` launch type, where Amazon ECS manages the physical machines that your containers are running on for you\. -+ Using the `EC2` launch type, where you do the managing, such as specifying autoscaling\. - -The following example creates a Fargate service running on an ECS cluster fronted by an internet\-facing application load balancer\. - -Add the following `import` statements to `lib/my_ecs_construct-stack.ts`\. - -``` -import ec2 = require('@aws-cdk/aws-ec2'); -import ecs = require('@aws-cdk/aws-ecs'); -``` - -Replace the comment at the end of the constructor with the following code\. - -``` -const vpc = new ec2.VpcNetwork(this, 'MyVpc', { - maxAZs: 3 // Default is all AZs in region -}); - -const cluster = new ecs.Cluster(this, 'MyCluster', { - vpc: vpc -}); - -// Create a load-balanced Fargate service and make it public -new ecs.LoadBalancedFargateService(this, 'MyFargateService', { - cluster: cluster, // Required - cpu: '512', // Default is 256 - desiredCount: 6, // Default is 1 - image: ecs.ContainerImage.fromDockerHub('amazon/amazon-ecs-sample'), // Required - memoryMiB: '2048', // Default is 512 - publicLoadBalancer: true // Default is false -}); -``` - -Save it and make sure it builds and creates a stack\. - -``` -npm run build -cdk synth -``` - -The stack is hundreds of lines, so we won't show it here\. The stack should contain one default instance, a private subnet and a public subnet for the three availability zones, and a security group\. - -Deploy the stack\. - -``` -cdk deploy -``` - -AWS CloudFormation displays information about the dozens of steps that it takes as it deploys your app\. - -That's how easy it is to create a Fargate service to run a Docker image\. \ No newline at end of file diff --git a/doc_source/ecs_tutorial.md b/doc_source/ecs_tutorial.md new file mode 100644 index 00000000..53568c07 --- /dev/null +++ b/doc_source/ecs_tutorial.md @@ -0,0 +1,132 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Creating an AWS Fargate Service Using the AWS CDK + +This tutorial walks you through how to create an AWS Fargate service running on an Amazon Elastic Container Service \(Amazon ECS\) cluster that's fronted by an internet\-facing Application Load Balancer from an image on DockerHub\. + +Amazon ECS is a highly scalable, fast, container management service that makes it easy to run, stop, and manage Docker containers on a cluster\. You can host your cluster on a serverless infrastructure that's managed by Amazon ECS by launching your services or tasks using the Fargate launch type\. For more control, you can host your tasks on a cluster of Amazon Elastic Compute Cloud \(Amazon EC2\) instances that you manage by using the Amazon EC2 launch type\. + +This tutorial shows you how to launch some services using the Fargate launch type\. If you've used the AWS Management Console to create a Fargate service, you know that there are many steps to follow to accomplish that task\. AWS has several tutorials and documentation topics that walk you through creating a Fargate service, including: ++ [How to Deploy Docker Containers \- AWS](https://aws.amazon.com/getting-started/tutorials/deploy-docker-containers) ++ [Setting Up with Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/get-set-up-for-amazon-ecs.html) ++ [Getting Started with Amazon ECS Using Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_GetStarted.html) + +This tutorial creates a similar Fargate service in CDK code\. + +The Amazon ECS construct used in this tutorial helps you use AWS services by providing the following benefits: ++ Automatically configures a load balancer\. ++ Automatically opens a security group for load balancers\. This enables load balancers to communicate with instances without you explicitly creating a security group\. ++ Automatically orders dependency between the service and the load balancer attaching to a target group, where the CDK enforces the correct order of creating the listener before an instance is created\. ++ Automatically configures user data on automatically scaling groups\. This creates the correct configuration to associate a cluster to AMIs\. ++ Validates parameter combinations early\. This exposes AWS CloudFormation issues earlier, thus saving you deployment time\. For example, depending on the task, it's easy to misconfigure the memory settings\. Previously, you would not encounter an error until you deployed your app\. But now the CDK can detect a misconfiguration and emit an error when you synthesize your app\. ++ Automatically adds permissions for Amazon Elastic Container Registry \(Amazon ECR\) if you use an image from Amazon ECR\. ++ Automatically scales\. The CDK supplies a method so you can autoscalinginstances when you use an Amazon EC2 cluster\. This happens automatically when you use an instance in a Fargate cluster\. + + In addition, the CDK prevents an instance from being deleted when automatic scaling tries to kill an instance, but either a task is running or is scheduled on that instance\. + + Previously, you had to create a Lambda function to have this functionality\. ++ Provides asset support, so that you can deploy a source from your machine to Amazon ECS in one step\. Previously, to use an application source you had to perform several manual steps, such as uploading to Amazon ECR and creating a Docker image\. + +See the [Amazon ECS Construct Library](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ecs.html#aws-elastic-container-service-ecs-construct-library) reference for details\. + +## Creating the Directory and Initializing the CDK + +Let's start by creating a directory to hold the CDK code, and then creating a CDK app in that directory\. + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language typescript +``` + +Build the app and confirm that it creates an empty stack\. + +``` +npm run build +cdk synth +``` + +You should see a stack like the following, where *CDK\-VERSION* is the version of the CDK\. + +``` +Resources: + CDKMetadata: + Type: 'AWS::CDK::Metadata' + Properties: + Modules: @aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_ecs_construct=0.1.0 +``` + +## Add the Amazon EC2 and Amazon ECS Packages + +Install support for Amazon EC2 and Amazon ECS\. + +``` +npm install @aws-cdk/aws-ec2 @aws-cdk/aws-ecs +``` + +## Create a Fargate Service + +There are two different ways to run your container tasks with Amazon ECS: ++ Use the `Fargate` launch type, where Amazon ECS manages the physical machines that your containers are running on for you\. ++ Use the `EC2` launch type, where you do the managing, such as specifying automatic scaling\. + +The following tutorial creates a Fargate service running on an ECS cluster fronted by an internet\-facing Application ad Balancer\. + +Add the following `import` statements to `lib/my_ecs_construct-stack.ts`\. + +``` +import ec2 = require('@aws-cdk/aws-ec2'); +import ecs = require('@aws-cdk/aws-ecs'); +``` + +Replace the comment at the end of the constructor with the following code\. + +``` + const vpc = new ec2.VpcNetwork(this, 'MyVpc', { + maxAZs: 3 // Default is all AZs in region + }); + + const cluster = new ecs.Cluster(this, 'MyCluster', { + vpc: vpc + }); + + // Create a load-balanced Fargate service and make it public + new ecs.LoadBalancedFargateService(this, 'MyFargateService', { + cluster: cluster, // Required + cpu: '512', // Default is 256 + desiredCount: 6, // Default is 1 + image: ecs.ContainerImage.fromDockerHub('amazon/amazon-ecs-sample'), // Required + memoryMiB: '2048', // Default is 512 + publicLoadBalancer: true // Default is false + }); +``` + +Save it and make sure it builds and creates a stack\. + +``` +npm run build +cdk synth +``` + +The stack is hundreds of lines, so we don't show it here\. The stack should contain one default instance, a private subnet and a public subnet for the three Availability Zones, and a security group\. + +Deploy the stack\. + +``` +cdk deploy +``` + +AWS CloudFormation displays information about the dozens of steps that it takes as it deploys your app\. + +That's how easy it is to create a Fargate service to run a Docker image\. + +## What Next? ++ Learn more about [AWS CDK Concepts](concepts.md) ++ Check out the [examples directory](https://github.com/awslabs/aws-cdk/tree/master/examples) in your GitHub repository ++ Learn about the rich APIs offered by the [AWS Construct Library](aws_construct_lib.md) ++ Work directly with CloudFormation using the [AWS CloudFormation Library](cloudformation.md) ++ Come talk to us on [Gitter](https://gitter.im/awslabs/aws-cdk) \ No newline at end of file diff --git a/doc_source/environments.md b/doc_source/environments.md deleted file mode 100644 index 7d1c4e20..00000000 --- a/doc_source/environments.md +++ /dev/null @@ -1,28 +0,0 @@ --------- - - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. - --------- - -# Environments and Authentication - -The AWS CDK refers to the combination of an account ID and a Region as an *environment*\. The simplest environment is the one you get by default, which is the one you get when you have set up your credentials and a default Region as described in [Configuring the AWS CDK Toolkit](install_config.md#credentials)\. - -When you create a [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) instance, you can supply the target deployment environment for the stack using the `env` property, as shown in the following example, where REGION is the Region in which you want to create the stack and ACCOUNT is your account ID\. - -``` -new MyStack(app, { env: { region: 'REGION', account: 'ACCOUNT' } }); -``` - -For each of the two arguments, **region** and **account**, the AWS CDK uses the following lookup procedure: -+ If **region** or **account** are provided directly as an property to the Stack, use that\. -+ Otherwise, read **default\-account** and **default\-region** from the application's context\. These can be set in the AWS CDK Toolkit in either the local `cdk.json` file or the global version in *$HOME/\.cdk* on Linux or MacOS or *%USERPROFILE%\\\\\.cdk* on Windows\. -+ If these are not defined, it will determine them as follows: - + **account**: use account from default SDK credentials\. Environment variables are tried first \(`AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`\), followed by credentials in *$HOME/\.aws/credentials* on Linux or MacOS or *%USERPROFILE%\\\\\.aws\\\\credentials* on Windows\. - + **region**: use the default region configured in *$HOME/\.aws/config* on Linux or MacOS or *%USERPROFILE%\\\\\.aws\\\\config* on Windows\. - + You can set these defaults manually, but we recommend you use `aws configure`, as described in [Installing and Configuring the AWS CDK](install_config.md) - -We recommend that you use the default environment for development stacks, and explicitly specify accounts and Regions for production stacks\. - -**Note** -Note that even though the region and account might explicitly be set on your Stack, if you run `cdk deploy`, the AWS CDK will still use the currently\-configured SDK credentials, as provided via the `AWS_` environment variables or `aws configure`\. This means that if you want to deploy stacks to multiple accounts, you will have to set the correct credentials for each invocation to `cdk deploy STACK`\. \ No newline at end of file diff --git a/doc_source/environments_and_context.md b/doc_source/environments_and_context.md new file mode 100644 index 00000000..04e4472c --- /dev/null +++ b/doc_source/environments_and_context.md @@ -0,0 +1,137 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Environments and Run\-Time Context + +The CDK refers to the combination of an account ID and an AWS Region as an *environment*\. The simplest environment is the one you get by default\. This is the one you get when you have set up your credentials and a default Region as described in [Specifying Your Credentials](install_config.md#credentials)\. + +When you synthesize a stack to create an AWS CloudFormation template, the CDK might need information based on the run time context, such as the Availability Zones or Amazon Machine Images \(AMIs\) that are available in the Region\. To enable this feature, the CDK Toolkit uses *context providers*, and saves the context information into the `cdk.json` file the first time you call `cdk synth`\. + +## Environments and Authentication + +When you create a [stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) instance, you can supply the target deployment environment for the stack using the `env` property\. This is shown in the following example, where *REGION* is the AWS Region in which you want to create the stack and *ACCOUNT* is your account ID\. + +``` +new MyStack(app, { env: { region: 'REGION', account: 'ACCOUNT' } }); +``` + +For each of the two arguments, `region` and `account`, the CDK uses the following lookup procedure: ++ If `region` or `account`is provided directly as a property to the stack, use that\. ++ If either property is not specified when you create a stack, the CDK determines them as follows: + + `account` – Use the account from the default SDK credentials\. Environment variables are tried first \(`AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`\), followed by credentials in `$HOME/.aws/credentials` on Linux or macOS, or `%USERPROFILE%\.aws\credentials` on Windows\. + + `region` – Use the default Region configured in `$HOME/.aws/config` on Linux or macOS, or `%USERPROFILE%\.aws\config` on Windows\. + + You can set these defaults manually, but we recommend you use `aws configure`, as described in [Installing and Configuring the AWS CDK](install_config.md)\. + +We recommend that you use the default environment for development stacks, and explicitly specify accounts and Regions for production stacks\. + +**Note** +Although the Region and account might explicitly be set on your stack, if you run `cdk deploy`, the CDK still uses the currently configured SDK credentials that are provided through environment variables or `aws configure`\. This means that if you want to deploy stacks to multiple accounts, you have to set the correct credentials for each invocation to `cdk deploy STACK`\. + +You can always find the Region within which your stack is deployed by using the `region` property of the stack, as follows\. + +``` +this.region +``` + +## Run\-Time Context + +The CDK uses context to retrieve information such as the Availability Zones in your account or Amazon Machine Image \(AMI\) IDs used to start your instances\. To avoid unexpected changes to your deployments, such as when a new Amazon Linux AMI is released, thus changing your Auto Scaling group, the CDK stores context values in `cdk.context.json`\. This ensures that the CDK retrieves the same value the next time it synthesises your app\. Don't forget to put this file under version control\. + +### Viewing and Managing Context + +Use the cdk context to see context values stored for your application\. The output should be something like the following\. + +``` +Context found in cdk.json: + +┌───┬────────────────────────────────────────────────────┬────────────────────────────────────────────────────┐ +│ # │ Key │ Value │ +├───┼────────────────────────────────────────────────────┼────────────────────────────────────────────────────┤ +│ 1 │ availability-zones:account=123456789012:region=us- │ [ "us-east-1a", "us-east-1b", "us-east-1c", │ +│ │ east-1 │ "us-east-1d", "us-east-1e", "us-east-1f" ] │ +├───┼────────────────────────────────────────────────────┼────────────────────────────────────────────────────┤ +│ 2 │ ssm:account=123456789012:parameterName=/aws/ │ "ami-013be31976ca2c322" │ +│ │ service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_ │ │ +│ │ 64-gp2:region=us-east-1 │ │ +└───┴────────────────────────────────────────────────────┴────────────────────────────────────────────────────┘ + +Run cdk context --reset KEY_OR_NUMBER to remove a context key. It will be refreshed on the next CDK synthesis run. +``` + +If at some point you want to update to the latest version of the Amazon Linux AMI, do a controlled update of the context value, reset it, and synthesize again\. + +``` +$ cdk context --reset 2 +``` + +``` +Context value +ssm:account=123456789012:parameterName=/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2:region=us-east-1 +reset. It will be refreshed on the next SDK synthesis run. +``` + +``` +cdk synth +``` + +``` +... +``` + +To clear all context values, run cdk context \-\-clear\. + +``` +cdk context --clear +``` + +### Context Providers + +The AWS CDK currently supports the following context providers\. + +[AvailabilityZoneProvider](@cdk-class-url;#@aws-cdk/cdk.AvailabilityZoneProvider) +Use this provider to get the list of all supported Availability Zones in this context, as shown in the following example\. + +``` +// "this" refers to a Construct scope +const zones: string[] = new AvailabilityZoneProvider(this).availabilityZones; + +for (let zone of zones) { + // Do something for each zone! +} +``` + +[HostedZoneProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-route53.html#@aws-cdk/aws-route53.HostedZoneProvider) +Use this provider to discover existing hosted zones in your account\. For example, the following code imports an existing hosted zone into your CDK app so you can add records to it\. + +``` +const zone: HostedZoneRef = new HostedZoneProvider(this, { + domainName: 'test.com' +}).findAndImport(this, 'HostedZone'); +``` + +[SSMParameterProvider](@cdk-class-url;#@aws-cdk/cdk.SSMParameterProvider) +Use this provider to read values from the current Region's AWS Systems Manager parameter store\. For example, the following code returns the value of the *my\-awesome\-parameter* key\. + +``` +const ami: string = new SSMParameterProvider(this, { + parameterName: 'my-awesome-parameter' +).parameterValue(); +``` +This is only for reading plain strings, and not recommended for secrets\. For reading secure strings from the Systems Manager Parameter Store, see [Get a Value from a Systems Manager Parameter Store Variable](get_ssm_value.md)\. + +[VpcNetworkProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#@aws-cdk/aws-ec2.VpcNetworkProvider) +Use this provider to look up and reference existing VPCs in your accounts\. For example, the following code imports a VPC by tag name\. + +``` +const provider = new VpcNetworkProvider(this, { + tags: { + "tag:Purpose": 'WebServices' + } +}); + +const vpc = VpcNetwork.import(this, 'VPC', provider.vpcProps); +``` \ No newline at end of file diff --git a/doc_source/examples.md b/doc_source/examples.md deleted file mode 100644 index e5612175..00000000 --- a/doc_source/examples.md +++ /dev/null @@ -1,11 +0,0 @@ --------- - - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. - --------- - -# AWS CDK Examples - -This topic contains examples to help you get started using some of the advanced constructs offered by the AWS CDK\. -+ [Creating a Serverless Application Using the AWS CDK](serverless_example.md) Creates a serverless application to dispense widgets\. -+ [Creating an Amazon ECS Fargate Service Using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service\. \ No newline at end of file diff --git a/doc_source/get_cfn_param.md b/doc_source/get_cfn_param.md new file mode 100644 index 00000000..28207f3d --- /dev/null +++ b/doc_source/get_cfn_param.md @@ -0,0 +1,11 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Use an AWS CloudFormation Parameter + +See [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for information about using the optional *Parameters* section to customize your AWS CloudFormation templates\. + +You can also get a reference to a resource in an existing AWS CloudFormation template, as described in the next section\. \ No newline at end of file diff --git a/doc_source/get_context_var.md b/doc_source/get_context_var.md new file mode 100644 index 00000000..7a723d65 --- /dev/null +++ b/doc_source/get_context_var.md @@ -0,0 +1,31 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Get a Value from a Context Variable + +You can specify a context variable either as part of a CDK Toolkit command, or in a **context** section of `cdk.json`\. + +To create a command line context variable, use the **\-\-context** \(**\-c**\) option of a CDK Toolkit command, as shown in the following example\. + +``` +cdk synth -c bucket_name=mygroovybucket +``` + +To specify the same context variable and value in the `cdk.json` file, use the following code\. + +``` +{ + "context": { + "bucket_name": "myotherbucket" + } +} +``` + +To get the value of a context variable in your app, use code like the following, which gets the value of the context variable **bucket\_name**\. + +``` +const bucket_name string = this.node.getContext("bucket_name"); +``` \ No newline at end of file diff --git a/doc_source/get_env_var.md b/doc_source/get_env_var.md new file mode 100644 index 00000000..a32fee3a --- /dev/null +++ b/doc_source/get_env_var.md @@ -0,0 +1,13 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Get a Value from an Environment Variable + +To get the value of an environment variable, use code like the following\. This code gets the value of the environment variable `MYBUCKET`\. + +``` +const bucket_name = process.env.MYBUCKET; +``` \ No newline at end of file diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md new file mode 100644 index 00000000..9ccab84c --- /dev/null +++ b/doc_source/get_ssm_value.md @@ -0,0 +1,43 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Get a Value from a Systems Manager Parameter Store Variable + +You can get the value of an AWS Systems Manager Parameter Store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It isn't possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from AWS Secrets Manager \(see [Get a Value from AWS Secrets Manager](passing_secrets_manager.md)\)\. + +To retrieve the latest value one time \(as a context value, see [Run\-Time Context](environments_and_context.md#context)\), and keep on using the same value until the context value is manually refreshed, use an [SSMParameterProvider](@cdk-class-url;#@aws-cdk/cdk.SSMParameterProvider)\. + +``` +import cdk = require('@aws-cdk/cdk'); + +const myvalue = new cdk.SSMParameterProvider(this).getString("my-parameter-name"); +``` + +To read a particular version of a Systems Manager Parameter Store plain string value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstorestring)\. + +``` +import ssm = require('@aws-cdk/aws-ssm'); + +const parameterString = new ssm.ParameterStoreString(this, 'MyParameter', { + parameterName: 'my-parameter-name', + version: 1, +}); + +const myvalue = parameterString.value; +``` + +To read a particular version of a Systems Manager Parameter Store `SecureString` value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreSecureString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstoresecurestring) + +``` +import ssm = require('@aws-cdk/aws-ssm'); + +const secureString = new ssm.ParameterStoreSecureString(this, 'MySecretParameter', { + parameterName: 'my-secret-parameter-name', + version: 1, +}); + +const myvalue = secureString.value; +``` \ No newline at end of file diff --git a/doc_source/glossary.md b/doc_source/glossary.md deleted file mode 100644 index c8e126f0..00000000 --- a/doc_source/glossary.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. - --------- - -# 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/hello_world_tutorial.md b/doc_source/hello_world_tutorial.md new file mode 100644 index 00000000..f1c3f690 --- /dev/null +++ b/doc_source/hello_world_tutorial.md @@ -0,0 +1,455 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Hello World Tutorial + +The typical workflow for creating a new app is: + +1. Create a directory and navigate to it\. + +1. To create the skeleton of the app in the programming language *LANGUAGE*, call cdk init \-\-language *LANGUAGE*\. + +1. Add constructs \(and stacks, if appropriate\) to the skeleton code\. + +1. Compile your code, if necessary\. + +1. To deploy the resources you've defined, call cdk deploy\. + +1. Test your deployment\. + +1. If there are any issues, loop through modify, compile \(if necessary\), deploy, and test again\. + +And of course, keep your code under version control\. + +This tutorial walks you through how to create and deploy a simple AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. The app contains one resource, an Amazon S3 bucket\. + +## Step 1: Create the Project Directory + +Create a directory for your project with an empty Git repository\. + +``` +mkdir hello-cdk +cd hello-cdk +``` + +## Initializing the Project + +Initialize an empty project, where *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), or **typescript** \(TypeScript\)\. + +``` +cdk init --language LANGUAGE +``` + +**Note** +Remember that every CDK command has a help option\. For example, cdk init help lists the available languages for the \-\-language \(\-l\) option\. + +## Compiling the Project + +Compile your program, as follows\. + +------ +#### [ TypeScript ] + +``` +npm run build +``` + +------ +#### [ JavaScript ] + +Nothing to compile\. + +------ +#### [ Java ] + +``` +mvn compile +``` + +------ +#### [ C\# ] + +Because we configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command\. + +``` +cdk +``` + +------ + +## Listing the Stacks in the App + +List the stacks in the app\. + +``` +cdk ls +``` + +The result is just the name of the stack\. + +``` +HelloCdkStack +``` + +## Adding an Amazon S3 Bucket + +At this point, what can you do with this app? Nothing, because the stack is empty, so there's nothing to deploy\. Let's define an Amazon S3 bucket\. + +Install the `@aws-cdk/aws-s3` package\. + +------ +#### [ TypeScript ] + +``` +npm install @aws-cdk/aws-s3 +``` + +------ +#### [ JavaScript ] + +``` +npm install @aws-cdk/aws-s3 +``` + +------ +#### [ Java ] + +Add the following to `pom.xml`, where *CDK\-VERSION* is the version of the CDK\. + +``` + + software.amazon.awscdk + s3 + CDK-VERSION + +``` + +------ +#### [ C\# ] + +``` +dotnet add package Amazon.CDK.AWS.S3 +``` + +------ + +Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represented by the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.Bucket) class\. + +------ +#### [ TypeScript ] + +In `lib/hello-cdk-stack.ts`: + +``` +import cdk = require('@aws-cdk/cdk'); +import s3 = require('@aws-cdk/aws-s3'); + +export class HelloCdkStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} +``` + +------ +#### [ JavaScript ] + +In `index.js`: + +``` +const cdk = require('@aws-cdk/cdk'); +const s3 = require('@aws-cdk/aws-s3'); + +class MyStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} +``` + +------ +#### [ Java ] + +In `src/main/java/com/acme/MyStack.java`: + +``` +package com.acme; + +import software.amazon.awscdk.App; +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.services.s3.Bucket; +import software.amazon.awscdk.services.s3.BucketProps; + +public class MyStack extends Stack { + public MyStack(final App scopy, final String id) { + this(scope, id, null); + } + + public MyStack(final App scope, final String id, final StackProps props) { + super(scope, id, props); + + new Bucket(this, "MyFirstBucket", BucketProps.builder() + .withVersioned(true) + .build()); + } +} +``` + +------ +#### [ C\# ] + +Create `MyStack.cs`\. + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +namespace HelloCdk +{ + public class MyStack : Stack + { + public MyStack(App scope, string id) : base(scope, id, null) + { + new Bucket(this, "MyFirstBucket", new BucketProps + { + Versioned = true + }); + } + } +} +``` + +------ + +Notice a few things: ++ [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.Bucket) is a construct\. This means it's initialization signature has `scope`, `id`, and `props`\. In this case, the bucket is an immediate child of **MyStack**\. ++ `MyFirstBucket` is the **id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. See [Logical IDs](logical_ids.md) for information about logical IDs\. To specify a physical name for your bucket, set the [bucketName](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketProps.bucketName) property when you define your bucket\. ++ Because the bucket's [versioned](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. + +Compile your program, as follows\. + +------ +#### [ TypeScript ] + +``` +npm run build +``` + +------ +#### [ JavaScript ] + +Nothing to compile\. + +------ +#### [ Java ] + +``` +mvn compile +``` + +------ +#### [ C\# ] + +Because we configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command\. + +``` +cdk +``` + +------ + +## Synthesizing an AWS CloudFormation Template + +Synthesize an AWS CloudFormation template for the stack, as follows\. + +``` +cdk synth HelloCdkStack +``` + +**Note** +Because the CDK app contains only a single stack, you can omit `HelloCdkStack`\. + +This command executes the CDK app and synthesizes an AWS CloudFormation template for the `HelloCdkStack` stack\. You should see something similar to the following, where *VERSION* is the version of the CDK\. + +``` +Resources: + MyFirstBucketB8884501: + Type: AWS::S3::Bucket + Properties: + VersioningConfiguration: + Status: Enabled + Metadata: + aws:cdk:path: HelloCdkStack/MyFirstBucket/Resource + CDKMetadata: + Type: AWS::CDK::Metadata + Properties: + Modules: "@aws-cdk/aws-codepipeline-api=VERSION,@aws-cdk/aws-events=VERSION,@aws-c\ + dk/aws-iam=VERSION,@aws-cdk/aws-kms=VERSION,@aws-cdk/aws-s3=VERSION,@aws-c\ + dk/aws-s3-notifications=VERSION,@aws-cdk/cdk=VERSION,@aws-cdk/cx-api=VERSION\ + .0,hello-cdk=0.1.0" +``` + +You can see that the stack contains an `AWS::S3::Bucket` resource with the versioning configuration we want\. + +**Note** +The toolkit automatically added the **AWS::CDK::Metadata** resource to your template\. The CDK uses metadata to gain insight into how the CDK is used\. One possible benefit is that the CDK team could notify users if a construct is going to be deprecated\. For details, including how to [opt out](tools.md#version_reporting_opt_out) of version reporting, see [Version Reporting](tools.md#version_reporting) \. + +## Deploying the Stack + +Deploy the stack, as follows\. + +``` +cdk deploy +``` + +The deploy command synthesizes an AWS CloudFormation template from the stack, and then invokes the AWS CloudFormation create/update API to deploy it into your AWS account\. If your code includes changes to your existing infrastructure, the command displays information about those changes and requires you to confirm them before it deploys the changes\. The command displays information as it completes various steps in the process\. There is no mechanism to detect or react to any specific step in the process\. + +## Modifying the Code + +Configure the bucket to use AWS Key Management Service \(AWS KMS\) managed encryption\. + +------ +#### [ TypeScript ] + +Update `lib/hello-cdk-stack.ts` + +``` +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true, + encryption: s3.BucketEncryption.KmsManaged +}); +``` + +------ +#### [ JavaScript ] + +Update `index.js`\. + +``` +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true, + encryption: s3.BucketEncryption.KmsManaged +}); +``` + +------ +#### [ Java ] + +Update `src/main/java/com/acme/MyStack.java`\. + +``` +new Bucket(this, "MyFirstBucket", BucketProps.builder() + .withVersioned(true) + .withEncryption(BucketEncryption.KmsManaged) + .build()); +``` + +------ +#### [ C\# ] + +Update `MyStack.cs`\. + +``` +new Bucket(this, "MyFirstBucket", new BucketProps +{ + Versioned = true, + Encryption = BucketEncryption.KmsManaged +}); +``` + +------ + +Compile your program, as follows\. + +------ +#### [ TypeScript ] + +``` +npm run build +``` + +------ +#### [ JavaScript ] + +Nothing to compile\. + +------ +#### [ Java ] + +``` +mvn compile +``` + +------ +#### [ C\# ] + +Because we configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command\. + +``` +cdk +``` + +------ + +## Preparing for Deployment + +Before you deploy the updated stack, evaluate the difference between the CDK app and the deployed stack\. + +``` +cdk diff +``` + +The toolkit queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares the result with the template synthesized from the app\. The output should look like the following\. + +``` +Resources +[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 + |- [+] BucketEncryption + |- {"ServerSideEncryptionConfiguration":[{"ServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms"}}]} +``` + +As you can see, the diff indicates that the `ServerSideEncryptionConfiguration` property of the bucket is now set to enable server\-side encryption\. + +You can also see that the bucket isn't going to be replaced, but will be updated instead \(**Updating MyFirstBucketB8884501**\)\. + +Deploy the changes\. + +``` +cdk deploy +``` + +The CDK Toolkit updates the bucket configuration to enable server\-side AWS KMS encryption for the bucket\. + +``` +HelloCdkStack: deploying... +HelloCdkStack: creating CloudFormation changeset... + 0/2 | 10:55:30 AM | UPDATE_IN_PROGRESS | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketB8884501) + 1/2 | 10:55:50 AM | UPDATE_COMPLETE | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketB8884501) + +HelloCdkStack + +Stack ARN: +arn:aws:cloudformation:us-west-2:188580781645:stack/HelloCdkStack/96956990-feff-11e8-9284-50a68a0e3256 +``` + +## Destroying the Stack + +Destroy the stack to avoid incurring any costs from the resources created in this tutorial, as follows\. + +``` +cdk destroy +``` + +In some cases this command fails, such as when a resource isn't empty and must be empty before it can be destroyed\. See [Delete Stack Fails](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#troubleshooting-errors-delete-stack-fails) in the *AWS CloudFormation User Guide* for details\. \ No newline at end of file diff --git a/doc_source/how_to_get_ext_values.md b/doc_source/how_to_get_ext_values.md new file mode 100644 index 00000000..a600244c --- /dev/null +++ b/doc_source/how_to_get_ext_values.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Get External Values in a CDK Application + +The following sections contains short code examples that show you how to get external values in a CDK application\. \ No newline at end of file diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md new file mode 100644 index 00000000..bd532640 --- /dev/null +++ b/doc_source/how_to_set_cw_alarm.md @@ -0,0 +1,41 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Set a CloudWatch Alarm + +The **aws\-cloudwatch** package supports setting CloudWatch alarms on CloudWatch metrics\. The syntax is as follows, where *METRIC* is a CloudWatch metric you have created, and the alarm is raised there are more than 100 of the measured metrics in two of the last three seconds: + +``` +new cloudwatch.Alarm(this, 'Alarm', { + metric: METRIC, + threshold: 100, + evaluationPeriods: 3, + datapointsToAlarm: 2, +}); +``` + +The syntax for creating a metric for a AWS CloudFormation Resource is as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. + +``` +const metric = new cloudwatch.Metric({ + namespace: 'MyNamespace', + metricName: 'MyMetric', + dimensions: { MyDimension: 'MyDimensionValue' } +}); +``` + +Many CDK packages contain an AWS Construct Library construct with functionality to enable setting an alarm based on an existing metric\. For example, you can create an Amazon SQS alarm for the **ApproximateNumberOfMessagesVisible** metric that raises an alarm if the queue has more than 100 messages available for retrieval in two of the last three seconds\. + +``` +const qMetric = queue.metric('ApproximateNumberOfMessagesVisible'); + +new cloudwatch.Alarm(this, 'Alarm', { + metric: qMetric, + threshold: 100, + evaluationPeriods: 3, + datapointsToAlarm: 2, +}); +``` \ No newline at end of file diff --git a/doc_source/how_tos.md b/doc_source/how_tos.md new file mode 100644 index 00000000..f11f4008 --- /dev/null +++ b/doc_source/how_tos.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# AWS CDK HowTos + +This section contains short code examples that show you how to accomplish a task using the AWS CDK\. \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index 70353b76..1741b521 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -1,4 +1,4 @@ -# AWS Cloud Development Kit User Guide +# AWS Cloud Development Kit (CDK) User Guide ----- *****Copyright © 2019 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** @@ -14,25 +14,33 @@ Amazon's trademarks and trade dress may not be used in ----- ## Contents -+ [What Is the AWS Cloud Development Kit?](what-is.md) ++ [What Is the AWS CDK?](what-is.md) + [Installing and Configuring the AWS CDK](install_config.md) -+ [AWS CDK Tutorial](tutorial.md) -+ [AWS CDK Examples](examples.md) - + [Creating a Serverless Application Using the AWS CDK](serverless_example.md) - + [Creating an Amazon ECS Fargate Service Using the AWS CDK](ecs_example.md) -+ [Command-line Toolkit (cdk)](tools.md) ++ [Hello World Tutorial](hello_world_tutorial.md) + [AWS CDK Concepts](concepts.md) - + [Constructs](constructs.md) - + [Stacks](stacks.md) - + [Logical IDs](logical_ids.md) - + [Environments and Authentication](environments.md) - + [Apps](apps.md) - + [Passing in External Values to Your AWS CDK App](passing_in_data.md) - + [Environmental Context](context.md) - + [Assets](assets.md) - + [Applets](applets.md) -+ [AWS Construct Library](aws_construct_lib.md) -+ [AWS AWS CloudFormation Library](cloudformation.md) + + [CDK Core](core_concepts.md) + + [Constructs](constructs.md) + + [Apps and Stacks](apps_and_stacks.md) + + [Logical IDs](logical_ids.md) + + [Environments and Run-Time Context](environments_and_context.md) + + [Assets](assets.md) + + [AWS Construct Library](aws_construct_lib.md) + + [AWS CloudFormation Library](cloudformation.md) + + [Accessing the AWS CloudFormation Layer](cfn_layer.md) ++ [AWS CDK HowTos](how_tos.md) + + [Get External Values in a CDK Application](how_to_get_ext_values.md) + + [Get a Value from a Context Variable](get_context_var.md) + + [Get a Value from an Environment Variable](get_env_var.md) + + [Get a Value from a Systems Manager Parameter Store Variable](get_ssm_value.md) + + [Get a Value from AWS Secrets Manager](passing_secrets_manager.md) + + [Pass in a Value from Another Stack](passing_stack_value.md) + + [Use an AWS CloudFormation Parameter](get_cfn_param.md) + + [Use an Existing AWS CloudFormation Template](use_cfn_template.md) + + [Set a CloudWatch Alarm](how_to_set_cw_alarm.md) + + [Stack How-Tos](stack_how_to.md) ++ [Advanced Tutorials](advanced_tutorials.md) + + [Creating a Serverless Application Using the AWS CDK](serverless_tutorial.md) + + [Creating an AWS Fargate Service Using the AWS CDK](ecs_tutorial.md) ++ [AWS CDK Command Line Toolkit (cdk)](tools.md) + [Writing AWS CDK Constructs](writing_constructs.md) -+ [Document History for the AWS Cloud Development Kit User Guide](doc-history.md) -+ [AWS Glossary](glossary.md) \ No newline at end of file ++ [Document History for the AWS CDK User Guide](doc-history.md) \ No newline at end of file diff --git a/doc_source/install_config.md b/doc_source/install_config.md index b823b29f..31c5f701 100644 --- a/doc_source/install_config.md +++ b/doc_source/install_config.md @@ -1,48 +1,141 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- # Installing and Configuring the AWS CDK -This topic describes how to install and configure the AWS CDK\. +This topic describes how to install the AWS CDK\. ## Prerequisites -You must install [Node\.js \(>= 8\.11\.x\)](https://nodejs.org/en/download) to use the command\-line toolkit and language bindings\. +**CDK command line tools** ++ [Node\.js \(>= 8\.11\.x\)](https://nodejs.org/en/download) ++ You must specify both your credentials and an AWS Region to use the CDK Toolkit;, as described in [Specifying Your Credentials](#credentials)\. -If you use Java, you must set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine to build an AWS CDK app in Java\. +------ +#### [ TypeScript ] -Specify your credentials and region with the [AWS CLI](https://aws.amazon.com/cli)\. You must specify both your credentials and a region to use the toolkit\. See [Configuring the AWS CDK Toolkit](#credentials) for information on using the AWS CLI to specify your credentials\. +TypeScript >= 2\.7 -## Installing the AWS CDK +------ +#### [ JavaScript ] -Install the AWS CDK using the following command: +TypeScript >= 2\.7 + +------ +#### [ Java ] ++ Maven 3\.5\.4 and Java 8 ++ Set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine + +------ +#### [ C\# ] + +TBD + +------ + +## Installing the CDK + +Install the CDK using the following command\. ``` npm install -g aws-cdk ``` -Run the following command to see the currently installed version of the AWS CDK: +Run the following command to see the version number of the CDK\. ``` cdk --version ``` -## Configuring the AWS CDK Toolkit +## Updating Your Language Dependencies + +If you get an error message that your language framework is out of date, use one of the following commands to update the components that the CDK needs to support the lanuage\. + +------ +#### [ TypeScript ] + +``` +npx npm-check-updates -u +``` + +------ +#### [ JavaScript ] + +``` +npx npm-check-updates -u +``` + +------ +#### [ Java ] + +``` +mvn versions:use-latest-versions +``` + +------ +#### [ C\# ] + +``` +nuget update +``` + +------ -Use the AWS CDK toolkit to view the contents of an app\. +## Specifying Your Credentials -**Note** -You must specify your default credentials and region to use the toolkit\. -Use the AWS Command Line Interface aws configure command to specify your default credentials and region\. -You can also set environment variables for your default credentials and region\. Environment variables take precedence over settings in the credentials or config file\. -`AWS_ACCESS_KEY_ID` specifies your access key -`AWS_SECRET_ACCESS_KEY` specifies your secret access key -`AWS_DEFAULT_REGION` specifies your default region -See [Environment Variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-environment.html) in the CLI User Guide for details\. +You must specify your default credentials and AWS Region to use the CDK Toolkit\. You can do that in the following ways: ++ Using the AWS Command Line Interface \(AWS CLI\)\. This is the method we recommend\. ++ Using environment variables\. ++ Using the \-\-profile option to cdk commands\. + +### Using the AWS CLI to Specify Credentials + +Use the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide) aws configure command to specify your default credentials and Region\. + +### Using Environment Variables to Specify Credentials + +You can also set environment variables for your default credentials and Region\. Environment variables take precedence over settings in the credentials or config file\. ++ `AWS_ACCESS_KEY_ID` – Specifies your access key\. ++ `AWS_SECRET_ACCESS_KEY` – Specifies your secret access key\. ++ `AWS_DEFAULT_REGION` – Specifies your default Region\. + +For example, to set the default Region to `us-east-2` on Linux or macOS: + +``` +export AWS_DEFAULT_REGION=us-east-2 +``` + +To do the same on Windows: + +``` +set AWS_DEFAULT_REGION=us-east-2 +``` + +See [Environment Variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-environment.html) in the *AWS Command Line Interface User Guide* for details\. + +### Using the \-\-profile Option to Specify Credentials + +Use the \-\-profile *PROFILE* option to a cdk command to the alternative profile *PROFILE* when executing the command\. + +For example, if the `~/.aws/credentials` \(Linux or Mac\) or `%USERPROFILE%\.aws\credentials` \(Windows\) file contains the following profiles: + +``` +[default] +aws_access_key_id=AKIAIOSFODNN7EXAMPLE +aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY + +[test] +aws_access_key_id=AKIAI44QH8DHBEXAMPLE +aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY +``` + +You can deploy your app using the **test** profile with the following command\. + +``` +cdk deploy --profile test +``` -**Note** -The China regions \(cn\-north\-1 and cn\-northwest\-1\) do not support version reporting\. -See [Version Reporting](tools.md#version_reporting) for details, including how to [opt\-out](tools.md#version_reporting_opt_out)\. \ No newline at end of file +See [Named Profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) in the AWS CLI documentation for details\. \ No newline at end of file diff --git a/doc_source/logical_ids.md b/doc_source/logical_ids.md index 2724d958..6aabe2d3 100644 --- a/doc_source/logical_ids.md +++ b/doc_source/logical_ids.md @@ -1,53 +1,53 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- # Logical IDs -When you synthesize a stack into an AWS CloudFormation template, the AWS CDK assigns a [ logical ID](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html), which must be unique within the template, to each resource in the stack\. +When you synthesize a stack into an AWS CloudFormation template, the CDK assigns a [ logical ID](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html), which must be unique within the template, to each resource in the stack\. **Important** When you update the template, AWS CloudFormation uses these logical IDs to plan the update and apply changes\. Therefore, logical IDs must remain "stable" across updates\. If you make a modification in your code that results in a change to a logical ID of a resource, AWS CloudFormation deletes the resource and creates a new resource when it updates the stack\. -Each resource in the construct tree has a unique path that represents its location within the tree\. Since logical IDs can only use alphanumeric characters and cannot exceed 255 characters, the CDK is unable to simply use a delimited path as the logical ID\. Instead, logical IDs are allocated by concatenating a human\-friendly rendition from the path \(concatenation, de\-duplicate, trim\) with an eight\-character MD5 hash of the delimited path\. This final component is necessary since AWS CloudFormation logical IDs cannot include the delimiting slash character \(/\), so simply concatenating the component values does not work\. For example, concatenating the components of the path */a/b/c* produces **abc**, which is the same as concatenating the components of the path */ab/c*\. +Each resource in the construct tree has a unique path that represents its location within the tree\. Because logical IDs can use only alphanumeric characters and can't exceed 255 characters, the CDK is unable to use a delimited path as the logical ID\. Instead, logical IDs are allocated by concatenating a human\-friendly rendition from the path \(concatenation, de\-duplicate, trim\) with an eight\-character MD5 hash of the delimited path\. This final component is necessary because AWS CloudFormation logical IDs can't include the delimiting slash character \(/\), so simply concatenating the component values doesn't work\. For example, concatenating the components of the path */a/b/c* produces **abc**, which is the same as concatenating the components of the path */ab/c*\. ``` VPCPrivateSubnet2RouteTable0A19E10E <-----------human---------><-hash-> ``` -Low\-level CloudFormation resources \(from `@aws-cdk/resources`\) that are direct children of the [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) class use their name as their logical ID without modification\. This makes it easier to port existing templates into a CDK app\. +Low\-level AWS CloudFormation resources \(from `@aws-cdk/resources`\) that are direct children of the [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) class use their names as their logical IDs without modification\. This makes it easier to port existing templates into a CDK app\. -This scheme ensures that: +This scheme ensures the following\. -Logical IDs have a human\-friendly portion +Logical IDs have a human\-friendly portion\. This is useful when interacting directly with the synthesized AWS CloudFormation template during development and deployment\. -Logical IDs are unique within the stack +Logical IDs are unique within the stack\. This is ensured by the MD5 component, which is based on the absolute path to the resource, which is unique within a stack\. -Logical IDs remain unchanged across updates -This is true as long as their location within the construct tree doesn't change\. +Logical IDs remain unchanged across updates\. +This is true as long as their location within the scope hierarchy doesn't change\. -The AWS CDK applies some heuristics to improve the human\-friendliness of the prefix: -+ If a path component is **Default**, it is hidden completely from the logical ID computation\. You will generally want to use this if you create a new construct that wraps an existing one\. By naming the inner construct **Default**, you ensure that the logical identifiers of resources in already\-deployed copy of that construct do not change\. -+ If a path component is **Resource**, it is omitted from the human readable portion of the logical ID\. This postfix does not normally contribute any additional useful information to the ID\. +The CDK applies some heuristics to improve the human friendliness of the prefix: ++ If a path component is **Default**, it's hidden completely from the logical ID computation\. Typically, you want to use this if you create a new construct that wraps an existing one\. By naming the inner construct **Default**, you ensure that the logical identifiers of resources in already\-deployed copies of that construct don't change\. ++ If a path component is **Resource**, it's omitted from the human\-readable portion of the logical ID\. This postfix doesn't normally contribute any additional useful information to the ID\. + If two subsequent names in the path are the same, only one is retained\. -+ If the prefix exceeds 240 characters, it is trimmed to 240 characters\. This ensures that the total length of the logical ID does not exceed the 255 character AWS CloudFormation limit for logical IDs\. ++ If the prefix exceeds 240 characters, it's trimmed to 240 characters\. This ensures that the total length of the logical ID doesn't exceed the 255 character AWS CloudFormation limit for logical IDs\. ## Renaming Logical IDs -The `aws-cdk.Stack.renameLogical` method can be used to explicitly assign logical IDs to certain resources\. +Use the `aws-cdk.Stack.renameLogical` method to explicitly assign logical IDs to certain resources\. ``` class MyStack extends Stack { - constructor(parent: App, name: string, props: StackProps) { - super(parent, name); + constructor(scope: App, id: string, props: StackProps) { + super(scope, id); - // note that renameLogical must be called /before/ defining the construct. - // a good practice would be to always put these at the top of your stack initializer. + // Note that renameLogical must be called /before/ defining the construct. + // A good practice would be to always put these at the top of your stack initializer. this.renameLogical('MyTableCD117FA1', 'MyTable'); this.renameLogical('MyQueueAB4432A3', 'MyAwesomeQueue'); @@ -57,19 +57,19 @@ class MyStack extends Stack { } ``` -In some cases changing a resource results in a structural change, which results in a different path, thus changing the logical ID of the resource\. +In some cases, changing a resource results in a structural change, which results in a different path\. This changes the logical ID of the resource\. -When a resource's logical ID changes, AWS CloudFormation eventually deletes the old resource and create a new resource, as it cannot determine that the two resources are the same\. Depending on the nature of the resource, this can be disastrous in production, such as when deleting a DynamoDB table\. +When a resource's logical ID changes, AWS CloudFormation eventually deletes the old resource and creates a new resource, as it can't determine that the two resources are the same\. Depending on the nature of the resource, this can be disastrous in production, such as when deleting an Amazon DynamoDB table\. -You could use [AWS CloudFormation Stack Policies](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html) to protect critical resources in your stack from accidental deletion\. Although this AWS CloudFormation feature is not supported in the AWS CDK and AWS CDK Toolkit, the AWS CDK does provide a few other mechanisms to help deal with logical ID changes\. +You could use [AWS CloudFormation stack policies](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html) to protect critical resources in your stack from accidental deletion\. Although this AWS CloudFormation feature isn't supported in the CDK and CDK Toolkit, the CDK does provide a few other mechanisms to help you handle logical ID changes\. -If you have CDK stacks deployed with persistent resources such as S3 buckets or DynamoDB tables, you might want to explicitly "rename" the new logical IDs to match your existing resources\. +If you have CDK stacks deployed with persistent resources, such as Amazon S3 buckets or DynamoDB tables, you might want to explicitly "rename" the new logical IDs to match your existing resources\. -First, make sure you compare the newly synthesized template with any deployed stacks\. `cdk diff` will tell you which resources are about to be destroyed: +First, make sure you compare the newly synthesized template with any deployed stacks\. `cdk diff` will tell you which resources are about to be destroyed\. ``` [-] ☢️ Destroying MyTable (type: AWS::DynamoDB::Table) [+] 🆕 Creating MyTableCD117FA1 (type: AWS::DynamoDB::Table) ``` -Now, you can add a `aws-cdk.Stack.renameLogical` call before the table is defined to rename **MyTableCD117FA1** to **MyTable**\. \ No newline at end of file +Now, you can add an `aws-cdk.Stack.renameLogical` call before the table is defined to rename **MyTableCD117FA1** to **MyTable**\. \ No newline at end of file diff --git a/doc_source/passing_in_data.md b/doc_source/passing_in_data.md deleted file mode 100644 index 523a8c5d..00000000 --- a/doc_source/passing_in_data.md +++ /dev/null @@ -1,215 +0,0 @@ --------- - - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. - --------- - -# Passing in External Values to Your AWS CDK App - -There may be cases where you want to parameterize one or more of your stack resources\. Therefore, you want to be able to pass values into your app from outside your app\. Currently, you can get values into your app from outside your app through any of the following\. -+ Using a context variable -+ Using an environment variable -+ Using an SSM Parameter Store variable -+ Using a Secrets manager value -+ Using a value from another stack -+ Using a AWS CloudFormation parameter -+ Using a resource in an existing AWS CloudFormation template - -Each of these techniques is described in the following sections\. - -## Getting a Value from a Context Variable - -You can specify a context variable either as part of a AWS CDK Toolkit command, or in a **context** section of `cdk.json`\. - -To create a command\-line context variable, use the **\-\-context** \(**\-c**\) option of a AWS CDK Toolkit command, as shown in the following example\. - -``` -cdk synth -c bucket_name=mygroovybucket -``` - -To specify the same context variable and value in *cdk\.json*: - -``` -{ - "context": { - "bucket_name": "myotherbucket" - } -} -``` - -To get the value of a context variable in your app, use code like the following, which gets the value of the context variable **bucket\_name**\. - -``` -const bucket_name string = this.getContext("bucket_name"); -``` - -## Getting a Value from an Environment Variable - -To get the value of an environment variable, use code like the following, which gets the value of the environment variable `MYBUCKET`\. - -``` -const bucket_name = process.env.MYBUCKET; -``` - -## Getting a Value from an SSM Store Variable - -There are three ways to get the value of an SSM parameter store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It is not possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from SecretsManager \(see [Getting a Value from AWS Secrets Manager](#passing_secrets_manager)\)\. - -The first two are not recommended for values that are supposed to be secrets, such as passwords\. - -To retrieve the latest value once \(as a context value, see [Environmental Context](context.md)\), and keep on using the same value until the context value manually refreshed, use a [SSMParameterProvider](@cdk-class-url;#@aws-cdk/cdk.SSMParameterProvider): - -``` -import cdk = require('@amp;aws-cdk/cdk'); - -const myvalue = new cdk.SSMParameterProvider(this).getString("my-parameter-name"); -``` - -To read a particular version of an SSM Parameter Store plain string value at CloudFormation deployment time, use [ssm\.ParameterStoreString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstorestring): - -``` -import ssm = require('@amp;aws-cdk/aws-ssm'); - -const parameterString = new ssm.ParameterStoreString(this, 'MyParameter', { - parameterName: 'my-parameter-name', - version: 1, -}); - -const myvalue = parameterString.value; -``` - -To read a particular version of an SSM Parameter Store SecureString value at CloudFormation deployment time, use [ssm\.ParameterStoreSecureString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstoresecurestring): - -``` -import ssm = require('@amp;aws-cdk/aws-ssm'); - -const secureString = new ssm.ParameterStoreSecureString(this, 'MySecretParameter', { - parameterName: 'my-secret-parameter-name', - version: 1, -}); - -const myvalue = secureString.value; -``` - -## Getting a Value from AWS Secrets Manager - -To use values from AWS Secrets Manager in your CDK app, create an instance of [SecretsManager](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-secretsmanager.html/_aws-cdk_aws-secretsmanager.html#aws-cdk-aws-secretsmanager)\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. - -``` -import secretsmanager = require('@amp;aws-cdk/aws-secretsmanager'); - -const loginSecret = new secretsmanager.SecretString(stack, 'Secret', { - secretId: 'MyLogin' - - // By default, the latest version is retrieved. It's possible to - // use a specific version instead. - // versionStage: 'AWSCURRENT' -}); - -// Retrieve a value from the secret's JSON -const username = loginSecret.jsonFieldValue('username'); -const password = loginSecret.jsonFieldValue('password'); - -// Retrieve the whole secret's string value -const fullValue = loginSecret.value; -``` - -## Passing in a Value From Another Stack - -You can pass a value from one stack to another stack in the same app by using the `export` method in one stack and the `import` method in the other stack\. - -The following example creates a bucket on one stack and passes a reference to that bucket to the other stack through an interface\. - -First create a stack with a bucket\. The stack includes a property we use to pass the bucket's properties to the other stack\. Note how we use the `export` method on the bucket to get its properties and save them in the stack property\. - -``` -class HelloCdkStack extends cdk.Stack { - // Property that defines the stack you are exporting from - public readonly myBucketRefProps: s3.BucketRefProps; - - constructor(parent: cdk.App, name: string, props?: cdk.StackProps) { - super(parent, name, props); - - const mybucket = new s3.Bucket(this, "MyFirstBucket"); - - // Save bucket's BucketRefProps - this.myBucketRefProps = mybucket.export(); - } -} -``` - -Create an interface for the second stack's properties\. We use this interface to pass the bucket properties between the two stacks\. - -``` -// Interface we'll use to pass the bucket's properties to another stack -interface MyCdkStackProps { - theBucketRefProps: s3.BucketRefProps; -} -``` - -Create the second stack that gets a reference to the other bucket from the properties passed in through the constructor\. - -``` -// The class for the other stack -class MyCdkStack extends cdk.Stack { - constructor(parent: cdk.App, name: string, props: MyCdkStackProps) { - super(parent, name); - - const myOtherBucket = s3.Bucket.import(this, "MyOtherBucket", props.theBucketRefProps); - - // Do something with myOtherBucket - } -} -``` - -Finally, connect the dots in your app\. - -``` -const app = new cdk.App(); - -const myStack = new HelloCdkStack(app, "HelloCdkStack"); - -new MyCdkStack(app, "MyCdkStack", { - theBucketRefProps: myStack.myBucketRefProps -}); - -app.run(); -``` - -## Using an AWS CloudFormation Parameter - -See [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for information about using the optional *Parameters* section to customize your AWS CloudFormation templates\. - -You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [AWS CDK Concepts](concepts.md)\. - -## Using an Existing AWS CloudFormation Template - -The AWS CDK provides a mechanism that you can use to incorporate resources from an existing AWS CloudFormation template into your AWS CDK app\. For example, suppose you have a template, `my-template.json`, with the following resource, where **S3Bucket** is the logical ID of the bucket in your template: - -``` -{ - "S3Bucket": { - "Type": "AWS::S3::Bucket", - "Properties": { - "prop1": "value1" - } - } -} -``` - -You can include this bucket in your AWS CDK app, as shown in the following example \(note that you cannot use this method in an AWS Construct Library construct\): - -``` -import cdk = require("@amp;aws-cdk/cdk"); -import fs = require("fs"); - -new cdk.Include(this, "ExistingInfrastructure", { - template: JSON.parse(fs.readFileSync("my-template.json").toString()) -}); -``` - -Then to access an attribute of the resource, such as the bucket's ARN: - -``` -const bucketArn = new cdk.FnGetAtt("S3Bucket", "Arn"); -``` \ No newline at end of file diff --git a/doc_source/passing_secrets_manager.md b/doc_source/passing_secrets_manager.md new file mode 100644 index 00000000..92e9d8a6 --- /dev/null +++ b/doc_source/passing_secrets_manager.md @@ -0,0 +1,28 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Get a Value from AWS Secrets Manager + +To use values from AWS Secrets Manager in your CDK app, create an instance of [SecretsManager](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-secretsmanager.html/_aws-cdk_aws-secretsmanager.html#aws-cdk-aws-secretsmanager)\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. + +``` +import secretsmanager = require('@amp;aws-cdk/aws-secretsmanager'); + +const loginSecret = new secretsmanager.SecretString(stack, 'Secret', { + secretId: 'MyLogin' + + // By default, the latest version is retrieved. It's possible to + // use a specific version instead. + // versionStage: 'AWSCURRENT' +}); + +// Retrieve a value from the secret's JSON +const username = loginSecret.jsonFieldValue('username'); +const password = loginSecret.jsonFieldValue('password'); + +// Retrieve the whole secret's string value +const fullValue = loginSecret.value; +``` \ No newline at end of file diff --git a/doc_source/passing_stack_value.md b/doc_source/passing_stack_value.md new file mode 100644 index 00000000..30f6d4d8 --- /dev/null +++ b/doc_source/passing_stack_value.md @@ -0,0 +1,67 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Pass in a Value from Another Stack + +You can pass a value from one stack to another stack in the same app by using the `export` method in one stack and the `import` method in the other stack\. + +The following example creates a bucket on one stack and passes a reference to that bucket to the other stack through an interface\. + +First create a stack with a bucket\. The stack includes a property we use to pass the bucket's properties to the other stack\. Notice how we use the `export` method on the bucket to get its properties and save them in the stack property\. + +``` +class HelloCdkStack extends cdk.Stack { + // Property that defines the stack you are exporting from + public readonly myBucketImportProps: s3.BucketImportProps; + + constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const mybucket = new s3.Bucket(this, "MyFirstBucket"); + + // Save bucket's BucketImportProps + this.myBucketImportProps = mybucket.export(); + } +} +``` + +Create an interface for the second stack's properties\. We use this interface to pass the bucket properties between the two stacks\. + +``` +// Interface we'll use to pass the bucket's properties to another stack +interface MyCdkStackProps { + theBucketImportProps: s3.BucketImportProps; +} +``` + +Create the second stack that gets a reference to the other bucket from the properties passed in through the constructor\. + +``` +// The class for the other stack +class MyCdkStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props: MyCdkStackProps) { + super(scope, id); + + const myOtherBucket = s3.Bucket.import(this, "MyOtherBucket", props.theBucketImportProps); + + // Do something with myOtherBucket + } +} +``` + +Finally, connect the dots in your app\. + +``` +const app = new cdk.App(); + +const myStack = new HelloCdkStack(app, "HelloCdkStack"); + +new MyCdkStack(app, "MyCdkStack", { + theBucketImportProps: myStack.myBucketImportProps +}); + +app.run(); +``` \ No newline at end of file diff --git a/doc_source/serverless_example.md b/doc_source/serverless_tutorial.md similarity index 56% rename from doc_source/serverless_example.md rename to doc_source/serverless_tutorial.md index cd1ee778..a32c62b3 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_tutorial.md @@ -1,38 +1,36 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- -# Creating a Serverless Application Using the AWS CDK +# Creating a Serverless Application Using the AWS CDK -This example walks you through creating the resources for a simple widget dispensing service\. It includes: -+ An AWS Lambda function -+ An API Gateway API to call our Lambda function -+ An Amazon S3 bucket that contains our Lambda function code +This tutorial walks you through how to create the resources for a simple widget dispensing service\. It includes: ++ An AWS Lambda function\. ++ An Amazon API Gateway API to call the Lambda function\. ++ An Amazon S3 bucket that contains the Lambda function code\. -## Overview +This tutorial contains the following steps\. -This example contains the following steps\. +1. Creates a CDK app -1. Create a AWS CDK app +1. Creates a Lambda function that gets a list of widgets with: GET / -1. Create a Lambda function that gets a list of widgets with: GET / +1. Creates the service that calls the Lambda function -1. Create the service that calls the Lambda function +1. Adds the service to the CDK app -1. Add the service to the AWS CDK app +1. Tests the app -1. Test the app +1. Add Lambda functions to do the following: + + Create a widget with POST /\{name\} + + Get a widget by name with GET /\{name\} + + Delete a widget by name with DELETE /\{name\} -1. Add Lambda functions to: - + create an widget based with: POST /\{name\} - + get an widget by name with: GET /\{name\} - + delete an widget by name with: DELETE /\{name\} +## Create a CDK App -## Create an AWS CDK App - -Create the TypeScript app **MyWidgetService** in in the current folder\. +Create the TypeScript app **MyWidgetService** in the current folder\. ``` mkdir MyWidgetService @@ -40,9 +38,9 @@ cd MyWidgetService cdk init --language typescript ``` -This creates `my_widget_service.ts` in the `bin` directory and `my_widget_service-stack.ts` in the `lib` directory\. +This creates `my_widget_service.ts` in the `bin` directory, and `my_widget_service-stack.ts` in the `lib` directory\. -Build it and note that it creates an empty stack\. +Build the app and notice that it creates an empty stack\. ``` npm run build @@ -59,17 +57,17 @@ Resources: Modules: "@aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_widget_service=0.1.0" ``` -## Create a Lambda Function to List all Widgets +## Create a Lambda Function to List All Widgets The next step is to create a Lambda function to list all of the widgets in our Amazon S3 bucket\. -Create the directory `resources` at the same level as the bin directory\. +Create the `resources` directory at the same level as the `bin` directory\. ``` mkdir resources ``` -Create the following Javascript file, `widgets.js`, in the `resources` directory\. +Create the following JavaScript file, `widgets.js`, in the `resources` directory\. ``` const AWS = require('aws-sdk'); @@ -112,22 +110,22 @@ exports.main = async function(event, context) { } ``` -Save it and make sure it builds and creates an empty stack\. Note that since we haven't wired the function to our app, the Lambda file does not appear in the output\. +Save it and be sure it builds and creates an empty stack\. Because we haven't wired the function to the app, the Lambda file doesn't appear in the output\. ``` npm run build cdk synth ``` -## Creating a Widget Service +## Creating a Widget Service -Add the API Gateway, Lambda, and Amazon S3 packages to our app\. +Add the API Gateway, Lambda, and Amazon S3 packages to the app\. ``` npm install @aws-cdk/aws-apigateway @aws-cdk/aws-lambda @aws-cdk/aws-s3 ``` -Create the Typescript file `widget_service.ts` in the `lib` directory\. +Create the TypeScript file `widget_service.ts` in the `lib` directory\. ``` import cdk = require('@aws-cdk/cdk'); @@ -136,51 +134,61 @@ import lambda = require('@aws-cdk/aws-lambda'); import s3 = require('@aws-cdk/aws-s3'); export class WidgetService extends cdk.Construct { - constructor(parent: cdk.Construct, name: string) { - super(parent, name); + constructor(scope: cdk.Construct, id: string) { + super(scope, id); - // Use S3 bucket to store our widgets const bucket = new s3.Bucket(this, 'WidgetStore'); - // Create a handler that calls the function main - // in the source file widgets(.js) in the resources directory - // to handle requests through API Gateway const handler = new lambda.Function(this, 'WidgetHandler', { - runtime: lambda.Runtime.NodeJS810, + runtime: lambda.Runtime.NodeJS810, // So we can use async in widget.js code: lambda.Code.directory('resources'), handler: 'widgets.main', environment: { - BUCKET: bucket.bucketName // So runtime has the bucket name + BUCKET: bucket.bucketName } }); bucket.grantReadWrite(handler.role); - // Create an API Gateway REST API const api = new apigateway.RestApi(this, 'widgets-api', { restApiName: 'Widget Service', description: 'This service serves widgets.' }); - // Pass the request to the handler - const getWidgetsIntegration = new apigateway.LambdaIntegration(handler); + const getWidgetsIntegration = new apigateway.LambdaIntegration(handler, { + requestTemplates: { "application/json": '{ "statusCode": "200" }' } + }); - // Use the getWidgetsIntegration when there is a GET request api.root.addMethod('GET', getWidgetsIntegration); // GET / + + const widget = api.root.addResource('{id}'); + + // Add new widget to bucket with: POST /{id} + const postWidgetIntegration = new apigateway.LambdaIntegration(handler); + + // Get a specific widget from bucket with: GET /{id} + const getWidgetIntegration = new apigateway.LambdaIntegration(handler); + + // Remove a specific widget from the bucket with: DELETE /{id} + const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); + + widget.addMethod('POST', postWidgetIntegration); // POST /{id} + widget.addMethod('GET', getWidgetIntegration); // GET /{id} + widget.addMethod('DELETE', deleteWidgetIntegration); // DELETE /{id} } } ``` -Save it and make sure it builds and creates a \(still empty\) stack\. +Save the app and be sure it builds and creates a \(still empty\) stack\. ``` npm run build cdk synth ``` -## Add the Service to the App +## Add the Service to the App -To add the service to our app, we need to first modify `my_widget_service-stack.ts`\. Add the following line of code after the existing **import** statement\. +To add the service to the app, first modify `my_widget_service-stack.ts`\. Add the following line of code after the existing `import` statement\. ``` import widget_service = require('../lib/widget_service'); @@ -189,57 +197,63 @@ import widget_service = require('../lib/widget_service'); Replace the comment in the constructor with the following line of code\. ``` -new widget_service.WidgetService(this, 'Widgets'); + new widget_service.WidgetService(this, 'Widgets'); ``` -Make sure it builds and creates a stack \(we don't show the stack as it's over 250 lines\)\. +Be sure the app builds and creates a stack \(we don't show the stack because it's over 250 lines\)\. ``` npm run build cdk synth ``` -## Deploy and Test the App +## Deploy and Test the App -Before you can deploy your first AWS CDK app, you must bootstrap your deployment, which creates some AWS infracture that the AWS CDK needs\. See the **bootstrap** section of [Command\-line Toolkit \(cdk\)](tools.md) for details \(you'll get a warning and nothing changes if you have already bootstrapped an AWS CDK app\)\. +Before you can deploy your first CDK app, you must bootstrap your deployment\. This creates some AWS infrastructure that the CDK needs\. For details, see the **bootstrap** section of the [AWS CDK Command Line Toolkit \(cdk\)](tools.md)\(if you've already bootstrapped a CDK app, you'll get a warning and nothing will change\)\. ``` cdk bootstrap ``` -Deploy your app: +Deploy your app, as follows\. ``` cdk deploy ``` -If the deployment is successfull, save the URL for your server, which appears in one of the last lines in the window, where *GUID* is an alpha\-numeric GUID and *REGION* is your region\. +If the deployment succeeds, save the URL for your server\. This URL appears in one of the last lines in the window, where *GUID* is an alphanumeric GUID and *REGION* is your AWS Region\. ``` https://GUID.execute-REGION.amazonaws.com/prod/ ``` -You can test your app by getting the list of widgets \(currently empty\) by navigating to this URL in a browser or use the following command\. +Test your app by getting the list of widgets \(currently empty\) by navigating to this URL in a browser, or use the following command\. ``` curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' ``` You can also test the app by: -+ Opening the AWS Management Console -+ Navigating to the API Gateway service -+ Finding **Widget Service** in the list -+ Selecting **GET** and **Test** to test the function\. -Since we haven't stored any widgets yet, the output should be similar to the following\. +1. Opening the AWS Management Console\. + +1. Navigating to the API Gateway service\. + +1. Finding **Widget Service** in the list\. + +1. Selecting **GET** and **Test** to test the function\. + +Because we haven't stored any widgets yet, the output should be similar to the following\. ``` { "widgets": [] } ``` -## Add the Individual Widget Functions +## Add the Individual Widget Functions + +The next step is to create Lambda functions to create, show, and delete individual widgets\. -The next step is to create Lambda functions to create, show, and delete individual widgets\. Replace the existing `exports.main` function in `widgets.js` with the following code\. +Replace the existing `exports.main` function in `widgets.js` with the following code\. ``` exports.main = async function(event, context) { @@ -345,7 +359,7 @@ exports.main = async function(event, context) { } ``` -Wire these functions up to our API Gateway code in `widget_service.ts` by adding the following code at the end of the constructor\. +Wire up these functions to your API Gateway code in `widget_service.ts` by adding the following code at the end of the constructor\. ``` const widget = api.root.addResource('{name}'); @@ -371,15 +385,15 @@ npm run build cdk deploy ``` -We can now store, show, or delete an individual widget\. Use the following commands to list the widgets, create the widget **dummy**, list all of the widgets, show the contents of **dummy** \(it should show today's date\), and delete **dummy**, and again show the list of widgets\. +We can now store, show, or delete an individual widget\. Use the following commands to list the widgets, create the widget **example**, list all of the widgets, show the contents of **example** \(it should show today's date\), delete **example**, and then show the list of widgets again\. ``` curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' -curl -X POST 'https://GUID.execute-REGION.amazonaws.com/prod/dummy' +curl -X POST 'https://GUID.execute-REGION.amazonaws.com/prod/example' curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' -curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod/dummy' -curl -X DELETE 'https://GUID.execute-REGION.amazonaws.com/prod/dummy' +curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod/example' +curl -X DELETE 'https://GUID.execute-REGION.amazonaws.com/prod/example' curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' ``` -You can also use the API Gateway console to test these functions\. You'll have to set the **name** entry to the name of an widget, such as **dummy**\. \ No newline at end of file +You can also use the API Gateway console to test these functions\. You have to set the **name** value to the name of a widget, such as **example**\. \ No newline at end of file diff --git a/doc_source/stack_how_to.md b/doc_source/stack_how_to.md new file mode 100644 index 00000000..06f99949 --- /dev/null +++ b/doc_source/stack_how_to.md @@ -0,0 +1,76 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Stack How\-Tos + +This section contains some additional information about using stacks, including how to create a stack in a specific region with a specific account ID, and creating an app with multiple stacks\. For conceptual information about stacks, see [Stacks](apps_and_stacks.md#stacks)\. + +## Create a Stack with an Account and Region + +The following example shows how to create a stack in `us-west-1` for the account with ID `11223344`\. + +``` +new HelloStack(this, 'hello-cdk-us-west-1', { + env: { + account: '11223344', + region: 'us-west-1' +}}); +``` + +## Create an App with Multiple Stacks + +The following example shows one solution to parameterizing how you create a stack\. It creates one stack with a `t2.micro` AMI for development, and three stacks with the more expensive `c5.2xlarge` AMI\. The development stack and one of the production stacks use the same account to create the stack in `us-east-1`; the other two production stacks use different account IDs and regions\. + +``` +// lib/mystack.ts +// Defines my parameterized application which can be deployed anywhere. +// If dev is true, the stack is used for development, +// so it does not require the more expensive AMI. +interface MyStackProps extends cdk.StackProps { + dev: boolean; +} + +class MyStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props: MyStackProps) { + super(scope, id, props); + + const instanceType = props.dev + ? new ec.InstanceType('t2.micro') + : new ec.InstanceType('c5.2xlarge'); + + const fleet new MyComputeFleet(this, 'Fleet', { + instanceType, }); + + const queue = new sqs.Queue(this, 'Queue'); + queue.grantConsumeMessages(fleet.role); + } +} + +// bin/myapp.ts +const app = new cdk.App(); + +// Specify where MyStack instances are deployed +// and under what account. +const environments = [ + { account: '12345678', region: 'us-east-1' }, + { account: '87654321', region: 'eu-west-1' }, + { account: '12344321', region: 'ap-southeast-1' }, +]; + +// Beta instance in the first environment +new MyStack(app, 'BetaStack', { dev: true, env: environments[0] }); + +// Production instance in every other environment +for (const env of environments) { + new MyStack(app, `ProdStack-${env.region}`, { dev: false, env }); +} +``` + +The following example shows how to deploy a production stack using the `c5.2xlarge` AMI to the `us-east-1` region\. + +``` +cdk deploy ProdStack-us-east-1 +``` \ No newline at end of file diff --git a/doc_source/stacks.md b/doc_source/stacks.md deleted file mode 100644 index e8de6bbe..00000000 --- a/doc_source/stacks.md +++ /dev/null @@ -1,38 +0,0 @@ --------- - - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. - --------- - -# Stacks - -A [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) is an AWS CDK construct that can be deployed into an AWS environment\. The combination of region and account becomes the stack's *environment*, as described in [Environments and Authentication](environments.md)\. Most production apps consist of multiple stacks of resources that are deployed as a single transaction using a resource provisioning service like AWS CloudFormation\. Any resources added directly or indirectly as children of a stack are included in the stack's template as it is synthesized by your AWS CDK program\. - -Define an application stack by extending the [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) class, as shown in the following example\. - -``` -import { Stack, StackProps } from '@aws-cdk/cdk' - -interface MyStackProps extends StackProps { - encryptedStorage: boolean; -} - -class MyStack extends Stack { - constructor(parent: Construct, name: string, props?: MyStackProps) { - super(parent, name, props); - - new MyStorageLayer(this, 'Storage', { encryptedStorage: props.encryptedStorage }); - new MyControlPlane(this, 'CPlane'); - new MyDataPlane(this, 'DPlane'); - } -} -``` - -And then, add instances of this class to your app: - -``` -const app = new App(); - -new MyStack(app, 'NorthAmerica', { env: { region: 'us-east-1' } }); -new MyStack(app, 'Europe', { env: { region: 'us-west-2' } }); -``` \ No newline at end of file diff --git a/doc_source/tools.md b/doc_source/tools.md index e96f7c93..7564532b 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -1,20 +1,20 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- -# Command\-line Toolkit \(cdk\) +# AWS CDK Command Line Toolkit \(cdk\) -cdk \(the AWS CDK Toolkit\) is the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you have written and compiled, interrogates the application model you have defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. +The CDK Toolkit, cdk, is the main tool you use to interact with your CDK app\. It executes the CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the CDK\. -There are two ways that you can tell cdk what command to use to run your AWS CDK app\. The first way is to include an explicit \-\-app option whenever you use a cdk command: +There are two ways to tell cdk what command to use to run your CDK app\. The first way is to include an explicit \-\-app option whenever you use a cdk command\. ``` cdk --app 'node bin/main.js' synth ``` -The second way is to add the following entry to the file `cdk.json`: +The second way is to add the following entry to the `cdk.json` file\. ``` { @@ -22,7 +22,7 @@ The second way is to add the following entry to the file `cdk.json`: } ``` -Here are the actions you can take on your CDK app \(this is the output of the cdk \-\-help command\): +Here are the actions you can take on your CDK app \(this is the output of the cdk \-\-help command\)\. ``` Usage: cdk -a COMMAND @@ -36,43 +36,51 @@ Commands: deploy [STACKS..] Deploys the stack(s) named STACKS into your AWS account destroy [STACKS..] Destroy the stack(s) named STACKS - diff [STACK] Compares the specified stack with the deployed - stack or a local template file + diff [STACKS..] Compares the specified stack with the deployed + stack or a local template file, and returns with + status 1 if any difference is found metadata [STACK] Returns all metadata associated with this stack init [TEMPLATE] Create a new, empty CDK project from a template. Invoked without TEMPLATE, the app template will be used. context Manage cached context values - docs Opens the documentation in a browser[aliases: doc] + docs Opens the reference documentation in a browser + [aliases: doc] doctor Check your set-up for potential problems Options: - --app, -a REQUIRED: Command-line for executing your CDK app (e.g. - "node bin/my-app.js") [string] - --context, -c Add contextual string parameter. [array] - --plugin, -p Name or path of a node package that extend the CDK - features. Can be specified multiple times [array] - --rename Rename stack name if different then the one defined in - the cloud executable [string] - --trace Print trace for stack warnings [boolean] - --strict Do not construct stacks with warnings [boolean] - --ignore-errors Ignores synthesis errors, which will likely produce an - invalid output [boolean] [default: false] - --json, -j Use JSON output instead of YAML [boolean] - --verbose, -v Show debug logs [boolean] - --profile Use the indicated AWS profile as the default environment + --app, -a REQUIRED: Command-line for executing your CDK app (e.g. + "node bin/my-app.js") [string] + --context, -c Add contextual string parameter. [array] + --plugin, -p Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] + --rename Rename stack name if different from the one defined in + the cloud executable [string] + --trace Print trace for stack warnings [boolean] + --strict Do not construct stacks with warnings [boolean] + --ignore-errors Ignores synthesis errors, which will likely produce an + invalid output [boolean] [default: false] + --json, -j Use JSON output instead of YAML [boolean] + --verbose, -v Show debug logs [boolean] + --profile Use the indicated AWS profile as the default environment [string] - --proxy Use the indicated proxy. Will read from HTTPS_PROXY - environment variable if not specified. [string] - --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: - guess EC2 instance status. [boolean] - --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized - templates (enabled by default) [boolean] - --path-metadata Include "aws:cdk:path" CloudFormation metadata for each - resource (enabled by default) [boolean] [default: true] - --role-arn, -r ARN of Role to use when invoking CloudFormation [string] - --version Show version number [boolean] - -h, --help Show help [boolean] + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified. [string] + --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: + guess EC2 instance status. [boolean] + --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized + templates (enabled by default) [boolean] + --path-metadata Include "aws:cdk:path" CloudFormation metadata for each + resource (enabled by default) [boolean] [default: true] + --asset-metadata Include "aws:asset:*" CloudFormation metadata for + resources that user assets (enabled by default) + [boolean] [default: true] + --role-arn, -r ARN of Role to use when invoking CloudFormation [string] + --toolkit-stack-name The name of the CDK toolkit stack [string] + --ci Force CI detection. Use --no-ci to disable CI + autodetection. [boolean] [default: false] + --version Show version number [boolean] + -h, --help Show help [boolean] If your app has a single stack, there is no need to specify the stack name @@ -80,13 +88,19 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -If your app has a single stack, there is no need to specify the stack name\. +If your app has a single stack, you don't have to specify the stack name\. -If one of `cdk.json` or `~/.cdk.json` exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. +If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. -## Security\-related changes +## Bootstrapping the CDK -In order to protect you against unintended changes that affect your security posture, the CDK toolkit will prompt you to approve security\-related changes before deploying them\. +Before you can use the CDK you must bootstrap the CDK to create the infrastructure that the CDK needs\. Currently the bootstrap command creates only an Amazon S3 bucket\. + +You incur any charges for what the CDK stores in the bucket\. Because the CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. + +## Security\-Related Changes + +To protect you against unintended changes that affect your security posture, the CDK toolkit prompts you to approve security\-related changes before deploying them\. You change the level of changes that requires approval by specifying: @@ -94,7 +108,7 @@ You change the level of changes that requires approval by specifying: cdk deploy --require-approval LEVEL ``` -Where *LEVEL* can be one of: +Where *LEVEL* can be one of the following: never Approval is never required\. @@ -103,9 +117,9 @@ any\-change Requires approval on any IAM or security\-group related change\. broadening -\(default\) Requires approval when IAM statements or traffic rules are added\. Removals do not require approval\. +\(default\) Requires approval when IAM statements or traffic rules are added\. Removals don't require approval\. -The setting also be configured in `cdk.json`: +The setting can also be configured in the `cdk.json` file\. ``` { @@ -116,11 +130,11 @@ The setting also be configured in `cdk.json`: ## Version Reporting -In order to gain insights in how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported using a resource identified as `AWS::CDK::Metadata` that is added to AWS CloudFormation templates, and can easily be reviewed\. This information may also be used to identify stacks using a package with known serious security or reliability issues and contact their users with important information\. +To gain insight into how the CDK is used, the versions of libraries used by CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. -The AWS CDK reports the name and version of npm modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. +The CDK reports the name and version of `npm` modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. -The `AWS::CDK::Metadata` resource looks like the following: +The `AWS::CDK::Metadata` resource looks like the following\. ``` CDKMetadata: @@ -129,15 +143,15 @@ CDKMetadata: Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,lodash=4.17.10" ``` -## Opting\-out from Version Reporting +## Opting Out from Version Reporting -To out\-out, use one of the following methods: -+ Use the cdk command with the the `--no-version-reporting` argument: +To opt out of version reporting, use one of the following methods: ++ Use the cdk command with the \-\-no\-version\-reporting argument\. ``` cdk --no-version-reporting synth ``` -+ Set `versionReporting` to **false** in `./cdk.json` or `~/cdk.json`: ++ Set versionReporting to **false** in `./cdk.json` or `~/cdk.json`\. ``` { @@ -148,18 +162,18 @@ To out\-out, use one of the following methods: ## Plugins -The AWS CDK toolkit provides extension points that enable users to augment the features provided by the toolkit\. There is currently only one extension point, allowing users to define custom AWS credential providers, but other extension points may be added in the future as the needs arise\. +The CDK Toolkit provides extension points that enable users to augment the features provided by the toolkit\. There is currently only one extension point, allowing users to define custom AWS credential providers, but other extension points may be added in the future as needed\. ### Loading Plugins -Plugins can be loaded by providing the Node module name \(or path\) to the AWS CDK toolkit: -+ Using the `--plugin` command line option, which can be specified multiple times: +Plugins can be loaded by providing the Node module name \(or path\) to the CDK Toolkit: ++ Using the \-\-plugin command line option, which can be specified multiple times\. ``` cdk list --plugin=module cdk deploy --plugin=module_1 --plugin=module_2 ``` -+ Adding entries to the `~/.cdk.json` or `cdk.json` file: ++ Adding entries to the `~/.cdk.json` or `cdk.json` file\. ``` { @@ -174,7 +188,7 @@ Plugins can be loaded by providing the Node module name \(or path\) to the AWS C ### Authoring Plugins -Plugins must be authored in TypeScript or Javascript, and are defined by implementing a Node module that implements the following protocol, and using [PluginHost\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost) methods: +Plugins must be authored in TypeScript or JavaScript, and are defined by implementing a Node\.js module that implements the following protocol, and using [PluginHost\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost) methods\. ------ #### [ TypeScript ] @@ -186,7 +200,7 @@ export = { version: '1', // Version of the plugin infrastructure (currently always '1') init(host: cdk.PluginHost): void { // Your plugin initialization hook. - // Use methods of host to register custom code with the CDK toolkit + // Use methods of host to register custom code with the CDK Toolkit. } }; ``` @@ -199,7 +213,7 @@ export = { version: '1', // Version of the plugin infrastructure (currently always '1') init(host) { // Your plugin initialization hook. - // Use methods of host to register custom code with the CDK toolkit + // Use methods of host to register custom code with the CDK Toolkit. } }; ``` @@ -208,7 +222,7 @@ export = { ### Credential Provider Plugins -Custom credential providers are classes implementing the [CredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.CredentialProviderSource) interface, and registered to the toolkit using the [registerCredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost.registerCredentialProviderSource) method\. +Custom credential providers are classes that implement the [CredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.CredentialProviderSource) interface, and that are registered to the toolkit using the [registerCredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost.registerCredentialProviderSource) method\. ------ #### [ TypeScript ] @@ -226,7 +240,7 @@ class CustomCredentialProviderSource implements cdk.CredentialProviderSource { public async canProvideCredentials(accountId: string): Promise { // Return false if the plugin is unable to provide credentials for the - // requested account (for example if it's not managed by the credentials + // requested account (for example, if it's not managed by the credentials // system that this plugin adds support for). return true; } @@ -283,4 +297,4 @@ export = { ------ -Note that the credentials obtained from the providers for a given account and mode will be cached, and as a consequence it is strongly advised that the credentials objects returned are self\-refreshing, as descibed in the [AWS SDK for Javascript](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html) documentation\. \ No newline at end of file +Note that the credentials obtained from the providers for a given account and mode will be cached, and as a consequence, we strongly advise that the credentials objects that are returned are self\-refreshing, as described in the [AWS SDK for JavaScript](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html) documentation\. \ No newline at end of file diff --git a/doc_source/tutorial.md b/doc_source/tutorial.md deleted file mode 100644 index 0e3a3479..00000000 --- a/doc_source/tutorial.md +++ /dev/null @@ -1,440 +0,0 @@ --------- - - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. - --------- - -# AWS CDK Tutorial - -This topic walks you through creating and deploying an AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. - -## Creating the Project - -Create a directory for your project with an empty Git repository\. - -``` -mkdir hello-cdk -cd hello-cdk -``` - -## Initializing the Project - -Initialize an empty project, where *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), or **typescript** \(TypeScript\)\. - -``` -cdk init --language LANGUAGE -``` - -## Compiling the Project - -Compile your program: - ------- -#### [ C\# ] - -Since configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command: - -``` -cdk -``` - ------- -#### [ JavaScript ] - -Nothing to compile\. - ------- -#### [ TypeScript ] - -``` -npm run build -``` - ------- -#### [ Java ] - -``` -mvn compile -``` - ------- - -## Listing the Stacks in the App - -List the stacks in the app\. - -``` -cdk ls -``` - -The result is just the name of the stack: - -``` -HelloCdkStack -``` - -**Note** -There is a known issue on Windows with the AWS CDK \.NET environment\. Whenever you use a cdk command, it issues a node warning similar to the following: - -``` -(node:27508) UnhandledPromiseRejectionWarning: Unhandled promise rejection -(rejection id: 1): Error: EPIPE: broken pipe, write -(node:27508) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. -In the future, promise rejections that are not handled will terminate the -Node.js process with a non-zero exit code. -``` - -You can safely ignore this warning\. - -## Adding an Amazon S3 Bucket - -What can you do with this app? Nothing\. Since the stack is empty, there's nothing to deploy\. Let's define an Amazon S3 bucket\. - -Install the `@aws-cdk/aws-s3` package: - ------- -#### [ C\# ] - -``` -dotnet add package Amazon.CDK.AWS.S3 -``` - ------- -#### [ JavaScript ] - -``` -npm install @aws-cdk/aws-s3 -``` - ------- -#### [ TypeScript ] - -``` -npm install @aws-cdk/aws-s3 -``` - ------- -#### [ Java ] - -Add the following to `pom.xml`, where *CDK\-VERSION* is the version of the AWS CDK: - -``` - - software.amazon.awscdk - s3 - CDK-VERSION - -``` - ------- - -Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represented by the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.Bucket) class: - ------- -#### [ C\# ] - -Create `MyStack.cs`: - -``` -using Amazon.CDK; -using Amazon.CDK.AWS.S3; - -namespace HelloCdk -{ - public class MyStack : Stack - { - public MyStack(App parent, string name) : base(parent, name, null) - { - new Bucket(this, "MyFirstBucket", new BucketProps - { - Versioned = true - }); - } - } -} -``` - ------- -#### [ JavaScript ] - -In `index.js`: - -``` -const cdk = require('@aws-cdk/cdk'); -const s3 = require('@aws-cdk/aws-s3'); - -class MyStack extends cdk.Stack { - constructor(parent, id, props) { - super(parent, id, props); - - new s3.Bucket(this, 'MyFirstBucket', { - versioned: true - }); - } -} -``` - ------- -#### [ TypeScript ] - -In `lib/hello-cdk-stack.ts`: - -``` -import cdk = require('@aws-cdk/cdk'); -import s3 = require('@aws-cdk/aws-s3'); - -export class HelloCdkStack extends cdk.Stack { - constructor(parent: cdk.App, id: string, props?: cdk.StackProps) { - super(parent, id, props); - - new s3.Bucket(this, 'MyFirstBucket', { - versioned: true - }); - } -} -``` - ------- -#### [ Java ] - -In `src/main/java/com/acme/MyStack.java`: - -``` -package com.acme; - -import software.amazon.awscdk.App; -import software.amazon.awscdk.Stack; -import software.amazon.awscdk.StackProps; -import software.amazon.awscdk.services.s3.Bucket; -import software.amazon.awscdk.services.s3.BucketProps; - -public class MyStack extends Stack { - public MyStack(final App parent, final String name) { - this(parent, name, null); - } - - public MyStack(final App parent, final String name, final StackProps props) { - super(parent, name, props); - - new Bucket(this, "MyFirstBucket", BucketProps.builder() - .withVersioned(true) - .build()); - } -} -``` - ------- - -A few things to notice: -+ [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.Bucket) is a construct\. This means it's initialization signature has **parent**, **id**, and **props**\. In this case, the bucket is an immediate child of **MyStack**\. -+ `MyFirstBucket` is the **logical id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. See [Logical IDs](logical_ids.md) for information on logical IDs\. To specify a physical name for your bucket, set the [bucketName](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketProps.bucketName) property when you define your bucket\. -+ Since the bucket's [versioned](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. - -Compile your program: - ------- -#### [ C\# ] - -Since configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command: - -``` -cdk -``` - ------- -#### [ JavaScript ] - -Nothing to compile\. - ------- -#### [ TypeScript ] - -``` -npm run build -``` - ------- -#### [ Java ] - -``` -mvn compile -``` - ------- - -## Synthesizing an AWS CloudFormation Template - -Synthesize a AWS CloudFormation template for the stack: - -``` -cdk synth HelloCdkStack -``` - -**Note** -Since the AWS CDK app only contains a single stack, you can omit `HelloCdkStack`\. - -This command executes the AWS CDK app and synthesize an AWS CloudFormation template for the **HelloCdkStack** stack\. You should see something similar to the following, where *VERSION* is the version of the AWS CDK\. - -``` -Resources: - MyFirstBucketB8884501: - Type: AWS::S3::Bucket - Properties: - VersioningConfiguration: - Status: Enabled - Metadata: - aws:cdk:path: HelloCdkStack/MyFirstBucket/Resource - CDKMetadata: - Type: AWS::CDK::Metadata - Properties: - Modules: "@aws-cdk/aws-codepipeline-api=VERSION,@aws-cdk/aws-events=VERSION,@aws-c\ - dk/aws-iam=VERSION,@aws-cdk/aws-kms=VERSION,@aws-cdk/aws-s3=VERSION,@aws-c\ - dk/aws-s3-notifications=VERSION,@aws-cdk/cdk=VERSION,@aws-cdk/cx-api=VERSION\ - .0,hello-cdk=0.1.0" -``` - -You can see that the stack contains an **AWS::S3::Bucket** resource with the desired versioning configuration\. - -**Note** -The **AWS::CDK::Metadata** resource was automatically added to your template by the toolkit\. This allows us to learn which libraries were used in your stack\. See [Version Reporting](tools.md#version_reporting) for details, including how to [opt out](tools.md#version_reporting_opt_out)\. - -## Deploying the Stack - -Deploy the stack: - -``` -cdk deploy -``` - -The deploy command synthesizes an AWS CloudFormation template from the stack and then invokes the AWS CloudFormation create/update API to deploy it into your AWS account\. The command displays information as it progresses\. - -## Modifying the Code - -Configure the bucket to use KMS managed encryption: - ------- -#### [ C\# ] - -Update `MyStack.cs`: - -``` -new Bucket(this, "MyFirstBucket", new BucketProps -{ - Versioned = true, - Encryption = BucketEncryption.KmsManaged -}); -``` - ------- -#### [ JavaScript ] - -Update `index.js`: - -``` -new s3.Bucket(this, 'MyFirstBucket', { - versioned: true, - encryption: s3.BucketEncryption.KmsManaged -}); -``` - ------- -#### [ TypeScript ] - -Update `lib/hello-cdk-stack.ts` - -``` -new s3.Bucket(this, 'MyFirstBucket', { - versioned: true, - encryption: s3.BucketEncryption.KmsManaged -}); -``` - ------- -#### [ Java ] - -Update `src/main/java/com/acme/MyStack.java` - -``` -new Bucket(this, "MyFirstBucket", BucketProps.builder() - .withVersioned(true) - .withEncryption(BucketEncryption.KmsManaged) - .build()); -``` - ------- - -Compile your program: - ------- -#### [ C\# ] - -Since configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command: - -``` -cdk -``` - ------- -#### [ JavaScript ] - -Nothing to compile\. - ------- -#### [ TypeScript ] - -``` -npm run build -``` - ------- -#### [ Java ] - -``` -mvn compile -``` - ------- - -## Preparing for Deployment - -Before you deploy the updated stack, evaluate the difference between the AWS CDK app and the deployed stack: - -``` -cdk diff -``` - -The toolkit queries your AWS account for the current AWS CloudFormation template for the **hello\-cdk** stack, and compares the result with the template synthesized from the app\. The output should look like the following: - -``` -[~] 🛠 Updating MyFirstBucketB8884501 (type: AWS::S3::Bucket) -└─ [+] .BucketEncryption: - └─ New value: {"ServerSideEncryptionConfiguration":[{"ServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms"}}]} -``` - -As you can see, the diff indicates that the `ServerSideEncryptionConfiguration` property of the bucket is now set to enable server\-side encryption\. - -You can also see that the bucket is not going to be replaced but rather updated \(**Updating MyFirstBucketB8884501**\)\. - -Update the stack: - -``` -cdk deploy -``` - -The toolkit updates the bucket configuration to enable server\-side KMS encryption for the bucket: - -``` -⏳ Starting deployment of stack hello-cdk... - [ 0/2 ] UPDATE_IN_PROGRESS [AWS::S3::Bucket ] MyFirstBucketB8884501 - [ 1/2 ] UPDATE_COMPLETE [AWS::S3::Bucket ] MyFirstBucketB8884501 - [ 1/2 ] UPDATE_COMPLETE_CLEANUP_IN_PROGRESS [AWS::CloudFormation::Stack ] hello-cdk - [ 2/2 ] UPDATE_COMPLETE [AWS::CloudFormation::Stack ] hello-cdk -✅ Deployment of stack hello-cdk completed successfully -``` - -## What Next? -+ Learn more about [AWS CDK Concepts](concepts.md) -+ Check out the [examples directory](https://github.com/awslabs/aws-cdk/tree/master/examples) in your GitHub repository -+ Learn about the rich APIs offered by the [AWS Construct Library](aws_construct_lib.md) -+ Work directly with CloudFormation using the [AWS AWS CloudFormation Library](cloudformation.md) -+ Come talk to us on [Gitter](https://gitter.im/awslabs/aws-cdk) \ No newline at end of file diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md new file mode 100644 index 00000000..c430b571 --- /dev/null +++ b/doc_source/use_cfn_template.md @@ -0,0 +1,37 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Use an Existing AWS CloudFormation Template + +The CDK provides a mechanism that you can use to incorporate resources from an existing AWS CloudFormation template into your CDK app\. For example, suppose you have a template, `my-template.json`, with the following resource, where *S3Bucket* is the logical ID of the bucket in your template: + +``` +{ + "S3Bucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "prop1": "value1" + } + } +} +``` + +You can include this bucket in your CDK app, as shown in the following example \(note that you cannot use this method in an AWS Construct Library construct\): + +``` +import cdk = require("@amp;aws-cdk/cdk"); +import fs = require("fs"); + +new cdk.Include(this, "ExistingInfrastructure", { + template: JSON.parse(fs.readFileSync("my-template.json").toString()) +}); +``` + +Then to access an attribute of the resource, such as the bucket's ARN: + +``` +const bucketArn = new cdk.Fn.getAtt("S3Bucket", "Arn"); +``` \ No newline at end of file diff --git a/doc_source/what-is.md b/doc_source/what-is.md index 517f808d..9b896d90 100644 --- a/doc_source/what-is.md +++ b/doc_source/what-is.md @@ -1,32 +1,34 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- -# What Is the AWS Cloud Development Kit? +# What Is the AWS CDK? -Welcome to the AWS Cloud Development Kit \(AWS CDK\) User's Guide\. +Welcome to the *AWS CDK \(CDK\) User's Guide*\. This document provides information about the CDK, which is a software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. Use the CDK to define your cloud resources using one of the supported programming languages: C\#/\.NET, Java, JavaScript, or TypeScript\. This document does not supply reference information for the CDK\. You can find that information in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. -The AWS CDK is an infrastructure modeling framework that allows you to define your cloud resources using an imperative programming interface\. *The AWS CDK is currently in developer preview\. We look forward to community feedback and collaboration*\. +Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](apps_and_stacks.md#stacks) and [Apps](apps_and_stacks.md#apps)\. -## Why Should you use the AWS CDK? +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/AppStacks.png) -Perhaps the best reason is shown graphically\. Here is the TypeScript code in an AWS CDK project to create a Fargate service \(this is the code we use in the [Creating an Amazon ECS Fargate Service Using the AWS CDK](ecs_example.md)\): +## Why Use the CDK? + +Let's look at the power of the CDK\. Here is some TypeScript code in a CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate Service Using the AWS CDK](ecs_tutorial.md)\)\. ``` export class MyEcsConstructStack extends cdk.Stack { - constructor(parent: cdk.App, name: string, props?: cdk.StackProps) { - super(parent, name, props); - + constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { + super(scope, id, props); + const vpc = new ec2.VpcNetwork(this, 'MyVpc', { maxAZs: 3 // Default is all AZs in region }); - + const cluster = new ecs.Cluster(this, 'MyCluster', { vpc: vpc }); - + // Create a load-balanced Fargate service and make it public new ecs.LoadBalancedFargateService(this, 'MyFargateService', { cluster: cluster, // Required @@ -36,11 +38,9 @@ export class MyEcsConstructStack extends cdk.Stack { memoryMiB: '2048', // Default is 512 publicLoadBalancer: true // Default is false }); - } -} ``` -This produces a AWS CloudFormation template of over 600 lines\. We'll show the first and last 25: +This produces an AWS CloudFormation template of over 600 lines\. We'll show the first 25 lines and Outputs\. ``` Resources: @@ -53,91 +53,67 @@ Resources: InstanceTenancy: default Tags: - Key: Name - Value: MyEcsConstructStack/MyVpc + Value: MyEcsConstruct/MyVpc Metadata: - aws:cdk:path: MyEcsConstructStack/MyVpc/Resource + aws:cdk:path: MyEcsConstruct/MyVpc/Resource MyVpcPublicSubnet1SubnetF6608456: Type: AWS::EC2::Subnet Properties: CidrBlock: 10.0.0.0/19 VpcId: Ref: MyVpcF9F0CA6F - AvailabilityZone: us-east-2a + AvailabilityZone: us-west-2a MapPublicIpOnLaunch: true Tags: - Key: Name - Value: MyEcsConstructStack/MyVpc/PublicSubnet1 + Value: MyEcsConstruct/MyVpc/PublicSubnet1 - Key: aws-cdk:subnet-name ... - Metadata: - aws:cdk:path: MyEcsConstructStack/MyFargateService/LB/PublicListener/ECSGroup/Resource - CDKMetadata: - Type: AWS::CDK::Metadata - Properties: - Modules: "@aws-cdk/assets=0.19.0,@aws-cdk/assets-docker=0.19.0,@aws-cdk/aws-appl\ - icationautoscaling=0.19.0,@aws-cdk/aws-autoscaling=0.19.0,@aws-cdk/aws-\ - autoscaling-common=0.19.0,@aws-cdk/aws-certificatemanager=0.19.0,@aws-c\ - dk/aws-cloudformation=0.19.0,@aws-cdk/aws-cloudwatch=0.19.0,@aws-cdk/aw\ - s-codedeploy-api=0.19.0,@aws-cdk/aws-codepipeline-api=0.19.0,@aws-cdk/a\ - ws-ec2=0.19.0,@aws-cdk/aws-ecr=0.19.0,@aws-cdk/aws-ecs=0.19.0,@aws-cdk/\ - aws-elasticloadbalancingv2=0.19.0,@aws-cdk/aws-events=0.19.0,@aws-cdk/a\ - ws-iam=0.19.0,@aws-cdk/aws-kms=0.19.0,@aws-cdk/aws-lambda=0.19.0,@aws-c\ - dk/aws-logs=0.19.0,@aws-cdk/aws-route53=0.19.0,@aws-cdk/aws-s3=0.19.0,@\ - aws-cdk/aws-s3-notifications=0.19.0,@aws-cdk/aws-sns=0.19.0,@aws-cdk/aw\ - s-sqs=0.19.0,@aws-cdk/cdk=0.19.0,@aws-cdk/cx-api=0.19.0,my_ecs_construc\ - t=0.1.0" -Outputs: MyFargateServiceLoadBalancerDNS704F6391: Value: Fn::GetAtt: - MyFargateServiceLBDE830E97 - DNSName - Export: - Name: MyEcsConstructStack:MyFargateServiceLoadBalancerDNS704F6391 ``` -Which creates the following AWS resources\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/MyEcsConstruct.png) - -## The Developer Experience +## Developing With the CDK -To get started see [Installing and Configuring the AWS CDK](install_config.md)\. +Unless otherwise indicated, the code examples in this guide are in TypeScript\. To aid you in porting a TypeScript example to a supported programming language, take a look at the example code for your language in the [CDK Reference](https://awslabs.github.io/aws-cdk/reference.html)\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/screencast.gif) +The [AWS CDK Command Line Toolkit \(cdk\)](tools.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. -Developers can use one of the supported programming languages to define reusable cloud components called [Constructs](constructs.md), which are composed together into [Stacks](stacks.md) and [Apps](apps.md)\. +The [AWS Construct Library](aws_construct_lib.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to create resources for an Amazon or AWS service\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. **Note** -Unless otherwise indicated, the code examples in this guide are in TypeScript\. -To aid you in porting a TypeScript example to a supported programming language, take a look at the example code for your language in the [Reference](https://awslabs.github.io/aws-cdk/reference.html)\. +There is no charge for using the CDK, however you might incur AWS charges for creating or using AWS [chargeable resources](http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Simple Monthly Calculator](http://calculator.s3.amazonaws.com/index.html) to estimate charges for the use of various AWS resources\. -The [Command\-line Toolkit \(cdk\)](tools.md) is a command\-line tool for interacting with CDK apps\. It allows developers to synthesize artifacts such as AWS CloudFormation Templates, deploy stacks to development AWS accounts and diff against a deployed stack to understand the impact of a code change\. +## Contributing to the CDK -The [AWS Construct Library](aws_construct_lib.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to use AWS\. The AWS Construct Library aims to reduce the complexity and glue\-logic required when integrating various AWS services to achieve your goals on AWS\. - -**Note** -There is no charge for using the AWS CDK, however you may incur AWS charges for creating or using AWS [chargeable resources](http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Simple Monthly Calculator](http://calculator.s3.amazonaws.com/index.html) to estimate charges for the use of various AWS resources\. +Because the AWS CDK is open source, the team encourages you contribute to make it an even better tool\. For details, see [Contributing](https://github.com/awslabs/aws-cdk/blob/master/CONTRIBUTING.md)\. ## Additional Documentation and Resources -In addition to this guide, the following are other resources available to AWS CDK users: +In addition to this guide, the following are other resources available to CDK users: + [CDK Reference](https://awslabs.github.io/aws-cdk/) -+ [AWS Developer blog](https://aws.amazon.com/blogs/developer) ++ [CDK Demo at re:Invent 2018](https://www.youtube.com/watch?v=Lh-kVC2r2AU) ++ [CDK Workshop](https://cdkworkshop.com/) ++ [AWS Developer Blog](https://aws.amazon.com/blogs/developer) + [Gitter Channel](https://gitter.im/awslabs/aws-cdk) + [Stack Overflow](https://stackoverflow.com/questions/tagged/aws-cdk) -+ [GitHub repository](https://github.com/awslabs/aws-cdk) - + [Examples](https://github.com/awslabs/aws-cdk/tree/master/examples) - + [Documentation source](https://github.com/awslabs/aws-cdk/docs_src) ++ [GitHub Repository](https://github.com/awslabs/aws-cdk) + [Issues](https://github.com/awslabs/aws-cdk/issues) + + [Examples](https://github.com/aws-samples/aws-cdk-examples) + + [Documentation Source](https://github.com/awsdocs/aws-cdk-user-guide/tree/master/doc_source) + [License](https://github.com/awslabs/aws-cdk/blob/master/LICENSE) + + [Releases](https://github.com/awslabs/aws-cdk/releases) + [AWS CDK Sample for Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/sample-cdk.html) + [AWS CloudFormation Concepts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html) ++ [AWS Glossary](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html) ## About Amazon Web Services -Amazon Web Services \(AWS\) is a collection of digital infrastructure services that developers can leverage when developing their applications\. The services include computing, storage, database, and application synchronization \(messaging and queuing\)\. +Amazon Web Services \(AWS\) is a collection of digital infrastructure services that developers can use when developing their applications\. The services include computing, storage, database, and application synchronization \(messaging and queuing\)\. AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. -To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com) and click **Create an AWS Account**\. \ No newline at end of file +To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file diff --git a/doc_source/writing_constructs.md b/doc_source/writing_constructs.md index db60adc5..b5b3ea48 100644 --- a/doc_source/writing_constructs.md +++ b/doc_source/writing_constructs.md @@ -1,49 +1,81 @@ -------- - This documentation is for the developer preview release of the AWS CDK\. Do not use this version of the AWS CDK in production\. Subsequent releases of the AWS CDK will likely include breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. -------- # Writing AWS CDK Constructs -This topic provides some tips writing idiomatic new constructs for the AWS CDK\. The tips here apply equally to constructs written for inclusion in the AWS Construct Library, purpose\-built constructs to achieve a well\-defined goal, or constructs that serve as building blocks for assembling your cloud applications\. +This topic provides some tips for writing idiomatic new constructs for the CDK\. These tips apply equally to constructs written for inclusion in the AWS Construct Library, purpose\-built constructs to achieve a well\-defined goal, or constructs that serve as building blocks for assembling your cloud applications\. -## General Design Priciples -+ Favor composition over inheritance; most of the constructs should directly extend the `Construct` class instead of some other construct\. Inheritance should mainly be used to allow polymorphism\. Typically, you'll add a child construct and expose any of its APIs and properties in the parent construct\. -+ Provide defaults for everything that a reasonable guess can be made for; ideally, props should be optional and `new MyAwesomeConstruct(this, "Foo")` should be enough to set up a reasonable variant of the construct\. This does not mean that the user should not have the opportunity to customize\! Rather, it means that the specific parameter should be optional and set to a reasonable value if not supplied\. This may involve creating other resources as part of initializing this construct\. For example, all resources that require a role allow passing in a `Role` object \(specifically, a `RoleRef` object\), but if the user does not supply one an appropriate `Role` object is defined in\-place\. -+ Use contextual defaulting between properties; the value of one property may affect sensible defaults for other properties\. For example: `enableDnsHostnames` and `enableDnsSupport`\. `dnsHostnames` requires `dnsSupport`, only throw an error if the user has explicitly disabled DNS Support, but tried to enable DNS Hostnames\. A user expects things to just work\. -+ Make the user think about intent, not implementation detail; for example, if establishing an association between two resources \(such as a `Topic` and a `Queue`\) requires multiple steps \(in this case, creating a `Subscription` but also setting appropriate IAM permissions\), make both things happen in a single call \(to `subscribeQueue()`\)\. -+ Do not rename concepts or terminology\. For example don't Amazon SQS's `dataKeyReusePeriod` with `keyRotation` because it will be hard for people to diagnose problems\. They won't be able to search for *sqs dataKeyReuse* and find topics on it\. It is permissable to introduce a concept if a counterpart does not exist in AWS CloudFormation, especially if it directly maps onto the mental model that users already have about a service\. +## General Design Principles ++ Favor composition over inheritance\. Most of the constructs should directly extend the `Construct` class instead of some other construct\. Use inheritance mainly to allow polymorphism\. Typically, you define a construct within your scope and expose any of its APIs and properties in the enclosing construct\. ++ Provide defaults for everything that a reasonable guess can be made for\. Ideally, `props` should be optional and `new MyAwesomeConstruct(this, "Foo")` should be enough to set up a reasonable variant of the construct\. This doesn't mean that the user should not have the opportunity to customize\! Instead, it means that the specific parameter should be optional and set to a reasonable value if it's not supplied\. This might involve creating other resources as part of initializing this construct\. For example, all resources that require a role allow passing in a `Role` object \(specifically, a `RoleRef` object\), but if the user doesn't supply one, an appropriate `Role` object is defined in place\. ++ Use contextual defaulting between properties\. The value of one property might affect sensible defaults for other properties\. For example: `enableDnsHostnames` and `enableDnsSupport`\. `dnsHostnames` require `dnsSupport`, so only throw an error if the user has explicitly disabled DNS Support, but tried to enable DNS ostnames\. A user expects things to just work\. ++ Make the user think about intent, not implementation detail\. For example, if establishing an association between two resources \(such as a `Topic` and a `Queue`\) requires multiple steps \(in this case, creating a `Subscription` but also setting appropriate IAM permissions\), make both things happen in a single call \(to `subscribeQueue()`\)\. ++ Don't rename concepts or terminology\. For example don't rename the Amazon SQS `dataKeyReusePeriod` to `keyRotation` because it will be hard for people to diagnose problems\. They won't be able to search for *sqs dataKeyReuse* and find topics on it\. It's permissible to introduce a concept if a counterpart doesn't exist in AWS CloudFormation, especially if it directly maps onto the mental model that users already have about a service\. + Optimize for the common case\. For example, `AutoScalingGroup` accepts a `VPC` and deploys in the private subnet by default because that's the common case, but has an option to `placementOptions` for special cases\. -+ If a class can have multiple modes/behaviors: prefer values over polymorphism\. Try switching behavior on property values first\. Switch to multiple classes with a shared base class/interface only if there value to be had from having multiple classes \(type safety, maybe one mode has different features/required parameters\)\. ++ If a class can have multiple modes or behaviors, prefer values over polymorphism\. Try switching behavior on property values first\. Switch to multiple classes with a shared base class or interface only if there's value to be had from having multiple classes \(type safety, maybe one mode has different featuresor required parameters\)\. + +## CDK Lifecycle + +The following illustration shows the phases that the CDK goes through when you call cdk deploy to create the resources defined by your application\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/Lifecycle.png) + +There are three actors at play to create the resources that your CDK application defines\. ++ Your CDK app\. ++ The CDK Toolkit\. ++ AWS CloudFormation, which the CDK Toolkit calls to deploy your application and create the resources\. + +After you use the toolkit to deploy a CDK application, the application goes through the following phases\. + +Construction +Your code instantiates all desired application constructs and links them together\. + +Preparation +All constructs that have implemented the `prepare` method participate in a final round of modifications, to set up any final state they want to\. The preparation phase happens automatically and users do not see any feedback from this phase\. + +Validation +All constructs that have implemented their `validate` method can validate themselves to make sure they've ended up in a state that will correctly deploy\. Users see any validation failures that are detected during this phase\. + +Synthesis +All constructs render themselves to a set of artifacts, representing AWS CloudFormation templates, AWS Lambda application bundles, and other deployment artifacts\. Users do not see any feedback from this phase\. + +Deployment +The toolkit takes the artifacts produced by the synthesis step, uploads them to Amazon S3 or wherever they need to go, and starts an AWS CloudFormation deployment to deploy the application and create the resources\. + +Note that your CDK app has already finished and exited by the time the AWS CloudFormation deployment starts\. This has the following implications\. ++ Your CDK app cannot respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a Custom Resource\. ++ Your CDK app might have to work with values that cannot be known at the time it executes\. For example, if your CDK application defines an Amazon S3 Bucket with an automatically generated name, and you retrieve the `bucket.bucketName` attribute, that value is not the name of the deployed bucket\. Instead, the value of the `bucketName` attribute is a symbolic value, looking like *$\{TOKEN\[Bucket\.Name\.1234\]\}*\. You can pass this value to constructs, or append it to other strings, and the CDK framework will translate that value\. You cannot examine the value and make decisions based on the deployed bucket name, because the bucket name not available until AWS CloudFormation is done deploying, and by that time your program is no longer running\. Call `cdk.unresolved(value)`, which returns `true` if `value` not known until deployment time\. ## Implementation Details -+ Every construct consists of an exported class \(`MyConstruct`\) and an exported interface \(`MyConstructProps`\) that defines the parameters for these classes\. The props argument is the 3rd to the construct \(after the mandatory `parent` and `id` arguments\), and the entire parameter should be optional if all of the properties on the props object are optional\. -+ Most of the logic happens in the constructor; the constructor will build up the state of the construct \(what children it has, which ones are always there and which ones are optional, etc\.\)\. -+ Validate as early as possible; throw an `Error` in the constructor if the parameters don't make sense\. Only if you want to validate mutations that can occur after construction time, override the `validate()` method\. The hierarchy of validation: - + Best: Incorrect code won't compile, because of type safety guarantees\. - + Good: Runtime check everything the type checker can't enforce and fail early \(error in the constructor\)\. - + Okay: Synth\-time validate everything that can't be checked at construction time \(error in `validate()`\)\. - + Not great: Fail with an error in AWS CloudFormation \(bad because the AWS CloudFormation deploy operation may take a long while, and the error may take several minutes to surface\)\. - + Very bad: Fail with a timeout during AWS CloudFormation deployment \(it may take up to an hour for resource stabilization to timeout\!\) - + Worst: Don't fail the deployment at all, but fail at runtime\. -+ Avoid unneeded hierarchy in props; try to keep the props interface flat to help discoverability\. -+ Constructs are classes that have a set of invariants they maintain over their lifetime \(such as which members are initialized and relationships between properties as members are mutated\)\. -+ Constructs mostly have write\-only scalar properties that are passed in the constructor, but mutating functions for collections \(for example, there will be `construct.addElement()` or `construct.onEvent()`\) functions, but not `construct.setProperty()`\. It is perfectly fine to deviate from this convention as it makes sense for your own constructs\. -+ Don't expose `Tokens` to your consumers; tokens are an implementation mechanism for one of two purpose: representing AWS CloudFormation intrinsic values, or representing lazily evaluated values\. They can be used for implementation purposes, but use more specific types as part of your public API\. -+ `Tokens` are \(mostly\) only used in the implementation of an AWS Construct Library to pass lazy values to other constructs\. For example, if you have an array that can be mutated during the lifetime of your class, you pass it to an CloudFormation Resource construct like so: `new cdk.Token(() => this.myList)`\. -+ Be aware that you might not be able to usefully inspect all strings\. Any string passed into your construct may contain special markers that represent values that will only be known at deploy time \(for example, the ARN of a resource that will be created during deployment\)\. Those are *stringified Tokens* and they look like `"${TOKEN[Token.123]}"`\. You will not be able to validate those against a regular expression, for example, as their real values are not known yet\. To figure out if your string contains a special marker, use `cdk.unresolved(string)`\. ++ Every construct consists of an exported class \(`MyConstruct`\) and an exported interface \(`MyConstructProps`\) that defines the parameters for these classes\. The `props` argument is the third to the construct \(after the mandatory `scope` and `id` arguments\), and the entire parameter should be optional if all of the properties on the `props` object are optional\. ++ Most of the logic happens in the constructor\. The constructor builds up the state of the construct \(what children it has, which ones are always there and which are optional, and so on\)\. ++ Validate as early as possible\. Throw an `Error` in the constructor if the parameters don't make sense\. Override the `validate()` method to validate mutations that can occur after construction time\. Validation has the following hierarchy: + + Best – Incorrect code won't compile, because of type safety guarantees\. + + Good – Runtime check everything the type checker can't enforce and fail early \(error in the constructor\)\. + + Okay – Validate everything that can't be checked at construction time at synth time \(error in `validate()`\)\. + + Not great – Fail with an error in AWS CloudFormation \(bad because the AWS CloudFormation deploy operation can take a long time, and the error can take several minutes to surface\)\. + + Very bad – Fail with a timeout during AWS CloudFormation deployment\. \(It can take up to an hour for resource stabilization to timeout\!\) + + Worst – Don't fail the deployment at all, but fail at runtime\. ++ Avoid unneeded hierarchy in `props`\. Try to keep the `props` interface flat to help discoverability\. ++ Constructs are classes that have a set of invariants they maintain over their lifetime \(such as which members are initialized, and relationships between properties as members that are mutated\)\. ++ Constructs mostly have write\-only scalar properties that are passed in the constructor, but mutating functions for collections \(for example, there will be `construct.addElement()` or `construct.onEvent()` functions, but not `construct.setProperty()`\)\. It's perfectly fine to deviate from this convention when it makes sense for your own constructs\. ++ Don't expose `Tokens` to your consumers\. Tokens are an implementation mechanism for one of two purposes: representing AWS CloudFormation intrinsic values, or representing lazily evaluated values\. You can use them for implementation purposes, but use more specific types as part of your public API\. ++ `Tokens` are \(mostly\) used only in the implementation of an AWS Construct Library to pass lazy values to other constructs\. For example, if you have an array that can be mutated during the lifetime of your class, you pass it to an AWS CloudFormation Resourceconstruct like so: `new cdk.Token(() => this.myList)`\. ++ Be aware that you might not be able to usefully inspect all strings\. Any string passed into your construct may contain special markers that represent values that will only be known at deploy time \(for example, the ARN of a resource that will be created during deployment\)\. Those are *stringified Tokens* and they look like `"${TOKEN[Token.123]}"`\. You will not be able to validate those against a regular expression, for example, as their real values are not known yet\. To determine whether your string contains a special marker, use `cdk.unresolved(string)`\. + Indicate units of measurement in property names that don't use a strong type\. For example, use **milli**, **sec**, **min**, **hr**, **Bytes**, **KiB**, **MiB**, and **GiB**\. -+ Be sure to define an `IMyResource` interface for your resources which defines the API area that other constructs are going to use\. Typical capabilities on this interface are querying for a resource ARN and adding resource permissions\. -+ Accept objects instead of ARNs or names; when accepting other resources as parameters, declare your property as `resource: IMyResource` instead of `resourceArn: string`\. This makes snapping objects together feel natural to consumers, and allows you to query/modify the incoming resource as well\. The latter is particularly useful if something about IAM permissions need to be set, for example\. -+ Implement `export()` and `import()` functions for your resource; these make it possible to interoperate with resources that are not defined in the same AWS CDK app \(they may be manually created, created using raw AWS CloudFormation, or created in a completely unrelated AWS CDK app\)\. -+ If your construct wraps a single \(or most prominent\) other construct, give it an id of either **"Resource"** or **"Default"**; The main resource that an AWS Construct represents should use the ID **"Resource"**, for higher\-level wrapping resources you will generally use **"Default"** \(resources named **"Default"** will inherit their parent's logical ID, while resources named **"Resource"** will have a distinct logical ID but the human\-readable part of it will not show the **"Resource"** part\)\. ++ Be sure to define an `IMyResource` interface for your resources that defines the API area that other constructs will use\. Typical capabilities on this interface are querying for a resource ARN and adding resource permissions\. ++ Accept objects instead of ARNs or names\. When accepting other resources as parameters, declare your property as `resource: IMyResource` instead of `resourceArn: string`\. This makes snapping objects together feel natural to consumers, and allows you to query or modify the incoming resource as well\. For example, the latter is particularly useful if something about IAM permissions needs to be set\. ++ Implement `export()` and `import()` functions for your resource\. These make it possible to interoperate with resources that are not defined in the same CDK app \(they might be manually created, created using raw AWS CloudFormation resources, or created in a completely unrelated CDK app\)\. ++ If your construct wraps a single \(or most prominent\) other construct, give it an ID of either **"Resource"** or **"Default"**\. The main resource that an AWS construct represents should use the ID **"Resource"** For higher\-level wrapping resources, you will generally use **"Default"** \(resources named **"Default"** will inherit their scope's logical ID, while resources named **"Resource"** will have a distinct logical ID, but the human\-readable part of it won't show the **"Resource"** part\)\. ## Implementation Language -In order for construct libraries to be reusable across programming languages, they need to be authored in a language that can compile to a jsii assembly\. +For construct libraries to be reusable across programming languages, they need to be authored in a language that can compile to a `jsii` assembly\. -At the moment, the only supported language is TypeScript, so prefer TypeScript unless you are planning to specifically isolate your constructs to a single developer base\. +Author in TypeScript unless you plan to isolate your constructs to a single programming language\. ## Code Organization @@ -62,29 +94,29 @@ your-package    ├── test.some-resource.ts    └── test.some-other-resource.ts ``` -+ Your package is named `@aws-cdk/aws-xxx` if it represents the canonical AWS Construct Library for this service; otherwise we recommend starting with `cdk-`, but you are to choose the name\. -+ Code goes under `lib/`, tests go under `test/`\. -+ Entry point should be `lib/index.ts` and should only contain `export`s for other files\. -+ No need to put every class in a separate file\. Try to think of a reader\-friendly organization of your source files\. -+ If you want to make package\-private utility functions, put them in a file that is not exported from `index.ts` and use that file as normal\. -+ Free\-floating functions \(functions that are not part of a class definition\) cannot be accessed through jsii \(i\.e\., from languages other than TypeScript and JavaScript\)\. Don't use them for public features of your construct library\. -+ Document all public APIs with doc comments \(JSdoc syntax\)\. Document defaults using the **@default** marker in doc comments\. ++ If it represents the canonical AWS Construct Library for this service, name your package is named `@aws-cdk/aws-xxx`\. We recommend starting with `cdk-`, but you are otherwise free to choose the name\. ++ Put code under `lib/`, and tests under `test/`\. ++ The entry point should be `lib/index.ts` and should only contain `export`s for other files\. ++ You don't need to put every class in a separate file\. Try to think of a reader\-friendly organization of your source files\. ++ To make package\-private utility functions, put them in a file that isn't exported from `index.ts`\. ++ Free\-floating functions \(functions that are not part of a class definition\) cannot be accessed through jsii \(that is, from languages other than TypeScript and JavaScript\)\. Don't use them for public features of your construct library\. ++ Document all public APIs with doc comments \(`JSdoc` syntax\)\. Document defaults using the **@default** marker in doc comments\. ## Testing -+ Add unit tests for every construct \(`test.xxx.ts`\), relating the construct's properties to the AWS CloudFormation that gets generated\. Use the `@aws-cdk/assert` library to make it easier to write assertions on the AWS CloudFormation output\. ++ Add unit tests for every construct \(`test.xxx.ts`\), relating the construct's properties to the AWS CloudFormation that is generated\. Use the `@aws-cdk/assert` library to make it easier to write assertions on the AWS CloudFormation output\. + Try to test one concern per unit test\. Even if you could test more than one feature of the construct per test, it's better to write multiple tests, one for each feature\. A test should have one reason to break\. -+ Add integration tests \(`integ.xxx.ts`\) that are AWS CDK apps which exercise the features of the construct, then load your shell with credentials and run npm run integ to exercise them\. You will also have to run this if the AWS CloudFormation output of the construct changes\. -+ If there are packages that you only depend on for testing, add them to `devDependencies` \(instead of regular `dependencies`\)\. You're still not allowed to create dependency cycles this way \(from the root, run scripts/find\-cycles\.sh to figure out if you have created any cycles\)\. -+ Try to make your integ test literate \(`integ.xxx.lit.ts`\) if possible and link to it from the `README`\. ++ Add integration tests \(`integ.xxx.ts`\) that are CDK apps that exercise the features of the construct, then load your shell with credentials and run npm run integ to exercise them\. You will also have to run this if the AWS CloudFormation output of the construct changes\. ++ If there are packages that you depend on only for testing, add them to `devDependencies` \(instead of regular `dependencies`\)\. You're still not allowed to create dependency cycles this way \(from the root, run scripts/find\-cycles\.sh to determine whether you have created any cycles\)\. ++ If possible, try to make your integ test literate \(`integ.xxx.lit.ts`\) and link to it from the `README`\. ## README + Header should include maturity level\. -+ Header should start at H2, not H1\. ++ Header should start at `H2`, not `H1`\. + Include some example code for the simple use case near the very top\. -+ If there are multiple common use cases, provide an example for each one and describe what happens under the hood at a high level \(e\.g\. which resources are created\)\. ++ If there are multiple common use cases, provide an example for each one and describe what happens under the hood at a high level \(for example, which resources are created\)\. + Reference docs are not needed\. -+ Use literate \(\.lit\.ts\) integration tests into README file\. ++ Use literate \(`.lit.ts`\) integration tests in the `README` file\. ## Construct IDs -All children's construct IDs are part of your public contract; those IDs are used to generate AWS CloudFormation logical names for resources\. If they change, AWS CloudFormation will replace the resource\. This technically means that if you change any ID of a child construct you will have to major\-version\-bump your library\. \ No newline at end of file +All child construct IDs are part of your public contract\. Those IDs are used to generate AWS CloudFormation logical names for resources\. If they change, AWS CloudFormation will replace the resource\. Technically, this means that if you change any ID of a child construct you will have to major\-version\-bump your library\. \ No newline at end of file From d849645acceb8ffb00102aeb9b90022d3bdafa1c Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Wed, 17 Apr 2019 09:44:13 -0700 Subject: [PATCH 013/655] Updated to latest version --- doc_source/about_examples.md | 45 +++ doc_source/advanced_tutorials.md | 11 - doc_source/apps_and_stacks.md | 8 +- doc_source/aws_construct_lib.md | 162 ++++++++- doc_source/cfn_layer.md | 40 ++- doc_source/cli.md | 310 ++++++++++++++++++ doc_source/cloudformation.md | 55 +--- doc_source/concepts.md | 11 - doc_source/constructs.md | 2 +- ...environments_and_context.md => context.md} | 43 +-- doc_source/core_concepts.md | 4 +- doc_source/doc-history.md | 12 +- .../{ecs_tutorial.md => ecs_example.md} | 23 +- doc_source/examples.md | 11 + doc_source/get_context_var.md | 4 +- doc_source/get_ssm_value.md | 16 +- ...o_world_tutorial.md => getting_started.md} | 262 +++++++++++++-- doc_source/index.md | 59 ++-- doc_source/install_config.md | 141 -------- doc_source/lifecycle.md | 37 +++ doc_source/logical_ids.md | 75 ----- doc_source/multiple_languages.md | 82 +++++ doc_source/passing_secrets_manager.md | 30 +- doc_source/passing_stack_value.md | 67 ---- doc_source/pgp-keys.md | 101 ++++++ doc_source/reference.md | 11 + doc_source/resources.md | 56 ++++ ...less_tutorial.md => serverless_example.md} | 56 ++-- doc_source/stack_how_to.md | 76 ----- .../stack_how_to_create_multiple_stacks.md | 75 +++++ .../{how_to_get_ext_values.md => tokens.md} | 4 +- doc_source/tools.md | 295 +---------------- doc_source/use_cfn_template.md | 2 +- doc_source/what-is.md | 27 +- doc_source/writing_constructs.md | 32 -- 35 files changed, 1260 insertions(+), 985 deletions(-) create mode 100644 doc_source/about_examples.md delete mode 100644 doc_source/advanced_tutorials.md create mode 100644 doc_source/cli.md delete mode 100644 doc_source/concepts.md rename doc_source/{environments_and_context.md => context.md} (63%) rename doc_source/{ecs_tutorial.md => ecs_example.md} (83%) create mode 100644 doc_source/examples.md rename doc_source/{hello_world_tutorial.md => getting_started.md} (56%) delete mode 100644 doc_source/install_config.md create mode 100644 doc_source/lifecycle.md delete mode 100644 doc_source/logical_ids.md create mode 100644 doc_source/multiple_languages.md delete mode 100644 doc_source/passing_stack_value.md create mode 100644 doc_source/pgp-keys.md create mode 100644 doc_source/reference.md create mode 100644 doc_source/resources.md rename doc_source/{serverless_tutorial.md => serverless_example.md} (84%) delete mode 100644 doc_source/stack_how_to.md create mode 100644 doc_source/stack_how_to_create_multiple_stacks.md rename doc_source/{how_to_get_ext_values.md => tokens.md} (52%) diff --git a/doc_source/about_examples.md b/doc_source/about_examples.md new file mode 100644 index 00000000..433710be --- /dev/null +++ b/doc_source/about_examples.md @@ -0,0 +1,45 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# AWS CDK Examples + +The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitHub includes the following examples\. + +## TypeScript examples + + +| Example | Description | +| --- |--- | +| [application\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/application-load-balancer/) | Using an AutoScalingGroup with an Application Load Balancer | +| [chat\-app](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/chat-app/) | A serverless chat application using Cognito | +| [classic\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/classic-load-balancer/) | Using an AutoScalingGroup with a Classic Load Balancer | +| [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) | Shows adding a Custom Resource to your CDK app | +| [elasticbeanstalk](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/elasticbeanstalk/) | Elastic Beanstalk example using L1 with a Blue/Green pipeline \(community contributed\) | +| [ecs\-cluster](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/cluster/) | Provision an ECS Cluster with custom Autoscaling Group configuration | +| [ecs\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-load-balanced-service/) | Starting a container fronted by a load balancer on ECS | +| [ecs\-service\-with\-task\-placement](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-task-placement/) | Starting a container ECS with task placement specifications | +| [ecs\-service\-with\-advanced\-alb\-config](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-advanced-alb-config/) | Starting a container fronted by a load balancer on ECS with added load balancer configuration | +| [fargate\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/fargate-load-balanced-service/) | Starting a container fronted by a load balancer on Fargate | +| [fargate\-service\-with\-auto\-scaling](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/fargate-service-with-auto-scaling/) | Starting an ECS service of FARGATE launch type that auto scales based on average CPU Utilization | +| [lambda\-cron](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/lambda-cron/) | Running a Lambda on a schedule | +| [my\-widget\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/my-widget-service/) | Use Lambda to serve up widgets | +| [resource\-overrides](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/resource-overrides/) | Shows how to override generated CloudFormation code | +| [static\-site](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/static-site/) | A static site using CloudFront | +| [stepfunctions\-job\-poller](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/stepfunctions-job-poller/) | A simple StepFunctions workflow | + +## Java examples + + +| Example | Description | +| --- |--- | +| [hello\-world](https://github.com/aws-samples/aws-cdk-examples/tree/master/java/hello-world/) | A demo application that uses the CDK in Java | + +## JavaScript examples + + +| Example | Description | +| --- |--- | +| [aws\-cdk\-changelogs\-demo](https://github.com/aws-samples/aws-cdk-changelogs-demo) | A full serverless Node\.js application stack deployed using CDK\. It uses AWS Lambda, AWS Fargate, DynamoDB, Elasticache, S3, and CloudFront\. | \ No newline at end of file diff --git a/doc_source/advanced_tutorials.md b/doc_source/advanced_tutorials.md deleted file mode 100644 index 37a49ebd..00000000 --- a/doc_source/advanced_tutorials.md +++ /dev/null @@ -1,11 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Advanced Tutorials - -This topic contains the following tutorials: -+ [Creating a Serverless Application Using the AWS CDK](serverless_tutorial.md)Creates a serverless application using Lambda, API Gateway, and Amazon S3\. -+ [Creating an AWS Fargate Service Using the AWS CDK](ecs_tutorial.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. \ No newline at end of file diff --git a/doc_source/apps_and_stacks.md b/doc_source/apps_and_stacks.md index 843d6bd5..267957d3 100644 --- a/doc_source/apps_and_stacks.md +++ b/doc_source/apps_and_stacks.md @@ -6,9 +6,9 @@ This documentation is for the developer preview release \(public beta\) of the A # Apps and Stacks -The main artifact of a CDK program known as a *CDK app*\. This is an executable program that you can use to synthesize deployment artifacts that supporting tools, such as the CDK Toolkit, can deploy, as described in [AWS CDK Command Line Toolkit \(cdk\)](tools.md)\. +The main artifact of a CDK program known as a *CDK app*\. This is an executable program that you can use to synthesize deployment artifacts that supporting tools, such as the CDK Toolkit, can deploy, as described in [AWS CDK Command Line Interface \(cdk\)](cli.md)\. -Stacks are CDK constructs that you can deploy into an AWS environment\. The combination of AWS Region and account becomes the stack's *environment*, as described in [Environments and Authentication](environments_and_context.md#environments)\. Most production apps consist of multiple stacks of resources that are deployed as a single transaction using a resource provisioning service such as AWS CloudFormation\. Any resources added directly or indirectly as children of a stack are included in the stack's template when it is synthesized by your CDK program\. +Stacks are CDK constructs that you can deploy into an AWS environment\. The combination of AWS Region and account becomes the stack's *environment*\. Most production apps consist of multiple stacks of resources that are deployed as a single transaction using a resource provisioning service such as AWS CloudFormation\. Any resources added directly or indirectly as children of a stack are included in the stack's template when it is synthesized by your CDK program\. ## Apps @@ -86,6 +86,4 @@ const app = new App(); new MyStack(app, 'NorthAmerica', { env: { region: 'us-east-1' } }); new MyStack(app, 'Europe', { env: { region: 'us-west-2' } }); -``` - -See [Stack How\-Tos](stack_how_to.md) for additional information about using stacks\. \ No newline at end of file +``` \ No newline at end of file diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md index ce6a2198..c2d40ba8 100644 --- a/doc_source/aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -10,19 +10,21 @@ The AWS Construct Library is a set of modules that expose APIs for defining AWS The AWS Construct Library modules are described in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. -The AWS Construct Library includes many common patterns and capabilities that are designed to enable developers to focus on their application\-specific architectures and reduce the boilerplate and glue logic needed when working with AWS services\. +## Versioning -## Grants +The CDK follows the semantic versioning model\. This means that breaking changes are limited to major releases, such as 2\.0\. -AWS Identity and Access Management \(IAM\) policies are automatically defined based on intent\. For example, when subscribing an Amazon Simple Notification Service \(Amazon SNS\) [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) to an AWS Lambda [Function](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.Function), the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. +Minor releases, such as 2\.4, guarantee that any code written in a previous minor version, such as 2\.1, will build, run, and produce the exact same results when built, run, and producing results, as before\. -Also, most AWS constructs expose `grant*` methods that allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct has a [grantRead\(principal\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.grantRead) method\. This method accepts an IAM [Principal](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#iprincipal-interface) such as a [User](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#user) or a [Role](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#role), which modifies the policy to allow the principal to read objects from the bucket\. +## CDK Patterns -## Security Groups +The AWS Construct Library includes many common patterns and capabilities that are designed to enable developers to focus on their application\-specific architectures and reduce the boilerplate and glue logic needed when working with AWS services\. -Amazon Elastic Compute Cloud \(Amazon EC2\) network entities, such as the [Elastic Load Balancing](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-elasticloadbalancingv2.html) and [Auto Scaling Group](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-autoscaling.html#auto-scaling-group) instances, can connect to each other based on definitions of security groups\. +### Grants + +AWS Identity and Access Management \(IAM\) policies are automatically defined based on intent\. For example, when subscribing an Amazon Simple Notification Service \(Amazon SNS\) [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) to an AWS Lambda [Function](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.Function), the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. -The CDK provides APIs for defining security group connections\. For more information, see [Allowing Connections](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#allowing-connections)\. +Also, most AWS constructs expose `grant*` methods that allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct has a [grantRead\(principal\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.grantRead) method\. This method accepts an IAM [Principal](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#iprincipal-interface) such as a [User](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#user) or a [Role](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#role), which modifies the policy to allow the principal to read objects from the bucket\. ## Metrics @@ -32,12 +34,148 @@ You can obtain [Metric](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-clou For more information, see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html)\. -## Exports and Imports +## Events + +Many AWS constructs include `on*` methods, which you can to react to events emitted by the construct\. For example, the CodeCommit [Repository](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#Repository) construct has an [onCommit](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#@aws-cdk/aws-codecommit.RepositoryRef.onCommit) method\. You can use AWS constructs as targets for various event provider interfaces, such as [IEventRuleTarget](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html#ieventruletarget-interface) \(for the CloudWatch event rule target\), [IAlarmAction](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#ialarmaction-interface) \(for Amazon CloudWatch alarm actions\), and so on\. + +For more information, see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html) and [@aws\-cdk/aws\-events](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html)\. + +## Referencing Constructs + +This section contains information about how to reference other constructs, either from within the same app, or across apps\. + +### Get a Value from Another Stack + +You can get a value from another stack in the same app by using the `export` method in one stack and the `import` method in the other stack\. + +The following example creates a bucket on one stack and passes a reference to that bucket to the other stack through an interface\. + +First create a stack with a bucket\. The stack includes a property we use to pass the bucket's properties to the other stack\. Notice how we use the `export` method on the bucket to get its properties and save them in the stack property\. + +``` +class HelloCdkStack extends cdk.Stack { + // Property that defines the stack you are exporting from + public readonly myBucketImportProps: s3.BucketImportProps; + + constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const mybucket = new s3.Bucket(this, "MyFirstBucket"); + + // Save bucket's BucketImportProps + this.myBucketImportProps = mybucket.export(); + } +} +``` + +Create an interface for the second stack's properties\. We use this interface to pass the bucket properties between the two stacks\. + +``` +// Interface we'll use to pass the bucket's properties to another stack +interface MyCdkStackProps { + theBucketImportProps: s3.BucketImportProps; +} +``` + +Create the second stack that gets a reference to the other bucket from the properties passed in through the constructor\. + +``` +// The class for the other stack +class MyCdkStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props: MyCdkStackProps) { + super(scope, id); + + const myOtherBucket = s3.Bucket.import(this, "MyOtherBucket", props.theBucketImportProps); + + // Do something with myOtherBucket + } +} +``` + +Finally, connect the dots in your app\. -If you need to reference a resource, such as an Amazon S3 bucket or VPC, that's defined outside of your CDK app, you can use the `Xxxx.import(...)` static methods that are available on AWS constructs\. For example, you can use the [Bucket\.import\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.import) method to obtain a [BucketRef](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef) object, which can be used in most places where a bucket is required\. This pattern enables treating resources defined outside of your app as if they are part of your app\. +``` +const app = new cdk.App(); -## Event\-Driven APIs +const myStack = new HelloCdkStack(app, "HelloCdkStack"); -Many AWS constructs include `on*` methods, which can be used to react to events emitted by the construct\. For example, the CodeCommit [Repository](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#Repository) construct has an [onCommit](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#@aws-cdk/aws-codecommit.RepositoryRef.onCommit) method\. You can use AWS constructs as targets for various event provider interfaces, such as [IEventRuleTarget](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html#ieventruletarget-interface) \(for the CloudWatch event rule target\), [IAlarmAction](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#ialarmaction-interface) \(for Amazon CloudWatch alarm actions\), and so on\. +new MyCdkStack(app, "MyCdkStack", { + theBucketImportProps: myStack.myBucketImportProps +}); + +app.run(); +``` + +### Referencing Constructs Across All App + +This section contains information about how to reference constructs from other apps\. + +To reference a resource, such as an Amazon S3 bucket or VPC, that's defined outside of your CDK app, use the `Xxxx.import(...)` static methods that are available on AWS constructs\. For example, use the [Bucket\.import\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.import) method to obtain a [BucketRef](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef) object, which can be used in most places where a bucket is required\. This pattern enables treating resources defined outside of your app as if they are part of your app\. + +## Get a Value from Another Stack + +You can get a value from another stack in the same app by using the `export` method in one stack and the `import` method in the other stack\. + +The following example creates a bucket on one stack and passes a reference to that bucket to the other stack through an interface\. + +First create a stack with a bucket\. The stack includes a property we use to pass the bucket's properties to the other stack\. Notice how we use the `export` method on the bucket to get its properties and save them in the stack property\. + +``` +class HelloCdkStack extends cdk.Stack { + // Property that defines the stack you are exporting from + public readonly myBucketImportProps: s3.BucketImportProps; + + constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const mybucket = new s3.Bucket(this, "MyFirstBucket"); + + // Save bucket's BucketImportProps + this.myBucketImportProps = mybucket.export(); + } +} +``` + +Create an interface for the second stack's properties\. We use this interface to pass the bucket properties between the two stacks\. + +``` +// Interface we'll use to pass the bucket's properties to another stack +interface MyCdkStackProps { + theBucketImportProps: s3.BucketImportProps; +} +``` + +Create the second stack that gets a reference to the other bucket from the properties passed in through the constructor\. + +``` +// The class for the other stack +class MyCdkStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props: MyCdkStackProps) { + super(scope, id); + + const myOtherBucket = s3.Bucket.import(this, "MyOtherBucket", props.theBucketImportProps); + + // Do something with myOtherBucket + } +} +``` + +Finally, connect the dots in your app\. + +``` +const app = new cdk.App(); + +const myStack = new HelloCdkStack(app, "HelloCdkStack"); + +new MyCdkStack(app, "MyCdkStack", { + theBucketImportProps: myStack.myBucketImportProps +}); + +app.run(); +``` + +## Security Groups + +Amazon Elastic Compute Cloud \(Amazon EC2\) network entities, such as the [Elastic Load Balancing](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-elasticloadbalancingv2.html) and [Auto Scaling Group](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-autoscaling.html#auto-scaling-group) instances, can connect to each other based on definitions of security groups\. -For more information, see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html) and [@aws\-cdk/aws\-events](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html)\. \ No newline at end of file +The CDK provides APIs for defining security group connections\. For more information, see [Allowing Connections](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#allowing-connections)\. \ No newline at end of file diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 4691ca43..56dfe5ee 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -4,7 +4,7 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# Accessing the AWS CloudFormation Layer +# Work Around Missing AWS CDK Features This topic describes how to modify the underlying AWS CloudFormation resources in the AWS Construct Library\. We also call this technique an "escape hatch" because it allows users to "escape" from the abstraction boundary defined by the AWS construct, and patch the underlying resources\. @@ -29,7 +29,7 @@ You can also find more information about how to work directly with the AWS Cloud ## Accessing Low\-Level Resources -Use [construct\.findChild\(\)](@cdk-class-url;#@aws-cdk/cdk.Construct.findChild) to access any child of a construct by its construct ID\. By convention, the main resource of any AWS construct is named **Resource**\. +Use [construct\.findChild\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Construct.findChild) to access any child of a construct by its construct ID\. By convention, the main resource of any AWS construct is named **Resource**\. The following example shows how to access the underlying Amazon Simple Storage Service \(Amazon S3\) bucket resource, given a [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct\. @@ -46,7 +46,7 @@ The `bucketResource` represents the low\-level AWS CloudFormation resource of ty If the child can't be located, [construct\.findChildren\(id\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/cdk.Construct.findChild) fails\. This means that if the underlying AWS Construct Library changes the IDs or structure for some reason, synthesis fails\. -You can also use[construct\.children](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/cdk.Construct.children) for more advanced queries\. For example, you can look for a child that has a certain AWS CloudFormation resource type\. +You can also use [construct\.children](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/cdk.Construct.children) for more advanced queries\. For example, you can look for a child that has a certain AWS CloudFormation resource type\. ``` const bucketResource = @@ -54,11 +54,11 @@ const bucketResource = as s3.CfnBucket; ``` -Once you have a AWS CloudFormation resource, you are interacting with AWS CloudFormation resource classes, which extend [cdk\.Resource](@cdk-class-url;#@aws-cdk/cdk.Resource)\. +Once you have a AWS CloudFormation resource, you are interacting with AWS CloudFormation resource classes, which extend [cdk\.CfnResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource)\. ## Resource Options -Set resource options using [cdk\.Resource](@cdk-class-url;#@aws-cdk/cdk.Resource) properties such as *Metadata* and *DependsOn*\. +Set resource options using [cdk\.CfnResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource) properties such as *Metadata* and *DependsOn*\. For example, the following code: @@ -101,25 +101,23 @@ Use this mechanism when a certain feature is available at the AWS CloudFormation The following example sets a bucket's analytics configuration\. ``` -bucketResource.propertyOverrides.analyticsConfigurations = [ - { - id: 'config1', - storageClassAnalysis: { - dataExport: { - outputSchemaVersion: '1', - destination: { - format: 'html', - bucketArn: otherBucket.bucketArn // use tokens freely - } - } + bucketResource.addPropertyOverride("AnalyticsConfigurations", { + Id: "config1", + StorageClassAnalysis: { + dataExport: { + OutputSchemaVersion: "1", + Destination: { + Format: "html", + BucketArn: "arn:aws:s3:::" + bucketName // use tokens freely + } } - } -]; + } + }); ``` ## Raw Overrides -If the strongly typed overrides aren't sufficient or, for example, if the schema defined in AWS CloudFormation is not up to date, use the [cdk\.Resource\.addOverride\(path, value\)](@cdk-class-url;#@aws-cdk/cdk.Resource.addOverride) method to define an override that is applied to the resource definition during synthesis\. This is shown in the following example\. +If the strongly typed overrides aren't sufficient or, for example, if the schema defined in AWS CloudFormation is not up to date, use the [cdk\.CfnResource\.addOverride\(path, value\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.addOverride) method to define an override that is applied to the resource definition during synthesis\. This is shown in the following example\. ``` // Define an override at the resource definition root, you can even modify the "Type" @@ -159,7 +157,7 @@ This synthesizes to the following\. } ``` -Use `undefined`, [cdk\.Resource\.addDeletionOverride](@cdk-class-url;#@aws-cdk/cdk.Resource.addDeletionOverride), or [cdk\.Resource\.addPropertyDeletionOverride](@cdk-class-url;#@aws-cdk/cdk.Resource.addPropertyDeletionOverride) to delete values\. +Use `undefined`, [cdk\.CfnResource\.addDeletionOverride](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.addDeletionOverride), or [cdk\.CfnResource\.addPropertyDeletionOverride](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.addPropertyDeletionOverride) to delete values\. ``` const bucket = new s3.Bucket(this, 'MyBucket', { @@ -206,7 +204,7 @@ new s3.CfnBucket(this, 'MyBucket', { }); ``` -In the rare case where you want to define a resource that doesn't have a corresponding `CfnXxx` class \(such as a new resource that wasn't published yet in the AWS CloudFormation resource specification\), you can instantiate the [cdk\.Resource](@cdk-class-url;#@aws-cdk/cdk.Resource)\. +In the rare case where you want to define a resource that doesn't have a corresponding `CfnXxx` class \(such as a new resource that wasn't published yet in the AWS CloudFormation resource specification\), you can instantiate the [cdk\.CfnResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource)\. ``` new cdk.Resource(this, 'MyBucket', { diff --git a/doc_source/cli.md b/doc_source/cli.md new file mode 100644 index 00000000..105f1bcc --- /dev/null +++ b/doc_source/cli.md @@ -0,0 +1,310 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# AWS CDK Command Line Interface \(cdk\) + +The CDK Toolkit, cdk, is the main tool you use to interact with your CDK app\. It executes the CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the CDK\. + +There are two ways to tell cdk what command to use to run your CDK app\. The first way is to include an explicit \-\-app option whenever you use a cdk command\. + +``` +cdk --app 'node bin/main.js' synth +``` + +The second way is to add the following entry to the `cdk.json` file\. + +``` +{ + "app": "node bin/main.js" +} +``` + +You can also use the npx cdk instead of just cdk\. + +Here are the actions you can take on your CDK app \(this is the output of the cdk \-\-help command\)\. + +``` +Usage: cdk -a COMMAND + +Commands: + list Lists all stacks in the app [aliases: ls] + synthesize [STACKS..] Synthesizes and prints the CloudFormation template + for this stack [aliases: synth] + bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS + environment + deploy [STACKS..] Deploys the stack(s) named STACKS into your AWS + account + destroy [STACKS..] Destroy the stack(s) named STACKS + diff [STACKS..] Compares the specified stack with the deployed + stack or a local template file, and returns with + status 1 if any difference is found + metadata [STACK] Returns all metadata associated with this stack + init [TEMPLATE] Create a new, empty CDK project from a template. + Invoked without TEMPLATE, the app template will be + used. + context Manage cached context values + docs Opens the reference documentation in a browser + [aliases: doc] + doctor Check your set-up for potential problems + +Options: + --app, -a REQUIRED: Command-line for executing your CDK app (e.g. + "node bin/my-app.js") [string] + --context, -c Add contextual string parameter. [array] + --plugin, -p Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] + --rename Rename stack name if different from the one defined in + the cloud executable [string] + --trace Print trace for stack warnings [boolean] + --strict Do not construct stacks with warnings [boolean] + --ignore-errors Ignores synthesis errors, which will likely produce an + invalid output [boolean] [default: false] + --json, -j Use JSON output instead of YAML [boolean] + --verbose, -v Show debug logs [boolean] + --profile Use the indicated AWS profile as the default environment + [string] + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified. [string] + --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: + guess EC2 instance status. [boolean] + --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized + templates (enabled by default) [boolean] + --path-metadata Include "aws:cdk:path" CloudFormation metadata for each + resource (enabled by default) [boolean] [default: true] + --asset-metadata Include "aws:asset:*" CloudFormation metadata for + resources that user assets (enabled by default) + [boolean] [default: true] + --role-arn, -r ARN of Role to use when invoking CloudFormation [string] + --toolkit-stack-name The name of the CDK toolkit stack [string] + --ci Force CI detection. Use --no-ci to disable CI + autodetection. [boolean] [default: false] + --version Show version number [boolean] + -h, --help Show help [boolean] + +If your app has a single stack, there is no need to specify the stack name + +If one of cdk.json or ~/.cdk.json exists, options specified there will be used +as defaults. Settings in cdk.json take precedence. +``` + +If your app has a single stack, you don't have to specify the stack name\. + +If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. + +## Bootstrapping the CDK + +Before you can use the CDK you must bootstrap the CDK to create the infrastructure that the CDK needs\. Currently the bootstrap command creates only an Amazon S3 bucket\. + +You incur any charges for what the CDK stores in the bucket\. Because the CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. + +## Security\-Related Changes + +To protect you against unintended changes that affect your security posture, the CDK toolkit prompts you to approve security\-related changes before deploying them\. + +You change the level of changes that requires approval by specifying: + +``` +cdk deploy --require-approval LEVEL +``` + +Where *LEVEL* can be one of the following: + +never +Approval is never required\. + +any\-change +Requires approval on any IAM or security\-group related change\. + +broadening +\(default\) Requires approval when IAM statements or traffic rules are added\. Removals don't require approval\. + +The setting can also be configured in the `cdk.json` file\. + +``` +{ + "app": "...", + "requireApproval": "never" +} +``` + +## Version Reporting + +To gain insight into how the CDK is used, the versions of libraries used by CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. + +The CDK reports the name and version of `npm` modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. + +The `AWS::CDK::Metadata` resource looks like the following\. + +``` +CDKMetadata: + Type: "AWS::CDK::Metadata" + Properties: + Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,lodash=4.17.10" +``` + +## Opting Out from Version Reporting + +To opt out of version reporting, use one of the following methods: ++ Use the cdk command with the \-\-no\-version\-reporting argument\. + + ``` + cdk --no-version-reporting synth + ``` ++ Set versionReporting to **false** in `./cdk.json` or `~/cdk.json`\. + + ``` + { + "app": "...", + "versionReporting": false + } + ``` + +## Plugins + +The CDK Toolkit provides extension points that enable users to augment the features provided by the toolkit\. There is currently only one extension point, allowing users to define custom AWS credential providers, but other extension points may be added in the future as needed\. + +### Loading Plugins + +Plugins can be loaded by providing the Node module name \(or path\) to the CDK Toolkit: ++ Using the \-\-plugin command line option, which can be specified multiple times\. + + ``` + cdk list --plugin=module + cdk deploy --plugin=module_1 --plugin=module_2 + ``` ++ Adding entries to the `~/.cdk.json` or `cdk.json` file\. + + ``` + { + // ... + "plugin": [ + "module_1", + "module_2" + ], + // ... + } + ``` + +### Initialization Templates + +The CDK provides a template for each of the supported languages\. Simply supply the name of the language after the \-\-language flag\. Use the help see a list of the language options: + +``` +cdk help init +``` + +### Authoring Plugins + +Plugins must be authored in TypeScript or JavaScript, and are defined by implementing a Node\.js module that implements the following protocol, and using [PluginHost\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost) methods\. + +------ +#### [ TypeScript ] + +``` +import cdk = require('aws-cdk'); + +export = { + version: '1', // Version of the plugin infrastructure (currently always '1') + init(host: cdk.PluginHost): void { + // Your plugin initialization hook. + // Use methods of host to register custom code with the CDK Toolkit. + } +}; +``` + +------ +#### [ JavaScript ] + +``` +export = { + version: '1', // Version of the plugin infrastructure (currently always '1') + init(host) { + // Your plugin initialization hook. + // Use methods of host to register custom code with the CDK Toolkit. + } +}; +``` + +------ + +### Credential Provider Plugins + +Custom credential providers are classes that implement the [CredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.CredentialProviderSource) interface, and that are registered to the toolkit using the [registerCredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost.registerCredentialProviderSource) method\. + +------ +#### [ TypeScript ] + +``` +import cdk = require('aws-cdk'); +import aws = require('aws-sdk'); + +class CustomCredentialProviderSource implements cdk.CredentialProviderSource { + public async isAvailable(): Promise { + // Return false if the plugin could determine it cannot be used (for example, + // if it depends on files that are not present on this host). + return true; + } + + public async canProvideCredentials(accountId: string): Promise { + // Return false if the plugin is unable to provide credentials for the + // requested account (for example, if it's not managed by the credentials + // system that this plugin adds support for). + return true; + } + + public async getProvider(accountId: string, mode: cdk.Mode): Promise { + let credentials: aws.Credentials; + // Somehow obtain credentials in credentials, and return those. + return credentials; + } +} + +export = { + version = '1', + init(host: cdk.PluginHost): void { + // Register the credential provider to the PluginHost. + host.registerCredentialProviderSource(new CustomCredentialProviderSource()); + } +}; +``` + +------ +#### [ JavaScript ] + +``` +class CustomCredentialProviderSource { + async isAvailable() { + // Return false if the plugin could determine it cannot be used (for example, + // if it depends on files that are not present on this host). + return true; + } + + async canProvideCredentials(accountId) { + // Return false if the plugin is unable to provide credentials for the + // requested account (for example if it's not managed by the credentials + // system that this plugin adds support for). + return true; + } + + async getProvider(accountId, mode) { + let credentials; + // Somehow obtain credentials in credentials, and return those. + return credentials; + } +} + +export = { + version = '1', + init(host) { + // Register the credential provider to the PluginHost. + host.registerCredentialProviderSource(new CustomCredentialProviderSource()); + } +}; +``` + +------ + +Note that the credentials obtained from the providers for a given account and mode will be cached, and as a consequence, we strongly advise that the credentials objects that are returned are self\-refreshing, as described in the [AWS SDK for JavaScript](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html) documentation\. \ No newline at end of file diff --git a/doc_source/cloudformation.md b/doc_source/cloudformation.md index a34ed002..684ce38a 100644 --- a/doc_source/cloudformation.md +++ b/doc_source/cloudformation.md @@ -4,62 +4,11 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# AWS CloudFormation Library +# AWS CloudFormation The [AWS Construct Library](aws_construct_lib.md)includes constructs with APIs for defining AWS infrastructure\. For example, you can use the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct to define Amazon Simple Storage Service \(Amazon S3\) buckets, and the [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) construct to define Amazon Simple Notification Service \(Amazon SNS\) topics\. Under the hood, these constructs are implemented using AWS CloudFormation resources, which are available in the `CfnXxx` classes in each library\. For example, the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct uses the [@aws\-cdk/aws\-s3\.cloudformation\.BucketResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.cloudformation.BucketResource) resource \(as well as other resources, depending on what bucket APIs are used\)\. **Important** -Generally, when building CDK apps, you shouldn't need to interact with AWS CloudFormation directly\. However, there might be advanced use cases and migration scenarios where this might be required\. We are also aware that there might be gaps in capabilities in the AWS Construct Library over time\. - -## Resources - -The CDK creates the low\-level resources from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) on a regular basis\. The classes are available under the `CfnXxx` classes of each AWS library\. Their API matches 1:1 with how you would use these resources in AWS CloudFormation\. - -When defining AWS CloudFormation resources, the `props` argument of the class initializer matches 1:1 to the resource's properties in AWS CloudFormation\. - -For example, to define an [AWS::SQS::Queue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html) resource encrypted with an AWS managed key, you can directly specify the [KmsMasterKeyId](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-kmsmasterkeyid) property\. - -``` -import sqs = require('@aws-cdk/aws-sqs'); - -new sqs.CfnQueue(this, 'MyQueueResource', { - kmsMasterKeyId: 'alias/aws/sqs' -}); -``` - -For reference, if you use the [Queue](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sqs.html#@aws-cdk/aws-sqs.Queue) construct, you can define managed queue encryption as follows\. - -``` -import sqs = require('@aws-cdk/aws-sqs'); - -new sqs.Queue(this, 'MyQueue', { - encryption: sqs.QueueEncryption.KmsManaged -}); -``` - -## Resource Object Properties - -Use resource object properties to get a runtime attribute of an AWS CloudFormation resource\. - -The following example configures the dead letter queue of an AWS Lambda function to use the Amazon Resource Name \(ARN\) of an Amazon SQS queue resource\. - -``` -import sqs = require('@aws-cdk/aws-sqs'); -import lambda = require('@aws-cdk/aws-lambda'); - -const dlq = new sqs.CfnQueue(this, { name: 'DLQ' }); - -new lambda.CfnFunction(this, { - deadLetterConfig: { - targetArn: dlq.queueArn - } -}); -``` - -The [cdk\.Resource\.ref](@cdk-class-url;#@aws-cdk/cdk.Resource.ref) attribute represents the AWS CloudFormation resource's intrinsic reference \(or *return value*\)\. For example, *dlq\.ref* also [refers](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-properties-sqs-queues-ref) to the queue's ARN\. When possible, use an explicitly named attribute instead of *ref*\. - -## Resource Options - -For resources, the [cdk\.Resource\.options](@cdk-class-url;#@aws-cdk/cdk.Resource.options) object includes AWS CloudFormation options, such as `condition`, `updatePolicy`, `createPolicy`, and `metadata`\. \ No newline at end of file +Avoid interacting directly with AWS CloudFormation unless absolutely necessary, such as when a CDK AWS Construct Library does not provide the needed functionality\. \ No newline at end of file diff --git a/doc_source/concepts.md b/doc_source/concepts.md deleted file mode 100644 index 33c92728..00000000 --- a/doc_source/concepts.md +++ /dev/null @@ -1,11 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# AWS CDK Concepts - -This topic describes some of the concepts \(the why and how\) behind the CDK\. It also discusses the advantages of the AWS Construct Library over a low\-level AWS CloudFormation Resource\. - -CDK apps are composed of building blocks known as [Constructs](constructs.md), which are used to create [stacks](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) and [apps](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app)\. \ No newline at end of file diff --git a/doc_source/constructs.md b/doc_source/constructs.md index b06c025d..2ada5f32 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -86,7 +86,7 @@ new s3.Bucket(this, 'MyBucket', { We recommend that you avoid specifying physical names\. Instead, let AWS CloudFormation generate names for you\. Use attributes, such as `bucket.bucketName`, to discover the generated names\. -When you synthesize a CDK app into an AWS CloudFormation template, the AWS CloudFormation logical ID for each resource in the template is allocated according to the path of that resource in the scope hierarchy\. For more information, see [Logical IDs](logical_ids.md)\. +When you synthesize a CDK app into an AWS CloudFormation template, the AWS CloudFormation logical ID for each resource in the template is allocated according to the path of that resource in the scope hierarchy\. ## Construct Properties diff --git a/doc_source/environments_and_context.md b/doc_source/context.md similarity index 63% rename from doc_source/environments_and_context.md rename to doc_source/context.md index 04e4472c..30c48df9 100644 --- a/doc_source/environments_and_context.md +++ b/doc_source/context.md @@ -4,44 +4,11 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# Environments and Run\-Time Context - -The CDK refers to the combination of an account ID and an AWS Region as an *environment*\. The simplest environment is the one you get by default\. This is the one you get when you have set up your credentials and a default Region as described in [Specifying Your Credentials](install_config.md#credentials)\. - -When you synthesize a stack to create an AWS CloudFormation template, the CDK might need information based on the run time context, such as the Availability Zones or Amazon Machine Images \(AMIs\) that are available in the Region\. To enable this feature, the CDK Toolkit uses *context providers*, and saves the context information into the `cdk.json` file the first time you call `cdk synth`\. - -## Environments and Authentication - -When you create a [stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) instance, you can supply the target deployment environment for the stack using the `env` property\. This is shown in the following example, where *REGION* is the AWS Region in which you want to create the stack and *ACCOUNT* is your account ID\. - -``` -new MyStack(app, { env: { region: 'REGION', account: 'ACCOUNT' } }); -``` - -For each of the two arguments, `region` and `account`, the CDK uses the following lookup procedure: -+ If `region` or `account`is provided directly as a property to the stack, use that\. -+ If either property is not specified when you create a stack, the CDK determines them as follows: - + `account` – Use the account from the default SDK credentials\. Environment variables are tried first \(`AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`\), followed by credentials in `$HOME/.aws/credentials` on Linux or macOS, or `%USERPROFILE%\.aws\credentials` on Windows\. - + `region` – Use the default Region configured in `$HOME/.aws/config` on Linux or macOS, or `%USERPROFILE%\.aws\config` on Windows\. - - You can set these defaults manually, but we recommend you use `aws configure`, as described in [Installing and Configuring the AWS CDK](install_config.md)\. - -We recommend that you use the default environment for development stacks, and explicitly specify accounts and Regions for production stacks\. - -**Note** -Although the Region and account might explicitly be set on your stack, if you run `cdk deploy`, the CDK still uses the currently configured SDK credentials that are provided through environment variables or `aws configure`\. This means that if you want to deploy stacks to multiple accounts, you have to set the correct credentials for each invocation to `cdk deploy STACK`\. - -You can always find the Region within which your stack is deployed by using the `region` property of the stack, as follows\. - -``` -this.region -``` - -## Run\-Time Context +# Run\-Time Context The CDK uses context to retrieve information such as the Availability Zones in your account or Amazon Machine Image \(AMI\) IDs used to start your instances\. To avoid unexpected changes to your deployments, such as when a new Amazon Linux AMI is released, thus changing your Auto Scaling group, the CDK stores context values in `cdk.context.json`\. This ensures that the CDK retrieves the same value the next time it synthesises your app\. Don't forget to put this file under version control\. -### Viewing and Managing Context +## Viewing and Managing Context Use the cdk context to see context values stored for your application\. The output should be something like the following\. @@ -88,11 +55,11 @@ To clear all context values, run cdk context \-\-clear\. cdk context --clear ``` -### Context Providers +## Context Providers The AWS CDK currently supports the following context providers\. -[AvailabilityZoneProvider](@cdk-class-url;#@aws-cdk/cdk.AvailabilityZoneProvider) +[AvailabilityZoneProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.AvailabilityZoneProvider) Use this provider to get the list of all supported Availability Zones in this context, as shown in the following example\. ``` @@ -113,7 +80,7 @@ const zone: HostedZoneRef = new HostedZoneProvider(this, { }).findAndImport(this, 'HostedZone'); ``` -[SSMParameterProvider](@cdk-class-url;#@aws-cdk/cdk.SSMParameterProvider) +[SSMParameterProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.SSMParameterProvider) Use this provider to read values from the current Region's AWS Systems Manager parameter store\. For example, the following code returns the value of the *my\-awesome\-parameter* key\. ``` diff --git a/doc_source/core_concepts.md b/doc_source/core_concepts.md index dec605d8..07bd171a 100644 --- a/doc_source/core_concepts.md +++ b/doc_source/core_concepts.md @@ -4,8 +4,8 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# CDK Core +# Concepts -This topic describes some of the core concepts \(the why and how\) behind the CDK\. It also discusses the advantages of using the AWS Construct Library instead of a low\-level AWS CloudFormation Resource\. +This topic describes some of the concepts \(the why and how\) behind the CDK\. It also discusses the advantages of using the AWS Construct Library instead of a low\-level AWS CloudFormation Resource\. CDK apps are composed of building blocks known as [Constructs](constructs.md), which are composed together to form [stacks](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) and [apps](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app)\. \ No newline at end of file diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 36d198e9..66db4a03 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -4,12 +4,10 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# Document History for the AWS CDK User Guide +# Document History for the AWS CDK Developer Guide -The following table describes the documentation for this release of the AWS Cloud Development Kit \(CDK\) \(CDK\)\. +This document is based on the following release of the AWS Cloud Development Kit \(CDK\) \(CDK\)\. ++ **API version: 0\.27\.0** ++ **Latest documentation update:** April 3, 2019 -See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the CDK releases\. -+ **API version: 0\.21\.0** -+ **Latest documentation update:** December 27, 2018 -| Change | Description | Date | -| --- |--- |--- | \ No newline at end of file +See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the CDK releases\. \ No newline at end of file diff --git a/doc_source/ecs_tutorial.md b/doc_source/ecs_example.md similarity index 83% rename from doc_source/ecs_tutorial.md rename to doc_source/ecs_example.md index 53568c07..cf31e933 100644 --- a/doc_source/ecs_tutorial.md +++ b/doc_source/ecs_example.md @@ -4,9 +4,9 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# Creating an AWS Fargate Service Using the AWS CDK +# Creating an AWS Fargate Service Using the AWS CDK -This tutorial walks you through how to create an AWS Fargate service running on an Amazon Elastic Container Service \(Amazon ECS\) cluster that's fronted by an internet\-facing Application Load Balancer from an image on DockerHub\. +This example walks you through how to create an AWS Fargate service running on an Amazon Elastic Container Service \(Amazon ECS\) cluster that's fronted by an internet\-facing Application Load Balancer from an image on Amazon ECR\. Amazon ECS is a highly scalable, fast, container management service that makes it easy to run, stop, and manage Docker containers on a cluster\. You can host your cluster on a serverless infrastructure that's managed by Amazon ECS by launching your services or tasks using the Fargate launch type\. For more control, you can host your tasks on a cluster of Amazon Elastic Compute Cloud \(Amazon EC2\) instances that you manage by using the Amazon EC2 launch type\. @@ -15,7 +15,7 @@ This tutorial shows you how to launch some services using the Fargate launch typ + [Setting Up with Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/get-set-up-for-amazon-ecs.html) + [Getting Started with Amazon ECS Using Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_GetStarted.html) -This tutorial creates a similar Fargate service in CDK code\. +This example creates a similar Fargate service in CDK code\. The Amazon ECS construct used in this tutorial helps you use AWS services by providing the following benefits: + Automatically configures a load balancer\. @@ -33,7 +33,7 @@ The Amazon ECS construct used in this tutorial helps you use AWS services by pro See the [Amazon ECS Construct Library](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ecs.html#aws-elastic-container-service-ecs-construct-library) reference for details\. -## Creating the Directory and Initializing the CDK +## Creating the Directory and Initializing the CDK Let's start by creating a directory to hold the CDK code, and then creating a CDK app in that directory\. @@ -60,7 +60,7 @@ Resources: Modules: @aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_ecs_construct=0.1.0 ``` -## Add the Amazon EC2 and Amazon ECS Packages +## Add the Amazon EC2 and Amazon ECS Packages Install support for Amazon EC2 and Amazon ECS\. @@ -68,7 +68,7 @@ Install support for Amazon EC2 and Amazon ECS\. npm install @aws-cdk/aws-ec2 @aws-cdk/aws-ecs ``` -## Create a Fargate Service +## Create a Fargate Service There are two different ways to run your container tasks with Amazon ECS: + Use the `Fargate` launch type, where Amazon ECS manages the physical machines that your containers are running on for you\. @@ -99,7 +99,7 @@ Replace the comment at the end of the constructor with the following code\. cluster: cluster, // Required cpu: '512', // Default is 256 desiredCount: 6, // Default is 1 - image: ecs.ContainerImage.fromDockerHub('amazon/amazon-ecs-sample'), // Required + image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"), // Required memoryMiB: '2048', // Default is 512 publicLoadBalancer: true // Default is false }); @@ -122,11 +122,4 @@ cdk deploy AWS CloudFormation displays information about the dozens of steps that it takes as it deploys your app\. -That's how easy it is to create a Fargate service to run a Docker image\. - -## What Next? -+ Learn more about [AWS CDK Concepts](concepts.md) -+ Check out the [examples directory](https://github.com/awslabs/aws-cdk/tree/master/examples) in your GitHub repository -+ Learn about the rich APIs offered by the [AWS Construct Library](aws_construct_lib.md) -+ Work directly with CloudFormation using the [AWS CloudFormation Library](cloudformation.md) -+ Come talk to us on [Gitter](https://gitter.im/awslabs/aws-cdk) \ No newline at end of file +That's how easy it is to create a Fargate service to run a Docker image\. \ No newline at end of file diff --git a/doc_source/examples.md b/doc_source/examples.md new file mode 100644 index 00000000..bf1ef053 --- /dev/null +++ b/doc_source/examples.md @@ -0,0 +1,11 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Examples + +This topic contains the following examples: ++ [Creating a Serverless Application Using the AWS CDK](serverless_example.md)Creates a serverless application using Lambda, API Gateway, and Amazon S3\. ++ [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. \ No newline at end of file diff --git a/doc_source/get_context_var.md b/doc_source/get_context_var.md index 7a723d65..fbc01ff4 100644 --- a/doc_source/get_context_var.md +++ b/doc_source/get_context_var.md @@ -6,7 +6,7 @@ This documentation is for the developer preview release \(public beta\) of the A # Get a Value from a Context Variable -You can specify a context variable either as part of a CDK Toolkit command, or in a **context** section of `cdk.json`\. +You can specify a context variable either as part of a CDK Toolkit command, or in `cdk.json`\. To create a command line context variable, use the **\-\-context** \(**\-c**\) option of a CDK Toolkit command, as shown in the following example\. @@ -27,5 +27,5 @@ To specify the same context variable and value in the `cdk.json` file, use the f To get the value of a context variable in your app, use code like the following, which gets the value of the context variable **bucket\_name**\. ``` -const bucket_name string = this.node.getContext("bucket_name"); +const bucket_name = this.node.getContext("bucket_name"); ``` \ No newline at end of file diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 9ccab84c..a776aef1 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -8,15 +8,7 @@ This documentation is for the developer preview release \(public beta\) of the A You can get the value of an AWS Systems Manager Parameter Store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It isn't possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from AWS Secrets Manager \(see [Get a Value from AWS Secrets Manager](passing_secrets_manager.md)\)\. -To retrieve the latest value one time \(as a context value, see [Run\-Time Context](environments_and_context.md#context)\), and keep on using the same value until the context value is manually refreshed, use an [SSMParameterProvider](@cdk-class-url;#@aws-cdk/cdk.SSMParameterProvider)\. - -``` -import cdk = require('@aws-cdk/cdk'); - -const myvalue = new cdk.SSMParameterProvider(this).getString("my-parameter-name"); -``` - -To read a particular version of a Systems Manager Parameter Store plain string value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstorestring)\. +To read a particular version of a Systems Manager Parameter Store plain string value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstorestring)\. If you don't supply a `version` value, you get the latest version\. ``` import ssm = require('@aws-cdk/aws-ssm'); @@ -26,10 +18,10 @@ const parameterString = new ssm.ParameterStoreString(this, 'MyParameter', { version: 1, }); -const myvalue = parameterString.value; +const myvalue = parameterString.stringValue; ``` -To read a particular version of a Systems Manager Parameter Store `SecureString` value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreSecureString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstoresecurestring) +To read a particular version of a Systems Manager Parameter Store `SecureString` value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreSecureString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstoresecurestring)\. You must supply a `version` value\. ``` import ssm = require('@aws-cdk/aws-ssm'); @@ -39,5 +31,5 @@ const secureString = new ssm.ParameterStoreSecureString(this, 'MySecretParameter version: 1, }); -const myvalue = secureString.value; +const myvalue = secureString.stringValue; ``` \ No newline at end of file diff --git a/doc_source/hello_world_tutorial.md b/doc_source/getting_started.md similarity index 56% rename from doc_source/hello_world_tutorial.md rename to doc_source/getting_started.md index f1c3f690..2cf46b7e 100644 --- a/doc_source/hello_world_tutorial.md +++ b/doc_source/getting_started.md @@ -4,21 +4,202 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# Hello World Tutorial +# Getting Started With the AWS CDK + +This topic describes how to install and configure the AWS CDK and create your first CDK app\. + +## Prerequisites + +**CDK command line tools** ++ [Node\.js \(>= 8\.11\.x\)](https://nodejs.org/en/download) ++ You must specify both your credentials and an AWS Region to use the CDK Toolkit;, as described in [Specifying Your Credentials](#getting_started_credentials)\. + +------ +#### [ TypeScript ] + +TypeScript >= 2\.7 + +------ +#### [ JavaScript ] + +none + +------ +#### [ Java ] ++ Maven 3\.5\.4 and Java 8 ++ Set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine + +------ +#### [ C\# ] + +\.NET standard 2\.0 compatible implementation: ++ \.NET Core >= 2\.0 ++ \.NET Framework >= 4\.6\.1 ++ Mono >= 5\.4 + +------ + +## Installing the CDK + +Install the CDK using the following command\. + +``` +npm install -g aws-cdk +``` + +Run the following command to see the version number of the CDK\. + +``` +cdk --version +``` + +## Installing the Core CDK Library for Your Language + +You must install the CDK core library to get the basic classes needed to create CDK stacks and apps\. + +------ +#### [ TypeScript ] + +``` +npm install @aws-cdk/cdk +``` + +------ +#### [ JavaScript ] + +``` +npm install @aws-cdk/cdk +``` + +------ +#### [ Java ] + +Add the following to your project’s pom\.xml file: + +``` + + + software.amazon.awscdk + cdk + + + +``` + +------ +#### [ C\# ] + +``` +dotnet add package Amazon.CDK +``` + +------ + +## Updating Your Language Dependencies + +If you get an error message that your language framework is out of date, use one of the following commands to update the components that the CDK needs to support the lanuage\. + +------ +#### [ TypeScript ] + +``` +npx npm-check-updates -u +``` + +------ +#### [ JavaScript ] + +``` +npx npm-check-updates -u +``` + +------ +#### [ Java ] + +``` +mvn versions:use-latest-versions +``` + +------ +#### [ C\# ] + +``` +nuget update +``` + +------ + +## Specifying Your Credentials + +You must specify your default credentials and AWS Region to use the CDK Toolkit\. You can do that in the following ways: ++ Using the AWS Command Line Interface \(AWS CLI\)\. This is the method we recommend\. ++ Using environment variables\. ++ Using the \-\-profile option to cdk commands\. + +### Using the AWS CLI to Specify Credentials + +Use the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide) aws configure command to specify your default credentials and Region\. + +### Using Environment Variables to Specify Credentials + +You can also set environment variables for your default credentials and Region\. Environment variables take precedence over settings in the credentials or config file\. ++ `AWS_ACCESS_KEY_ID` – Specifies your access key\. ++ `AWS_SECRET_ACCESS_KEY` – Specifies your secret access key\. ++ `AWS_DEFAULT_REGION` – Specifies your default Region\. + +For example, to set the default Region to `us-east-2` on Linux or macOS: + +``` +export AWS_DEFAULT_REGION=us-east-2 +``` + +To do the same on Windows: + +``` +set AWS_DEFAULT_REGION=us-east-2 +``` + +See [Environment Variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-environment.html) in the *AWS Command Line Interface User Guide* for details\. + +### Using the \-\-profile Option to Specify Credentials + +Use the \-\-profile *PROFILE* option to a cdk command to the alternative profile *PROFILE* when executing the command\. + +For example, if the `~/.aws/credentials` \(Linux or Mac\) or `%USERPROFILE%\.aws\credentials` \(Windows\) file contains the following profiles: + +``` +[default] +aws_access_key_id=AKIAIOSFODNN7EXAMPLE +aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY + +[test] +aws_access_key_id=AKIAI44QH8DHBEXAMPLE +aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY +``` + +You can deploy your app using the **test** profile with the following command\. + +``` +cdk deploy --profile test +``` + +See [Named Profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) in the AWS CLI documentation for details\. + +## Hello World Tutorial The typical workflow for creating a new app is: -1. Create a directory and navigate to it\. +1. Create the app directory\. -1. To create the skeleton of the app in the programming language *LANGUAGE*, call cdk init \-\-language *LANGUAGE*\. +1. Initialize the app\. -1. Add constructs \(and stacks, if appropriate\) to the skeleton code\. +1. Add code to the app\. -1. Compile your code, if necessary\. +1. Compile the app, if necessary\. -1. To deploy the resources you've defined, call cdk deploy\. +1. To deploy the resources defined in the app\. -1. Test your deployment\. +1. Test the app\. 1. If there are any issues, loop through modify, compile \(if necessary\), deploy, and test again\. @@ -26,27 +207,50 @@ And of course, keep your code under version control\. This tutorial walks you through how to create and deploy a simple AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. The app contains one resource, an Amazon S3 bucket\. -## Step 1: Create the Project Directory +### Creating the App Directory -Create a directory for your project with an empty Git repository\. +Create a directory for your app with an empty Git repository\. ``` mkdir hello-cdk cd hello-cdk ``` -## Initializing the Project +### Initializing the App -Initialize an empty project, where *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), or **typescript** \(TypeScript\)\. +Initialize an empty app, where *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), or **typescript** \(TypeScript\)\. + +------ +#### [ TypeScript ] ``` -cdk init --language LANGUAGE +cdk init --language typescript ``` -**Note** -Remember that every CDK command has a help option\. For example, cdk init help lists the available languages for the \-\-language \(\-l\) option\. +------ +#### [ JavaScript ] + +``` +cdk init --language javascript +``` + +------ +#### [ Java ] + +``` +cdk init --language java +``` + +------ +#### [ C\# ] + +``` +cdk init --language csharp +``` + +------ -## Compiling the Project +### Compiling the App Compile your program, as follows\. @@ -80,7 +284,7 @@ cdk ------ -## Listing the Stacks in the App +### Listing the Stacks in the App List the stacks in the app\. @@ -94,7 +298,7 @@ The result is just the name of the stack\. HelloCdkStack ``` -## Adding an Amazon S3 Bucket +### Adding an Amazon S3 Bucket At this point, what can you do with this app? Nothing, because the stack is empty, so there's nothing to deploy\. Let's define an Amazon S3 bucket\. @@ -235,7 +439,7 @@ namespace HelloCdk Notice a few things: + [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.Bucket) is a construct\. This means it's initialization signature has `scope`, `id`, and `props`\. In this case, the bucket is an immediate child of **MyStack**\. -+ `MyFirstBucket` is the **id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. See [Logical IDs](logical_ids.md) for information about logical IDs\. To specify a physical name for your bucket, set the [bucketName](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketProps.bucketName) property when you define your bucket\. ++ `MyFirstBucket` is the **id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. To specify a physical name for your bucket, set the [bucketName](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketProps.bucketName) property when you define your bucket\. + Because the bucket's [versioned](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. Compile your program, as follows\. @@ -270,9 +474,9 @@ cdk ------ -## Synthesizing an AWS CloudFormation Template +### Synthesizing an AWS CloudFormation Template -Synthesize an AWS CloudFormation template for the stack, as follows\. +Synthesize an AWS CloudFormation template for the app, as follows\. ``` cdk synth HelloCdkStack @@ -304,19 +508,19 @@ Resources: You can see that the stack contains an `AWS::S3::Bucket` resource with the versioning configuration we want\. **Note** -The toolkit automatically added the **AWS::CDK::Metadata** resource to your template\. The CDK uses metadata to gain insight into how the CDK is used\. One possible benefit is that the CDK team could notify users if a construct is going to be deprecated\. For details, including how to [opt out](tools.md#version_reporting_opt_out) of version reporting, see [Version Reporting](tools.md#version_reporting) \. +The toolkit automatically added the **AWS::CDK::Metadata** resource to your template\. The CDK uses metadata to gain insight into how the CDK is used\. One possible benefit is that the CDK team could notify users if a construct is going to be deprecated\. For details, including how to [opt out](cli.md#version_reporting_opt_out) of version reporting, see [Version Reporting](cli.md#version_reporting) \. -## Deploying the Stack +### Deploying the Stack -Deploy the stack, as follows\. +Deploy the app, as follows\. ``` cdk deploy ``` -The deploy command synthesizes an AWS CloudFormation template from the stack, and then invokes the AWS CloudFormation create/update API to deploy it into your AWS account\. If your code includes changes to your existing infrastructure, the command displays information about those changes and requires you to confirm them before it deploys the changes\. The command displays information as it completes various steps in the process\. There is no mechanism to detect or react to any specific step in the process\. +The deploy command synthesizes an AWS CloudFormation template from the app, and then invokes the AWS CloudFormation create/update API to deploy it into your AWS account\. If your code includes changes to your existing infrastructure, the command displays information about those changes and requires you to confirm them before it deploys the changes\. The command displays information as it completes various steps in the process\. There is no mechanism to detect or react to any specific step in the process\. -## Modifying the Code +### Modifying the App Configure the bucket to use AWS Key Management Service \(AWS KMS\) managed encryption\. @@ -403,9 +607,9 @@ cdk ------ -## Preparing for Deployment +### Preparing for Deployment -Before you deploy the updated stack, evaluate the difference between the CDK app and the deployed stack\. +Before you deploy the updated app, evaluate the difference between the CDK app and the deployed app\. ``` cdk diff @@ -444,9 +648,9 @@ Stack ARN: arn:aws:cloudformation:us-west-2:188580781645:stack/HelloCdkStack/96956990-feff-11e8-9284-50a68a0e3256 ``` -## Destroying the Stack +### Destroying the App's Resources -Destroy the stack to avoid incurring any costs from the resources created in this tutorial, as follows\. +Destroy the app's resources to avoid incurring any costs from the resources created in this tutorial, as follows\. ``` cdk destroy diff --git a/doc_source/index.md b/doc_source/index.md index 1741b521..84271a48 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -1,4 +1,4 @@ -# AWS Cloud Development Kit (CDK) User Guide +# AWS Cloud Development Kit (CDK) Developer Guide ----- *****Copyright © 2019 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** @@ -15,32 +15,35 @@ Amazon's trademarks and trade dress may not be used in ----- ## Contents + [What Is the AWS CDK?](what-is.md) -+ [Installing and Configuring the AWS CDK](install_config.md) -+ [Hello World Tutorial](hello_world_tutorial.md) -+ [AWS CDK Concepts](concepts.md) - + [CDK Core](core_concepts.md) - + [Constructs](constructs.md) - + [Apps and Stacks](apps_and_stacks.md) - + [Logical IDs](logical_ids.md) - + [Environments and Run-Time Context](environments_and_context.md) - + [Assets](assets.md) - + [AWS Construct Library](aws_construct_lib.md) - + [AWS CloudFormation Library](cloudformation.md) - + [Accessing the AWS CloudFormation Layer](cfn_layer.md) ++ [Getting Started With the AWS CDK](getting_started.md) ++ [Concepts](core_concepts.md) + + [Constructs](constructs.md) + + [Apps and Stacks](apps_and_stacks.md) + + [Resources](resources.md) + + [Run-Time Context](context.md) + + [Assets](assets.md) + + [AWS CloudFormation](cloudformation.md) + + [Tokens](tokens.md) + + [AWS CDK Lifecycle](lifecycle.md) ++ [Writing AWS CDK Constructs](writing_constructs.md) + + [Multi-Language Support in the CDK](multiple_languages.md) ++ [AWS Construct Library](aws_construct_lib.md) ++ [About the Reference](reference.md) ++ [Examples](examples.md) + + [Creating a Serverless Application Using the AWS CDK](serverless_example.md) + + [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) + + [AWS CDK Examples](about_examples.md) + [AWS CDK HowTos](how_tos.md) - + [Get External Values in a CDK Application](how_to_get_ext_values.md) - + [Get a Value from a Context Variable](get_context_var.md) - + [Get a Value from an Environment Variable](get_env_var.md) - + [Get a Value from a Systems Manager Parameter Store Variable](get_ssm_value.md) - + [Get a Value from AWS Secrets Manager](passing_secrets_manager.md) - + [Pass in a Value from Another Stack](passing_stack_value.md) - + [Use an AWS CloudFormation Parameter](get_cfn_param.md) - + [Use an Existing AWS CloudFormation Template](use_cfn_template.md) + + [Get a Value from an Environment Variable](get_env_var.md) + + [Use an AWS CloudFormation Parameter](get_cfn_param.md) + + [Use an Existing AWS CloudFormation Template](use_cfn_template.md) + + [Get a Value from a Systems Manager Parameter Store Variable](get_ssm_value.md) + + [Get a Value from AWS Secrets Manager](passing_secrets_manager.md) + + [Work Around Missing AWS CDK Features](cfn_layer.md) + + [Create an App with Multiple Stacks](stack_how_to_create_multiple_stacks.md) + [Set a CloudWatch Alarm](how_to_set_cw_alarm.md) - + [Stack How-Tos](stack_how_to.md) -+ [Advanced Tutorials](advanced_tutorials.md) - + [Creating a Serverless Application Using the AWS CDK](serverless_tutorial.md) - + [Creating an AWS Fargate Service Using the AWS CDK](ecs_tutorial.md) -+ [AWS CDK Command Line Toolkit (cdk)](tools.md) -+ [Writing AWS CDK Constructs](writing_constructs.md) -+ [Document History for the AWS CDK User Guide](doc-history.md) \ No newline at end of file + + [Get a Value from a Context Variable](get_context_var.md) ++ [CDK Toolchain](tools.md) + + [AWS CDK Command Line Interface (cdk)](cli.md) ++ [OpenPGP Keys for the AWS CDK and JSII](pgp-keys.md) ++ [Document History for the AWS CDK Developer Guide](doc-history.md) \ No newline at end of file diff --git a/doc_source/install_config.md b/doc_source/install_config.md deleted file mode 100644 index 31c5f701..00000000 --- a/doc_source/install_config.md +++ /dev/null @@ -1,141 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Installing and Configuring the AWS CDK - -This topic describes how to install the AWS CDK\. - -## Prerequisites - -**CDK command line tools** -+ [Node\.js \(>= 8\.11\.x\)](https://nodejs.org/en/download) -+ You must specify both your credentials and an AWS Region to use the CDK Toolkit;, as described in [Specifying Your Credentials](#credentials)\. - ------- -#### [ TypeScript ] - -TypeScript >= 2\.7 - ------- -#### [ JavaScript ] - -TypeScript >= 2\.7 - ------- -#### [ Java ] -+ Maven 3\.5\.4 and Java 8 -+ Set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine - ------- -#### [ C\# ] - -TBD - ------- - -## Installing the CDK - -Install the CDK using the following command\. - -``` -npm install -g aws-cdk -``` - -Run the following command to see the version number of the CDK\. - -``` -cdk --version -``` - -## Updating Your Language Dependencies - -If you get an error message that your language framework is out of date, use one of the following commands to update the components that the CDK needs to support the lanuage\. - ------- -#### [ TypeScript ] - -``` -npx npm-check-updates -u -``` - ------- -#### [ JavaScript ] - -``` -npx npm-check-updates -u -``` - ------- -#### [ Java ] - -``` -mvn versions:use-latest-versions -``` - ------- -#### [ C\# ] - -``` -nuget update -``` - ------- - -## Specifying Your Credentials - -You must specify your default credentials and AWS Region to use the CDK Toolkit\. You can do that in the following ways: -+ Using the AWS Command Line Interface \(AWS CLI\)\. This is the method we recommend\. -+ Using environment variables\. -+ Using the \-\-profile option to cdk commands\. - -### Using the AWS CLI to Specify Credentials - -Use the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide) aws configure command to specify your default credentials and Region\. - -### Using Environment Variables to Specify Credentials - -You can also set environment variables for your default credentials and Region\. Environment variables take precedence over settings in the credentials or config file\. -+ `AWS_ACCESS_KEY_ID` – Specifies your access key\. -+ `AWS_SECRET_ACCESS_KEY` – Specifies your secret access key\. -+ `AWS_DEFAULT_REGION` – Specifies your default Region\. - -For example, to set the default Region to `us-east-2` on Linux or macOS: - -``` -export AWS_DEFAULT_REGION=us-east-2 -``` - -To do the same on Windows: - -``` -set AWS_DEFAULT_REGION=us-east-2 -``` - -See [Environment Variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-environment.html) in the *AWS Command Line Interface User Guide* for details\. - -### Using the \-\-profile Option to Specify Credentials - -Use the \-\-profile *PROFILE* option to a cdk command to the alternative profile *PROFILE* when executing the command\. - -For example, if the `~/.aws/credentials` \(Linux or Mac\) or `%USERPROFILE%\.aws\credentials` \(Windows\) file contains the following profiles: - -``` -[default] -aws_access_key_id=AKIAIOSFODNN7EXAMPLE -aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY - -[test] -aws_access_key_id=AKIAI44QH8DHBEXAMPLE -aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY -``` - -You can deploy your app using the **test** profile with the following command\. - -``` -cdk deploy --profile test -``` - -See [Named Profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) in the AWS CLI documentation for details\. \ No newline at end of file diff --git a/doc_source/lifecycle.md b/doc_source/lifecycle.md new file mode 100644 index 00000000..ade3fe2b --- /dev/null +++ b/doc_source/lifecycle.md @@ -0,0 +1,37 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# AWS CDK Lifecycle + +The following illustration shows the phases that the CDK goes through when you call cdk deploy to create the resources defined by your application\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/Lifecycle.png) + +There are three actors at play to create the resources that your CDK application defines\. ++ Your CDK app\. ++ The CDK Toolkit\. ++ AWS CloudFormation, which the CDK Toolkit calls to deploy your application and create the resources\. + +After you use the toolkit to deploy a CDK application, the application goes through the following phases\. + +Construction +Your code instantiates all desired application constructs and links them together\. + +Preparation +All constructs that have implemented the `prepare` method participate in a final round of modifications, to set up any final state they want to\. The preparation phase happens automatically and users do not see any feedback from this phase\. + +Validation +All constructs that have implemented their `validate` method can validate themselves to make sure they've ended up in a state that will correctly deploy\. Users see any validation failures that are detected during this phase\. + +Synthesis +All constructs render themselves to a set of artifacts, representing AWS CloudFormation templates, AWS Lambda application bundles, and other deployment artifacts\. Users do not see any feedback from this phase\. + +Deployment +The toolkit takes the artifacts produced by the synthesis step, uploads them to Amazon S3 or wherever they need to go, and starts an AWS CloudFormation deployment to deploy the application and create the resources\. + +Note that your CDK app has already finished and exited by the time the AWS CloudFormation deployment starts\. This has the following implications\. ++ Your CDK app cannot respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a Custom Resource\. ++ Your CDK app might have to work with values that cannot be known at the time it executes\. For example, if your CDK application defines an Amazon S3 Bucket with an automatically generated name, and you retrieve the `bucket.bucketName` attribute, that value is not the name of the deployed bucket\. Instead, the value of the `bucketName` attribute is a symbolic value, looking like *$\{TOKEN\[Bucket\.Name\.1234\]\}*\. You can pass this value to constructs, or append it to other strings, and the CDK framework will translate that value\. You cannot examine the value and make decisions based on the deployed bucket name, because the bucket name not available until AWS CloudFormation is done deploying, and by that time your program is no longer running\. Call `cdk.unresolved(value)`, which returns `true` if `value` not known until deployment time\. \ No newline at end of file diff --git a/doc_source/logical_ids.md b/doc_source/logical_ids.md deleted file mode 100644 index 6aabe2d3..00000000 --- a/doc_source/logical_ids.md +++ /dev/null @@ -1,75 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Logical IDs - -When you synthesize a stack into an AWS CloudFormation template, the CDK assigns a [ logical ID](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html), which must be unique within the template, to each resource in the stack\. - -**Important** -When you update the template, AWS CloudFormation uses these logical IDs to plan the update and apply changes\. Therefore, logical IDs must remain "stable" across updates\. If you make a modification in your code that results in a change to a logical ID of a resource, AWS CloudFormation deletes the resource and creates a new resource when it updates the stack\. - -Each resource in the construct tree has a unique path that represents its location within the tree\. Because logical IDs can use only alphanumeric characters and can't exceed 255 characters, the CDK is unable to use a delimited path as the logical ID\. Instead, logical IDs are allocated by concatenating a human\-friendly rendition from the path \(concatenation, de\-duplicate, trim\) with an eight\-character MD5 hash of the delimited path\. This final component is necessary because AWS CloudFormation logical IDs can't include the delimiting slash character \(/\), so simply concatenating the component values doesn't work\. For example, concatenating the components of the path */a/b/c* produces **abc**, which is the same as concatenating the components of the path */ab/c*\. - -``` -VPCPrivateSubnet2RouteTable0A19E10E -<-----------human---------><-hash-> -``` - -Low\-level AWS CloudFormation resources \(from `@aws-cdk/resources`\) that are direct children of the [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) class use their names as their logical IDs without modification\. This makes it easier to port existing templates into a CDK app\. - -This scheme ensures the following\. - -Logical IDs have a human\-friendly portion\. -This is useful when interacting directly with the synthesized AWS CloudFormation template during development and deployment\. - -Logical IDs are unique within the stack\. -This is ensured by the MD5 component, which is based on the absolute path to the resource, which is unique within a stack\. - -Logical IDs remain unchanged across updates\. -This is true as long as their location within the scope hierarchy doesn't change\. - -The CDK applies some heuristics to improve the human friendliness of the prefix: -+ If a path component is **Default**, it's hidden completely from the logical ID computation\. Typically, you want to use this if you create a new construct that wraps an existing one\. By naming the inner construct **Default**, you ensure that the logical identifiers of resources in already\-deployed copies of that construct don't change\. -+ If a path component is **Resource**, it's omitted from the human\-readable portion of the logical ID\. This postfix doesn't normally contribute any additional useful information to the ID\. -+ If two subsequent names in the path are the same, only one is retained\. -+ If the prefix exceeds 240 characters, it's trimmed to 240 characters\. This ensures that the total length of the logical ID doesn't exceed the 255 character AWS CloudFormation limit for logical IDs\. - -## Renaming Logical IDs - -Use the `aws-cdk.Stack.renameLogical` method to explicitly assign logical IDs to certain resources\. - -``` -class MyStack extends Stack { - constructor(scope: App, id: string, props: StackProps) { - super(scope, id); - - // Note that renameLogical must be called /before/ defining the construct. - // A good practice would be to always put these at the top of your stack initializer. - this.renameLogical('MyTableCD117FA1', 'MyTable'); - this.renameLogical('MyQueueAB4432A3', 'MyAwesomeQueue'); - - new Table(this, 'MyTable'); - new Queue(this, 'MyQueue'); - } -} -``` - -In some cases, changing a resource results in a structural change, which results in a different path\. This changes the logical ID of the resource\. - -When a resource's logical ID changes, AWS CloudFormation eventually deletes the old resource and creates a new resource, as it can't determine that the two resources are the same\. Depending on the nature of the resource, this can be disastrous in production, such as when deleting an Amazon DynamoDB table\. - -You could use [AWS CloudFormation stack policies](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html) to protect critical resources in your stack from accidental deletion\. Although this AWS CloudFormation feature isn't supported in the CDK and CDK Toolkit, the CDK does provide a few other mechanisms to help you handle logical ID changes\. - -If you have CDK stacks deployed with persistent resources, such as Amazon S3 buckets or DynamoDB tables, you might want to explicitly "rename" the new logical IDs to match your existing resources\. - -First, make sure you compare the newly synthesized template with any deployed stacks\. `cdk diff` will tell you which resources are about to be destroyed\. - -``` -[-] ☢️ Destroying MyTable (type: AWS::DynamoDB::Table) -[+] 🆕 Creating MyTableCD117FA1 (type: AWS::DynamoDB::Table) -``` - -Now, you can add an `aws-cdk.Stack.renameLogical` call before the table is defined to rename **MyTableCD117FA1** to **MyTable**\. \ No newline at end of file diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md new file mode 100644 index 00000000..66d482f7 --- /dev/null +++ b/doc_source/multiple_languages.md @@ -0,0 +1,82 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Multi\-Language Support in the CDK + +This section describes the multi\-language support in the CDK, including hints for porting TypeScript to one of the supported languages\. See [Hello World Tutorial](getting_started.md#hello_world_tutorial) for an example of creating a CDK app in a supported language\. + +The CDK supports C\#, Java, JavaScript, and TypeScript\. Since the CDK is developed in TypeScript, many code examples are still only available in TypeScript\. This section will help you port those TypeScript examples to one of the other programming languages\. + +## Importing a Package + +In TypeScript, you import a package as follows \(we'll use Amazon S3 for our examples\): + +``` +import lambda = require("@aws-cdk/aws-s3"); +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.S3; +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.s3.*; +``` + +------ +#### [ JavaScript ] + +``` +const s3 = require('@aws-cdk/aws-s3'); +``` + +------ + +## Creating a New Object + +In TypeScript, you create a new object as follows\. The first argument, `scope`, is always `this`, the second is the `id` of the construct, and the last is a list of properties, often optional\. + +``` +new s3.Bucket(this, 'MyFirstBucket', { + // options +}); +``` + +------ +#### [ C\# ] + +``` +new Bucket(this, "MyFirstBucket", new BucketProps +{ + // options +}); +``` + +------ +#### [ Java ] + +``` +new Bucket(this, "MyFirstBucket", BucketProps.builder() + // options +} +``` + +------ +#### [ JavaScript ] + +``` +new s3.Bucket(this, 'MyFirstBucket', { + // options +}); +``` + +------ \ No newline at end of file diff --git a/doc_source/passing_secrets_manager.md b/doc_source/passing_secrets_manager.md index 92e9d8a6..168d915b 100644 --- a/doc_source/passing_secrets_manager.md +++ b/doc_source/passing_secrets_manager.md @@ -6,23 +6,19 @@ This documentation is for the developer preview release \(public beta\) of the A # Get a Value from AWS Secrets Manager -To use values from AWS Secrets Manager in your CDK app, create an instance of [SecretsManager](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-secretsmanager.html/_aws-cdk_aws-secretsmanager.html#aws-cdk-aws-secretsmanager)\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. +To use values from AWS Secrets Manager in your CDK app, use the [Secret](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-secretsmanager.html#secret) class's `import` method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. ``` -import secretsmanager = require('@amp;aws-cdk/aws-secretsmanager'); - -const loginSecret = new secretsmanager.SecretString(stack, 'Secret', { - secretId: 'MyLogin' - - // By default, the latest version is retrieved. It's possible to - // use a specific version instead. - // versionStage: 'AWSCURRENT' -}); - -// Retrieve a value from the secret's JSON -const username = loginSecret.jsonFieldValue('username'); -const password = loginSecret.jsonFieldValue('password'); - -// Retrieve the whole secret's string value -const fullValue = loginSecret.value; +import sm = require("@aws-cdk/aws-secretsmanager"); + +export class SecretsManagerStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const secret = sm.Secret.import(this, "ImportedSecret", { + secretArn: + "arn:aws:secretsmanager:::secret:-" + // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: + // encryptionKey, + }); ``` \ No newline at end of file diff --git a/doc_source/passing_stack_value.md b/doc_source/passing_stack_value.md deleted file mode 100644 index 30f6d4d8..00000000 --- a/doc_source/passing_stack_value.md +++ /dev/null @@ -1,67 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Pass in a Value from Another Stack - -You can pass a value from one stack to another stack in the same app by using the `export` method in one stack and the `import` method in the other stack\. - -The following example creates a bucket on one stack and passes a reference to that bucket to the other stack through an interface\. - -First create a stack with a bucket\. The stack includes a property we use to pass the bucket's properties to the other stack\. Notice how we use the `export` method on the bucket to get its properties and save them in the stack property\. - -``` -class HelloCdkStack extends cdk.Stack { - // Property that defines the stack you are exporting from - public readonly myBucketImportProps: s3.BucketImportProps; - - constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { - super(scope, id, props); - - const mybucket = new s3.Bucket(this, "MyFirstBucket"); - - // Save bucket's BucketImportProps - this.myBucketImportProps = mybucket.export(); - } -} -``` - -Create an interface for the second stack's properties\. We use this interface to pass the bucket properties between the two stacks\. - -``` -// Interface we'll use to pass the bucket's properties to another stack -interface MyCdkStackProps { - theBucketImportProps: s3.BucketImportProps; -} -``` - -Create the second stack that gets a reference to the other bucket from the properties passed in through the constructor\. - -``` -// The class for the other stack -class MyCdkStack extends cdk.Stack { - constructor(scope: cdk.App, id: string, props: MyCdkStackProps) { - super(scope, id); - - const myOtherBucket = s3.Bucket.import(this, "MyOtherBucket", props.theBucketImportProps); - - // Do something with myOtherBucket - } -} -``` - -Finally, connect the dots in your app\. - -``` -const app = new cdk.App(); - -const myStack = new HelloCdkStack(app, "HelloCdkStack"); - -new MyCdkStack(app, "MyCdkStack", { - theBucketImportProps: myStack.myBucketImportProps -}); - -app.run(); -``` \ No newline at end of file diff --git a/doc_source/pgp-keys.md b/doc_source/pgp-keys.md new file mode 100644 index 00000000..44c927fc --- /dev/null +++ b/doc_source/pgp-keys.md @@ -0,0 +1,101 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# OpenPGP Keys for the AWS CDK and JSII + +This topic contains the OpenPGP keys for the CDK and JSII\. + +## CDK OpenPGP Key + + +| | | +| --- |--- | +| Key ID: | 0x0566A784E17F3870 | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2018\-06\-19 | +| Expires: | 2022\-06\-18 | +| User ID: | AWS CDK Team | +| Key fingerprint: | E88B E3B6 F0B1 E350 9E36 4F96 0566 A784 E17F 3870 | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBFsovE8BEADEFVCHeAVPvoQgsjVu9FPUczxy9P+2zGIT/MLI3/vPLiULQwRy +IN2oxyBNDtcDToNa/fTkW3Ev0NTP4V1h+uBoKDZD/p+dTmSDRfByECMI0sGZ3UsG +Ohhyl2Of44s0sL8gdLtDnqSRLf+ZrfT3gpgUnplW7VitkwLxr78jDpW4QD8p8dZ9 +WNm3JgB55jyPgaJKqA1Ln4Vduni/1XkrG42nxrrU71uUdZPvPZ2ELLJa6n0/raG8 +jq3le+xQh45gAIs6PGaAgy7jAsfbwkGTBHjjujITAY1DwvQH5iS31OaCM9n4JNpc +xGZeJAVYTLilznf2QtS/a50t+ZOmpq67Ssp2j6qYpiumm0Lo9q3K/R4/yF0FZ8SL +1TuNX0ecXEptiMVUfTiqrLsANg18EPtLZZOYW+ZkbcVytkDpiqj7bMwA7mI7zGCJ +1gjaTbcEmOmVdQYS1G6ZptwbTtvrgA6AfnZxX1HUxLRQ7tT/wvRtABfbQKAh85Ff +a3U9W4oC3c1MP5IyhNV1Wo8Zm0flZiZc0iZnojTtSG6UbcxNNL4Q8e08FWjhungj +yxSsIBnQO1Aeo1N4BbzlI+n9iaXVDUN7Kz1QEyS4PNpjvUyrUiQ+a9C5sRA7WP+x +IEOaBBGpoAXB3oLsdTNO6AcwcDd9+r2NlXlhWC4/uH2YHQUIegPqHmPWxwARAQAB +tCFBV1MgQ0RLIFRlYW0gPGF3cy1jZGtAYW1hem9uLmNvbT6JAj8EEwEIACkFAlso +vE8CGy8FCQeEzgAHCwkIBwMCAQYVCAIJCgsEFgIDAQIeAQIXgAAKCRAFZqeE4X84 +cLGxD/0XHnhoR2xvz38GM8HQlwlZy9W1wVhQKmNDQUavw8Zx7+iRR3m7nq3xM7Qq +BDbcbKSg1lVLSBQ6H2V6vRpysOhkPSH1nN2dO8DtvSKIPcxK48+1x7lmO+ksSs/+ +oo1UvOmTDaRzOitYh3kOGXHHXk/l11GtF2FGQzYssX5iM4PHcjBsK1unThs56IMh +OJeZezEYzBaskTu/ytRJ236bPP2kZIEXfzAvhmTytuXWUXEftxOxc6fIAcYiKTha +aofG7WyR+Fvb1j5gNLcbY552QMxa23NZd5cSZH7468WEW1SGJ3AdLA7k5xvsPPOC +2YvQFD+vUOZ1JJuu6B5rHkiEMhRTLklkvqXEShTxuXiCp7iTOo6TBCmrWAT4eQr7 +htLmqlXrgKi8qPkWmRdXXG+MQBzI/UyZq2q8KC6cx2md1PhANmeefhiM7FZZfeNM +WLonWfh8gVCsNH5h8WJ9fxsQCADd3Xxx3NelS2zDYBPRoaqZEEBbgUP6LnWFprA2 +EkSlc/RoDqZCpBGgcoy1FFWvV/ZLgNU6OTQlYH6oYOWiylSJnaTDyurrktsxJI6d +4gdsFb6tqwTGecuUPvvZaEuvhWExLxAebhu780FdAPXgVTX+YCLI2zf+dWQvkFQf +80RE7ayn7BsiaLzFBVux/zz/WgvudsZX18r8tDiVQBL51ORmqw== +=0wuQ +-----END PGP PUBLIC KEY BLOCK----- +``` + +## JSII OpenPGP Key + + +| | | +| --- |--- | +| Key ID: | 0x1C7ACE4CB2A1B93A | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2018\-08\-06 | +| Expires: | 2022\-08\-05 | +| User ID: | AWS JSII Team | +| Key fingerprint: | 85EF 6522 4CE2 1E8C 72DB 28EC 1C7A CE4C B2A1 B93A | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBFtoSs0BEAD6WweLD0B26h0F7Jo9iR6tVQ4PgQBK1Va5H/eP+A2Iqw79UyxZ +WNzHYhzQ5MjYYI1SgcPavXy5/LV1N8HJ7QzyKszybnLYpNTLPYArWE8ZM9ZmjvIR +p1GzwnVBGQfoOlxyeutE9T5ZkAn45dTS5jlno4unji4gHjnwXKf2nP1APU2CZfdK +8vDpLOgj9LeeGlerYNbx+7xtY/I+csFIQvK09FPLSNMJQLlkBhY0r6Rt9ZQG+653 +tJn+AUjyM237w0UIX1IqyYc5IONXu8HklPGu0NYuX9AY/63Ak2Cyfj0w/PZlvueQ +noQNM3j0nkOEsTOEXCyaLQw9iBKpxvLnm5RjMSODDCkj8c9uu0LHr7J4EOtgt2S1 +pem7Y/c/N+/Z+Ksg9fP8fVTfYwRPvdI1x2sCiRDfLoQSG9tdrN5VwPFi4sGV04sI +x7Al8Vf/OBjAGZrDaJgM/gVvb9SKAQUA6t3ofeP14gDrS0eYodEXZ+lamnxFglxF +Sn8NRC4JFNmkXSUaTNGUdFf//F0D69PRNT8CnFfmniGj0CphN5037PCA2LC/Buq2 +3+K6mTPkCcCHYPC/SwItp/xIDAQsGuDc1i1SfDYXrjsK7uOuwC5jLA9X6wZ/jgXQ +4umRRJBAV1aW8b1+yfaYYCO2AfXXO6caObv8IvH7Pc4leC2DoqylD3KklQARAQAB +tCNBV1MgSlNJSSBUZWFtIDxhd3MtanNpaUBhbWF6b24uY29tPokCPwQTAQgAKQUC +W2hKzQIbLwUJB4TOAAcLCQgHAwIBBhUIAgkKCwQWAgMBAh4BAheAAAoJEBx6zkyy +obk6B34P/iNb5QjKyhT0glZiq1wK7tuDDRpR6fC/sp6Jd/GhaNjO4BzlDbUPSjW5 +950VT+qwaHXbIma/QVP7EIRztfwWy7m8eOodjpiu7JyJprhwG9nocXiNsLADcMoH +BvabkDRWXWIWSurq2wbcFMlTVwxjHPIQs6kt2oojpzP985CDS/KTzyjow6/gfMim +DLdhSSbDUM34STEgew79L2sQzL7cvM/N59k+AGyEMHZDXHkEw/Bge5Ovz50YOnsp +lisH4BzPRIw7uWqPlkVPzJKwMuo2WvMjDfgbYLbyjfvs5mqDxT2GTwAx/rd2taU6 +iSqP0QmLM54BtTVVdoVXZSmJyTmXAAGlITq8ECZ/coUW9K2pUSgVuWyu63lktFP6 +MyCQYRmXPh9aSd4+ielteXM9Y39snlyLgEJBhMxioZXVO2oszwluPuhPoAp4ekwj +/umVsBf6As6PoAchg7Qzr+lRZGmV9YTJOgDn2Z7jf/7tOes0g/mdiXTQMSGtp/Fp +ggnifTBx3iXkrQhqHlwtam8XTHGHy3MvX17ZslNuB8Pjh+07hhCxv0VUVZPUHJqJ +ZsLa398LMteQ8UMxwJ3t06jwDWAd7mbr2tatIilLHtWWBFoCwBh1XLe/03ENCpDp +njZ7OsBsBK2nVVcN0H2v5ey0T1yE93o6r7xOwCwBiVp5skTCRUob +=2Tag +-----END PGP PUBLIC KEY BLOCK----- +``` \ No newline at end of file diff --git a/doc_source/reference.md b/doc_source/reference.md new file mode 100644 index 00000000..2a57db1c --- /dev/null +++ b/doc_source/reference.md @@ -0,0 +1,11 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# About the Reference + +See the [CDK Reference](https://awslabs.github.io/aws-cdk/) for information about the CDK libraries\. + +Each library contains information about how to use the library\. For example, the [Amazon S3](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html) library demonstrates how to set default encryption on an Amazon S3 bucket\. \ No newline at end of file diff --git a/doc_source/resources.md b/doc_source/resources.md new file mode 100644 index 00000000..05875b5d --- /dev/null +++ b/doc_source/resources.md @@ -0,0 +1,56 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Resources + +The CDK creates the low\-level resources from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) on a regular basis\. The classes are available under the `CfnXxx` classes of each AWS library\. Their API matches 1:1 with how you would use these resources in AWS CloudFormation\. + +When defining AWS CloudFormation resources, the `props` argument of the class initializer matches 1:1 to the resource's properties in AWS CloudFormation\. + +For example, to define an [AWS::SQS::Queue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html) resource encrypted with an AWS managed key, you can directly specify the [KmsMasterKeyId](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-kmsmasterkeyid) property\. + +``` +import sqs = require('@aws-cdk/aws-sqs'); + +new sqs.CfnQueue(this, 'MyQueueResource', { + kmsMasterKeyId: 'alias/aws/sqs' +}); +``` + +For reference, if you use the [Queue](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sqs.html#@aws-cdk/aws-sqs.Queue) construct, you can define managed queue encryption as follows\. + +``` +import sqs = require('@aws-cdk/aws-sqs'); + +new sqs.Queue(this, 'MyQueue', { + encryption: sqs.QueueEncryption.KmsManaged +}); +``` + +## Resource Object Properties + +Use resource object properties to get a runtime attribute of an AWS CloudFormation resource\. + +The following example configures the dead letter queue of an AWS Lambda function to use the Amazon Resource Name \(ARN\) of an Amazon SQS queue resource\. + +``` +import sqs = require('@aws-cdk/aws-sqs'); +import lambda = require('@aws-cdk/aws-lambda'); + +const dlq = new sqs.CfnQueue(this, { name: 'DLQ' }); + +new lambda.CfnFunction(this, { + deadLetterConfig: { + targetArn: dlq.queueArn + } +}); +``` + +The [cdk\.CfnResource\.ref](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.ref) attribute represents the AWS CloudFormation resource's intrinsic reference \(or *return value*\)\. For example, *dlq\.ref* also [refers](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-properties-sqs-queues-ref) to the queue's ARN\. When possible, use an explicitly named attribute instead of *ref*\. + +## Resource Options + +For resources, the [cdk\.CfnResource\.options](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.options) object includes AWS CloudFormation options, such as `condition`, `updatePolicy`, `createPolicy`, and `metadata`\. \ No newline at end of file diff --git a/doc_source/serverless_tutorial.md b/doc_source/serverless_example.md similarity index 84% rename from doc_source/serverless_tutorial.md rename to doc_source/serverless_example.md index a32c62b3..9d142965 100644 --- a/doc_source/serverless_tutorial.md +++ b/doc_source/serverless_example.md @@ -4,9 +4,9 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# Creating a Serverless Application Using the AWS CDK +# Creating a Serverless Application Using the AWS CDK -This tutorial walks you through how to create the resources for a simple widget dispensing service\. It includes: +This example walks you through how to create the resources for a simple widget dispensing service\. It includes: + An AWS Lambda function\. + An Amazon API Gateway API to call the Lambda function\. + An Amazon S3 bucket that contains the Lambda function code\. @@ -28,7 +28,7 @@ This tutorial contains the following steps\. + Get a widget by name with GET /\{name\} + Delete a widget by name with DELETE /\{name\} -## Create a CDK App +## Create a CDK App Create the TypeScript app **MyWidgetService** in the current folder\. @@ -57,7 +57,7 @@ Resources: Modules: "@aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_widget_service=0.1.0" ``` -## Create a Lambda Function to List All Widgets +## Create a Lambda Function to List All Widgets The next step is to create a Lambda function to list all of the widgets in our Amazon S3 bucket\. @@ -117,7 +117,7 @@ npm run build cdk synth ``` -## Creating a Widget Service +## Creating a Widget Service Add the API Gateway, Lambda, and Amazon S3 packages to the app\. @@ -128,40 +128,40 @@ npm install @aws-cdk/aws-apigateway @aws-cdk/aws-lambda @aws-cdk/aws-s3 Create the TypeScript file `widget_service.ts` in the `lib` directory\. ``` -import cdk = require('@aws-cdk/cdk'); -import apigateway = require('@aws-cdk/aws-apigateway'); -import lambda = require('@aws-cdk/aws-lambda'); -import s3 = require('@aws-cdk/aws-s3'); +import cdk = require("@aws-cdk/cdk"); +import apigateway = require("@aws-cdk/aws-apigateway"); +import lambda = require("@aws-cdk/aws-lambda"); +import s3 = require("@aws-cdk/aws-s3"); export class WidgetService extends cdk.Construct { constructor(scope: cdk.Construct, id: string) { super(scope, id); - const bucket = new s3.Bucket(this, 'WidgetStore'); + const bucket = new s3.Bucket(this, "WidgetStore"); - const handler = new lambda.Function(this, 'WidgetHandler', { - runtime: lambda.Runtime.NodeJS810, // So we can use async in widget.js - code: lambda.Code.directory('resources'), - handler: 'widgets.main', + const handler = new lambda.Function(this, "WidgetHandler", { + runtime: lambda.Runtime.NodeJS810, // So we can use async in widget.js + code: lambda.Code.directory("resources"), + handler: "widgets.main", environment: { BUCKET: bucket.bucketName } }); - bucket.grantReadWrite(handler.role); + bucket.grantReadWrite(handler); // was: handler.role); - const api = new apigateway.RestApi(this, 'widgets-api', { - restApiName: 'Widget Service', - description: 'This service serves widgets.' + const api = new apigateway.RestApi(this, "widgets-api", { + restApiName: "Widget Service", + description: "This service serves widgets." }); const getWidgetsIntegration = new apigateway.LambdaIntegration(handler, { - requestTemplates: { "application/json": '{ "statusCode": "200" }' } + requestTemplates: { "application/json": '{ "statusCode": "200" }' } }); - api.root.addMethod('GET', getWidgetsIntegration); // GET / + api.root.addMethod("GET", getWidgetsIntegration); // GET / - const widget = api.root.addResource('{id}'); + const widget = api.root.addResource("{id}"); // Add new widget to bucket with: POST /{id} const postWidgetIntegration = new apigateway.LambdaIntegration(handler); @@ -172,9 +172,9 @@ export class WidgetService extends cdk.Construct { // Remove a specific widget from the bucket with: DELETE /{id} const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); - widget.addMethod('POST', postWidgetIntegration); // POST /{id} - widget.addMethod('GET', getWidgetIntegration); // GET /{id} - widget.addMethod('DELETE', deleteWidgetIntegration); // DELETE /{id} + widget.addMethod("POST", postWidgetIntegration); // POST /{id} + widget.addMethod("GET", getWidgetIntegration); // GET /{id} + widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} } } ``` @@ -186,7 +186,7 @@ npm run build cdk synth ``` -## Add the Service to the App +## Add the Service to the App To add the service to the app, first modify `my_widget_service-stack.ts`\. Add the following line of code after the existing `import` statement\. @@ -207,9 +207,9 @@ npm run build cdk synth ``` -## Deploy and Test the App +## Deploy and Test the App -Before you can deploy your first CDK app, you must bootstrap your deployment\. This creates some AWS infrastructure that the CDK needs\. For details, see the **bootstrap** section of the [AWS CDK Command Line Toolkit \(cdk\)](tools.md)\(if you've already bootstrapped a CDK app, you'll get a warning and nothing will change\)\. +Before you can deploy your first CDK app, you must bootstrap your deployment\. This creates some AWS infrastructure that the CDK needs\. For details, see the **bootstrap** section of the [CDK Toolchain](tools.md)\(if you've already bootstrapped a CDK app, you'll get a warning and nothing will change\)\. ``` cdk bootstrap @@ -249,7 +249,7 @@ Because we haven't stored any widgets yet, the output should be similar to the f { "widgets": [] } ``` -## Add the Individual Widget Functions +## Add the Individual Widget Functions The next step is to create Lambda functions to create, show, and delete individual widgets\. diff --git a/doc_source/stack_how_to.md b/doc_source/stack_how_to.md deleted file mode 100644 index 06f99949..00000000 --- a/doc_source/stack_how_to.md +++ /dev/null @@ -1,76 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Stack How\-Tos - -This section contains some additional information about using stacks, including how to create a stack in a specific region with a specific account ID, and creating an app with multiple stacks\. For conceptual information about stacks, see [Stacks](apps_and_stacks.md#stacks)\. - -## Create a Stack with an Account and Region - -The following example shows how to create a stack in `us-west-1` for the account with ID `11223344`\. - -``` -new HelloStack(this, 'hello-cdk-us-west-1', { - env: { - account: '11223344', - region: 'us-west-1' -}}); -``` - -## Create an App with Multiple Stacks - -The following example shows one solution to parameterizing how you create a stack\. It creates one stack with a `t2.micro` AMI for development, and three stacks with the more expensive `c5.2xlarge` AMI\. The development stack and one of the production stacks use the same account to create the stack in `us-east-1`; the other two production stacks use different account IDs and regions\. - -``` -// lib/mystack.ts -// Defines my parameterized application which can be deployed anywhere. -// If dev is true, the stack is used for development, -// so it does not require the more expensive AMI. -interface MyStackProps extends cdk.StackProps { - dev: boolean; -} - -class MyStack extends cdk.Stack { - constructor(scope: cdk.App, id: string, props: MyStackProps) { - super(scope, id, props); - - const instanceType = props.dev - ? new ec.InstanceType('t2.micro') - : new ec.InstanceType('c5.2xlarge'); - - const fleet new MyComputeFleet(this, 'Fleet', { - instanceType, }); - - const queue = new sqs.Queue(this, 'Queue'); - queue.grantConsumeMessages(fleet.role); - } -} - -// bin/myapp.ts -const app = new cdk.App(); - -// Specify where MyStack instances are deployed -// and under what account. -const environments = [ - { account: '12345678', region: 'us-east-1' }, - { account: '87654321', region: 'eu-west-1' }, - { account: '12344321', region: 'ap-southeast-1' }, -]; - -// Beta instance in the first environment -new MyStack(app, 'BetaStack', { dev: true, env: environments[0] }); - -// Production instance in every other environment -for (const env of environments) { - new MyStack(app, `ProdStack-${env.region}`, { dev: false, env }); -} -``` - -The following example shows how to deploy a production stack using the `c5.2xlarge` AMI to the `us-east-1` region\. - -``` -cdk deploy ProdStack-us-east-1 -``` \ No newline at end of file diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md new file mode 100644 index 00000000..7fe83c55 --- /dev/null +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -0,0 +1,75 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Create an App with Multiple Stacks + +The following example shows one solution to parameterizing how you create a stack\. It creates one stack with a `t2.micro` AMI for development, and three stacks with the more expensive `c5.2xlarge` AMI\. The development stack and one of the production stacks use the same account to create the stack in `us-east-1`; the other two production stacks use different account IDs and regions\. + +The file `MyApp-stack.ts` defines a property set that extends the `cdk.StackProps` class to add one additional property, `enc`, which specifies whether to set encryption on the Amazon S3 bucket in the stack\. + +``` +import cdk = require("@aws-cdk/cdk"); +import s3 = require("@aws-cdk/aws-s3"); + +interface MyStackProps extends cdk.StackProps { + enc: boolean; +} + +export class MyStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props: MyStackProps) { + super(scope, id, props); + + if (props.enc) { + new s3.Bucket(this, "MyGroovyBucket", { + encryption: s3.BucketEncryption.KmsManaged + }); + } else { + new s3.Bucket(this, "MyGroovyBucket"); + } + } +} +``` + +The file `MyApp.ts` creates two stacks\. One with an unencrypted bucket in the `us-west-2` region; the other with an encrypted bucket in the `us-east-1` region\. + +``` +import cdk = require("@aws-cdk/cdk"); +import { MyStack } from "../lib/MyApp-stack"; + +const app = new cdk.App(); + +new MyStack(app, "MyWestCdkStack", { + env: { + region: "us-west-2" + }, + enc: false +}); + +new MyStack(app, "MyEastCdkStack", { + env: { + region: "us-east-1" + }, + enc: true +}); +``` + +The following example shows how to deploy a stack with an encrypted bucket to the `us-east-1` region\. + +``` +cdk deploy MyEastCdkStack +``` + +If you look at the stack using cdk synth MyEastCdkStack, you should see a bucket similar to the following: + +``` + MyGroovyBucketFD9882AC: + Type: AWS::S3::Bucket + Properties: + BucketEncryption: + ServerSideEncryptionConfiguration: + - ServerSideEncryptionByDefault: + SSEAlgorithm: aws:kms +``` \ No newline at end of file diff --git a/doc_source/how_to_get_ext_values.md b/doc_source/tokens.md similarity index 52% rename from doc_source/how_to_get_ext_values.md rename to doc_source/tokens.md index a600244c..3b5c286c 100644 --- a/doc_source/how_to_get_ext_values.md +++ b/doc_source/tokens.md @@ -4,6 +4,6 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# Get External Values in a CDK Application +# Tokens -The following sections contains short code examples that show you how to get external values in a CDK application\. \ No newline at end of file +Tokens represent instrinsic AWS CloudFormation values or values that not are known until deployment\. \ No newline at end of file diff --git a/doc_source/tools.md b/doc_source/tools.md index 7564532b..78003d8a 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -4,297 +4,6 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# AWS CDK Command Line Toolkit \(cdk\) +# CDK Toolchain -The CDK Toolkit, cdk, is the main tool you use to interact with your CDK app\. It executes the CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the CDK\. - -There are two ways to tell cdk what command to use to run your CDK app\. The first way is to include an explicit \-\-app option whenever you use a cdk command\. - -``` -cdk --app 'node bin/main.js' synth -``` - -The second way is to add the following entry to the `cdk.json` file\. - -``` -{ - "app": "node bin/main.js" -} -``` - -Here are the actions you can take on your CDK app \(this is the output of the cdk \-\-help command\)\. - -``` -Usage: cdk -a COMMAND - -Commands: - list Lists all stacks in the app [aliases: ls] - synthesize [STACKS..] Synthesizes and prints the CloudFormation template - for this stack [aliases: synth] - bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS - environment - deploy [STACKS..] Deploys the stack(s) named STACKS into your AWS - account - destroy [STACKS..] Destroy the stack(s) named STACKS - diff [STACKS..] Compares the specified stack with the deployed - stack or a local template file, and returns with - status 1 if any difference is found - metadata [STACK] Returns all metadata associated with this stack - init [TEMPLATE] Create a new, empty CDK project from a template. - Invoked without TEMPLATE, the app template will be - used. - context Manage cached context values - docs Opens the reference documentation in a browser - [aliases: doc] - doctor Check your set-up for potential problems - -Options: - --app, -a REQUIRED: Command-line for executing your CDK app (e.g. - "node bin/my-app.js") [string] - --context, -c Add contextual string parameter. [array] - --plugin, -p Name or path of a node package that extend the CDK - features. Can be specified multiple times [array] - --rename Rename stack name if different from the one defined in - the cloud executable [string] - --trace Print trace for stack warnings [boolean] - --strict Do not construct stacks with warnings [boolean] - --ignore-errors Ignores synthesis errors, which will likely produce an - invalid output [boolean] [default: false] - --json, -j Use JSON output instead of YAML [boolean] - --verbose, -v Show debug logs [boolean] - --profile Use the indicated AWS profile as the default environment - [string] - --proxy Use the indicated proxy. Will read from HTTPS_PROXY - environment variable if not specified. [string] - --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: - guess EC2 instance status. [boolean] - --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized - templates (enabled by default) [boolean] - --path-metadata Include "aws:cdk:path" CloudFormation metadata for each - resource (enabled by default) [boolean] [default: true] - --asset-metadata Include "aws:asset:*" CloudFormation metadata for - resources that user assets (enabled by default) - [boolean] [default: true] - --role-arn, -r ARN of Role to use when invoking CloudFormation [string] - --toolkit-stack-name The name of the CDK toolkit stack [string] - --ci Force CI detection. Use --no-ci to disable CI - autodetection. [boolean] [default: false] - --version Show version number [boolean] - -h, --help Show help [boolean] - -If your app has a single stack, there is no need to specify the stack name - -If one of cdk.json or ~/.cdk.json exists, options specified there will be used -as defaults. Settings in cdk.json take precedence. -``` - -If your app has a single stack, you don't have to specify the stack name\. - -If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. - -## Bootstrapping the CDK - -Before you can use the CDK you must bootstrap the CDK to create the infrastructure that the CDK needs\. Currently the bootstrap command creates only an Amazon S3 bucket\. - -You incur any charges for what the CDK stores in the bucket\. Because the CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. - -## Security\-Related Changes - -To protect you against unintended changes that affect your security posture, the CDK toolkit prompts you to approve security\-related changes before deploying them\. - -You change the level of changes that requires approval by specifying: - -``` -cdk deploy --require-approval LEVEL -``` - -Where *LEVEL* can be one of the following: - -never -Approval is never required\. - -any\-change -Requires approval on any IAM or security\-group related change\. - -broadening -\(default\) Requires approval when IAM statements or traffic rules are added\. Removals don't require approval\. - -The setting can also be configured in the `cdk.json` file\. - -``` -{ - "app": "...", - "requireApproval": "never" -} -``` - -## Version Reporting - -To gain insight into how the CDK is used, the versions of libraries used by CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. - -The CDK reports the name and version of `npm` modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. - -The `AWS::CDK::Metadata` resource looks like the following\. - -``` -CDKMetadata: - Type: "AWS::CDK::Metadata" - Properties: - Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,lodash=4.17.10" -``` - -## Opting Out from Version Reporting - -To opt out of version reporting, use one of the following methods: -+ Use the cdk command with the \-\-no\-version\-reporting argument\. - - ``` - cdk --no-version-reporting synth - ``` -+ Set versionReporting to **false** in `./cdk.json` or `~/cdk.json`\. - - ``` - { - "app": "...", - "versionReporting": false - } - ``` - -## Plugins - -The CDK Toolkit provides extension points that enable users to augment the features provided by the toolkit\. There is currently only one extension point, allowing users to define custom AWS credential providers, but other extension points may be added in the future as needed\. - -### Loading Plugins - -Plugins can be loaded by providing the Node module name \(or path\) to the CDK Toolkit: -+ Using the \-\-plugin command line option, which can be specified multiple times\. - - ``` - cdk list --plugin=module - cdk deploy --plugin=module_1 --plugin=module_2 - ``` -+ Adding entries to the `~/.cdk.json` or `cdk.json` file\. - - ``` - { - // ... - "plugin": [ - "module_1", - "module_2" - ], - // ... - } - ``` - -### Authoring Plugins - -Plugins must be authored in TypeScript or JavaScript, and are defined by implementing a Node\.js module that implements the following protocol, and using [PluginHost\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost) methods\. - ------- -#### [ TypeScript ] - -``` -import cdk = require('aws-cdk'); - -export = { - version: '1', // Version of the plugin infrastructure (currently always '1') - init(host: cdk.PluginHost): void { - // Your plugin initialization hook. - // Use methods of host to register custom code with the CDK Toolkit. - } -}; -``` - ------- -#### [ JavaScript ] - -``` -export = { - version: '1', // Version of the plugin infrastructure (currently always '1') - init(host) { - // Your plugin initialization hook. - // Use methods of host to register custom code with the CDK Toolkit. - } -}; -``` - ------- - -### Credential Provider Plugins - -Custom credential providers are classes that implement the [CredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.CredentialProviderSource) interface, and that are registered to the toolkit using the [registerCredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost.registerCredentialProviderSource) method\. - ------- -#### [ TypeScript ] - -``` -import cdk = require('aws-cdk'); -import aws = require('aws-sdk'); - -class CustomCredentialProviderSource implements cdk.CredentialProviderSource { - public async isAvailable(): Promise { - // Return false if the plugin could determine it cannot be used (for example, - // if it depends on files that are not present on this host). - return true; - } - - public async canProvideCredentials(accountId: string): Promise { - // Return false if the plugin is unable to provide credentials for the - // requested account (for example, if it's not managed by the credentials - // system that this plugin adds support for). - return true; - } - - public async getProvider(accountId: string, mode: cdk.Mode): Promise { - let credentials: aws.Credentials; - // Somehow obtain credentials in credentials, and return those. - return credentials; - } -} - -export = { - version = '1', - init(host: cdk.PluginHost): void { - // Register the credential provider to the PluginHost. - host.registerCredentialProviderSource(new CustomCredentialProviderSource()); - } -}; -``` - ------- -#### [ JavaScript ] - -``` -class CustomCredentialProviderSource { - async isAvailable() { - // Return false if the plugin could determine it cannot be used (for example, - // if it depends on files that are not present on this host). - return true; - } - - async canProvideCredentials(accountId) { - // Return false if the plugin is unable to provide credentials for the - // requested account (for example if it's not managed by the credentials - // system that this plugin adds support for). - return true; - } - - async getProvider(accountId, mode) { - let credentials; - // Somehow obtain credentials in credentials, and return those. - return credentials; - } -} - -export = { - version = '1', - init(host) { - // Register the credential provider to the PluginHost. - host.registerCredentialProviderSource(new CustomCredentialProviderSource()); - } -}; -``` - ------- - -Note that the credentials obtained from the providers for a given account and mode will be cached, and as a consequence, we strongly advise that the credentials objects that are returned are self\-refreshing, as described in the [AWS SDK for JavaScript](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html) documentation\. \ No newline at end of file +This section contains information about CDK tools\. \ No newline at end of file diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index c430b571..87c45b13 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -33,5 +33,5 @@ new cdk.Include(this, "ExistingInfrastructure", { Then to access an attribute of the resource, such as the bucket's ARN: ``` -const bucketArn = new cdk.Fn.getAtt("S3Bucket", "Arn"); +const bucketArn = cdk.Fn.getAtt("S3Bucket", "Arn"); ``` \ No newline at end of file diff --git a/doc_source/what-is.md b/doc_source/what-is.md index 9b896d90..d172a4b2 100644 --- a/doc_source/what-is.md +++ b/doc_source/what-is.md @@ -6,7 +6,15 @@ This documentation is for the developer preview release \(public beta\) of the A # What Is the AWS CDK? -Welcome to the *AWS CDK \(CDK\) User's Guide*\. This document provides information about the CDK, which is a software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. Use the CDK to define your cloud resources using one of the supported programming languages: C\#/\.NET, Java, JavaScript, or TypeScript\. This document does not supply reference information for the CDK\. You can find that information in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. +Welcome to the *AWS CDK \(CDK\) Developer Guide*\. This document provides information about the CDK, which is a software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. + +AWS CloudFormation enables you to: ++ Create and provision AWS infrastructure deployments predictably and repeatedly\. ++ Leverage AWS products such as Amazon EC2, Amazon Elastic Block Store, Amazon SNS, Elastic Load Balancing, and Auto Scaling\. ++ Build highly reliable, highly scalable, cost\-effective applications in the cloud without worrying about creating and configuring the underlying AWS infrastructure\. ++ Use a template file to create and delete a collection of resources together as a single unit \(a stack\)\. + +Use the CDK to define your cloud resources using one of the supported programming languages: C\#/\.NET, Java, JavaScript, or TypeScript\. This document does not supply reference information for the CDK\. You can find that information in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](apps_and_stacks.md#stacks) and [Apps](apps_and_stacks.md#apps)\. @@ -14,7 +22,7 @@ Developers can use one of the supported programming languages to define reusable ## Why Use the CDK? -Let's look at the power of the CDK\. Here is some TypeScript code in a CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate Service Using the AWS CDK](ecs_tutorial.md)\)\. +Let's look at the power of the CDK\. Here is some TypeScript code in a CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md)\)\. ``` export class MyEcsConstructStack extends cdk.Stack { @@ -34,13 +42,13 @@ export class MyEcsConstructStack extends cdk.Stack { cluster: cluster, // Required cpu: '512', // Default is 256 desiredCount: 6, // Default is 1 - image: ecs.ContainerImage.fromDockerHub('amazon/amazon-ecs-sample'), // Required + image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"), // Required memoryMiB: '2048', // Default is 512 publicLoadBalancer: true // Default is false }); ``` -This produces an AWS CloudFormation template of over 600 lines\. We'll show the first 25 lines and Outputs\. +This produces an AWS CloudFormation template of over 600 lines\. We'll show the first 25 lines and Outputs of a cdk synth command\. ``` Resources: @@ -76,11 +84,15 @@ Resources: - DNSName ``` +Another advantage of IAC \(infrastructure as code\) is that you get code completion within your IDE: + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/CodeCompletion.png) + ## Developing With the CDK -Unless otherwise indicated, the code examples in this guide are in TypeScript\. To aid you in porting a TypeScript example to a supported programming language, take a look at the example code for your language in the [CDK Reference](https://awslabs.github.io/aws-cdk/reference.html)\. +Unless otherwise indicated, the code examples in this guide are in TypeScript\. To aid you in porting a TypeScript example to a supported programming language, take a look at the example code for your language in the [CDK Reference](https://awslabs.github.io/aws-cdk/reference.html)\. The CDK also includes some [TypeScript examples](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript)\. -The [AWS CDK Command Line Toolkit \(cdk\)](tools.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. +The [CDK Toolchain](tools.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. The [AWS Construct Library](aws_construct_lib.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to create resources for an Amazon or AWS service\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. @@ -97,6 +109,7 @@ In addition to this guide, the following are other resources available to CDK us + [CDK Reference](https://awslabs.github.io/aws-cdk/) + [CDK Demo at re:Invent 2018](https://www.youtube.com/watch?v=Lh-kVC2r2AU) + [CDK Workshop](https://cdkworkshop.com/) ++ [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) + [AWS Developer Blog](https://aws.amazon.com/blogs/developer) + [Gitter Channel](https://gitter.im/awslabs/aws-cdk) + [Stack Overflow](https://stackoverflow.com/questions/tagged/aws-cdk) @@ -106,6 +119,8 @@ In addition to this guide, the following are other resources available to CDK us + [Documentation Source](https://github.com/awsdocs/aws-cdk-user-guide/tree/master/doc_source) + [License](https://github.com/awslabs/aws-cdk/blob/master/LICENSE) + [Releases](https://github.com/awslabs/aws-cdk/releases) + + [CDK OpenPGP Key](pgp-keys.md#cdk_pgp_key) + + [JSII OpenPGP Key](pgp-keys.md#jsii_pgp_key) + [AWS CDK Sample for Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/sample-cdk.html) + [AWS CloudFormation Concepts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html) + [AWS Glossary](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html) diff --git a/doc_source/writing_constructs.md b/doc_source/writing_constructs.md index b5b3ea48..72ef6320 100644 --- a/doc_source/writing_constructs.md +++ b/doc_source/writing_constructs.md @@ -17,38 +17,6 @@ This topic provides some tips for writing idiomatic new constructs for the CDK\. + Optimize for the common case\. For example, `AutoScalingGroup` accepts a `VPC` and deploys in the private subnet by default because that's the common case, but has an option to `placementOptions` for special cases\. + If a class can have multiple modes or behaviors, prefer values over polymorphism\. Try switching behavior on property values first\. Switch to multiple classes with a shared base class or interface only if there's value to be had from having multiple classes \(type safety, maybe one mode has different featuresor required parameters\)\. -## CDK Lifecycle - -The following illustration shows the phases that the CDK goes through when you call cdk deploy to create the resources defined by your application\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/Lifecycle.png) - -There are three actors at play to create the resources that your CDK application defines\. -+ Your CDK app\. -+ The CDK Toolkit\. -+ AWS CloudFormation, which the CDK Toolkit calls to deploy your application and create the resources\. - -After you use the toolkit to deploy a CDK application, the application goes through the following phases\. - -Construction -Your code instantiates all desired application constructs and links them together\. - -Preparation -All constructs that have implemented the `prepare` method participate in a final round of modifications, to set up any final state they want to\. The preparation phase happens automatically and users do not see any feedback from this phase\. - -Validation -All constructs that have implemented their `validate` method can validate themselves to make sure they've ended up in a state that will correctly deploy\. Users see any validation failures that are detected during this phase\. - -Synthesis -All constructs render themselves to a set of artifacts, representing AWS CloudFormation templates, AWS Lambda application bundles, and other deployment artifacts\. Users do not see any feedback from this phase\. - -Deployment -The toolkit takes the artifacts produced by the synthesis step, uploads them to Amazon S3 or wherever they need to go, and starts an AWS CloudFormation deployment to deploy the application and create the resources\. - -Note that your CDK app has already finished and exited by the time the AWS CloudFormation deployment starts\. This has the following implications\. -+ Your CDK app cannot respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a Custom Resource\. -+ Your CDK app might have to work with values that cannot be known at the time it executes\. For example, if your CDK application defines an Amazon S3 Bucket with an automatically generated name, and you retrieve the `bucket.bucketName` attribute, that value is not the name of the deployed bucket\. Instead, the value of the `bucketName` attribute is a symbolic value, looking like *$\{TOKEN\[Bucket\.Name\.1234\]\}*\. You can pass this value to constructs, or append it to other strings, and the CDK framework will translate that value\. You cannot examine the value and make decisions based on the deployed bucket name, because the bucket name not available until AWS CloudFormation is done deploying, and by that time your program is no longer running\. Call `cdk.unresolved(value)`, which returns `true` if `value` not known until deployment time\. - ## Implementation Details + Every construct consists of an exported class \(`MyConstruct`\) and an exported interface \(`MyConstructProps`\) that defines the parameters for these classes\. The `props` argument is the third to the construct \(after the mandatory `scope` and `id` arguments\), and the entire parameter should be optional if all of the properties on the `props` object are optional\. + Most of the logic happens in the constructor\. The constructor builds up the state of the construct \(what children it has, which ones are always there and which are optional, and so on\)\. From bfcc5a2e39dd9cc138b5986f9ad86ed47c87eb8e Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Wed, 24 Apr 2019 11:04:23 -0700 Subject: [PATCH 014/655] Updated CDK guide MD files --- CODE_OF_CONDUCT.md | 4 -- CONTRIBUTING.md | 56 --------------------------- README.md | 9 ----- doc_source/aspects.md | 9 +++++ doc_source/aws_construct_lib.md | 16 ++++++++ doc_source/build_lambda_sam.md | 9 +++++ doc_source/cfn_layer.md | 25 +----------- doc_source/cloudwatch_events.md | 9 +++++ doc_source/codepipeline_example.md | 9 +++++ doc_source/complex_auth.md | 9 +++++ doc_source/constructs.md | 4 ++ doc_source/control_cfn_template.md | 9 +++++ doc_source/create_custom_resources.md | 9 +++++ doc_source/debugging.md | 9 +++++ doc_source/deploy_pipeline.md | 9 +++++ doc_source/grant_permissions.md | 9 +++++ doc_source/identifiers.md | 9 +++++ doc_source/index.md | 19 +++++++++ doc_source/lifecycle.md | 2 +- doc_source/migrate_cfn.md | 9 +++++ doc_source/passing_secrets_manager.md | 10 ++++- doc_source/permissions.md | 9 +++++ doc_source/references.md | 9 +++++ doc_source/setup_asg.md | 9 +++++ doc_source/start_ec2_asg.md | 9 +++++ doc_source/toolchain_cicd.md | 9 +++++ doc_source/toolchain_sam.md | 9 +++++ doc_source/troubleshooting.md | 9 +++++ doc_source/what-is.md | 4 +- 29 files changed, 223 insertions(+), 97 deletions(-) delete mode 100644 CODE_OF_CONDUCT.md delete mode 100644 CONTRIBUTING.md delete mode 100644 README.md create mode 100644 doc_source/aspects.md create mode 100644 doc_source/build_lambda_sam.md create mode 100644 doc_source/cloudwatch_events.md create mode 100644 doc_source/codepipeline_example.md create mode 100644 doc_source/complex_auth.md create mode 100644 doc_source/control_cfn_template.md create mode 100644 doc_source/create_custom_resources.md create mode 100644 doc_source/debugging.md create mode 100644 doc_source/deploy_pipeline.md create mode 100644 doc_source/grant_permissions.md create mode 100644 doc_source/identifiers.md create mode 100644 doc_source/migrate_cfn.md create mode 100644 doc_source/permissions.md create mode 100644 doc_source/references.md create mode 100644 doc_source/setup_asg.md create mode 100644 doc_source/start_ec2_asg.md create mode 100644 doc_source/toolchain_cicd.md create mode 100644 doc_source/toolchain_sam.md create mode 100644 doc_source/troubleshooting.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 3b644668..00000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,4 +0,0 @@ -## 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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 18841707..00000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,56 +0,0 @@ -# Guidelines for contributing - -Thank you for your interest in contributing to AWS documentation! 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. - -## 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. - -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 look forward to receiving your pull requests for: - -* 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 - -**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 - -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: - -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. - -Before you send us a pull request, please be sure that: - -1. You're working from the latest source on the **master** branch. -2. You check [existing open](https://github.com/awsdocs/aws-cdk-user-guide/pulls), and [recently closed](https://github.com/awsdocs/aws-cdk-user-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-cdk-user-guide/issues/new) before working on a contribution that will take a significant amount of your time. - -For contributions that will take a significant amount of time, [open a new issue](https://github.com/awsdocs/aws-cdk-user-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-cdk-user-guide/issues) in this repository for some ideas. Any issues with the [help wanted](https://github.com/awsdocs/aws-cdk-user-guide/labels/help%20wanted) or [enhancement](https://github.com/awsdocs/aws-cdk-user-guide/labels/enhancement) labels are 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 - -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. - -## Licensing - -See the [LICENSE](https://github.com/awsdocs/aws-cdk-user-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. diff --git a/README.md b/README.md deleted file mode 100644 index 563defe1..00000000 --- a/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## AWS Cdk User Guide - -The markdown (MD) source for the [AWS Cloud Development Kit (CDK) User Guide](https://docs.aws.amazon.com/CDK/latest/userguide). - -## License Summary - -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/doc_source/aspects.md b/doc_source/aspects.md new file mode 100644 index 00000000..f8af4d40 --- /dev/null +++ b/doc_source/aspects.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Aspects + +TBD \ No newline at end of file diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md index c2d40ba8..0dc337ca 100644 --- a/doc_source/aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -20,12 +20,24 @@ Minor releases, such as 2\.4, guarantee that any code written in a previous mino The AWS Construct Library includes many common patterns and capabilities that are designed to enable developers to focus on their application\-specific architectures and reduce the boilerplate and glue logic needed when working with AWS services\. +### Roles + +Roles \.\.\. + ### Grants AWS Identity and Access Management \(IAM\) policies are automatically defined based on intent\. For example, when subscribing an Amazon Simple Notification Service \(Amazon SNS\) [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) to an AWS Lambda [Function](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.Function), the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. Also, most AWS constructs expose `grant*` methods that allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct has a [grantRead\(principal\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.grantRead) method\. This method accepts an IAM [Principal](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#iprincipal-interface) such as a [User](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#user) or a [Role](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#role), which modifies the policy to allow the principal to read objects from the bucket\. +### Resource Policies + +Resource policies \.\.\. + +### Principals + +Principals \.\.\. + ## Metrics Many AWS resources emit [Amazon CloudWatch metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html) as part of their normal operation\. Metrics can be used to set up an [Alarm](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Alarm) or can be included in a [Dashboard](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Dashboard)\. @@ -174,6 +186,10 @@ new MyCdkStack(app, "MyCdkStack", { app.run(); ``` +## Get a Value from Another App + +You can get a value from a stack in another app by ??? + ## Security Groups Amazon Elastic Compute Cloud \(Amazon EC2\) network entities, such as the [Elastic Load Balancing](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-elasticloadbalancingv2.html) and [Auto Scaling Group](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-autoscaling.html#auto-scaling-group) instances, can connect to each other based on definitions of security groups\. diff --git a/doc_source/build_lambda_sam.md b/doc_source/build_lambda_sam.md new file mode 100644 index 00000000..0bd52f76 --- /dev/null +++ b/doc_source/build_lambda_sam.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Building a Lambda App with the AWS SAM + +This section describes how to build and test a Lambda\-based app with the AWS SAM\. \ No newline at end of file diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 56dfe5ee..28d6f001 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -92,32 +92,9 @@ Synthesizes into the following template\. } ``` -## Overriding Resource Properties - -Each low\-level resource in the CDK has a strongly typed property named `propertyOverrides`\. It enables users to apply overrides that adhere to the AWS CloudFormation schema of the resource, and use code completion and type checking\. - -Use this mechanism when a certain feature is available at the AWS CloudFormation layer but isn't exposed by the AWS construct\. - -The following example sets a bucket's analytics configuration\. - -``` - bucketResource.addPropertyOverride("AnalyticsConfigurations", { - Id: "config1", - StorageClassAnalysis: { - dataExport: { - OutputSchemaVersion: "1", - Destination: { - Format: "html", - BucketArn: "arn:aws:s3:::" + bucketName // use tokens freely - } - } - } - }); -``` - ## Raw Overrides -If the strongly typed overrides aren't sufficient or, for example, if the schema defined in AWS CloudFormation is not up to date, use the [cdk\.CfnResource\.addOverride\(path, value\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.addOverride) method to define an override that is applied to the resource definition during synthesis\. This is shown in the following example\. + Use the [cdk\.CfnResource\.addOverride\(path, value\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.addOverride) method to define an override that is applied to the resource definition during synthesis, as shown in the following example\. ``` // Define an override at the resource definition root, you can even modify the "Type" diff --git a/doc_source/cloudwatch_events.md b/doc_source/cloudwatch_events.md new file mode 100644 index 00000000..d29e59ba --- /dev/null +++ b/doc_source/cloudwatch_events.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# ??? Amazon CloudWatch Events + +This section describes how to ??? CloudWatch events\. \ No newline at end of file diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md new file mode 100644 index 00000000..f5da9b9b --- /dev/null +++ b/doc_source/codepipeline_example.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Creating an AWS CodePipeline Service Using the AWS CDK + +This example creates a CodePipeline pipeline\. \ No newline at end of file diff --git a/doc_source/complex_auth.md b/doc_source/complex_auth.md new file mode 100644 index 00000000..1402bc04 --- /dev/null +++ b/doc_source/complex_auth.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Complex Authentication with the CDK + +This section describes how to perform complex authentication using the CDK\. \ No newline at end of file diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 2ada5f32..cb26ade2 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -106,6 +106,10 @@ const props: QueueProps = { new Queue(this, 'MyQueue', props); ``` +## Resource Attributes + +tba + ## Construct Metadata Attach metadata to a construct using the `addMetadata` method\. Metadata is an AWS CDK\-level annotation, and as such, does not appear in the deployed resources\. Metadata entries automatically include the stack trace from which the metadata entry was added to allow tracing back to your code, even if the entry was defined by a lower\-level library that you don't own\. diff --git a/doc_source/control_cfn_template.md b/doc_source/control_cfn_template.md new file mode 100644 index 00000000..4ed57435 --- /dev/null +++ b/doc_source/control_cfn_template.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Controlling an AWS CloudFormation Template Using the CDK + +This section describes how to control an AWS CloudFormation template using the CDK\. \ No newline at end of file diff --git a/doc_source/create_custom_resources.md b/doc_source/create_custom_resources.md new file mode 100644 index 00000000..e4900d64 --- /dev/null +++ b/doc_source/create_custom_resources.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Creating Custom Resources + +This section describes how to create custom resources\. A custom resource is a ??? \ No newline at end of file diff --git a/doc_source/debugging.md b/doc_source/debugging.md new file mode 100644 index 00000000..a3e66bbc --- /dev/null +++ b/doc_source/debugging.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Debugging Your CDK App + +This section describes how to debug your CDK app\. \ No newline at end of file diff --git a/doc_source/deploy_pipeline.md b/doc_source/deploy_pipeline.md new file mode 100644 index 00000000..554e95aa --- /dev/null +++ b/doc_source/deploy_pipeline.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Deploying an App Through a Pipeline + +This section describes how to deploy an app through a pipeline\. \ No newline at end of file diff --git a/doc_source/grant_permissions.md b/doc_source/grant_permissions.md new file mode 100644 index 00000000..07f775e0 --- /dev/null +++ b/doc_source/grant_permissions.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Granting Permissions + +This section describes how to grant permissions\. \ No newline at end of file diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md new file mode 100644 index 00000000..9f9b0b45 --- /dev/null +++ b/doc_source/identifiers.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Identifiers + +TBD \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index 84271a48..14e6ad3a 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -20,8 +20,12 @@ Amazon's trademarks and trade dress may not be used in + [Constructs](constructs.md) + [Apps and Stacks](apps_and_stacks.md) + [Resources](resources.md) + + [Identifiers](identifiers.md) + + [References](references.md) + + [Permissions](permissions.md) + [Run-Time Context](context.md) + [Assets](assets.md) + + [Aspects](aspects.md) + [AWS CloudFormation](cloudformation.md) + [Tokens](tokens.md) + [AWS CDK Lifecycle](lifecycle.md) @@ -32,8 +36,10 @@ Amazon's trademarks and trade dress may not be used in + [Examples](examples.md) + [Creating a Serverless Application Using the AWS CDK](serverless_example.md) + [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) + + [Creating an AWS CodePipeline Service Using the AWS CDK](codepipeline_example.md) + [AWS CDK Examples](about_examples.md) + [AWS CDK HowTos](how_tos.md) + + [Migrate AWS CloudFormation to the CDK](migrate_cfn.md) + [Get a Value from an Environment Variable](get_env_var.md) + [Use an AWS CloudFormation Parameter](get_cfn_param.md) + [Use an Existing AWS CloudFormation Template](use_cfn_template.md) @@ -42,8 +48,21 @@ Amazon's trademarks and trade dress may not be used in + [Work Around Missing AWS CDK Features](cfn_layer.md) + [Create an App with Multiple Stacks](stack_how_to_create_multiple_stacks.md) + [Set a CloudWatch Alarm](how_to_set_cw_alarm.md) + + [Granting Permissions](grant_permissions.md) + + [Complex Authentication with the CDK](complex_auth.md) + + [??? Amazon CloudWatch Events](cloudwatch_events.md) + [Get a Value from a Context Variable](get_context_var.md) + + [Creating Custom Resources](create_custom_resources.md) + + [Setting up an Auto Scaling Group](setup_asg.md) + + [Starting an Amazon EC2 Instance in an Auto Scaling Group](start_ec2_asg.md) + + [Deploying an App Through a Pipeline](deploy_pipeline.md) + + [Controlling an AWS CloudFormation Template Using the CDK](control_cfn_template.md) + + [Building a Lambda App with the AWS SAM](build_lambda_sam.md) + [CDK Toolchain](tools.md) + [AWS CDK Command Line Interface (cdk)](cli.md) + + [SAM CLI](toolchain_sam.md) + + [CI/CD for CDK Apps](toolchain_cicd.md) ++ [Troubleshooting the CDK](troubleshooting.md) + + [Debugging Your CDK App](debugging.md) + [OpenPGP Keys for the AWS CDK and JSII](pgp-keys.md) + [Document History for the AWS CDK Developer Guide](doc-history.md) \ No newline at end of file diff --git a/doc_source/lifecycle.md b/doc_source/lifecycle.md index ade3fe2b..4bde0aae 100644 --- a/doc_source/lifecycle.md +++ b/doc_source/lifecycle.md @@ -8,7 +8,7 @@ This documentation is for the developer preview release \(public beta\) of the A The following illustration shows the phases that the CDK goes through when you call cdk deploy to create the resources defined by your application\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/Lifecycle.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/guide/images/Lifecycle.png) There are three actors at play to create the resources that your CDK application defines\. + Your CDK app\. diff --git a/doc_source/migrate_cfn.md b/doc_source/migrate_cfn.md new file mode 100644 index 00000000..55ab09f5 --- /dev/null +++ b/doc_source/migrate_cfn.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Migrate AWS CloudFormation to the CDK + +This section describes how to migrate from AWS CloudFormation to the CDK\. \ No newline at end of file diff --git a/doc_source/passing_secrets_manager.md b/doc_source/passing_secrets_manager.md index 168d915b..40aff912 100644 --- a/doc_source/passing_secrets_manager.md +++ b/doc_source/passing_secrets_manager.md @@ -21,4 +21,12 @@ export class SecretsManagerStack extends cdk.Stack { // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: // encryptionKey, }); -``` \ No newline at end of file +``` + +Use the [create\-secret](https://docs.aws.amazon.com/cli/latest/reference/secretsmanager/create-secret.html) CLI command to create a secret from the command\-line, such as when testing: + +``` +aws secretsmanager create-secret --name ImportedSecret --secret-string mygroovybucket +``` + +The command returns an ARN you can use for the example\. \ No newline at end of file diff --git a/doc_source/permissions.md b/doc_source/permissions.md new file mode 100644 index 00000000..07230403 --- /dev/null +++ b/doc_source/permissions.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Permissions + +TBD \ No newline at end of file diff --git a/doc_source/references.md b/doc_source/references.md new file mode 100644 index 00000000..714dfc48 --- /dev/null +++ b/doc_source/references.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# References + +TBD \ No newline at end of file diff --git a/doc_source/setup_asg.md b/doc_source/setup_asg.md new file mode 100644 index 00000000..049d57eb --- /dev/null +++ b/doc_source/setup_asg.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Setting up an Auto Scaling Group + +This section describes how to set up an Auto Scaling group using the CDK\. \ No newline at end of file diff --git a/doc_source/start_ec2_asg.md b/doc_source/start_ec2_asg.md new file mode 100644 index 00000000..defb7dbb --- /dev/null +++ b/doc_source/start_ec2_asg.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Starting an Amazon EC2 Instance in an Auto Scaling Group + +This section describes how to start an Amazon EC2 in Auto Scaling group\. \ No newline at end of file diff --git a/doc_source/toolchain_cicd.md b/doc_source/toolchain_cicd.md new file mode 100644 index 00000000..a46dc1d7 --- /dev/null +++ b/doc_source/toolchain_cicd.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# CI/CD for CDK Apps + +This topic describes how to configure continuous integration and delivery for your CDK application\. \ No newline at end of file diff --git a/doc_source/toolchain_sam.md b/doc_source/toolchain_sam.md new file mode 100644 index 00000000..2cda5d48 --- /dev/null +++ b/doc_source/toolchain_sam.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# SAM CLI + +This topic describes the SAM CLI\. For further information, see ???\. \ No newline at end of file diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md new file mode 100644 index 00000000..6bacb83c --- /dev/null +++ b/doc_source/troubleshooting.md @@ -0,0 +1,9 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Troubleshooting the CDK + +This section describes how to troubleshoot problems with your CDK app\. \ No newline at end of file diff --git a/doc_source/what-is.md b/doc_source/what-is.md index d172a4b2..540b57bb 100644 --- a/doc_source/what-is.md +++ b/doc_source/what-is.md @@ -18,7 +18,7 @@ Use the CDK to define your cloud resources using one of the supported programmin Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](apps_and_stacks.md#stacks) and [Apps](apps_and_stacks.md#apps)\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/AppStacks.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/guide/images/AppStacks.png) ## Why Use the CDK? @@ -86,7 +86,7 @@ Resources: Another advantage of IAC \(infrastructure as code\) is that you get code completion within your IDE: -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/userguide/images/CodeCompletion.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/guide/images/CodeCompletion.png) ## Developing With the CDK From 4ad3cdf26d4947b6833bf5ffc8834803d35d4f70 Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Mon, 6 May 2019 10:41:22 -0700 Subject: [PATCH 015/655] Updated CDK guide files based on 0.30.0 --- doc_source/about_examples.md | 22 +- doc_source/apps_and_stacks.md | 120 ++++--- doc_source/aspects.md | 9 - doc_source/aws_construct_lib.md | 20 -- doc_source/build_lambda_sam.md | 9 - doc_source/cli.md | 310 ------------------ doc_source/cloudwatch_events.md | 9 - doc_source/codepipeline_example.md | 9 - doc_source/complex_auth.md | 9 - doc_source/constructs.md | 4 - doc_source/control_cfn_template.md | 9 - doc_source/create_custom_resources.md | 9 - doc_source/debugging.md | 9 - doc_source/deploy_pipeline.md | 9 - doc_source/doc-history.md | 6 +- doc_source/examples.md | 2 +- ...anager.md => get_secrets_manager_value.md} | 2 +- doc_source/get_ssm_value.md | 16 +- doc_source/getting_started.md | 136 +++++++- doc_source/grant_permissions.md | 9 - doc_source/identifiers.md | 9 - doc_source/index.md | 24 +- doc_source/lifecycle.md | 2 +- doc_source/migrate_cfn.md | 9 - doc_source/permissions.md | 9 - doc_source/references.md | 9 - doc_source/setup_asg.md | 9 - doc_source/start_ec2_asg.md | 9 - doc_source/toolchain_cicd.md | 9 - doc_source/toolchain_sam.md | 9 - doc_source/tools.md | 241 +++++++++++++- doc_source/troubleshooting.md | 9 - doc_source/what-is.md | 6 +- 33 files changed, 475 insertions(+), 607 deletions(-) delete mode 100644 doc_source/aspects.md delete mode 100644 doc_source/build_lambda_sam.md delete mode 100644 doc_source/cli.md delete mode 100644 doc_source/cloudwatch_events.md delete mode 100644 doc_source/codepipeline_example.md delete mode 100644 doc_source/complex_auth.md delete mode 100644 doc_source/control_cfn_template.md delete mode 100644 doc_source/create_custom_resources.md delete mode 100644 doc_source/debugging.md delete mode 100644 doc_source/deploy_pipeline.md rename doc_source/{passing_secrets_manager.md => get_secrets_manager_value.md} (94%) delete mode 100644 doc_source/grant_permissions.md delete mode 100644 doc_source/identifiers.md delete mode 100644 doc_source/migrate_cfn.md delete mode 100644 doc_source/permissions.md delete mode 100644 doc_source/references.md delete mode 100644 doc_source/setup_asg.md delete mode 100644 doc_source/start_ec2_asg.md delete mode 100644 doc_source/toolchain_cicd.md delete mode 100644 doc_source/toolchain_sam.md delete mode 100644 doc_source/troubleshooting.md diff --git a/doc_source/about_examples.md b/doc_source/about_examples.md index 433710be..6c3a26ef 100644 --- a/doc_source/about_examples.md +++ b/doc_source/about_examples.md @@ -14,7 +14,6 @@ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitH | Example | Description | | --- |--- | | [application\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/application-load-balancer/) | Using an AutoScalingGroup with an Application Load Balancer | -| [chat\-app](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/chat-app/) | A serverless chat application using Cognito | | [classic\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/classic-load-balancer/) | Using an AutoScalingGroup with a Classic Load Balancer | | [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) | Shows adding a Custom Resource to your CDK app | | [elasticbeanstalk](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/elasticbeanstalk/) | Elastic Beanstalk example using L1 with a Blue/Green pipeline \(community contributed\) | @@ -22,6 +21,7 @@ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitH | [ecs\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-load-balanced-service/) | Starting a container fronted by a load balancer on ECS | | [ecs\-service\-with\-task\-placement](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-task-placement/) | Starting a container ECS with task placement specifications | | [ecs\-service\-with\-advanced\-alb\-config](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-advanced-alb-config/) | Starting a container fronted by a load balancer on ECS with added load balancer configuration | +| [ecs\-service\-with\-task\-networking](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-task-networking/) | Starting an ECS service with task networking, allowing ingress traffic to the task but blocking for the instance | | [fargate\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/fargate-load-balanced-service/) | Starting a container fronted by a load balancer on Fargate | | [fargate\-service\-with\-auto\-scaling](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/fargate-service-with-auto-scaling/) | Starting an ECS service of FARGATE launch type that auto scales based on average CPU Utilization | | [lambda\-cron](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/lambda-cron/) | Running a Lambda on a schedule | @@ -29,6 +29,8 @@ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitH | [resource\-overrides](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/resource-overrides/) | Shows how to override generated CloudFormation code | | [static\-site](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/static-site/) | A static site using CloudFront | | [stepfunctions\-job\-poller](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/stepfunctions-job-poller/) | A simple StepFunctions workflow | +| [ecs\-service\-with\-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs-service-with-logging/) | Starting a container fronted by a load balancer on Fargate | +| [fargate\-service\-with\-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/fargate-service-with-logging/) | Starting a container fronted by a load balancer on Fargate | ## Java examples @@ -37,6 +39,24 @@ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitH | --- |--- | | [hello\-world](https://github.com/aws-samples/aws-cdk-examples/tree/master/java/hello-world/) | A demo application that uses the CDK in Java | +## Python examples + + +| Example | Description | +| --- |--- | +| [application\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/application-load-balancer/) | Using an AutoScalingGroup with an Application Load Balancer | +| [classic\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/classic-load-balancer/) | Using an AutoScalingGroup with a Classic Load Balancer | +| [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/custom-resource/) | Shows adding a Custom Resource to your CDK app | +| [ecs\-cluster](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/cluster/) | Provision an ECS Cluster with custom Autoscaling Group configuration | +| [ecs\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/ecs-load-balanced-service/) | Starting a container fronted by a load balancer on ECS | +| [ecs\-service\-with\-task\-placement](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/ecs-service-with-task-placement/) | Starting a container ECS with task placement specifications | +| [ecs\-service\-with\-advanced\-alb\-config](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/ecs-service-with-advanced-alb-config/) | Starting a container fronted by a load balancer on ECS with added load balancer configuration | +| [ecs\-service\-with\-task\-networking](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/ecs-service-with-task-networking/) | Starting an ECS service with task networking, allowing ingress traffic to the task but blocking for the instance | +| [fargate\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/fargate-load-balanced-service/) | Starting a container fronted by a load balancer on Fargate | +| [fargate\-service\-with\-auto\-scaling](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/fargate-service-with-auto-scaling/) | Starting an ECS service of FARGATE launch type that auto scales based on average CPU Utilization | +| [lambda\-cron](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/lambda-cron/) | Running a Lambda on a schedule | +| [stepfunctions](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/stepfunctions/) | A simple StepFunctions workflow | + ## JavaScript examples diff --git a/doc_source/apps_and_stacks.md b/doc_source/apps_and_stacks.md index 267957d3..854c248b 100644 --- a/doc_source/apps_and_stacks.md +++ b/doc_source/apps_and_stacks.md @@ -4,86 +4,104 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# Apps and Stacks +# Apps, Stacks, and Environments and Authentication -The main artifact of a CDK program known as a *CDK app*\. This is an executable program that you can use to synthesize deployment artifacts that supporting tools, such as the CDK Toolkit, can deploy, as described in [AWS CDK Command Line Interface \(cdk\)](cli.md)\. +The main artifact of a CDK program known as a *CDK app*\. This is an executable program that you can use to synthesize deployment artifacts that supporting tools, such as the CDK Toolkit, can deploy, as described in [AWS CDK Command Line Interface \(cdk\)](tools.md#cli)\. Stacks are CDK constructs that you can deploy into an AWS environment\. The combination of AWS Region and account becomes the stack's *environment*\. Most production apps consist of multiple stacks of resources that are deployed as a single transaction using a resource provisioning service such as AWS CloudFormation\. Any resources added directly or indirectly as children of a stack are included in the stack's template when it is synthesized by your CDK program\. +Let's look at apps and stacks from the bottom up\. + +## Stacks + +Define an application stack by extending the [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) class, as shown in the following example\. + +``` +import cdk = require("@aws-cdk/cdk"); +import s3 = require("@aws-cdk/aws-s3"); + +interface MyStackProps extends cdk.StackProps { + enc: boolean; +} + +export class MyStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props: MyStackProps) { + super(scope, id, props); + + if (props.enc) { + new s3.Bucket(this, "MyGroovyBucket", { + encryption: s3.BucketEncryption.KmsManaged + }); + } else { + new s3.Bucket(this, "MyGroovyBucket"); + } + } +} +``` + +Next we'll show you how to use one or more stacks to create a CDK app\. + ## Apps An [app](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app) is a collection of [stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) objects, as shown in the following example\. ``` -import { App } from '@aws-cdk/cdk' -import { MyStack } from './my-stack' - -const app = new App(); - -const dev = new MyStack(app, { name: 'Dev', region: 'us-west-2', dev: true }) -const preProd = new MyStack(app, { name: 'PreProd', region: 'us-west-2', preProd: true }) -const prod = [ - new MyStack(app, { name: 'NAEast', region: 'us-east-1' }), - new MyStack(app, { name: 'NAWest', region: 'us-west-2' }), - new MyStack(app, { name: 'EU', region: 'eu-west-1', encryptedStorage: true }) -] - -new DeploymentPipeline(app, { - region: 'us-east-1', - strategy: DeploymentStrategy.Waved, - preProdStages: [ preProd ], - prodStages: prod +import cdk = require("@aws-cdk/cdk"); +import { MyStack } from "../lib/MyApp-stack"; + +const app = new cdk.App(); + +new MyStack(app, "MyWestCdkStack", { + env: { + region: "us-west-2" + }, + enc: false }); -app.run(); +new MyStack(app, "MyEastCdkStack", { + env: { + region: "us-east-1" + }, + enc: true +}); ``` -Use the cdk list command to list the stacks in this executable, as shown in the following example\. +Use the cdk ls command to list the stacks in this executable, as shown in the following example\. ``` -[ - { name: "Dev", region: "us-west-2" } - { name: "PreProd", region: "us-west-2" }, - { name: "NAEast", region: "us-east-1" }, - { name: "NAWest", region: "us-west-2" }, - { name: "EU", region: "eu-west-1" }, - { name: "DeploymentPipeline", region: 'us-east-1' } -] +MyEastCdkStack +MyWestCdkStack ``` Use the cdk deploy command to deploy an individual stack\. ``` -cdk deploy Dev +cdk deploy MyWestCdkStack ``` -## Stacks +## Environments and Authentication -Define an application stack by extending the [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) class, as shown in the following example\. +When you create a [stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) instance, you can supply the target deployment environment for the stack using the `env` property\. This is shown in the following example, where *REGION* is the AWS Region in which you want to create the stack and *ACCOUNT* is your account ID\. ``` -import { Stack, StackProps } from '@aws-cdk/cdk' +new MyStack(app, { env: { region: 'REGION', account: 'ACCOUNT' } }); +``` -interface MyStackProps extends StackProps { - encryptedStorage: boolean; -} +For each of the two arguments, `region` and `account`, the CDK uses the following lookup procedure: ++ If `region` or `account`is provided directly as a property to the stack, use that\. ++ If either property is not specified when you create a stack, the CDK determines them as follows: + + `account` – Use the account from the default SDK credentials\. Environment variables are tried first \(`AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`\), followed by credentials in `$HOME/.aws/credentials` on Linux or macOS, or `%USERPROFILE%\.aws\credentials` on Windows\. + + `region` – Use the default Region configured in `$HOME/.aws/config` on Linux or macOS, or `%USERPROFILE%\.aws\config` on Windows\. -class MyStack extends Stack { - constructor(scope: Construct, id: string, props?: MyStackProps) { - super(scope, id, props); + You can set these defaults manually, but we recommend you use `aws configure`, as described in [Specifying Your Credentials](getting_started.md#getting_started_credentials)\. - new MyStorageLayer(this, 'Storage', { encryptedStorage: props.encryptedStorage }); - new MyControlPlane(this, 'CPlane'); - new MyDataPlane(this, 'DPlane'); - } -} -``` +We recommend that you use the default environment for development stacks, and explicitly specify accounts and Regions for production stacks\. -And then, add instances of this class to your app\. +**Note** +Although the Region and account might explicitly be set on your stack, if you run `cdk deploy`, the CDK still uses the currently configured SDK credentials that are provided through environment variables or `aws configure`\. This means that if you want to deploy stacks to multiple accounts, you have to set the correct credentials for each invocation to `cdk deploy STACK`\. -``` -const app = new App(); +You can always find the Region within which your stack is deployed by using the `region` property of the stack, as follows\. -new MyStack(app, 'NorthAmerica', { env: { region: 'us-east-1' } }); -new MyStack(app, 'Europe', { env: { region: 'us-west-2' } }); +``` +this.region ``` \ No newline at end of file diff --git a/doc_source/aspects.md b/doc_source/aspects.md deleted file mode 100644 index f8af4d40..00000000 --- a/doc_source/aspects.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Aspects - -TBD \ No newline at end of file diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md index 0dc337ca..613d7b53 100644 --- a/doc_source/aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -20,24 +20,12 @@ Minor releases, such as 2\.4, guarantee that any code written in a previous mino The AWS Construct Library includes many common patterns and capabilities that are designed to enable developers to focus on their application\-specific architectures and reduce the boilerplate and glue logic needed when working with AWS services\. -### Roles - -Roles \.\.\. - ### Grants AWS Identity and Access Management \(IAM\) policies are automatically defined based on intent\. For example, when subscribing an Amazon Simple Notification Service \(Amazon SNS\) [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) to an AWS Lambda [Function](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.Function), the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. Also, most AWS constructs expose `grant*` methods that allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct has a [grantRead\(principal\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.grantRead) method\. This method accepts an IAM [Principal](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#iprincipal-interface) such as a [User](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#user) or a [Role](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#role), which modifies the policy to allow the principal to read objects from the bucket\. -### Resource Policies - -Resource policies \.\.\. - -### Principals - -Principals \.\.\. - ## Metrics Many AWS resources emit [Amazon CloudWatch metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html) as part of their normal operation\. Metrics can be used to set up an [Alarm](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Alarm) or can be included in a [Dashboard](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Dashboard)\. @@ -114,8 +102,6 @@ const myStack = new HelloCdkStack(app, "HelloCdkStack"); new MyCdkStack(app, "MyCdkStack", { theBucketImportProps: myStack.myBucketImportProps }); - -app.run(); ``` ### Referencing Constructs Across All App @@ -182,14 +168,8 @@ const myStack = new HelloCdkStack(app, "HelloCdkStack"); new MyCdkStack(app, "MyCdkStack", { theBucketImportProps: myStack.myBucketImportProps }); - -app.run(); ``` -## Get a Value from Another App - -You can get a value from a stack in another app by ??? - ## Security Groups Amazon Elastic Compute Cloud \(Amazon EC2\) network entities, such as the [Elastic Load Balancing](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-elasticloadbalancingv2.html) and [Auto Scaling Group](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-autoscaling.html#auto-scaling-group) instances, can connect to each other based on definitions of security groups\. diff --git a/doc_source/build_lambda_sam.md b/doc_source/build_lambda_sam.md deleted file mode 100644 index 0bd52f76..00000000 --- a/doc_source/build_lambda_sam.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Building a Lambda App with the AWS SAM - -This section describes how to build and test a Lambda\-based app with the AWS SAM\. \ No newline at end of file diff --git a/doc_source/cli.md b/doc_source/cli.md deleted file mode 100644 index 105f1bcc..00000000 --- a/doc_source/cli.md +++ /dev/null @@ -1,310 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# AWS CDK Command Line Interface \(cdk\) - -The CDK Toolkit, cdk, is the main tool you use to interact with your CDK app\. It executes the CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the CDK\. - -There are two ways to tell cdk what command to use to run your CDK app\. The first way is to include an explicit \-\-app option whenever you use a cdk command\. - -``` -cdk --app 'node bin/main.js' synth -``` - -The second way is to add the following entry to the `cdk.json` file\. - -``` -{ - "app": "node bin/main.js" -} -``` - -You can also use the npx cdk instead of just cdk\. - -Here are the actions you can take on your CDK app \(this is the output of the cdk \-\-help command\)\. - -``` -Usage: cdk -a COMMAND - -Commands: - list Lists all stacks in the app [aliases: ls] - synthesize [STACKS..] Synthesizes and prints the CloudFormation template - for this stack [aliases: synth] - bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS - environment - deploy [STACKS..] Deploys the stack(s) named STACKS into your AWS - account - destroy [STACKS..] Destroy the stack(s) named STACKS - diff [STACKS..] Compares the specified stack with the deployed - stack or a local template file, and returns with - status 1 if any difference is found - metadata [STACK] Returns all metadata associated with this stack - init [TEMPLATE] Create a new, empty CDK project from a template. - Invoked without TEMPLATE, the app template will be - used. - context Manage cached context values - docs Opens the reference documentation in a browser - [aliases: doc] - doctor Check your set-up for potential problems - -Options: - --app, -a REQUIRED: Command-line for executing your CDK app (e.g. - "node bin/my-app.js") [string] - --context, -c Add contextual string parameter. [array] - --plugin, -p Name or path of a node package that extend the CDK - features. Can be specified multiple times [array] - --rename Rename stack name if different from the one defined in - the cloud executable [string] - --trace Print trace for stack warnings [boolean] - --strict Do not construct stacks with warnings [boolean] - --ignore-errors Ignores synthesis errors, which will likely produce an - invalid output [boolean] [default: false] - --json, -j Use JSON output instead of YAML [boolean] - --verbose, -v Show debug logs [boolean] - --profile Use the indicated AWS profile as the default environment - [string] - --proxy Use the indicated proxy. Will read from HTTPS_PROXY - environment variable if not specified. [string] - --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: - guess EC2 instance status. [boolean] - --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized - templates (enabled by default) [boolean] - --path-metadata Include "aws:cdk:path" CloudFormation metadata for each - resource (enabled by default) [boolean] [default: true] - --asset-metadata Include "aws:asset:*" CloudFormation metadata for - resources that user assets (enabled by default) - [boolean] [default: true] - --role-arn, -r ARN of Role to use when invoking CloudFormation [string] - --toolkit-stack-name The name of the CDK toolkit stack [string] - --ci Force CI detection. Use --no-ci to disable CI - autodetection. [boolean] [default: false] - --version Show version number [boolean] - -h, --help Show help [boolean] - -If your app has a single stack, there is no need to specify the stack name - -If one of cdk.json or ~/.cdk.json exists, options specified there will be used -as defaults. Settings in cdk.json take precedence. -``` - -If your app has a single stack, you don't have to specify the stack name\. - -If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. - -## Bootstrapping the CDK - -Before you can use the CDK you must bootstrap the CDK to create the infrastructure that the CDK needs\. Currently the bootstrap command creates only an Amazon S3 bucket\. - -You incur any charges for what the CDK stores in the bucket\. Because the CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. - -## Security\-Related Changes - -To protect you against unintended changes that affect your security posture, the CDK toolkit prompts you to approve security\-related changes before deploying them\. - -You change the level of changes that requires approval by specifying: - -``` -cdk deploy --require-approval LEVEL -``` - -Where *LEVEL* can be one of the following: - -never -Approval is never required\. - -any\-change -Requires approval on any IAM or security\-group related change\. - -broadening -\(default\) Requires approval when IAM statements or traffic rules are added\. Removals don't require approval\. - -The setting can also be configured in the `cdk.json` file\. - -``` -{ - "app": "...", - "requireApproval": "never" -} -``` - -## Version Reporting - -To gain insight into how the CDK is used, the versions of libraries used by CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. - -The CDK reports the name and version of `npm` modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. - -The `AWS::CDK::Metadata` resource looks like the following\. - -``` -CDKMetadata: - Type: "AWS::CDK::Metadata" - Properties: - Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,lodash=4.17.10" -``` - -## Opting Out from Version Reporting - -To opt out of version reporting, use one of the following methods: -+ Use the cdk command with the \-\-no\-version\-reporting argument\. - - ``` - cdk --no-version-reporting synth - ``` -+ Set versionReporting to **false** in `./cdk.json` or `~/cdk.json`\. - - ``` - { - "app": "...", - "versionReporting": false - } - ``` - -## Plugins - -The CDK Toolkit provides extension points that enable users to augment the features provided by the toolkit\. There is currently only one extension point, allowing users to define custom AWS credential providers, but other extension points may be added in the future as needed\. - -### Loading Plugins - -Plugins can be loaded by providing the Node module name \(or path\) to the CDK Toolkit: -+ Using the \-\-plugin command line option, which can be specified multiple times\. - - ``` - cdk list --plugin=module - cdk deploy --plugin=module_1 --plugin=module_2 - ``` -+ Adding entries to the `~/.cdk.json` or `cdk.json` file\. - - ``` - { - // ... - "plugin": [ - "module_1", - "module_2" - ], - // ... - } - ``` - -### Initialization Templates - -The CDK provides a template for each of the supported languages\. Simply supply the name of the language after the \-\-language flag\. Use the help see a list of the language options: - -``` -cdk help init -``` - -### Authoring Plugins - -Plugins must be authored in TypeScript or JavaScript, and are defined by implementing a Node\.js module that implements the following protocol, and using [PluginHost\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost) methods\. - ------- -#### [ TypeScript ] - -``` -import cdk = require('aws-cdk'); - -export = { - version: '1', // Version of the plugin infrastructure (currently always '1') - init(host: cdk.PluginHost): void { - // Your plugin initialization hook. - // Use methods of host to register custom code with the CDK Toolkit. - } -}; -``` - ------- -#### [ JavaScript ] - -``` -export = { - version: '1', // Version of the plugin infrastructure (currently always '1') - init(host) { - // Your plugin initialization hook. - // Use methods of host to register custom code with the CDK Toolkit. - } -}; -``` - ------- - -### Credential Provider Plugins - -Custom credential providers are classes that implement the [CredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.CredentialProviderSource) interface, and that are registered to the toolkit using the [registerCredentialProviderSource\(\)](https://awslabs.github.io/aws-cdk/tools.html#aws-cdk.PluginHost.registerCredentialProviderSource) method\. - ------- -#### [ TypeScript ] - -``` -import cdk = require('aws-cdk'); -import aws = require('aws-sdk'); - -class CustomCredentialProviderSource implements cdk.CredentialProviderSource { - public async isAvailable(): Promise { - // Return false if the plugin could determine it cannot be used (for example, - // if it depends on files that are not present on this host). - return true; - } - - public async canProvideCredentials(accountId: string): Promise { - // Return false if the plugin is unable to provide credentials for the - // requested account (for example, if it's not managed by the credentials - // system that this plugin adds support for). - return true; - } - - public async getProvider(accountId: string, mode: cdk.Mode): Promise { - let credentials: aws.Credentials; - // Somehow obtain credentials in credentials, and return those. - return credentials; - } -} - -export = { - version = '1', - init(host: cdk.PluginHost): void { - // Register the credential provider to the PluginHost. - host.registerCredentialProviderSource(new CustomCredentialProviderSource()); - } -}; -``` - ------- -#### [ JavaScript ] - -``` -class CustomCredentialProviderSource { - async isAvailable() { - // Return false if the plugin could determine it cannot be used (for example, - // if it depends on files that are not present on this host). - return true; - } - - async canProvideCredentials(accountId) { - // Return false if the plugin is unable to provide credentials for the - // requested account (for example if it's not managed by the credentials - // system that this plugin adds support for). - return true; - } - - async getProvider(accountId, mode) { - let credentials; - // Somehow obtain credentials in credentials, and return those. - return credentials; - } -} - -export = { - version = '1', - init(host) { - // Register the credential provider to the PluginHost. - host.registerCredentialProviderSource(new CustomCredentialProviderSource()); - } -}; -``` - ------- - -Note that the credentials obtained from the providers for a given account and mode will be cached, and as a consequence, we strongly advise that the credentials objects that are returned are self\-refreshing, as described in the [AWS SDK for JavaScript](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html) documentation\. \ No newline at end of file diff --git a/doc_source/cloudwatch_events.md b/doc_source/cloudwatch_events.md deleted file mode 100644 index d29e59ba..00000000 --- a/doc_source/cloudwatch_events.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# ??? Amazon CloudWatch Events - -This section describes how to ??? CloudWatch events\. \ No newline at end of file diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md deleted file mode 100644 index f5da9b9b..00000000 --- a/doc_source/codepipeline_example.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Creating an AWS CodePipeline Service Using the AWS CDK - -This example creates a CodePipeline pipeline\. \ No newline at end of file diff --git a/doc_source/complex_auth.md b/doc_source/complex_auth.md deleted file mode 100644 index 1402bc04..00000000 --- a/doc_source/complex_auth.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Complex Authentication with the CDK - -This section describes how to perform complex authentication using the CDK\. \ No newline at end of file diff --git a/doc_source/constructs.md b/doc_source/constructs.md index cb26ade2..2ada5f32 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -106,10 +106,6 @@ const props: QueueProps = { new Queue(this, 'MyQueue', props); ``` -## Resource Attributes - -tba - ## Construct Metadata Attach metadata to a construct using the `addMetadata` method\. Metadata is an AWS CDK\-level annotation, and as such, does not appear in the deployed resources\. Metadata entries automatically include the stack trace from which the metadata entry was added to allow tracing back to your code, even if the entry was defined by a lower\-level library that you don't own\. diff --git a/doc_source/control_cfn_template.md b/doc_source/control_cfn_template.md deleted file mode 100644 index 4ed57435..00000000 --- a/doc_source/control_cfn_template.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Controlling an AWS CloudFormation Template Using the CDK - -This section describes how to control an AWS CloudFormation template using the CDK\. \ No newline at end of file diff --git a/doc_source/create_custom_resources.md b/doc_source/create_custom_resources.md deleted file mode 100644 index e4900d64..00000000 --- a/doc_source/create_custom_resources.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Creating Custom Resources - -This section describes how to create custom resources\. A custom resource is a ??? \ No newline at end of file diff --git a/doc_source/debugging.md b/doc_source/debugging.md deleted file mode 100644 index a3e66bbc..00000000 --- a/doc_source/debugging.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Debugging Your CDK App - -This section describes how to debug your CDK app\. \ No newline at end of file diff --git a/doc_source/deploy_pipeline.md b/doc_source/deploy_pipeline.md deleted file mode 100644 index 554e95aa..00000000 --- a/doc_source/deploy_pipeline.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Deploying an App Through a Pipeline - -This section describes how to deploy an app through a pipeline\. \ No newline at end of file diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 66db4a03..36606945 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -6,8 +6,8 @@ This documentation is for the developer preview release \(public beta\) of the A # Document History for the AWS CDK Developer Guide -This document is based on the following release of the AWS Cloud Development Kit \(CDK\) \(CDK\)\. -+ **API version: 0\.27\.0** -+ **Latest documentation update:** April 3, 2019 +This document is based on the following release of the AWS Cloud Development Kit \(CDK\)\. ++ **API version: 0\.30\.0** ++ **Latest documentation update:** May 2, 2019 See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the CDK releases\. \ No newline at end of file diff --git a/doc_source/examples.md b/doc_source/examples.md index bf1ef053..18f24a52 100644 --- a/doc_source/examples.md +++ b/doc_source/examples.md @@ -7,5 +7,5 @@ This documentation is for the developer preview release \(public beta\) of the A # Examples This topic contains the following examples: -+ [Creating a Serverless Application Using the AWS CDK](serverless_example.md)Creates a serverless application using Lambda, API Gateway, and Amazon S3\. ++ [Creating a Serverless Application Using the AWS CDK](serverless_example.md) Creates a serverless application using Lambda, API Gateway, and Amazon S3\. + [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. \ No newline at end of file diff --git a/doc_source/passing_secrets_manager.md b/doc_source/get_secrets_manager_value.md similarity index 94% rename from doc_source/passing_secrets_manager.md rename to doc_source/get_secrets_manager_value.md index 40aff912..656d4812 100644 --- a/doc_source/passing_secrets_manager.md +++ b/doc_source/get_secrets_manager_value.md @@ -4,7 +4,7 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# Get a Value from AWS Secrets Manager +# Get a Value from AWS Secrets Manager To use values from AWS Secrets Manager in your CDK app, use the [Secret](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-secretsmanager.html#secret) class's `import` method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index a776aef1..29b7939f 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -6,9 +6,9 @@ This documentation is for the developer preview release \(public beta\) of the A # Get a Value from a Systems Manager Parameter Store Variable -You can get the value of an AWS Systems Manager Parameter Store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It isn't possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from AWS Secrets Manager \(see [Get a Value from AWS Secrets Manager](passing_secrets_manager.md)\)\. +You can get the value of an AWS Systems Manager Parameter Store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It isn't possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from AWS Secrets Manager \(see [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. -To read a particular version of a Systems Manager Parameter Store plain string value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstorestring)\. If you don't supply a `version` value, you get the latest version\. +To read a particular version of a Systems Manager Parameter Store plain string value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html#parameterstorestring)\. If you don't supply a `version` value, you get the latest version\. ``` import ssm = require('@aws-cdk/aws-ssm'); @@ -21,7 +21,7 @@ const parameterString = new ssm.ParameterStoreString(this, 'MyParameter', { const myvalue = parameterString.stringValue; ``` -To read a particular version of a Systems Manager Parameter Store `SecureString` value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreSecureString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html/#parameterstoresecurestring)\. You must supply a `version` value\. +To read a particular version of a Systems Manager Parameter Store `SecureString` value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreSecureString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html#parameterstoresecurestring)\. You must supply a `version` value\. ``` import ssm = require('@aws-cdk/aws-ssm'); @@ -32,4 +32,12 @@ const secureString = new ssm.ParameterStoreSecureString(this, 'MySecretParameter }); const myvalue = secureString.stringValue; -``` \ No newline at end of file +``` + +Use the [put\-parameter](https://docs.aws.amazon.com/cli/latest/reference/ssm/put-parameter.html) CLI command to add a string parameter to the system, such as when testing: + +``` +aws ssm put-parameter --name "my-parameter-name" --type "String" --value "my-parameter-value" +``` + +The command returns an ARN you can use for the example\. \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 2cf46b7e..b449e0bc 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -37,6 +37,10 @@ none + \.NET Framework >= 4\.6\.1 + Mono >= 5\.4 +------ +#### [ Python ] ++ Python >= 3\.7\.1 + ------ ## Installing the CDK @@ -93,6 +97,16 @@ Add the following to your project’s pom\.xml file: dotnet add package Amazon.CDK ``` +------ +#### [ Python ] + +``` +pip install aws-cdk.cdk +``` + +**Note** +If you have both Python 2\.7 and 3\.7 installed, you might have to pip3 instead of pip\. + ------ ## Updating Your Language Dependencies @@ -127,6 +141,15 @@ mvn versions:use-latest-versions nuget update ``` +------ +#### [ Python ] + +``` +pip install --upgrade aws-cdk.cdk +``` + +You might have to call this multiple times to update all dependencies\. + ------ ## Specifying Your Credentials @@ -248,6 +271,40 @@ cdk init --language java cdk init --language csharp ``` +------ +#### [ Python ] + +``` +cdk init --language python +``` + +Once the init command finishes, your prompt should show **\(\.env\)**, indicating you are running under virtualenv\. If not, you must perform one or two more tasks, depending upon your operating system\. + +On Linux/MacOS: + +``` +python3 -m venv .env +source .env/bin/activate +``` + +On Windows: + +``` +.env\Scripts\activate.bat +``` + +Once you've got your virtualenv running, run the following command to install the required dependencies\. + +``` +pip install -r requirements.txt +``` + +Change the instantiation of **HelloCdkStack** in `app.py` to the following\. + +``` +HelloCdkStack(app, "HelloCdkStack") +``` + ------ ### Compiling the App @@ -282,6 +339,11 @@ Because we configured `cdk.json` to run dotnet run, which restores dependencies, cdk ``` +------ +#### [ Python ] + +Nothing to compile\. + ------ ### Listing the Stacks in the App @@ -338,6 +400,15 @@ Add the following to `pom.xml`, where *CDK\-VERSION* is the version of the CDK\. dotnet add package Amazon.CDK.AWS.S3 ``` +------ +#### [ Python ] + +``` +pip install aws-cdk.aws-s3 +``` + +You might have to execute this command multiple times to resolve dependencies\. + ------ Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represented by the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.Bucket) class\. @@ -435,6 +506,26 @@ namespace HelloCdk } ``` +------ +#### [ Python ] + +Replace the import statement in `hello_cdk_stack.py` in the `hello_cdk` directory with the following code\. + +``` +from aws_cdk import ( + aws_s3 as s3, + cdk +) +``` + +Replace the comment with the following code\. + +``` +bucket = s3.Bucket(self, + "MyFirstBucket", + versioned=True,) +``` + ------ Notice a few things: @@ -472,19 +563,21 @@ Because we configured `cdk.json` to run dotnet run, which restores dependencies, cdk ``` +------ +#### [ Python ] + +Nothing to compile\. + ------ ### Synthesizing an AWS CloudFormation Template -Synthesize an AWS CloudFormation template for the app, as follows\. +Synthesize an AWS CloudFormation template for the app, as follows\. If you get an error like "\-\-app is required\.\.\.", it's because you are running the command from within the `hello_cdk` sub\-directory\. Navigate to the parent directory and try again\. ``` -cdk synth HelloCdkStack +cdk synth ``` -**Note** -Because the CDK app contains only a single stack, you can omit `HelloCdkStack`\. - This command executes the CDK app and synthesizes an AWS CloudFormation template for the `HelloCdkStack` stack\. You should see something similar to the following, where *VERSION* is the version of the CDK\. ``` @@ -508,7 +601,7 @@ Resources: You can see that the stack contains an `AWS::S3::Bucket` resource with the versioning configuration we want\. **Note** -The toolkit automatically added the **AWS::CDK::Metadata** resource to your template\. The CDK uses metadata to gain insight into how the CDK is used\. One possible benefit is that the CDK team could notify users if a construct is going to be deprecated\. For details, including how to [opt out](cli.md#version_reporting_opt_out) of version reporting, see [Version Reporting](cli.md#version_reporting) \. +The toolkit automatically added the **AWS::CDK::Metadata** resource to your template\. The CDK uses metadata to gain insight into how the CDK is used\. One possible benefit is that the CDK team could notify users if a construct is going to be deprecated\. For details, including how to [opt out](tools.md#version_reporting_opt_out) of version reporting, see [Version Reporting](tools.md#version_reporting) \. ### Deploying the Stack @@ -573,6 +666,16 @@ new Bucket(this, "MyFirstBucket", new BucketProps }); ``` +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, + "MyFirstBucket", + versioned=True, + encryption=s3.BucketEncryption.KmsManaged,) +``` + ------ Compile your program, as follows\. @@ -605,6 +708,11 @@ Because we configured `cdk.json` to run dotnet run, which restores dependencies, cdk ``` +------ +#### [ Python ] + +Nothing to compile\. + ------ ### Preparing for Deployment @@ -615,18 +723,18 @@ Before you deploy the updated app, evaluate the difference between the CDK app a cdk diff ``` -The toolkit queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares the result with the template synthesized from the app\. The output should look like the following\. +The toolkit queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares the result with the template synthesized from the app\. The Resources section of the output should look like the following\. ``` Resources -[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 +[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketID |- [+] BucketEncryption |- {"ServerSideEncryptionConfiguration":[{"ServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms"}}]} ``` As you can see, the diff indicates that the `ServerSideEncryptionConfiguration` property of the bucket is now set to enable server\-side encryption\. -You can also see that the bucket isn't going to be replaced, but will be updated instead \(**Updating MyFirstBucketB8884501**\)\. +You can also see that the bucket isn't going to be replaced, but will be updated instead \(**Updating MyFirstBucket\.\.\.**\)\. Deploy the changes\. @@ -634,18 +742,18 @@ Deploy the changes\. cdk deploy ``` -The CDK Toolkit updates the bucket configuration to enable server\-side AWS KMS encryption for the bucket\. +Enter y to approve the changes and deploy the updated stack\. The CDK Toolkit updates the bucket configuration to enable server\-side AWS KMS encryption for the bucket\. The final output is the ARN of the stack, where *REGION* is your default region, *ACCOUNT\-ID* is your account ID, and *ID* is a unique identifier for the bucket or stack\. ``` HelloCdkStack: deploying... HelloCdkStack: creating CloudFormation changeset... - 0/2 | 10:55:30 AM | UPDATE_IN_PROGRESS | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketB8884501) - 1/2 | 10:55:50 AM | UPDATE_COMPLETE | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketB8884501) + 0/2 | 10:55:30 AM | UPDATE_IN_PROGRESS | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketID) + 1/2 | 10:55:50 AM | UPDATE_COMPLETE | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketID) HelloCdkStack Stack ARN: -arn:aws:cloudformation:us-west-2:188580781645:stack/HelloCdkStack/96956990-feff-11e8-9284-50a68a0e3256 +arn:aws:cloudformation:REGION:ACCOUNT-ID:stack/HelloCdkStack/ID ``` ### Destroying the App's Resources @@ -656,4 +764,4 @@ Destroy the app's resources to avoid incurring any costs from the resources crea cdk destroy ``` -In some cases this command fails, such as when a resource isn't empty and must be empty before it can be destroyed\. See [Delete Stack Fails](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#troubleshooting-errors-delete-stack-fails) in the *AWS CloudFormation User Guide* for details\. \ No newline at end of file +Enter y to approve the changes and delete any stack resources\. In some cases this command fails, such as when a resource isn't empty and must be empty before it can be destroyed\. See [Delete Stack Fails](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#troubleshooting-errors-delete-stack-fails) in the *AWS CloudFormation User Guide* for details\. \ No newline at end of file diff --git a/doc_source/grant_permissions.md b/doc_source/grant_permissions.md deleted file mode 100644 index 07f775e0..00000000 --- a/doc_source/grant_permissions.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Granting Permissions - -This section describes how to grant permissions\. \ No newline at end of file diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md deleted file mode 100644 index 9f9b0b45..00000000 --- a/doc_source/identifiers.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Identifiers - -TBD \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index 14e6ad3a..2342a092 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -18,14 +18,10 @@ Amazon's trademarks and trade dress may not be used in + [Getting Started With the AWS CDK](getting_started.md) + [Concepts](core_concepts.md) + [Constructs](constructs.md) - + [Apps and Stacks](apps_and_stacks.md) + + [Apps, Stacks, and Environments and Authentication](apps_and_stacks.md) + [Resources](resources.md) - + [Identifiers](identifiers.md) - + [References](references.md) - + [Permissions](permissions.md) + [Run-Time Context](context.md) + [Assets](assets.md) - + [Aspects](aspects.md) + [AWS CloudFormation](cloudformation.md) + [Tokens](tokens.md) + [AWS CDK Lifecycle](lifecycle.md) @@ -36,33 +32,17 @@ Amazon's trademarks and trade dress may not be used in + [Examples](examples.md) + [Creating a Serverless Application Using the AWS CDK](serverless_example.md) + [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) - + [Creating an AWS CodePipeline Service Using the AWS CDK](codepipeline_example.md) + [AWS CDK Examples](about_examples.md) + [AWS CDK HowTos](how_tos.md) - + [Migrate AWS CloudFormation to the CDK](migrate_cfn.md) + [Get a Value from an Environment Variable](get_env_var.md) + [Use an AWS CloudFormation Parameter](get_cfn_param.md) + [Use an Existing AWS CloudFormation Template](use_cfn_template.md) + [Get a Value from a Systems Manager Parameter Store Variable](get_ssm_value.md) - + [Get a Value from AWS Secrets Manager](passing_secrets_manager.md) + + [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md) + [Work Around Missing AWS CDK Features](cfn_layer.md) + [Create an App with Multiple Stacks](stack_how_to_create_multiple_stacks.md) + [Set a CloudWatch Alarm](how_to_set_cw_alarm.md) - + [Granting Permissions](grant_permissions.md) - + [Complex Authentication with the CDK](complex_auth.md) - + [??? Amazon CloudWatch Events](cloudwatch_events.md) + [Get a Value from a Context Variable](get_context_var.md) - + [Creating Custom Resources](create_custom_resources.md) - + [Setting up an Auto Scaling Group](setup_asg.md) - + [Starting an Amazon EC2 Instance in an Auto Scaling Group](start_ec2_asg.md) - + [Deploying an App Through a Pipeline](deploy_pipeline.md) - + [Controlling an AWS CloudFormation Template Using the CDK](control_cfn_template.md) - + [Building a Lambda App with the AWS SAM](build_lambda_sam.md) + [CDK Toolchain](tools.md) - + [AWS CDK Command Line Interface (cdk)](cli.md) - + [SAM CLI](toolchain_sam.md) - + [CI/CD for CDK Apps](toolchain_cicd.md) -+ [Troubleshooting the CDK](troubleshooting.md) - + [Debugging Your CDK App](debugging.md) + [OpenPGP Keys for the AWS CDK and JSII](pgp-keys.md) + [Document History for the AWS CDK Developer Guide](doc-history.md) \ No newline at end of file diff --git a/doc_source/lifecycle.md b/doc_source/lifecycle.md index 4bde0aae..2d4caef0 100644 --- a/doc_source/lifecycle.md +++ b/doc_source/lifecycle.md @@ -8,7 +8,7 @@ This documentation is for the developer preview release \(public beta\) of the A The following illustration shows the phases that the CDK goes through when you call cdk deploy to create the resources defined by your application\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/guide/images/Lifecycle.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/Lifecycle.png) There are three actors at play to create the resources that your CDK application defines\. + Your CDK app\. diff --git a/doc_source/migrate_cfn.md b/doc_source/migrate_cfn.md deleted file mode 100644 index 55ab09f5..00000000 --- a/doc_source/migrate_cfn.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Migrate AWS CloudFormation to the CDK - -This section describes how to migrate from AWS CloudFormation to the CDK\. \ No newline at end of file diff --git a/doc_source/permissions.md b/doc_source/permissions.md deleted file mode 100644 index 07230403..00000000 --- a/doc_source/permissions.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Permissions - -TBD \ No newline at end of file diff --git a/doc_source/references.md b/doc_source/references.md deleted file mode 100644 index 714dfc48..00000000 --- a/doc_source/references.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# References - -TBD \ No newline at end of file diff --git a/doc_source/setup_asg.md b/doc_source/setup_asg.md deleted file mode 100644 index 049d57eb..00000000 --- a/doc_source/setup_asg.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Setting up an Auto Scaling Group - -This section describes how to set up an Auto Scaling group using the CDK\. \ No newline at end of file diff --git a/doc_source/start_ec2_asg.md b/doc_source/start_ec2_asg.md deleted file mode 100644 index defb7dbb..00000000 --- a/doc_source/start_ec2_asg.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Starting an Amazon EC2 Instance in an Auto Scaling Group - -This section describes how to start an Amazon EC2 in Auto Scaling group\. \ No newline at end of file diff --git a/doc_source/toolchain_cicd.md b/doc_source/toolchain_cicd.md deleted file mode 100644 index a46dc1d7..00000000 --- a/doc_source/toolchain_cicd.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# CI/CD for CDK Apps - -This topic describes how to configure continuous integration and delivery for your CDK application\. \ No newline at end of file diff --git a/doc_source/toolchain_sam.md b/doc_source/toolchain_sam.md deleted file mode 100644 index 2cda5d48..00000000 --- a/doc_source/toolchain_sam.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# SAM CLI - -This topic describes the SAM CLI\. For further information, see ???\. \ No newline at end of file diff --git a/doc_source/tools.md b/doc_source/tools.md index 78003d8a..e308e880 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -6,4 +6,243 @@ This documentation is for the developer preview release \(public beta\) of the A # CDK Toolchain -This section contains information about CDK tools\. \ No newline at end of file +This section contains information about CDK tools\. + +## AWS CDK Command Line Interface \(cdk\) + +The CDK Toolkit, cdk, is the main tool you use to interact with your CDK app\. It executes the CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the CDK\. + +There are two ways to tell cdk what command to use to run your CDK app\. The first way is to include an explicit \-\-app option whenever you use a cdk command\. + +``` +cdk --app 'node bin/main.js' synth +``` + +The second way is to add the following entry to the `cdk.json` file\. + +``` +{ + "app": "node bin/main.js" +} +``` + +You can also use the npx cdk instead of just cdk\. + +Here are the actions you can take on your CDK app \(this is the output of the cdk \-\-help command\)\. + +``` +Usage: cdk -a COMMAND + +Commands: + cdk list Lists all stacks in the app [aliases: ls] + cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation + template for this stack [aliases: synth] + cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS + environment + cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your + AWS account + cdk destroy [STACKS..] Destroy the stack(s) named STACKS + cdk diff [STACKS..] Compares the specified stack with the deployed + stack or a local template file, and returns + with status 1 if any difference is found + cdk metadata [STACK] Returns all metadata associated with this + stack + cdk init [TEMPLATE] Create a new, empty CDK project from a + template. Invoked without TEMPLATE, the app + template will be used. + cdk context Manage cached context values + cdk docs Opens the reference documentation in a browser + [aliases: doc] + cdk doctor Check your set-up for potential problems + +Options: + --app, -a REQUIRED: Command-line for executing your CDK app (e.g. + "node bin/my-app.js") [string] + --context, -c Add contextual string parameter (KEY=VALUE) [array] + --plugin, -p Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] + --rename Rename stack name if different from the one defined in + the cloud executable ([ORIGINAL:]RENAMED) [string] + --trace Print trace for stack warnings [boolean] + --strict Do not construct stacks with warnings [boolean] + --ignore-errors Ignores synthesis errors, which will likely produce an + invalid output [boolean] [default: false] + --json, -j Use JSON output instead of YAML + [boolean] [default: false] + --verbose, -v Show debug logs [boolean] [default: false] + --profile Use the indicated AWS profile as the default environment + [string] + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified. [string] + --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: + guess EC2 instance status. [boolean] + --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized + templates (enabled by default) [boolean] + --path-metadata Include "aws:cdk:path" CloudFormation metadata for each + resource (enabled by default) [boolean] [default: true] + --asset-metadata Include "aws:asset:*" CloudFormation metadata for + resources that user assets (enabled by default) + [boolean] [default: true] + --role-arn, -r ARN of Role to use when invoking CloudFormation [string] + --toolkit-stack-name The name of the CDK toolkit stack [string] + --staging directory name for staging assets (use + --no-asset-staging to disable) + [string] [default: ".cdk.staging"] + --ci Force CI detection. Use --no-ci to disable CI + autodetection. [boolean] [default: false] + --version Show version number [boolean] + -h, --help Show help [boolean] + +If your app has a single stack, there is no need to specify the stack name + +If one of cdk.json or ~/.cdk.json exists, options specified there will be used +as defaults. Settings in cdk.json take precedence. +``` + +If your app has a single stack, you don't have to specify the stack name\. + +If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. + +### Bootstrapping the CDK + +Before you can use the CDK you must bootstrap the CDK to create the infrastructure that the CDK needs\. Currently the bootstrap command creates only an Amazon S3 bucket\. + +You incur any charges for what the CDK stores in the bucket\. Because the CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. + +### Security\-Related Changes + +To protect you against unintended changes that affect your security posture, the CDK toolkit prompts you to approve security\-related changes before deploying them\. + +You change the level of changes that requires approval by specifying: + +``` +cdk deploy --require-approval LEVEL +``` + +Where *LEVEL* can be one of the following: + +never +Approval is never required\. + +any\-change +Requires approval on any IAM or security\-group related change\. + +broadening +\(default\) Requires approval when IAM statements or traffic rules are added\. Removals don't require approval\. + +The setting can also be configured in the `cdk.json` file\. + +``` +{ + "app": "...", + "requireApproval": "never" +} +``` + +### Version Reporting + +To gain insight into how the CDK is used, the versions of libraries used by CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. + +The CDK reports the name and version of `npm` modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. + +The `AWS::CDK::Metadata` resource looks like the following\. + +``` +CDKMetadata: + Type: "AWS::CDK::Metadata" + Properties: + Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,lodash=4.17.10" +``` + +### Opting Out from Version Reporting + +To opt out of version reporting, use one of the following methods: ++ Use the cdk command with the \-\-no\-version\-reporting argument\. + + ``` + cdk --no-version-reporting synth + ``` ++ Set versionReporting to **false** in `./cdk.json` or `~/cdk.json`\. + + ``` + { + "app": "...", + "versionReporting": false + } + ``` + +## SAM CLI + +This topic describes how to use the SAM CLI with the CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. + +1. The first step is to create a CDK application and add the Lambda package\. + + ``` + mkdir cdk-sam-example + cd cdk-sam-example + cdk init app --language typescript + npm install @aws-cdk/aws-lambda + ``` + +1. Add a Lambda reference to `lib/cdk-sam-example-stack.ts`: + + ``` + import lambda = require('@aws-cdk/aws-lambda'); + ``` + +1. Replace the comment in `lib/cdk-sam-example-stack.ts` with the following Lambda function: + + ``` + new lambda.Function(this, 'MyFunction', { + runtime: lambda.Runtime.Python37, + handler: 'app.lambda_handler', + code: lambda.Code.asset('./my_function'), + }); + ``` + +1. Create the directory `my_function` + + ``` + mkdir my_function + ``` + +1. Create the file `app.py` in `my_function` with the following content: + + ``` + def lambda_handler(event, context): + return "This is a Lambda Function defined through CDK" + ``` + +1. Compile your CDK app and create a AWS CloudFormation template + + ``` + npm run build + cdk synth > template.yaml + ``` + +1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the CDK generates for all resources\. The line right after it should look like: + + ``` + Type: AWS::Lambda::Function + ``` + +1. Run the function by executing: + + ``` + sam local invoke MyFunction12345678 --no-event + ``` + + The output should look something like the following\. + + ``` + 2019-04-01 12:22:41 Found credentials in shared credentials file: ~/.aws/credentials + 2019-04-01 12:22:41 Invoking app.lambda_handler (python3.7) + + Fetching lambci/lambda:python3.7 Docker container image...... + 2019-04-01 12:22:43 Mounting D:\cdk-sam-example\.cdk.staging\a57f59883918e662ab3c46b964d2faa5 as /var/task:ro,delegated inside runtime container + START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST + END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 + REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB + + "This is a Lambda Function defined through CDK" + ``` \ No newline at end of file diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md deleted file mode 100644 index 6bacb83c..00000000 --- a/doc_source/troubleshooting.md +++ /dev/null @@ -1,9 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Troubleshooting the CDK - -This section describes how to troubleshoot problems with your CDK app\. \ No newline at end of file diff --git a/doc_source/what-is.md b/doc_source/what-is.md index 540b57bb..2bc52fef 100644 --- a/doc_source/what-is.md +++ b/doc_source/what-is.md @@ -14,11 +14,11 @@ AWS CloudFormation enables you to: + Build highly reliable, highly scalable, cost\-effective applications in the cloud without worrying about creating and configuring the underlying AWS infrastructure\. + Use a template file to create and delete a collection of resources together as a single unit \(a stack\)\. -Use the CDK to define your cloud resources using one of the supported programming languages: C\#/\.NET, Java, JavaScript, or TypeScript\. This document does not supply reference information for the CDK\. You can find that information in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. +Use the CDK to define your cloud resources using one of the supported programming languages: C\#/\.NET, Java, JavaScript, Python, or TypeScript\. This document does not supply reference information for the CDK\. You can find that information in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](apps_and_stacks.md#stacks) and [Apps](apps_and_stacks.md#apps)\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/guide/images/AppStacks.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/AppStacks.png) ## Why Use the CDK? @@ -86,7 +86,7 @@ Resources: Another advantage of IAC \(infrastructure as code\) is that you get code completion within your IDE: -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/CDK/latest/guide/images/CodeCompletion.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/CodeCompletion.png) ## Developing With the CDK From ea2d251e282e5988086afb8a8afee9f2ffcd2c0e Mon Sep 17 00:00:00 2001 From: FantasticFiasco Date: Mon, 13 May 2019 23:35:37 +0200 Subject: [PATCH 016/655] fix(multiple languages): typescript import typo --- doc_source/multiple_languages.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 66d482f7..fe570c58 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -15,7 +15,7 @@ The CDK supports C\#, Java, JavaScript, and TypeScript\. Since the CDK is develo In TypeScript, you import a package as follows \(we'll use Amazon S3 for our examples\): ``` -import lambda = require("@aws-cdk/aws-s3"); +import s3 = require("@aws-cdk/aws-s3"); ``` ------ From 4bbb464f6ced0c8743aaf2782eb3efae7282e0b0 Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Tue, 14 May 2019 06:47:00 -0700 Subject: [PATCH 017/655] Updated markdown to 0.31.0 --- doc_source/apps_and_stacks.md | 6 +- doc_source/aws_construct_lib.md | 162 +++++++----------------- doc_source/cfn_layer.md | 22 ++-- doc_source/cloudformation.md | 4 +- doc_source/constructs.md | 2 +- doc_source/context.md | 8 +- doc_source/core_concepts.md | 2 +- doc_source/doc-history.md | 4 +- doc_source/get_secrets_manager_value.md | 2 +- doc_source/get_ssm_value.md | 4 +- doc_source/getting_started.md | 20 ++- doc_source/reference.md | 2 +- doc_source/resources.md | 6 +- doc_source/what-is.md | 6 +- 14 files changed, 96 insertions(+), 154 deletions(-) diff --git a/doc_source/apps_and_stacks.md b/doc_source/apps_and_stacks.md index 854c248b..9eaa9973 100644 --- a/doc_source/apps_and_stacks.md +++ b/doc_source/apps_and_stacks.md @@ -14,7 +14,7 @@ Let's look at apps and stacks from the bottom up\. ## Stacks -Define an application stack by extending the [Stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) class, as shown in the following example\. +Define an application stack by extending the [Stack]() class, as shown in the following example\. ``` import cdk = require("@aws-cdk/cdk"); @@ -43,7 +43,7 @@ Next we'll show you how to use one or more stacks to create a CDK app\. ## Apps -An [app](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app) is a collection of [stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) objects, as shown in the following example\. +An [app]() is a collection of [stack]() objects, as shown in the following example\. ``` import cdk = require("@aws-cdk/cdk"); @@ -81,7 +81,7 @@ cdk deploy MyWestCdkStack ## Environments and Authentication -When you create a [stack](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) instance, you can supply the target deployment environment for the stack using the `env` property\. This is shown in the following example, where *REGION* is the AWS Region in which you want to create the stack and *ACCOUNT* is your account ID\. +When you create a [stack]() instance, you can supply the target deployment environment for the stack using the `env` property\. This is shown in the following example, where *REGION* is the AWS Region in which you want to create the stack and *ACCOUNT* is your account ID\. ``` new MyStack(app, { env: { region: 'REGION', account: 'ACCOUNT' } }); diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md index 613d7b53..db1ddedd 100644 --- a/doc_source/aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -6,7 +6,7 @@ This documentation is for the developer preview release \(public beta\) of the A # AWS Construct Library -The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, the [@aws\-cdk/aws\-ec2](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#module-@aws-cdk/aws-ec2) module includes the [@aws\-cdk/aws\-ec2\.VpcNetwork](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#@aws-cdk/aws-ec2.VpcNetwork) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your CDK app\. +The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [VpcNetwork](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2vpcnetwork.html) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your CDK app\. The AWS Construct Library modules are described in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. @@ -22,156 +22,90 @@ The AWS Construct Library includes many common patterns and capabilities that ar ### Grants -AWS Identity and Access Management \(IAM\) policies are automatically defined based on intent\. For example, when subscribing an Amazon Simple Notification Service \(Amazon SNS\) [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) to an AWS Lambda [Function](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.Function), the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. +AWS Identity and Access Management \(IAM\) policies are automatically defined based on intent\. For example, when subscribing an Amazon Simple Notification Service \(Amazon SNS\) [Topic]("https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns"/topic.html) to an AWS Lambda [Function](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-lambda/function.html), the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. -Also, most AWS constructs expose `grant*` methods that allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct has a [grantRead\(principal\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.grantRead) method\. This method accepts an IAM [Principal](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#iprincipal-interface) such as a [User](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#user) or a [Role](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-iam.html#role), which modifies the policy to allow the principal to read objects from the bucket\. +Also, most AWS constructs expose `grant*` methods that allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](s3-base-url;/.bucket.html) construct has a [grantRead](s3-base-url;/.bucket.html#grantreadidentity-objectskeypattern) method\. This method accepts an IAM [IPrincipal](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/iprincipal.html) such as a [User](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/user.html) or a [Role](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/role.html), which modifies the policy to allow the principal to read objects from the bucket\. ## Metrics -Many AWS resources emit [Amazon CloudWatch metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html) as part of their normal operation\. Metrics can be used to set up an [Alarm](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Alarm) or can be included in a [Dashboard](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Dashboard)\. +Many AWS resources emit [Amazon CloudWatch metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html) as part of their normal operation\. Metrics can be used to set up an [Alarm](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-cloudwatch/alarm.html) or can be included in a [Dashboard](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-cloudwatch/dashboard.html)\. -You can obtain [Metric](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#@aws-cdk/aws-cloudwatch.Metric) objects for AWS constructs by using `metricXxx()` methods\. For example, the [metricDuration\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-lambda.html#@aws-cdk/aws-lambda.FunctionRef.metricDuration) method reports the execution time of an AWS Lambda function\. +You can obtain [Metric](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-cloudwatch/metric.html) objects for AWS constructs by using `metricXxx()` methods\. For example, the [metricAllDuration](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-lambda/function.html#aws_lambda_Function_metricAllDuration) method reports the execution time of an AWS Lambda function\. -For more information, see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html)\. +For more information, see [CloudWatch](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudwatch-readme.html)\. ## Events -Many AWS constructs include `on*` methods, which you can to react to events emitted by the construct\. For example, the CodeCommit [Repository](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#Repository) construct has an [onCommit](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-codecommit.html#@aws-cdk/aws-codecommit.RepositoryRef.onCommit) method\. You can use AWS constructs as targets for various event provider interfaces, such as [IEventRuleTarget](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html#ieventruletarget-interface) \(for the CloudWatch event rule target\), [IAlarmAction](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html#ialarmaction-interface) \(for Amazon CloudWatch alarm actions\), and so on\. +Many AWS constructs include `on*` methods, which you can to react to events emitted by the construct\. For example, the CodeCommit [Repository](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-codecommit/repository.html) construct implements the [onCommit](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-codecommit/irepository.html#aws_codecommit_IRepository_onCommit) method\. You can use AWS constructs as targets for various event provider interfaces, such as [IEventRuleTarget](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-events/ieventruletarget.html) \(for the CloudWatch event rule target\), [IAlarmAction](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-cloudwatch/ialarmaction.html) \(for Amazon CloudWatch alarm actions\), and so on\. -For more information, see [@aws\-cdk/aws\-cloudwatch](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-cloudwatch.html) and [@aws\-cdk/aws\-events](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-events.html)\. +For more information, see [CloudWatch](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudwatch-readme.html) and [Events](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-events-readme.html)\. -## Referencing Constructs +## Referencing Resources -This section contains information about how to reference other constructs, either from within the same app, or across apps\. +This section contains information about how to reference other resources, either from within the same app, or across apps\. The only caveat is that the resource must be in the same account and region\. -### Get a Value from Another Stack +Many CDK classes have required properties that are CDK resource objects \(resources\)\. To satisfy these requirements, you can refer to a resource in one of two ways: ++ By passing the resource directly\. ++ By passing the resource's unique identifier\. This is typically an ARN, but it could also be an ID or a name\. -You can get a value from another stack in the same app by using the `export` method in one stack and the `import` method in the other stack\. +For example, an Amazon ECS service requires a reference to the cluster on which it runs; a CloudFront distribution requires a reference to the bucket containing source code\. -The following example creates a bucket on one stack and passes a reference to that bucket to the other stack through an interface\. +In the AWS CDK, all AWS Construct Library resources that expect another resource take a property that is of the interface type of that resource\. For example, the Amazon ECS service takes a property of type `cluster: ICluster;` the CloudFront distribution takes a property of type `sourceBucket: IBucket`\. -First create a stack with a bucket\. The stack includes a property we use to pass the bucket's properties to the other stack\. Notice how we use the `export` method on the bucket to get its properties and save them in the stack property\. +Since every resource implements its corresponding interface, you can directly pass any resources you're defining in the same AWS CDK application, as shown in the following example, which creates a new Amazon ECS cluster\. ``` -class HelloCdkStack extends cdk.Stack { - // Property that defines the stack you are exporting from - public readonly myBucketImportProps: s3.BucketImportProps; +const cluster = new ecs.Cluster(this, 'Cluster', { /* ... */ }); - constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { - super(scope, id, props); - - const mybucket = new s3.Bucket(this, "MyFirstBucket"); - - // Save bucket's BucketImportProps - this.myBucketImportProps = mybucket.export(); - } -} -``` - -Create an interface for the second stack's properties\. We use this interface to pass the bucket properties between the two stacks\. - -``` -// Interface we'll use to pass the bucket's properties to another stack -interface MyCdkStackProps { - theBucketImportProps: s3.BucketImportProps; -} -``` - -Create the second stack that gets a reference to the other bucket from the properties passed in through the constructor\. - -``` -// The class for the other stack -class MyCdkStack extends cdk.Stack { - constructor(scope: cdk.App, id: string, props: MyCdkStackProps) { - super(scope, id); - - const myOtherBucket = s3.Bucket.import(this, "MyOtherBucket", props.theBucketImportProps); - - // Do something with myOtherBucket - } -} -``` - -Finally, connect the dots in your app\. - -``` -const app = new cdk.App(); - -const myStack = new HelloCdkStack(app, "HelloCdkStack"); - -new MyCdkStack(app, "MyCdkStack", { - theBucketImportProps: myStack.myBucketImportProps +const service = new ecs.Service(this, 'Service', { + cluster: cluster, + /* ... */ }); ``` -### Referencing Constructs Across All App - -This section contains information about how to reference constructs from other apps\. - -To reference a resource, such as an Amazon S3 bucket or VPC, that's defined outside of your CDK app, use the `Xxxx.import(...)` static methods that are available on AWS constructs\. For example, use the [Bucket\.import\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef.import) method to obtain a [BucketRef](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketRef) object, which can be used in most places where a bucket is required\. This pattern enables treating resources defined outside of your app as if they are part of your app\. - -## Get a Value from Another Stack - -You can get a value from another stack in the same app by using the `export` method in one stack and the `import` method in the other stack\. +### Passing Resources from a Different Stack -The following example creates a bucket on one stack and passes a reference to that bucket to the other stack through an interface\. - -First create a stack with a bucket\. The stack includes a property we use to pass the bucket's properties to the other stack\. Notice how we use the `export` method on the bucket to get its properties and save them in the stack property\. +You can refer to resources in a different stack, but in the same account and region\. If you need to refer to a resource in a different account or region, see the next section\. ``` -class HelloCdkStack extends cdk.Stack { - // Property that defines the stack you are exporting from - public readonly myBucketImportProps: s3.BucketImportProps; - - constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { - super(scope, id, props); +const account = '123456789012'; +const region = 'us-east-1'; - const mybucket = new s3.Bucket(this, "MyFirstBucket"); - - // Save bucket's BucketImportProps - this.myBucketImportProps = mybucket.export(); - } -} -``` +const stack1 = new StackThatProvidesABucket(app, 'Stack1'); -Create an interface for the second stack's properties\. We use this interface to pass the bucket properties between the two stacks\. - -``` -// Interface we'll use to pass the bucket's properties to another stack -interface MyCdkStackProps { - theBucketImportProps: s3.BucketImportProps; -} +// stack2 takes a property of type IBucket +const stack2 = new StackThatExpectsABucket(app, 'Stack2', { + bucket: stack1.bucket +}); ``` -Create the second stack that gets a reference to the other bucket from the properties passed in through the constructor\. - -``` -// The class for the other stack -class MyCdkStack extends cdk.Stack { - constructor(scope: cdk.App, id: string, props: MyCdkStackProps) { - super(scope, id); +If the resource is in the same account and region, but in a different stack, the CDK creates the relevant information, such as the bucket name, that is necessary to transfer that information from one stack to the other\. - const myOtherBucket = s3.Bucket.import(this, "MyOtherBucket", props.theBucketImportProps); +### Passing Resources from a Different Account or Region - // Do something with myOtherBucket - } -} -``` +You can refer to a resource in a different account or region by using the resource's unique indentifier, such as: ++ `bucketName` for `bucket` ++ `functionArn` for `lambda` ++ `securityGroupId` for `securityGroup` -Finally, connect the dots in your app\. +The following example shows how to pass a generated bucket name to a Lambda function\. ``` -const app = new cdk.App(); +const bucket = new s3.Bucket(this, 'Bucket'); -const myStack = new HelloCdkStack(app, "HelloCdkStack"); - -new MyCdkStack(app, "MyCdkStack", { - theBucketImportProps: myStack.myBucketImportProps +new lambda.Function(this, 'MyLambda', { + /* ... */, + environment: { + BUCKET_NAME: bucket.bucketName, + }, }); ``` -## Security Groups +### Turning Unique Identifiers into Objects -Amazon Elastic Compute Cloud \(Amazon EC2\) network entities, such as the [Elastic Load Balancing](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-elasticloadbalancingv2.html) and [Auto Scaling Group](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-autoscaling.html#auto-scaling-group) instances, can connect to each other based on definitions of security groups\. +If you have the unique identifier for a resource, such as a bucket ARN, but you need to pass it to a AWS CDK construct that expects an object, you can turn the ARN into a AWS CDK object in the current stack by calling a static factory method on the resource's class\. The following example shows how to create a bucket from an existing bucket ARN\. -The CDK provides APIs for defining security group connections\. For more information, see [Allowing Connections](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#allowing-connections)\. \ No newline at end of file +``` +// Construct a resource (bucket) by its full ARN (can be cross account) +Bucket.fromBucketArn(this, 'Bucket', 'arn:aws:s3:::my-bucket-name'); +``` \ No newline at end of file diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 28d6f001..0c8bb3a5 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -12,7 +12,7 @@ This topic describes how to modify the underlying AWS CloudFormation resources i We don't recommend this method because it breaks the abstraction layer and might produce unexpected results\. If you modify an AWS construct in this way, we can't ensure that your code will be compatible with subsequent releases\. -AWS constructs, such as [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic), encapsulate one or more AWS CloudFormation resources behind their APIs\. These resources are also represented as `CfnXxx` constructs in each library\. For example, the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct encapsulates the [@aws\-cdk/aws\-s3\.cloudformation\.BucketResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.cloudformation.BucketResource)\. When a stack that includes an AWS construct is synthesized, the AWS CloudFormation definitions of the underlying resources are included in the resulting template\. +AWS constructs, such as [Topic]("https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns"/topic.html), encapsulate one or more AWS CloudFormation resources behind their APIs\. These resources are also represented as `CfnXxx` constructs in each library\. For example, the [Bucket](s3-base-url;/.bucket.html) construct encapsulates the [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/cfnbucket.html)\. When a stack that includes an AWS construct is synthesized, the AWS CloudFormation definitions of the underlying resources are included in the resulting template\. Eventually, we expect the APIs provided by AWS constructs to support all of the services and capabilities offered by AWS\. But we're aware that the library still has many gaps, both at the service level \(some services don't have any constructs yet\) and at the resource level \(an AWS construct exists, but some features are missing\)\. @@ -29,9 +29,9 @@ You can also find more information about how to work directly with the AWS Cloud ## Accessing Low\-Level Resources -Use [construct\.findChild\(\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Construct.findChild) to access any child of a construct by its construct ID\. By convention, the main resource of any AWS construct is named **Resource**\. +Use [construct\.findChild\(\)](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.Construct.findChild) to access any child of a construct by its construct ID\. By convention, the main resource of any AWS construct is named **Resource**\. -The following example shows how to access the underlying Amazon Simple Storage Service \(Amazon S3\) bucket resource, given a [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct\. +The following example shows how to access the underlying Amazon Simple Storage Service \(Amazon S3\) bucket resource, given a [Bucket](s3-base-url;/.bucket.html) construct\. ``` // Create an AWS bucket construct @@ -42,11 +42,11 @@ const bucket = new s3.Bucket(this, 'MyBucket'); const bucketResource = bucket.node.findChild('Resource') as s3.CfnBucket; ``` -The `bucketResource` represents the low\-level AWS CloudFormation resource of type [@aws\-cdk/aws\-s3\.cloudformation\.BucketResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.cloudformation.BucketResource) that's encapsulated by the bucket\. +The `bucketResource` represents the low\-level AWS CloudFormation resource of type [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/cfnbucket.html) that's encapsulated by the bucket\. -If the child can't be located, [construct\.findChildren\(id\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/cdk.Construct.findChild) fails\. This means that if the underlying AWS Construct Library changes the IDs or structure for some reason, synthesis fails\. +If the child can't be located, [construct\.findChildren\(id\)](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3#@aws-cdk/cdk.Construct.findChild) fails\. This means that if the underlying AWS Construct Library changes the IDs or structure for some reason, synthesis fails\. -You can also use [construct\.children](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/cdk.Construct.children) for more advanced queries\. For example, you can look for a child that has a certain AWS CloudFormation resource type\. +You can also use [construct\.children](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3#@aws-cdk/cdk.Construct.children) for more advanced queries\. For example, you can look for a child that has a certain AWS CloudFormation resource type\. ``` const bucketResource = @@ -54,11 +54,11 @@ const bucketResource = as s3.CfnBucket; ``` -Once you have a AWS CloudFormation resource, you are interacting with AWS CloudFormation resource classes, which extend [cdk\.CfnResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource)\. +Once you have a AWS CloudFormation resource, you are interacting with AWS CloudFormation resource classes, which extend [cdk\.CfnResource](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource)\. ## Resource Options -Set resource options using [cdk\.CfnResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource) properties such as *Metadata* and *DependsOn*\. +Set resource options using [cdk\.CfnResource](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource) properties such as *Metadata* and *DependsOn*\. For example, the following code: @@ -94,7 +94,7 @@ Synthesizes into the following template\. ## Raw Overrides - Use the [cdk\.CfnResource\.addOverride\(path, value\)](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.addOverride) method to define an override that is applied to the resource definition during synthesis, as shown in the following example\. + Use the [cdk\.CfnResource\.addOverride\(path, value\)](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource.addOverride) method to define an override that is applied to the resource definition during synthesis, as shown in the following example\. ``` // Define an override at the resource definition root, you can even modify the "Type" @@ -134,7 +134,7 @@ This synthesizes to the following\. } ``` -Use `undefined`, [cdk\.CfnResource\.addDeletionOverride](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.addDeletionOverride), or [cdk\.CfnResource\.addPropertyDeletionOverride](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.addPropertyDeletionOverride) to delete values\. +Use `undefined`, [cdk\.CfnResource\.addDeletionOverride](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource.addDeletionOverride), or [cdk\.CfnResource\.addPropertyDeletionOverride](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource.addPropertyDeletionOverride) to delete values\. ``` const bucket = new s3.Bucket(this, 'MyBucket', { @@ -181,7 +181,7 @@ new s3.CfnBucket(this, 'MyBucket', { }); ``` -In the rare case where you want to define a resource that doesn't have a corresponding `CfnXxx` class \(such as a new resource that wasn't published yet in the AWS CloudFormation resource specification\), you can instantiate the [cdk\.CfnResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource)\. +In the rare case where you want to define a resource that doesn't have a corresponding `CfnXxx` class \(such as a new resource that wasn't published yet in the AWS CloudFormation resource specification\), you can instantiate the [cdk\.CfnResource](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource)\. ``` new cdk.Resource(this, 'MyBucket', { diff --git a/doc_source/cloudformation.md b/doc_source/cloudformation.md index 684ce38a..057c54d4 100644 --- a/doc_source/cloudformation.md +++ b/doc_source/cloudformation.md @@ -6,9 +6,9 @@ This documentation is for the developer preview release \(public beta\) of the A # AWS CloudFormation -The [AWS Construct Library](aws_construct_lib.md)includes constructs with APIs for defining AWS infrastructure\. For example, you can use the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct to define Amazon Simple Storage Service \(Amazon S3\) buckets, and the [Topic](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sns.html#@aws-cdk/aws-sns.Topic) construct to define Amazon Simple Notification Service \(Amazon SNS\) topics\. +The [AWS Construct Library](aws_construct_lib.md) includes constructs with APIs for defining AWS infrastructure\. For example, you can use the [Bucket](s3-base-url;/.bucket.html) construct to define Amazon Simple Storage Service \(Amazon S3\) buckets, and the [Topic]("https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns"/topic.html) construct to define Amazon Simple Notification Service \(Amazon SNS\) topics\. -Under the hood, these constructs are implemented using AWS CloudFormation resources, which are available in the `CfnXxx` classes in each library\. For example, the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#bucket) construct uses the [@aws\-cdk/aws\-s3\.cloudformation\.BucketResource](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.cloudformation.BucketResource) resource \(as well as other resources, depending on what bucket APIs are used\)\. +Under the hood, these constructs are implemented using AWS CloudFormation resources, which are available in the `CfnXxx` classes in each library\. For example, the [Bucket](s3-base-url;/.bucket.html) construct uses the [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/cfnbucket.html) resource \(as well as other resources, depending on what bucket APIs are used\)\. **Important** Avoid interacting directly with AWS CloudFormation unless absolutely necessary, such as when a CDK AWS Construct Library does not provide the needed functionality\. \ No newline at end of file diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 2ada5f32..5a5e7a16 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -20,7 +20,7 @@ The CDK creates the low\-level resources from the [AWS CloudFormation Resource S High\-level resource constructs are authored by AWS and offer an intent\-based API for using AWS services\. They provide the same functionality as the low\-level resources, but encode much of the details, boilerplate, and glue logic required to use AWS\. High\-level resources offer convenient defaults and additional knowledge about the inner workings of the AWS resources they represent\. -Similarly to the AWS SDKs and AWS CloudFormation, the AWS Construct Library is organized into modules, one for each AWS service\. For example, the `@aws-cdk/aws-ec2` module includes resources for Amazon EC2 instances and networking\. The `aws-sns` module includes resources such as `Topic` and `Subscription`\. See the [Reference](https://awslabs.github.io/aws-cdk/reference.html) for descriptions of the CDK packages and constructs\. +Similarly to the AWS SDKs and AWS CloudFormation, the AWS Construct Library is organized into modules, one for each AWS service\. For example, the `@aws-cdk/aws-ec2` module includes resources for Amazon EC2 instances and networking\. The `aws-sns` module includes resources such as `Topic` and `Subscription`\. See the [Reference](https://docs.aws.amazon.com/cdk/api/latest) for descriptions of the CDK packages and constructs\. AWS Construct Library members are found in the `@aws-cdk/aws-NAMESPACE` packages, where `NAMESPACE` is the short name for the associated service, such as `SQS` for the AWS Construct Library for the Amazon Simple Queue Service \(Amazon SQS\) service\. diff --git a/doc_source/context.md b/doc_source/context.md index 30c48df9..04b57864 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -59,7 +59,7 @@ cdk context --clear The AWS CDK currently supports the following context providers\. -[AvailabilityZoneProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.AvailabilityZoneProvider) +[AvailabilityZoneProvider](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/availabilityzoneprovider.html) Use this provider to get the list of all supported Availability Zones in this context, as shown in the following example\. ``` @@ -71,7 +71,7 @@ for (let zone of zones) { } ``` -[HostedZoneProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-route53.html#@aws-cdk/aws-route53.HostedZoneProvider) +[HostedZoneProvider](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-route53/hostedzoneprovider.html) Use this provider to discover existing hosted zones in your account\. For example, the following code imports an existing hosted zone into your CDK app so you can add records to it\. ``` @@ -80,7 +80,7 @@ const zone: HostedZoneRef = new HostedZoneProvider(this, { }).findAndImport(this, 'HostedZone'); ``` -[SSMParameterProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.SSMParameterProvider) +[SSMParameterProvider](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/ssmparameterprovider.html) Use this provider to read values from the current Region's AWS Systems Manager parameter store\. For example, the following code returns the value of the *my\-awesome\-parameter* key\. ``` @@ -90,7 +90,7 @@ const ami: string = new SSMParameterProvider(this, { ``` This is only for reading plain strings, and not recommended for secrets\. For reading secure strings from the Systems Manager Parameter Store, see [Get a Value from a Systems Manager Parameter Store Variable](get_ssm_value.md)\. -[VpcNetworkProvider](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#@aws-cdk/aws-ec2.VpcNetworkProvider) +[VpcNetworkProvider](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpcnetworkprovider.html) Use this provider to look up and reference existing VPCs in your accounts\. For example, the following code imports a VPC by tag name\. ``` diff --git a/doc_source/core_concepts.md b/doc_source/core_concepts.md index 07bd171a..5533118d 100644 --- a/doc_source/core_concepts.md +++ b/doc_source/core_concepts.md @@ -8,4 +8,4 @@ This documentation is for the developer preview release \(public beta\) of the A This topic describes some of the concepts \(the why and how\) behind the CDK\. It also discusses the advantages of using the AWS Construct Library instead of a low\-level AWS CloudFormation Resource\. -CDK apps are composed of building blocks known as [Constructs](constructs.md), which are composed together to form [stacks](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.Stack) and [apps](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#app)\. \ No newline at end of file +CDK apps are composed of building blocks known as [Constructs](constructs.md), which are composed together to form stacks \. \ No newline at end of file diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 36606945..38370c8f 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -7,7 +7,7 @@ This documentation is for the developer preview release \(public beta\) of the A # Document History for the AWS CDK Developer Guide This document is based on the following release of the AWS Cloud Development Kit \(CDK\)\. -+ **API version: 0\.30\.0** -+ **Latest documentation update:** May 2, 2019 ++ **API version: 0\.31\.0** ++ **Latest documentation update:** May 14, 2019 See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the CDK releases\. \ No newline at end of file diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index 656d4812..7ca4f2de 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -6,7 +6,7 @@ This documentation is for the developer preview release \(public beta\) of the A # Get a Value from AWS Secrets Manager -To use values from AWS Secrets Manager in your CDK app, use the [Secret](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-secretsmanager.html#secret) class's `import` method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. +To use values from AWS Secrets Manager in your CDK app, use the [fromSecretAttributes](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-secretsmanager/secret.html#aws_secretsmanager_Secret_fromSecretAttributes) method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. ``` import sm = require("@aws-cdk/aws-secretsmanager"); diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 29b7939f..10b12519 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -8,7 +8,7 @@ This documentation is for the developer preview release \(public beta\) of the A You can get the value of an AWS Systems Manager Parameter Store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It isn't possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from AWS Secrets Manager \(see [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. -To read a particular version of a Systems Manager Parameter Store plain string value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html#parameterstorestring)\. If you don't supply a `version` value, you get the latest version\. +To read a particular version of a Systems Manager Parameter Store plain string value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreString](#parameterstorestring)\. If you don't supply a `version` value, you get the latest version\. ``` import ssm = require('@aws-cdk/aws-ssm'); @@ -21,7 +21,7 @@ const parameterString = new ssm.ParameterStoreString(this, 'MyParameter', { const myvalue = parameterString.stringValue; ``` -To read a particular version of a Systems Manager Parameter Store `SecureString` value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreSecureString](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ssm.html#parameterstoresecurestring)\. You must supply a `version` value\. +To read a particular version of a Systems Manager Parameter Store `SecureString` value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreSecureString](#parameterstoresecurestring)\. You must supply a `version` value\. ``` import ssm = require('@aws-cdk/aws-ssm'); diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index b449e0bc..16cbaeaa 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -241,7 +241,15 @@ cd hello-cdk ### Initializing the App -Initialize an empty app, where *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), or **typescript** \(TypeScript\)\. +Initialize an app, where *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), **python** \(Python\), or **typescript** \(TypeScript\) and *TEMPLATE* is an optional template that creates an app with different resources than the default app that cdk init creates for the language\. + +``` +cdk init --language LANGUAGE [TEMPLATE] +``` + +The following table describes the templates provided by the supported languages\. + +[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) ------ #### [ TypeScript ] @@ -411,7 +419,7 @@ You might have to execute this command multiple times to resolve dependencies\. ------ -Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represented by the [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.Bucket) class\. +Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represented by the [Bucket](s3-base-url;/.bucket.html) class\. ------ #### [ TypeScript ] @@ -468,7 +476,7 @@ import software.amazon.awscdk.services.s3.Bucket; import software.amazon.awscdk.services.s3.BucketProps; public class MyStack extends Stack { - public MyStack(final App scopy, final String id) { + public MyStack(final App scope, final String id) { this(scope, id, null); } @@ -529,9 +537,9 @@ bucket = s3.Bucket(self, ------ Notice a few things: -+ [Bucket](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.Bucket) is a construct\. This means it's initialization signature has `scope`, `id`, and `props`\. In this case, the bucket is an immediate child of **MyStack**\. -+ `MyFirstBucket` is the **id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. To specify a physical name for your bucket, set the [bucketName](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.BucketProps.bucketName) property when you define your bucket\. -+ Because the bucket's [versioned](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html#@aws-cdk/aws-s3.versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. ++ [Bucket](s3-base-url;/.bucket.html) is a construct\. This means it's initialization signature has `scope`, `id`, and `props`\. In this case, the bucket is an immediate child of **MyStack**\. ++ `MyFirstBucket` is the **id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. To specify a physical name for your bucket, set the [bucketName](s3-base-url;/.bucket.html#bucketname) property when you define your bucket\. ++ Because the bucket's [versioned](s3-base-url;/.bucket.html#versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. Compile your program, as follows\. diff --git a/doc_source/reference.md b/doc_source/reference.md index 2a57db1c..d8f87232 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -8,4 +8,4 @@ This documentation is for the developer preview release \(public beta\) of the A See the [CDK Reference](https://awslabs.github.io/aws-cdk/) for information about the CDK libraries\. -Each library contains information about how to use the library\. For example, the [Amazon S3](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-s3.html) library demonstrates how to set default encryption on an Amazon S3 bucket\. \ No newline at end of file +Each library contains information about how to use the library\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) library demonstrates how to set default encryption on an Amazon S3 bucket\. \ No newline at end of file diff --git a/doc_source/resources.md b/doc_source/resources.md index 05875b5d..7c866beb 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -20,7 +20,7 @@ new sqs.CfnQueue(this, 'MyQueueResource', { }); ``` -For reference, if you use the [Queue](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-sqs.html#@aws-cdk/aws-sqs.Queue) construct, you can define managed queue encryption as follows\. +For reference, if you use the [Queue]("https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sqs"/queue.html) construct, you can define managed queue encryption as follows\. ``` import sqs = require('@aws-cdk/aws-sqs'); @@ -49,8 +49,8 @@ new lambda.CfnFunction(this, { }); ``` -The [cdk\.CfnResource\.ref](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.ref) attribute represents the AWS CloudFormation resource's intrinsic reference \(or *return value*\)\. For example, *dlq\.ref* also [refers](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-properties-sqs-queues-ref) to the queue's ARN\. When possible, use an explicitly named attribute instead of *ref*\. +The [cdk\.CfnResource\.ref](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource.ref) attribute represents the AWS CloudFormation resource's intrinsic reference \(or *return value*\)\. For example, *dlq\.ref* also [refers](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-properties-sqs-queues-ref) to the queue's ARN\. When possible, use an explicitly named attribute instead of *ref*\. ## Resource Options -For resources, the [cdk\.CfnResource\.options](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html#@aws-cdk/cdk.CfnResource.options) object includes AWS CloudFormation options, such as `condition`, `updatePolicy`, `createPolicy`, and `metadata`\. \ No newline at end of file +For resources, the [CfnResource\.options](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/cfnresource.html#cdk_CfnResource_options) object includes AWS CloudFormation options, such as `condition`, `updatePolicy`, `createPolicy`, and `metadata`\. \ No newline at end of file diff --git a/doc_source/what-is.md b/doc_source/what-is.md index 2bc52fef..f8fdff73 100644 --- a/doc_source/what-is.md +++ b/doc_source/what-is.md @@ -14,7 +14,7 @@ AWS CloudFormation enables you to: + Build highly reliable, highly scalable, cost\-effective applications in the cloud without worrying about creating and configuring the underlying AWS infrastructure\. + Use a template file to create and delete a collection of resources together as a single unit \(a stack\)\. -Use the CDK to define your cloud resources using one of the supported programming languages: C\#/\.NET, Java, JavaScript, Python, or TypeScript\. This document does not supply reference information for the CDK\. You can find that information in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. +Use the CDK to define your cloud resources using one of the supported programming languages: C\#/\.NET, Java, JavaScript, Python, or TypeScript\. This document does not supply reference information for the CDK\. You can find that information in the [CDK Reference](https://docs.aws.amazon.com/cdk/api/latest)\. Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](apps_and_stacks.md#stacks) and [Apps](apps_and_stacks.md#apps)\. @@ -90,7 +90,7 @@ Another advantage of IAC \(infrastructure as code\) is that you get code complet ## Developing With the CDK -Unless otherwise indicated, the code examples in this guide are in TypeScript\. To aid you in porting a TypeScript example to a supported programming language, take a look at the example code for your language in the [CDK Reference](https://awslabs.github.io/aws-cdk/reference.html)\. The CDK also includes some [TypeScript examples](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript)\. +Unless otherwise indicated, the code examples in this guide are in TypeScript\. To aid you in porting a TypeScript example to a supported programming language, see [Multi\-Language Support in the CDK](multiple_languages.md)\. The CDK also includes examples in the supported programming languages\. See [AWS CDK Examples](about_examples.md) for a list of the examples\. The [CDK Toolchain](tools.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. @@ -106,7 +106,7 @@ Because the AWS CDK is open source, the team encourages you contribute to make i ## Additional Documentation and Resources In addition to this guide, the following are other resources available to CDK users: -+ [CDK Reference](https://awslabs.github.io/aws-cdk/) ++ [Reference](https://docs.aws.amazon.com/cdk/api/latest) + [CDK Demo at re:Invent 2018](https://www.youtube.com/watch?v=Lh-kVC2r2AU) + [CDK Workshop](https://cdkworkshop.com/) + [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) From 8762529ea37e1645b82ac806c53eaa21b057b184 Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Mon, 20 May 2019 10:42:12 -0700 Subject: [PATCH 018/655] Updated docs to include identifiers section --- doc_source/apps_and_stacks.md | 19 +-- doc_source/aws_construct_lib.md | 6 +- doc_source/cfn_layer.md | 4 +- doc_source/cloudformation.md | 4 +- doc_source/doc-history.md | 2 +- doc_source/ecs_example.md | 2 +- doc_source/get_ssm_value.md | 4 +- doc_source/getting_started.md | 211 ++++++++++++++++--------------- doc_source/identifiers.md | 70 ++++++++++ doc_source/index.md | 1 + doc_source/multiple_languages.md | 18 ++- doc_source/resources.md | 4 +- 12 files changed, 213 insertions(+), 132 deletions(-) create mode 100644 doc_source/identifiers.md diff --git a/doc_source/apps_and_stacks.md b/doc_source/apps_and_stacks.md index 9eaa9973..bee7e0d6 100644 --- a/doc_source/apps_and_stacks.md +++ b/doc_source/apps_and_stacks.md @@ -81,24 +81,9 @@ cdk deploy MyWestCdkStack ## Environments and Authentication -When you create a [stack]() instance, you can supply the target deployment environment for the stack using the `env` property\. This is shown in the following example, where *REGION* is the AWS Region in which you want to create the stack and *ACCOUNT* is your account ID\. +When you create a [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/stack.html) instance, you can supply the target deployment environment for the stack using the `env` property, as described in [Specifying Your Credentials and Region](getting_started.md#getting_started_credentials)\. -``` -new MyStack(app, { env: { region: 'REGION', account: 'ACCOUNT' } }); -``` - -For each of the two arguments, `region` and `account`, the CDK uses the following lookup procedure: -+ If `region` or `account`is provided directly as a property to the stack, use that\. -+ If either property is not specified when you create a stack, the CDK determines them as follows: - + `account` – Use the account from the default SDK credentials\. Environment variables are tried first \(`AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`\), followed by credentials in `$HOME/.aws/credentials` on Linux or macOS, or `%USERPROFILE%\.aws\credentials` on Windows\. - + `region` – Use the default Region configured in `$HOME/.aws/config` on Linux or macOS, or `%USERPROFILE%\.aws\config` on Windows\. - - You can set these defaults manually, but we recommend you use `aws configure`, as described in [Specifying Your Credentials](getting_started.md#getting_started_credentials)\. - -We recommend that you use the default environment for development stacks, and explicitly specify accounts and Regions for production stacks\. - -**Note** -Although the Region and account might explicitly be set on your stack, if you run `cdk deploy`, the CDK still uses the currently configured SDK credentials that are provided through environment variables or `aws configure`\. This means that if you want to deploy stacks to multiple accounts, you have to set the correct credentials for each invocation to `cdk deploy STACK`\. +We recommend that you use the default environment for development stacks, and explicitly specify accounts and regions using the `env` property for production stacks\. You can always find the Region within which your stack is deployed by using the `region` property of the stack, as follows\. diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md index db1ddedd..b4d7b5d2 100644 --- a/doc_source/aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -6,7 +6,7 @@ This documentation is for the developer preview release \(public beta\) of the A # AWS Construct Library -The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [VpcNetwork](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2vpcnetwork.html) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your CDK app\. +The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [VpcNetwork](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpcnetwork.html) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your CDK app\. The AWS Construct Library modules are described in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. @@ -22,9 +22,9 @@ The AWS Construct Library includes many common patterns and capabilities that ar ### Grants -AWS Identity and Access Management \(IAM\) policies are automatically defined based on intent\. For example, when subscribing an Amazon Simple Notification Service \(Amazon SNS\) [Topic]("https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns"/topic.html) to an AWS Lambda [Function](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-lambda/function.html), the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. +AWS Identity and Access Management \(IAM\) policies are automatically defined based on intent\. For example, when subscribing an Amazon Simple Notification Service \(Amazon SNS\) [Topic](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns/topic.html) to an AWS Lambda [Function](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-lambda/function.html), the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. -Also, most AWS constructs expose `grant*` methods that allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](s3-base-url;/.bucket.html) construct has a [grantRead](s3-base-url;/.bucket.html#grantreadidentity-objectskeypattern) method\. This method accepts an IAM [IPrincipal](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/iprincipal.html) such as a [User](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/user.html) or a [Role](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/role.html), which modifies the policy to allow the principal to read objects from the bucket\. +Also, most AWS constructs expose `grant*` methods that allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct has a [grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grantreadidentity-objectskeypattern) method\. This method accepts an IAM [IPrincipal](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/iprincipal.html) such as a [User](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/user.html) or a [Role](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/role.html), which modifies the policy to allow the principal to read objects from the bucket\. ## Metrics diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 0c8bb3a5..4446913e 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -12,7 +12,7 @@ This topic describes how to modify the underlying AWS CloudFormation resources i We don't recommend this method because it breaks the abstraction layer and might produce unexpected results\. If you modify an AWS construct in this way, we can't ensure that your code will be compatible with subsequent releases\. -AWS constructs, such as [Topic]("https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns"/topic.html), encapsulate one or more AWS CloudFormation resources behind their APIs\. These resources are also represented as `CfnXxx` constructs in each library\. For example, the [Bucket](s3-base-url;/.bucket.html) construct encapsulates the [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/cfnbucket.html)\. When a stack that includes an AWS construct is synthesized, the AWS CloudFormation definitions of the underlying resources are included in the resulting template\. +AWS constructs, such as [Topic](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns/topic.html), encapsulate one or more AWS CloudFormation resources behind their APIs\. These resources are also represented as `CfnXxx` constructs in each library\. For example, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct encapsulates the [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/cfnbucket.html)\. When a stack that includes an AWS construct is synthesized, the AWS CloudFormation definitions of the underlying resources are included in the resulting template\. Eventually, we expect the APIs provided by AWS constructs to support all of the services and capabilities offered by AWS\. But we're aware that the library still has many gaps, both at the service level \(some services don't have any constructs yet\) and at the resource level \(an AWS construct exists, but some features are missing\)\. @@ -31,7 +31,7 @@ You can also find more information about how to work directly with the AWS Cloud Use [construct\.findChild\(\)](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.Construct.findChild) to access any child of a construct by its construct ID\. By convention, the main resource of any AWS construct is named **Resource**\. -The following example shows how to access the underlying Amazon Simple Storage Service \(Amazon S3\) bucket resource, given a [Bucket](s3-base-url;/.bucket.html) construct\. +The following example shows how to access the underlying Amazon Simple Storage Service \(Amazon S3\) bucket resource, given a [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct\. ``` // Create an AWS bucket construct diff --git a/doc_source/cloudformation.md b/doc_source/cloudformation.md index 057c54d4..bb708737 100644 --- a/doc_source/cloudformation.md +++ b/doc_source/cloudformation.md @@ -6,9 +6,9 @@ This documentation is for the developer preview release \(public beta\) of the A # AWS CloudFormation -The [AWS Construct Library](aws_construct_lib.md) includes constructs with APIs for defining AWS infrastructure\. For example, you can use the [Bucket](s3-base-url;/.bucket.html) construct to define Amazon Simple Storage Service \(Amazon S3\) buckets, and the [Topic]("https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns"/topic.html) construct to define Amazon Simple Notification Service \(Amazon SNS\) topics\. +The [AWS Construct Library](aws_construct_lib.md) includes constructs with APIs for defining AWS infrastructure\. For example, you can use the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct to define Amazon Simple Storage Service \(Amazon S3\) buckets, and the [Topic](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns/topic.html) construct to define Amazon Simple Notification Service \(Amazon SNS\) topics\. -Under the hood, these constructs are implemented using AWS CloudFormation resources, which are available in the `CfnXxx` classes in each library\. For example, the [Bucket](s3-base-url;/.bucket.html) construct uses the [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/cfnbucket.html) resource \(as well as other resources, depending on what bucket APIs are used\)\. +Under the hood, these constructs are implemented using AWS CloudFormation resources, which are available in the `CfnXxx` classes in each library\. For example, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct uses the [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/cfnbucket.html) resource \(as well as other resources, depending on what bucket APIs are used\)\. **Important** Avoid interacting directly with AWS CloudFormation unless absolutely necessary, such as when a CDK AWS Construct Library does not provide the needed functionality\. \ No newline at end of file diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 38370c8f..82150512 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -8,6 +8,6 @@ This documentation is for the developer preview release \(public beta\) of the A This document is based on the following release of the AWS Cloud Development Kit \(CDK\)\. + **API version: 0\.31\.0** -+ **Latest documentation update:** May 14, 2019 ++ **Latest documentation update:** May 16, 2019 See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the CDK releases\. \ No newline at end of file diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index cf31e933..c4ee95db 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -31,7 +31,7 @@ The Amazon ECS construct used in this tutorial helps you use AWS services by pro Previously, you had to create a Lambda function to have this functionality\. + Provides asset support, so that you can deploy a source from your machine to Amazon ECS in one step\. Previously, to use an application source you had to perform several manual steps, such as uploading to Amazon ECR and creating a Docker image\. -See the [Amazon ECS Construct Library](https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ecs.html#aws-elastic-container-service-ecs-construct-library) reference for details\. +See [ECS](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html) for details\. ## Creating the Directory and Initializing the CDK diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 10b12519..b13bc78b 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -8,7 +8,7 @@ This documentation is for the developer preview release \(public beta\) of the A You can get the value of an AWS Systems Manager Parameter Store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It isn't possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from AWS Secrets Manager \(see [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. -To read a particular version of a Systems Manager Parameter Store plain string value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreString](#parameterstorestring)\. If you don't supply a `version` value, you get the latest version\. +To read a particular version of a Systems Manager Parameter Store plain string value at AWS CloudFormation deployment time, use [ParameterStoreString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.ParameterStoreString.html)\. If you don't supply a `version` value, you get the latest version\. ``` import ssm = require('@aws-cdk/aws-ssm'); @@ -21,7 +21,7 @@ const parameterString = new ssm.ParameterStoreString(this, 'MyParameter', { const myvalue = parameterString.stringValue; ``` -To read a particular version of a Systems Manager Parameter Store `SecureString` value at AWS CloudFormation deployment time, use [ssm\.ParameterStoreSecureString](#parameterstoresecurestring)\. You must supply a `version` value\. +To read a particular version of a Systems Manager Parameter Store `SecureString` value at AWS CloudFormation deployment time, use [ParameterStoreSecureString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.ParameterStoreSecureString.html)\. You must supply a `version` value\. ``` import ssm = require('@aws-cdk/aws-ssm'); diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 16cbaeaa..916b49aa 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -12,7 +12,7 @@ This topic describes how to install and configure the AWS CDK and create your fi **CDK command line tools** + [Node\.js \(>= 8\.11\.x\)](https://nodejs.org/en/download) -+ You must specify both your credentials and an AWS Region to use the CDK Toolkit;, as described in [Specifying Your Credentials](#getting_started_credentials)\. ++ You must specify both your credentials and an AWS Region to use the CDK Toolkit;, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. ------ #### [ TypeScript ] @@ -57,120 +57,119 @@ Run the following command to see the version number of the CDK\. cdk --version ``` -## Installing the Core CDK Library for Your Language +## Updating Your Language Dependencies -You must install the CDK core library to get the basic classes needed to create CDK stacks and apps\. +If you get an error message that your language framework is out of date, use one of the following commands to update the components that the CDK needs to support the lanuage\. ------ #### [ TypeScript ] ``` -npm install @aws-cdk/cdk +npx npm-check-updates -u ``` ------ #### [ JavaScript ] ``` -npm install @aws-cdk/cdk +npx npm-check-updates -u ``` ------ #### [ Java ] -Add the following to your project’s pom\.xml file: - ``` - - - software.amazon.awscdk - cdk - - - +mvn versions:use-latest-versions ``` ------ #### [ C\# ] ``` -dotnet add package Amazon.CDK +nuget update ``` ------ #### [ Python ] ``` -pip install aws-cdk.cdk +pip install --upgrade aws-cdk.cdk ``` -**Note** -If you have both Python 2\.7 and 3\.7 installed, you might have to pip3 instead of pip\. +You might have to call this multiple times to update all dependencies\. ------ -## Updating Your Language Dependencies +## Using the env Property to Specify Account and Region -If you get an error message that your language framework is out of date, use one of the following commands to update the components that the CDK needs to support the lanuage\. - ------- -#### [ TypeScript ] +You can use the `env` property on a stack to specify the account and region used when deploying a stack, as shown in the following example, where *REGION* is the region and *ACCOUNT* is the account ID\. ``` -npx npm-check-updates -u +new MyStack(app, { env: { region: 'REGION', account: 'ACCOUNT' } }); ``` ------- -#### [ JavaScript ] +**Note** +The CDK team recommends that you explicitly set your account and region using the `env` property on a stack when you deploy stacks to production\. + +Since you can create any number of stacks in any of your accounts in any region that supports all of the stack's resources, the CDK team recommends that you create your production stacks in one CDK app, and deploy them as necessary\. For example, if you own three accounts, with account IDs *ONE*, *TWO*, and *THREE* and want to be able to deploy each one in **us\-west\-2** and **us\-east\-1**, you might declare them as: ``` -npx npm-check-updates -u +new MyStack(app, 'Stack-One-W', { env: { account: 'ONE', region: 'us-west-2' }}); +new MyStack(app, 'Stack-One-E', { env: { account: 'ONE', region: 'us-east-1' }}); +new MyStack(app, 'Stack-Two-W', { env: { account: 'TWO', region: 'us-west-2' }}); +new MyStack(app, 'Stack-Two-E', { env: { account: 'TWO', region: 'us-east-1' }}); +new MyStack(app, 'Stack-Three-W', { env: { account: 'THREE', region: 'us-west-2' }}); +new MyStack(app, 'Stack-Three-E', { env: { account: 'THREE', region: 'us-east-1' }}); ``` ------- -#### [ Java ] +And deploy the stack for account *TWO* in **us\-east\-1** with: ``` -mvn versions:use-latest-versions +cdk deploy Stack-Two-E ``` ------- -#### [ C\# ] +**Note** +If the existing credentials do not have permission to create resources within the account you specify, the CDK returns an AWS CloudFormation error when you attempt to deploy the stack\. -``` -nuget update -``` +## Specifying Your Credentials and Region ------- -#### [ Python ] +You must specify your credentials and an AWS Region to use the CDK Toolkit\. The CDK looks for credentials and region in the following order: ++ Using the \-\-profile option to cdk commands\. ++ Using environment variables\. ++ Using the default profile as set by the AWS Command Line Interface \(AWS CLI\)\. -``` -pip install --upgrade aws-cdk.cdk -``` +### Using the \-\-profile Option to Specify Credentials and Region -You might have to call this multiple times to update all dependencies\. +Use the \-\-profile *PROFILE* option to a cdk command to use a specific profile when executing the command\. ------- +For example, if the `~/.aws/config` \(Linux or Mac\) or `%USERPROFILE%\.aws\config` \(Windows\) file contains the following profile: + +``` +[profile test] +aws_access_key_id=AKIAI44QH8DHBEXAMPLE +aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY +region=us-west-2 +``` -## Specifying Your Credentials +You can deploy your app using the **test** profile with the following command\. -You must specify your default credentials and AWS Region to use the CDK Toolkit\. You can do that in the following ways: -+ Using the AWS Command Line Interface \(AWS CLI\)\. This is the method we recommend\. -+ Using environment variables\. -+ Using the \-\-profile option to cdk commands\. +``` +cdk deploy --profile test +``` -### Using the AWS CLI to Specify Credentials +**Note** +The profile must contain the access key, secret access key, and region\. -Use the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide) aws configure command to specify your default credentials and Region\. +See [Named Profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) in the AWS CLI documentation for details\. -### Using Environment Variables to Specify Credentials +### Using Environment Variables to Specify Credentials and a Region -You can also set environment variables for your default credentials and Region\. Environment variables take precedence over settings in the credentials or config file\. +Use environment variables to specify your credentials and region\. + `AWS_ACCESS_KEY_ID` – Specifies your access key\. + `AWS_SECRET_ACCESS_KEY` – Specifies your secret access key\. + `AWS_DEFAULT_REGION` – Specifies your default Region\. -For example, to set the default Region to `us-east-2` on Linux or macOS: +For example, to set the region to `us-east-2` on Linux or macOS: ``` export AWS_DEFAULT_REGION=us-east-2 @@ -184,29 +183,9 @@ set AWS_DEFAULT_REGION=us-east-2 See [Environment Variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-environment.html) in the *AWS Command Line Interface User Guide* for details\. -### Using the \-\-profile Option to Specify Credentials - -Use the \-\-profile *PROFILE* option to a cdk command to the alternative profile *PROFILE* when executing the command\. - -For example, if the `~/.aws/credentials` \(Linux or Mac\) or `%USERPROFILE%\.aws\credentials` \(Windows\) file contains the following profiles: - -``` -[default] -aws_access_key_id=AKIAIOSFODNN7EXAMPLE -aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY - -[test] -aws_access_key_id=AKIAI44QH8DHBEXAMPLE -aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY -``` - -You can deploy your app using the **test** profile with the following command\. - -``` -cdk deploy --profile test -``` +### Using the AWS CLI to Specify Credentials and a Region -See [Named Profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) in the AWS CLI documentation for details\. +Use the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide) aws configure command to specify your default credentials and a region\. ## Hello World Tutorial @@ -272,6 +251,14 @@ cdk init --language javascript cdk init --language java ``` +Once the init command finishes, we need to modify the template's output\. ++ Open `src/main/java/com/myorg/HelloApp.java`\. ++ Change the two stacks to one: + + ``` + new HelloStack(app, "HelloCdkStack"); + ``` + ------ #### [ C\# ] @@ -279,6 +266,21 @@ cdk init --language java cdk init --language csharp ``` +Once the init command finishes, we need to modify the template's output\. ++ Open `src/HelloCdk/Program.cs`\. ++ Change the two stacks to one: + + ``` + new HelloStack(app, "HelloCdkStack", new StackProps()); + ``` ++ Open `src/HelloCdk/HelloStack.cs`\. ++ Delete all of the using statements except the first\. + + ``` + using Amazon.CDK; + ``` ++ Delete everything from the constructor\. + ------ #### [ Python ] @@ -341,10 +343,8 @@ mvn compile ------ #### [ C\# ] -Because we configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command\. - ``` -cdk +dotnet build src ``` ------ @@ -354,6 +354,13 @@ Nothing to compile\. ------ +**Note** +If you are using Java and get annoyed by the **\[INFO\]** log messages, you can suppress them by including the **\-q** option to your **mvn** commands\. This includes changing `cdk.json to:` + +``` +"app": "mvn -q exec:java" +``` + ### Listing the Stacks in the App List the stacks in the app\. @@ -391,7 +398,7 @@ npm install @aws-cdk/aws-s3 ------ #### [ Java ] -Add the following to `pom.xml`, where *CDK\-VERSION* is the version of the CDK\. +If necessary, add the following to `pom.xml`, where *CDK\-VERSION* is the version of the CDK\. ``` @@ -404,6 +411,8 @@ Add the following to `pom.xml`, where *CDK\-VERSION* is the version of the CDK\. ------ #### [ C\# ] +Run the following command in the src/HelloCdk directory\. + ``` dotnet add package Amazon.CDK.AWS.S3 ``` @@ -419,7 +428,7 @@ You might have to execute this command multiple times to resolve dependencies\. ------ -Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represented by the [Bucket](s3-base-url;/.bucket.html) class\. +Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represented by the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) class\. ------ #### [ TypeScript ] @@ -464,24 +473,24 @@ class MyStack extends cdk.Stack { ------ #### [ Java ] -In `src/main/java/com/acme/MyStack.java`: +In `src/main/java/com/myorg/HelloStack.java`: ``` -package com.acme; +package com.myorg; -import software.amazon.awscdk.App; +import software.amazon.awscdk.Construct; import software.amazon.awscdk.Stack; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.services.s3.Bucket; import software.amazon.awscdk.services.s3.BucketProps; -public class MyStack extends Stack { - public MyStack(final App scope, final String id) { - this(scope, id, null); +public class HelloStack extends Stack { + public HelloStack(final Construct parent, final String id) { + this(parent, id, null); } - public MyStack(final App scope, final String id, final StackProps props) { - super(scope, id, props); + public HelloStack(final Construct parent, final String id, final StackProps props) { + super(parent, id, props); new Bucket(this, "MyFirstBucket", BucketProps.builder() .withVersioned(true) @@ -493,7 +502,7 @@ public class MyStack extends Stack { ------ #### [ C\# ] -Create `MyStack.cs`\. +Update `HelloStack.cs` to include a Amazon S3 bucket with versioning enabled\. ``` using Amazon.CDK; @@ -501,9 +510,9 @@ using Amazon.CDK.AWS.S3; namespace HelloCdk { - public class MyStack : Stack + public class HelloStack : Stack { - public MyStack(App scope, string id) : base(scope, id, null) + public HelloStack(Construct parent, string id, IStackProps props) : base(parent, id, props) { new Bucket(this, "MyFirstBucket", new BucketProps { @@ -537,9 +546,9 @@ bucket = s3.Bucket(self, ------ Notice a few things: -+ [Bucket](s3-base-url;/.bucket.html) is a construct\. This means it's initialization signature has `scope`, `id`, and `props`\. In this case, the bucket is an immediate child of **MyStack**\. -+ `MyFirstBucket` is the **id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. To specify a physical name for your bucket, set the [bucketName](s3-base-url;/.bucket.html#bucketname) property when you define your bucket\. -+ Because the bucket's [versioned](s3-base-url;/.bucket.html#versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. ++ [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) is a construct\. This means it's initialization signature has `scope`, `id`, and `props` and it is a child of the stack\. ++ `MyFirstBucket` is the **id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. To specify a physical name for your bucket, set the [bucketName](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#bucketname) property when you define your bucket\. ++ Because the bucket's [versioned](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. Compile your program, as follows\. @@ -565,10 +574,8 @@ mvn compile ------ #### [ C\# ] -Because we configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command\. - ``` -cdk +dotnet build src ``` ------ @@ -652,7 +659,11 @@ new s3.Bucket(this, 'MyFirstBucket', { ------ #### [ Java ] -Update `src/main/java/com/acme/MyStack.java`\. +Update `src/main/java/com/myorg/HelloStack.java`\. + +``` +import software.amazon.awscdk.services.s3.BucketEncryption; +``` ``` new Bucket(this, "MyFirstBucket", BucketProps.builder() @@ -664,7 +675,7 @@ new Bucket(this, "MyFirstBucket", BucketProps.builder() ------ #### [ C\# ] -Update `MyStack.cs`\. +Update `HelloStack.cs`\. ``` new Bucket(this, "MyFirstBucket", new BucketProps @@ -710,10 +721,8 @@ mvn compile ------ #### [ C\# ] -Because we configured `cdk.json` to run dotnet run, which restores dependencies, builds, and runs your application, run the following command\. - ``` -cdk +dotnet build src ``` ------ diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md new file mode 100644 index 00000000..69133ed1 --- /dev/null +++ b/doc_source/identifiers.md @@ -0,0 +1,70 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Identifiers + +The CDK deals with many types of identifiers and names\. To use the AWS CDK effectively and avoid errors, you need to understand the types of identifiers\. + +Identifiers must be unique within the scope in which they are created; they do not need to be globally unique in your CDK application\. + +If you attempt to create an identifier with the same value within the same scope, the CDK throws an exception\. + +## Construct IDs + +The most common identifier, `id`, is the identifier passed as the second argument when instantiating a construct object\. This identifier, like all identifiers, need only be unique within the scope in which it is created, which is the first argument when instantiating a construct object\. + +Lets look at an example where we have two constructs with the identifier `MyBucket` in our app\. However, since they are defined in different scopes, the first in the scope of the stack with the identifier `Stack1`, and the second in the scope of a stack with the identifier `Stack2`, that doesn't cause any sort of conflict, and they can co\-exist in the same app without any issues\. + +``` +import { App, Construct, Stack, StackProps } from '@aws-cdk/cdk'; +import s3 = require('@aws-cdk/aws-s3'); + +class MyStack extends Stack { + constructor(scope: Construct, id: string, props: StackProps = {}) { + super(scope, id, props); + + new s3.Bucket(this, 'MyBucket'); + } +} + +const app = new App(); +new MyStack(app, 'Stack1'); +new MyStack(app, 'Stack2'); +``` + +## Paths + +As the constructs in an CDK application form a hierarchy, we refer to the collection of ids from a given construct, then of its parent construct, then grandparent construct, and so on up to the root of the construct tree, which is an instance of the `App` class as a *path*\. + +The CDK typically displays paths in your templates as a string, with the ids from the levels separated by slashes, starting at the node just below the root `App` instance, which is usually a stack\. For example, the paths of the two Amazon S3 bucket resources in the previous code example are `Stack1/MyBucket` and `Stack2/MyBucket`\. + +You can access the path of any construct programatically, as shown in the following example, which gets the path of `myConstruct`\. Since ids must be unique within the scope they are created, their paths are always unique within a CDK application\. + +``` +const path: string = myConstruct.node.path; +``` + +## Unique IDs + +Since AWS CloudFormation requires that all logical IDs in a template are unique, the CDK must be able to generate unique identifier for each construct in an application\. Since the CDK already has paths that are globally unique, the CDK generates these unique identifiers by concatenating the elements of the path, and adds an 8\-digit hash\. The hash is necessary, as otherwise two distinct paths, such as `A/B/C` and `A/BC` would result in the same identifier\. The CDK calls this concatenated path elements and hash the *unique ID* of the construct\. + +You can access the unique ID of any construct programatically, as shown in the following example, which gets the unique ID of `myConstruct`\. Since ids must be unique within the scope they are created, their paths are always unique within a CDK application\. + +``` +const uid: string = myConstruct.node.uniqueId; +``` + +## Logical IDs + +Unique IDs serve as the *logical identifiers*, which are sometimes called *logical names*, of resources in the generated AWS CloudFormation templates for those constructs that represent AWS resources\. + +For example, the Amazon S3 bucket in the previous example that is created within `Stack2` results in an `AWS::S3::Bucket` resource with the logical ID `Stack2MyBucket4DD88B4F` in the resulting AWS CloudFormation template\. + +Think of construct IDs as part of your construct's public contract\. If you change the ID of a construct in your construct tree, AWS CloudFormation will replace the deployed resource instances of that construct, potentially causing service interruption or data loss\. + +### Logical ID Stability + +Avoid changing the logical ID of a resource between deployments\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID\. \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index 2342a092..7151f601 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -20,6 +20,7 @@ Amazon's trademarks and trade dress may not be used in + [Constructs](constructs.md) + [Apps, Stacks, and Environments and Authentication](apps_and_stacks.md) + [Resources](resources.md) + + [Identifiers](identifiers.md) + [Run-Time Context](context.md) + [Assets](assets.md) + [AWS CloudFormation](cloudformation.md) diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 66d482f7..1458bbfc 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -15,7 +15,7 @@ The CDK supports C\#, Java, JavaScript, and TypeScript\. Since the CDK is develo In TypeScript, you import a package as follows \(we'll use Amazon S3 for our examples\): ``` -import lambda = require("@aws-cdk/aws-s3"); +import s3 = require("@aws-cdk/aws-s3"); ``` ------ @@ -39,6 +39,13 @@ import software.amazon.awscdk.services.s3.*; const s3 = require('@aws-cdk/aws-s3'); ``` +------ +#### [ Python ] + +``` +from aws_cdk import aws_s3 as s3 +``` + ------ ## Creating a New Object @@ -79,4 +86,13 @@ new s3.Bucket(this, 'MyFirstBucket', { }); ``` +------ +#### [ Python ] + +``` +s3.Bucket(self, + "MyFirstBucket", + # options,) +``` + ------ \ No newline at end of file diff --git a/doc_source/resources.md b/doc_source/resources.md index 7c866beb..3ac510e8 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -20,7 +20,7 @@ new sqs.CfnQueue(this, 'MyQueueResource', { }); ``` -For reference, if you use the [Queue]("https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sqs"/queue.html) construct, you can define managed queue encryption as follows\. +For reference, if you use the [Queue](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sqs/queue.html) construct, you can define managed queue encryption as follows\. ``` import sqs = require('@aws-cdk/aws-sqs'); @@ -49,7 +49,7 @@ new lambda.CfnFunction(this, { }); ``` -The [cdk\.CfnResource\.ref](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource.ref) attribute represents the AWS CloudFormation resource's intrinsic reference \(or *return value*\)\. For example, *dlq\.ref* also [refers](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-properties-sqs-queues-ref) to the queue's ARN\. When possible, use an explicitly named attribute instead of *ref*\. +The [cdk\.CfnReference](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/cfnreference.html) attribute represents the AWS CloudFormation resource's intrinsic reference \(or *return value*\)\. For example, *dlq\.ref* also [refers](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-properties-sqs-queues-ref) to the queue's ARN\. When possible, use an explicitly named attribute instead of *ref*\. ## Resource Options From 7c8017a9f934db9bb62dfb7fc6b0f315190d1427 Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Thu, 6 Jun 2019 12:54:50 -0700 Subject: [PATCH 019/655] Updated CDK to 0.33.0; fixed Python version; renamed landing page home.html --- doc_source/about_examples.md | 9 +++++--- doc_source/aws_construct_lib.md | 2 +- doc_source/context.md | 2 +- doc_source/doc-history.md | 11 +++++++--- doc_source/getting_started.md | 7 +++--- doc_source/{what-is.md => home.md} | 2 +- doc_source/index.md | 3 ++- doc_source/serverless_example.md | 14 ++++++------ doc_source/tools.md | 11 +++++----- doc_source/troubleshooting.md | 35 ++++++++++++++++++++++++++++++ doc_source/writing_constructs.md | 1 - 11 files changed, 71 insertions(+), 26 deletions(-) rename doc_source/{what-is.md => home.md} (99%) create mode 100644 doc_source/troubleshooting.md diff --git a/doc_source/about_examples.md b/doc_source/about_examples.md index 6c3a26ef..ba2663fb 100644 --- a/doc_source/about_examples.md +++ b/doc_source/about_examples.md @@ -13,7 +13,9 @@ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitH | Example | Description | | --- |--- | +| [api\-cors\-lambda\-crud\-dynamodb](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/api-cors-lambda-crud-dynamodb/) | Creating a single API with CORS, and five Lambdas doing CRUD operations over a single DynamoDB | | [application\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/application-load-balancer/) | Using an AutoScalingGroup with an Application Load Balancer | +| [appsync\-graphql\-dynamodb](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/appsync-graphql-dynamodb/) | Creating a single GraphQL API with an API Key, and four Resolvers doing CRUD operations over a single DynamoDB | | [classic\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/classic-load-balancer/) | Using an AutoScalingGroup with a Classic Load Balancer | | [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) | Shows adding a Custom Resource to your CDK app | | [elasticbeanstalk](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/elasticbeanstalk/) | Elastic Beanstalk example using L1 with a Blue/Green pipeline \(community contributed\) | @@ -29,8 +31,8 @@ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitH | [resource\-overrides](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/resource-overrides/) | Shows how to override generated CloudFormation code | | [static\-site](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/static-site/) | A static site using CloudFront | | [stepfunctions\-job\-poller](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/stepfunctions-job-poller/) | A simple StepFunctions workflow | -| [ecs\-service\-with\-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs-service-with-logging/) | Starting a container fronted by a load balancer on Fargate | -| [fargate\-service\-with\-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/fargate-service-with-logging/) | Starting a container fronted by a load balancer on Fargate | +| [ecs\-service\-with\-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-logging/) | Starting a container fronted by a load balancer on Fargate | +| [fargate\-service\-with\-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/fargate-service-with-logging/) | Starting a container fronted by a load balancer on Fargate | ## Java examples @@ -38,6 +40,7 @@ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitH | Example | Description | | --- |--- | | [hello\-world](https://github.com/aws-samples/aws-cdk-examples/tree/master/java/hello-world/) | A demo application that uses the CDK in Java | +| [lambda\-cron](https://github.com/aws-samples/aws-cdk-examples/tree/master/java/lambda-cron/) | Running a Lambda on a schedule | ## Python examples @@ -53,7 +56,7 @@ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitH | [ecs\-service\-with\-advanced\-alb\-config](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/ecs-service-with-advanced-alb-config/) | Starting a container fronted by a load balancer on ECS with added load balancer configuration | | [ecs\-service\-with\-task\-networking](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/ecs-service-with-task-networking/) | Starting an ECS service with task networking, allowing ingress traffic to the task but blocking for the instance | | [fargate\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/fargate-load-balanced-service/) | Starting a container fronted by a load balancer on Fargate | -| [fargate\-service\-with\-auto\-scaling](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/fargate-service-with-auto-scaling/) | Starting an ECS service of FARGATE launch type that auto scales based on average CPU Utilization | +| [fargate\-service\-with\-autoscaling](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/fargate-service-with-autoscaling/) | Starting an ECS service of FARGATE launch type that auto scales based on average CPU Utilization | | [lambda\-cron](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/lambda-cron/) | Running a Lambda on a schedule | | [stepfunctions](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/stepfunctions/) | A simple StepFunctions workflow | diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md index b4d7b5d2..9a621081 100644 --- a/doc_source/aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -6,7 +6,7 @@ This documentation is for the developer preview release \(public beta\) of the A # AWS Construct Library -The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [VpcNetwork](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpcnetwork.html) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your CDK app\. +The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [Vpc](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your CDK app\. The AWS Construct Library modules are described in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. diff --git a/doc_source/context.md b/doc_source/context.md index 04b57864..5e489d7c 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -100,5 +100,5 @@ const provider = new VpcNetworkProvider(this, { } }); -const vpc = VpcNetwork.import(this, 'VPC', provider.vpcProps); +const vpc = Vpc.import(this, 'VPC', provider.vpcProps); ``` \ No newline at end of file diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 82150512..e9a0f243 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -7,7 +7,12 @@ This documentation is for the developer preview release \(public beta\) of the A # Document History for the AWS CDK Developer Guide This document is based on the following release of the AWS Cloud Development Kit \(CDK\)\. -+ **API version: 0\.31\.0** -+ **Latest documentation update:** May 16, 2019 ++ **API version: 0\.33\.0** ++ **Latest documentation update:** June 6, 2019 -See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the CDK releases\. \ No newline at end of file +See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the CDK releases\. + +| Change | Description | Date | +| --- |--- |--- | +| [Kindle](#doc-history) | The developer guide is now available as a free Kindle download\. | May 22, 2019 | +| [Identifiers](#doc-history) | The Concepts section now has information about Identifiers\. | May 20, 2019 | \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 916b49aa..b50fed93 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -39,7 +39,7 @@ none ------ #### [ Python ] -+ Python >= 3\.7\.1 ++ Python >= 3\.6 ------ @@ -59,7 +59,7 @@ cdk --version ## Updating Your Language Dependencies -If you get an error message that your language framework is out of date, use one of the following commands to update the components that the CDK needs to support the lanuage\. +If you get an error message that your language framework is out of date, use one of the following commands to update the components that the CDK needs to support the language\. ------ #### [ TypeScript ] @@ -743,8 +743,9 @@ cdk diff The toolkit queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares the result with the template synthesized from the app\. The Resources section of the output should look like the following\. ``` +Stack HelloCdkStack Resources -[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketID +[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 |- [+] BucketEncryption |- {"ServerSideEncryptionConfiguration":[{"ServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms"}}]} ``` diff --git a/doc_source/what-is.md b/doc_source/home.md similarity index 99% rename from doc_source/what-is.md rename to doc_source/home.md index f8fdff73..980e7d21 100644 --- a/doc_source/what-is.md +++ b/doc_source/home.md @@ -4,7 +4,7 @@ This documentation is for the developer preview release \(public beta\) of the A -------- -# What Is the AWS CDK? +# What is the AWS Cloud Development Kit? Welcome to the *AWS CDK \(CDK\) Developer Guide*\. This document provides information about the CDK, which is a software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. diff --git a/doc_source/index.md b/doc_source/index.md index 7151f601..3d0c739d 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -14,7 +14,7 @@ Amazon's trademarks and trade dress may not be used in ----- ## Contents -+ [What Is the AWS CDK?](what-is.md) ++ [What is the AWS Cloud Development Kit?](home.md) + [Getting Started With the AWS CDK](getting_started.md) + [Concepts](core_concepts.md) + [Constructs](constructs.md) @@ -45,5 +45,6 @@ Amazon's trademarks and trade dress may not be used in + [Set a CloudWatch Alarm](how_to_set_cw_alarm.md) + [Get a Value from a Context Variable](get_context_var.md) + [CDK Toolchain](tools.md) ++ [Troubleshooting the CDK](troubleshooting.md) + [OpenPGP Keys for the AWS CDK and JSII](pgp-keys.md) + [Document History for the AWS CDK Developer Guide](doc-history.md) \ No newline at end of file diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 9d142965..85adae74 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -224,7 +224,7 @@ cdk deploy If the deployment succeeds, save the URL for your server\. This URL appears in one of the last lines in the window, where *GUID* is an alphanumeric GUID and *REGION* is your AWS Region\. ``` -https://GUID.execute-REGION.amazonaws.com/prod/ +https://GUID.execute-api-REGION.amazonaws.com/prod/ ``` Test your app by getting the list of widgets \(currently empty\) by navigating to this URL in a browser, or use the following command\. @@ -388,12 +388,12 @@ cdk deploy We can now store, show, or delete an individual widget\. Use the following commands to list the widgets, create the widget **example**, list all of the widgets, show the contents of **example** \(it should show today's date\), delete **example**, and then show the list of widgets again\. ``` -curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' -curl -X POST 'https://GUID.execute-REGION.amazonaws.com/prod/example' -curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' -curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod/example' -curl -X DELETE 'https://GUID.execute-REGION.amazonaws.com/prod/example' -curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' +curl -X GET 'https://GUID.execute-api-REGION.amazonaws.com/prod' +curl -X POST 'https://GUID.execute-api-REGION.amazonaws.com/prod/example' +curl -X GET 'https://GUID.execute-api-REGION.amazonaws.com/prod' +curl -X GET 'https://GUID.execute-api-REGION.amazonaws.com/prod/example' +curl -X DELETE 'https://GUID.execute-api-REGION.amazonaws.com/prod/example' +curl -X GET 'https://GUID.execute-api-REGION.amazonaws.com/prod' ``` You can also use the API Gateway console to test these functions\. You have to set the **name** value to the name of a widget, such as **example**\. \ No newline at end of file diff --git a/doc_source/tools.md b/doc_source/tools.md index e308e880..48018438 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -56,8 +56,8 @@ Commands: cdk doctor Check your set-up for potential problems Options: - --app, -a REQUIRED: Command-line for executing your CDK app (e.g. - "node bin/my-app.js") [string] + --app, -a REQUIRED: command-line for executing your app or a cloud + assembly directory (e.g. "node bin/my-app.js") [string] --context, -c Add contextual string parameter (KEY=VALUE) [array] --plugin, -p Name or path of a node package that extend the CDK features. Can be specified multiple times [array] @@ -85,9 +85,10 @@ Options: [boolean] [default: true] --role-arn, -r ARN of Role to use when invoking CloudFormation [string] --toolkit-stack-name The name of the CDK toolkit stack [string] - --staging directory name for staging assets (use - --no-asset-staging to disable) - [string] [default: ".cdk.staging"] + --staging copy assets to the output directory (use --no-staging to + disable) [boolean] [default: true] + --output, -o emits the synthesized cloud assembly into a directory + (default: cdk.out) [string] --ci Force CI detection. Use --no-ci to disable CI autodetection. [boolean] [default: false] --version Show version number [boolean] diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md new file mode 100644 index 00000000..1fa6d5e3 --- /dev/null +++ b/doc_source/troubleshooting.md @@ -0,0 +1,35 @@ +-------- + +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. + +-------- + +# Troubleshooting the CDK + +This section describes how to troubleshoot problems with your CDK app\. + +## Inconsistent Module Versions + +If you have inconsistent module versions in your `package.json` file or `node_modules` directory, you might see error messages such as the following: + +``` +lib/my_ecs_construct-stack.ts:56:49 - error TS2345: Argument of type 'this' is not assignable to parameter of type 'Construct'. + Type 'MyEcsConstructStack' is not assignable to type 'Construct'. + Types of property 'node' are incompatible. + Property 'root' is missing in type 'ConstructNode' but required in type 'ConstructNode'. + +56 new ecs_patterns.LoadBalancedFargateService(this, "MyNewFargateService", { + ~~~~ + + node_modules/@aws-cdk/aws-ecs-patterns/node_modules/@aws-cdk/cdk/lib/construct.d.ts:187:14 + 187 readonly root: IConstruct; + ~~~~ + 'root' is declared here. +``` + +The solution is to delete the `node_modules` directory and re\-install your CDK modules: + +``` +rm -rf node_modules +npm install @aws-cdk/... +``` \ No newline at end of file diff --git a/doc_source/writing_constructs.md b/doc_source/writing_constructs.md index 72ef6320..4645fd0d 100644 --- a/doc_source/writing_constructs.md +++ b/doc_source/writing_constructs.md @@ -36,7 +36,6 @@ This topic provides some tips for writing idiomatic new constructs for the CDK\. + Indicate units of measurement in property names that don't use a strong type\. For example, use **milli**, **sec**, **min**, **hr**, **Bytes**, **KiB**, **MiB**, and **GiB**\. + Be sure to define an `IMyResource` interface for your resources that defines the API area that other constructs will use\. Typical capabilities on this interface are querying for a resource ARN and adding resource permissions\. + Accept objects instead of ARNs or names\. When accepting other resources as parameters, declare your property as `resource: IMyResource` instead of `resourceArn: string`\. This makes snapping objects together feel natural to consumers, and allows you to query or modify the incoming resource as well\. For example, the latter is particularly useful if something about IAM permissions needs to be set\. -+ Implement `export()` and `import()` functions for your resource\. These make it possible to interoperate with resources that are not defined in the same CDK app \(they might be manually created, created using raw AWS CloudFormation resources, or created in a completely unrelated CDK app\)\. + If your construct wraps a single \(or most prominent\) other construct, give it an ID of either **"Resource"** or **"Default"**\. The main resource that an AWS construct represents should use the ID **"Resource"** For higher\-level wrapping resources, you will generally use **"Default"** \(resources named **"Default"** will inherit their scope's logical ID, while resources named **"Resource"** will have a distinct logical ID, but the human\-readable part of it won't show the **"Resource"** part\)\. ## Implementation Language From 5b420c1386e8b6004f026971fdb9cd1845141394 Mon Sep 17 00:00:00 2001 From: Masayoshi Wada Date: Tue, 18 Jun 2019 17:07:28 +0900 Subject: [PATCH 020/655] fix typo: exludeResourceTypes => excludeResourceTypes --- doc_source/constructs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 5a5e7a16..d8d2e36b 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -145,7 +145,7 @@ theBestStack.node.apply(new cdk.Tag('StackType', 'TheBest')); theBestStack.node.apply(new cdk.RemoveTag('TheBest')); // To remove the tag from all EXCEPT the subnets: -theBestStack.node.apply(new cdk.RemoveTag('TheBest'), {exludeResourceTypes: ['AWS::EC2::Subnet']})); +theBestStack.node.apply(new cdk.RemoveTag('TheBest'), {excludeResourceTypes: ['AWS::EC2::Subnet']})); ``` The tag operations include some properties to fine\-tune how tags are applied to or removed from the resources that the construct creates\. From 222341a64e32d2ab39a77fe2760501481fde933f Mon Sep 17 00:00:00 2001 From: Doug Date: Tue, 18 Jun 2019 13:15:02 -0700 Subject: [PATCH 021/655] Add files via upload --- doc_source/my_ecs_construct-stack.yaml | 627 +++++++++++++++++++++++++ 1 file changed, 627 insertions(+) create mode 100644 doc_source/my_ecs_construct-stack.yaml diff --git a/doc_source/my_ecs_construct-stack.yaml b/doc_source/my_ecs_construct-stack.yaml new file mode 100644 index 00000000..2f4ab4d7 --- /dev/null +++ b/doc_source/my_ecs_construct-stack.yaml @@ -0,0 +1,627 @@ +Resources: + MyVpcF9F0CA6F: + Type: AWS::EC2::VPC + Properties: + CidrBlock: 10.0.0.0/16 + EnableDnsHostnames: true + EnableDnsSupport: true + InstanceTenancy: default + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/Resource + MyVpcPublicSubnet1SubnetF6608456: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: 10.0.0.0/19 + VpcId: + Ref: MyVpcF9F0CA6F + AvailabilityZone: us-west-2a + MapPublicIpOnLaunch: true + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet1 + - Key: aws-cdk:subnet-name + Value: Public + - Key: aws-cdk:subnet-type + Value: Public + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/Subnet + MyVpcPublicSubnet1RouteTableC46AB2F4: + Type: AWS::EC2::RouteTable + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet1 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/RouteTable + MyVpcPublicSubnet1RouteTableAssociation2ECEE1CB: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: + Ref: MyVpcPublicSubnet1RouteTableC46AB2F4 + SubnetId: + Ref: MyVpcPublicSubnet1SubnetF6608456 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/RouteTableAssociation + MyVpcPublicSubnet1DefaultRoute95FDF9EB: + Type: AWS::EC2::Route + Properties: + RouteTableId: + Ref: MyVpcPublicSubnet1RouteTableC46AB2F4 + DestinationCidrBlock: 0.0.0.0/0 + GatewayId: + Ref: MyVpcIGW5C4A4F63 + DependsOn: + - MyVpcVPCGW488ACE0D + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/DefaultRoute + MyVpcPublicSubnet1EIP096967CB: + Type: AWS::EC2::EIP + Properties: + Domain: vpc + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/EIP + MyVpcPublicSubnet1NATGatewayAD3400C1: + Type: AWS::EC2::NatGateway + Properties: + AllocationId: + Fn::GetAtt: + - MyVpcPublicSubnet1EIP096967CB + - AllocationId + SubnetId: + Ref: MyVpcPublicSubnet1SubnetF6608456 + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet1 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/NATGateway + MyVpcPublicSubnet2Subnet492B6BFB: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: 10.0.32.0/19 + VpcId: + Ref: MyVpcF9F0CA6F + AvailabilityZone: us-west-2b + MapPublicIpOnLaunch: true + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet2 + - Key: aws-cdk:subnet-name + Value: Public + - Key: aws-cdk:subnet-type + Value: Public + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/Subnet + MyVpcPublicSubnet2RouteTable1DF17386: + Type: AWS::EC2::RouteTable + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet2 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/RouteTable + MyVpcPublicSubnet2RouteTableAssociation227DE78D: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: + Ref: MyVpcPublicSubnet2RouteTable1DF17386 + SubnetId: + Ref: MyVpcPublicSubnet2Subnet492B6BFB + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/RouteTableAssociation + MyVpcPublicSubnet2DefaultRoute052936F6: + Type: AWS::EC2::Route + Properties: + RouteTableId: + Ref: MyVpcPublicSubnet2RouteTable1DF17386 + DestinationCidrBlock: 0.0.0.0/0 + GatewayId: + Ref: MyVpcIGW5C4A4F63 + DependsOn: + - MyVpcVPCGW488ACE0D + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/DefaultRoute + MyVpcPublicSubnet2EIP8CCBA239: + Type: AWS::EC2::EIP + Properties: + Domain: vpc + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/EIP + MyVpcPublicSubnet2NATGateway91BFBEC9: + Type: AWS::EC2::NatGateway + Properties: + AllocationId: + Fn::GetAtt: + - MyVpcPublicSubnet2EIP8CCBA239 + - AllocationId + SubnetId: + Ref: MyVpcPublicSubnet2Subnet492B6BFB + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet2 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/NATGateway + MyVpcPublicSubnet3Subnet57EEE236: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: 10.0.64.0/19 + VpcId: + Ref: MyVpcF9F0CA6F + AvailabilityZone: us-west-2c + MapPublicIpOnLaunch: true + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet3 + - Key: aws-cdk:subnet-name + Value: Public + - Key: aws-cdk:subnet-type + Value: Public + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/Subnet + MyVpcPublicSubnet3RouteTable15028F08: + Type: AWS::EC2::RouteTable + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet3 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/RouteTable + MyVpcPublicSubnet3RouteTableAssociation5C27DDA4: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: + Ref: MyVpcPublicSubnet3RouteTable15028F08 + SubnetId: + Ref: MyVpcPublicSubnet3Subnet57EEE236 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/RouteTableAssociation + MyVpcPublicSubnet3DefaultRoute3A83AB36: + Type: AWS::EC2::Route + Properties: + RouteTableId: + Ref: MyVpcPublicSubnet3RouteTable15028F08 + DestinationCidrBlock: 0.0.0.0/0 + GatewayId: + Ref: MyVpcIGW5C4A4F63 + DependsOn: + - MyVpcVPCGW488ACE0D + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/DefaultRoute + MyVpcPublicSubnet3EIPC5ACADAB: + Type: AWS::EC2::EIP + Properties: + Domain: vpc + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/EIP + MyVpcPublicSubnet3NATGatewayD4B50EBE: + Type: AWS::EC2::NatGateway + Properties: + AllocationId: + Fn::GetAtt: + - MyVpcPublicSubnet3EIPC5ACADAB + - AllocationId + SubnetId: + Ref: MyVpcPublicSubnet3Subnet57EEE236 + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet3 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/NATGateway + MyVpcPrivateSubnet1Subnet5057CF7E: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: 10.0.96.0/19 + VpcId: + Ref: MyVpcF9F0CA6F + AvailabilityZone: us-west-2a + MapPublicIpOnLaunch: false + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PrivateSubnet1 + - Key: aws-cdk:subnet-name + Value: Private + - Key: aws-cdk:subnet-type + Value: Private + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/Subnet + MyVpcPrivateSubnet1RouteTable8819E6E2: + Type: AWS::EC2::RouteTable + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PrivateSubnet1 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/RouteTable + MyVpcPrivateSubnet1RouteTableAssociation56D38C7E: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: + Ref: MyVpcPrivateSubnet1RouteTable8819E6E2 + SubnetId: + Ref: MyVpcPrivateSubnet1Subnet5057CF7E + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/RouteTableAssociation + MyVpcPrivateSubnet1DefaultRouteA8CDE2FA: + Type: AWS::EC2::Route + Properties: + RouteTableId: + Ref: MyVpcPrivateSubnet1RouteTable8819E6E2 + DestinationCidrBlock: 0.0.0.0/0 + NatGatewayId: + Ref: MyVpcPublicSubnet1NATGatewayAD3400C1 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/DefaultRoute + MyVpcPrivateSubnet2Subnet0040C983: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: 10.0.128.0/19 + VpcId: + Ref: MyVpcF9F0CA6F + AvailabilityZone: us-west-2b + MapPublicIpOnLaunch: false + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PrivateSubnet2 + - Key: aws-cdk:subnet-name + Value: Private + - Key: aws-cdk:subnet-type + Value: Private + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/Subnet + MyVpcPrivateSubnet2RouteTableCEDCEECE: + Type: AWS::EC2::RouteTable + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PrivateSubnet2 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/RouteTable + MyVpcPrivateSubnet2RouteTableAssociation86A610DA: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: + Ref: MyVpcPrivateSubnet2RouteTableCEDCEECE + SubnetId: + Ref: MyVpcPrivateSubnet2Subnet0040C983 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/RouteTableAssociation + MyVpcPrivateSubnet2DefaultRoute9CE96294: + Type: AWS::EC2::Route + Properties: + RouteTableId: + Ref: MyVpcPrivateSubnet2RouteTableCEDCEECE + DestinationCidrBlock: 0.0.0.0/0 + NatGatewayId: + Ref: MyVpcPublicSubnet2NATGateway91BFBEC9 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/DefaultRoute + MyVpcPrivateSubnet3Subnet772D6AD7: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: 10.0.160.0/19 + VpcId: + Ref: MyVpcF9F0CA6F + AvailabilityZone: us-west-2c + MapPublicIpOnLaunch: false + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PrivateSubnet3 + - Key: aws-cdk:subnet-name + Value: Private + - Key: aws-cdk:subnet-type + Value: Private + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet3/Subnet + MyVpcPrivateSubnet3RouteTableB790927C: + Type: AWS::EC2::RouteTable + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PrivateSubnet3 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet3/RouteTable + MyVpcPrivateSubnet3RouteTableAssociationD951741C: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: + Ref: MyVpcPrivateSubnet3RouteTableB790927C + SubnetId: + Ref: MyVpcPrivateSubnet3Subnet772D6AD7 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet3/RouteTableAssociation + MyVpcPrivateSubnet3DefaultRouteEC11C0C5: + Type: AWS::EC2::Route + Properties: + RouteTableId: + Ref: MyVpcPrivateSubnet3RouteTableB790927C + DestinationCidrBlock: 0.0.0.0/0 + NatGatewayId: + Ref: MyVpcPublicSubnet3NATGatewayD4B50EBE + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet3/DefaultRoute + MyVpcIGW5C4A4F63: + Type: AWS::EC2::InternetGateway + Properties: + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/IGW + MyVpcVPCGW488ACE0D: + Type: AWS::EC2::VPCGatewayAttachment + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + InternetGatewayId: + Ref: MyVpcIGW5C4A4F63 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/VPCGW + MyCluster4C1BA579: + Type: AWS::ECS::Cluster + Metadata: + aws:cdk:path: MyEcsConstruct/MyCluster/Resource + MyFargateServiceLBDE830E97: + Type: AWS::ElasticLoadBalancingV2::LoadBalancer + Properties: + LoadBalancerAttributes: [] + Scheme: internet-facing + SecurityGroups: + - Fn::GetAtt: + - MyFargateServiceLBSecurityGroup6FBF16F1 + - GroupId + Subnets: + - Ref: MyVpcPublicSubnet1SubnetF6608456 + - Ref: MyVpcPublicSubnet2Subnet492B6BFB + - Ref: MyVpcPublicSubnet3Subnet57EEE236 + Type: application + DependsOn: + - MyVpcPublicSubnet1DefaultRoute95FDF9EB + - MyVpcPublicSubnet2DefaultRoute052936F6 + - MyVpcPublicSubnet3DefaultRoute3A83AB36 + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/LB/Resource + MyFargateServiceLBSecurityGroup6FBF16F1: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: Automatically created Security Group for ELB + MyEcsConstructMyFargateServiceLB5E4E9AE3 + SecurityGroupEgress: [] + SecurityGroupIngress: + - CidrIp: 0.0.0.0/0 + Description: Allow from anyone on port 80 + FromPort: 80 + IpProtocol: tcp + ToPort: 80 + VpcId: + Ref: MyVpcF9F0CA6F + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/LB/SecurityGroup/Resource + MyFargateServiceLBSecurityGrouptoMyEcsConstructMyFargateServiceSecurityGroup67F71DB380B308A4F1: + Type: AWS::EC2::SecurityGroupEgress + Properties: + GroupId: + Fn::GetAtt: + - MyFargateServiceLBSecurityGroup6FBF16F1 + - GroupId + IpProtocol: tcp + Description: Load balancer to target + DestinationSecurityGroupId: + Fn::GetAtt: + - MyFargateServiceSecurityGroup7016792A + - GroupId + FromPort: 80 + ToPort: 80 + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/LB/SecurityGroup/to + MyEcsConstructMyFargateServiceSecurityGroup67F71DB3:80 + MyFargateServiceLBPublicListener61A1042F: + Type: AWS::ElasticLoadBalancingV2::Listener + Properties: + DefaultActions: + - TargetGroupArn: + Ref: MyFargateServiceLBPublicListenerECSGroup4A3EDF05 + Type: forward + LoadBalancerArn: + Ref: MyFargateServiceLBDE830E97 + Port: 80 + Protocol: HTTP + Certificates: [] + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/LB/PublicListener/Resource + MyFargateServiceLBPublicListenerECSGroup4A3EDF05: + Type: AWS::ElasticLoadBalancingV2::TargetGroup + Properties: + Port: 80 + Protocol: HTTP + TargetGroupAttributes: [] + Targets: [] + TargetType: ip + VpcId: + Ref: MyVpcF9F0CA6F + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/LB/PublicListener/ECSGroup/Resource + MyFargateServiceTaskDefTaskRole62C7D397: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Action: sts:AssumeRole + Effect: Allow + Principal: + Service: + Fn::Join: + - "" + - - ecs-tasks. + - Ref: AWS::URLSuffix + Version: "2012-10-17" + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/TaskRole/Resource + MyFargateServiceTaskDef5DA17B39: + Type: AWS::ECS::TaskDefinition + Properties: + ContainerDefinitions: + - Essential: true + Image: amazon/amazon-ecs-sample + Links: [] + LogConfiguration: + LogDriver: awslogs + Options: + awslogs-group: + Ref: MyFargateServiceLoggingLogGroup271A17C2 + awslogs-stream-prefix: MyFargateService + awslogs-region: + Ref: AWS::Region + MountPoints: [] + Name: web + PortMappings: + - ContainerPort: 80 + Protocol: tcp + Ulimits: [] + VolumesFrom: [] + Cpu: "512" + ExecutionRoleArn: + Fn::GetAtt: + - MyFargateServiceTaskDefExecutionRoleD6305504 + - Arn + Family: MyEcsConstructMyFargateServiceTaskDef164AB9B9 + Memory: "2048" + NetworkMode: awsvpc + RequiresCompatibilities: + - FARGATE + TaskRoleArn: + Fn::GetAtt: + - MyFargateServiceTaskDefTaskRole62C7D397 + - Arn + Volumes: [] + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/Resource + MyFargateServiceTaskDefExecutionRoleD6305504: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Action: sts:AssumeRole + Effect: Allow + Principal: + Service: + Fn::Join: + - "" + - - ecs-tasks. + - Ref: AWS::URLSuffix + Version: "2012-10-17" + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/ExecutionRole/Resource + MyFargateServiceTaskDefExecutionRoleDefaultPolicyEC22B20F: + Type: AWS::IAM::Policy + Properties: + PolicyDocument: + Statement: + - Action: + - logs:CreateLogStream + - logs:PutLogEvents + Effect: Allow + Resource: + Fn::GetAtt: + - MyFargateServiceLoggingLogGroup271A17C2 + - Arn + Version: "2012-10-17" + PolicyName: MyFargateServiceTaskDefExecutionRoleDefaultPolicyEC22B20F + Roles: + - Ref: MyFargateServiceTaskDefExecutionRoleD6305504 + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/ExecutionRole/DefaultPolicy/Resource + MyFargateServiceLoggingLogGroup271A17C2: + Type: AWS::Logs::LogGroup + DeletionPolicy: Retain + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/Logging/LogGroup/Resource + MyFargateServiceF490C034: + Type: AWS::ECS::Service + Properties: + TaskDefinition: + Ref: MyFargateServiceTaskDef5DA17B39 + Cluster: + Ref: MyCluster4C1BA579 + DeploymentConfiguration: + MaximumPercent: 200 + MinimumHealthyPercent: 50 + DesiredCount: 6 + LaunchType: FARGATE + LoadBalancers: + - ContainerName: web + ContainerPort: 80 + TargetGroupArn: + Ref: MyFargateServiceLBPublicListenerECSGroup4A3EDF05 + NetworkConfiguration: + AwsvpcConfiguration: + AssignPublicIp: DISABLED + SecurityGroups: + - Fn::GetAtt: + - MyFargateServiceSecurityGroup7016792A + - GroupId + Subnets: + - Ref: MyVpcPrivateSubnet1Subnet5057CF7E + - Ref: MyVpcPrivateSubnet2Subnet0040C983 + - Ref: MyVpcPrivateSubnet3Subnet772D6AD7 + ServiceRegistries: [] + DependsOn: + - MyFargateServiceLBPublicListenerECSGroup4A3EDF05 + - MyFargateServiceLBPublicListener61A1042F + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/Service/Service + MyFargateServiceSecurityGroup7016792A: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: MyEcsConstruct/MyFargateService/Service/SecurityGroup + SecurityGroupEgress: + - CidrIp: 0.0.0.0/0 + Description: Allow all outbound traffic by default + IpProtocol: "-1" + SecurityGroupIngress: [] + VpcId: + Ref: MyVpcF9F0CA6F + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/Service/SecurityGroup/Resource + MyFargateServiceSecurityGroupfromMyEcsConstructMyFargateServiceLBSecurityGroup8793A2F780B3ABD3C6: + Type: AWS::EC2::SecurityGroupIngress + Properties: + IpProtocol: tcp + Description: Load balancer to target + FromPort: 80 + GroupId: + Fn::GetAtt: + - MyFargateServiceSecurityGroup7016792A + - GroupId + SourceSecurityGroupId: + Fn::GetAtt: + - MyFargateServiceLBSecurityGroup6FBF16F1 + - GroupId + ToPort: 80 + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/Service/SecurityGroup/from + MyEcsConstructMyFargateServiceLBSecurityGroup8793A2F7:80 + CDKMetadata: + Type: AWS::CDK::Metadata + Properties: + Modules: aws-cdk=0.34.0,@aws-cdk/assets=0.34.0,@aws-cdk/assets-docker=0.34.0,@aws-cdk/aws-applicationautoscaling=0.34.0,@aws-cdk/aws-autoscaling=0.34.0,@aws-cdk/aws-autoscaling-common=0.34.0,@aws-cdk/aws-autoscaling-hooktargets=0.34.0,@aws-cdk/aws-cloudformation=0.34.0,@aws-cdk/aws-cloudwatch=0.34.0,@aws-cdk/aws-ec2=0.34.0,@aws-cdk/aws-ecr=0.34.0,@aws-cdk/aws-ecs=0.34.0,@aws-cdk/aws-ecs-patterns=0.34.0,@aws-cdk/aws-elasticloadbalancingv2=0.34.0,@aws-cdk/aws-events=0.34.0,@aws-cdk/aws-events-targets=0.34.0,@aws-cdk/aws-iam=0.34.0,@aws-cdk/aws-kms=0.34.0,@aws-cdk/aws-lambda=0.34.0,@aws-cdk/aws-logs=0.34.0,@aws-cdk/aws-route53=0.34.0,@aws-cdk/aws-route53-targets=0.34.0,@aws-cdk/aws-s3=0.34.0,@aws-cdk/aws-servicediscovery=0.34.0,@aws-cdk/aws-sns=0.34.0,@aws-cdk/aws-sqs=0.34.0,@aws-cdk/cdk=0.34.0,@aws-cdk/cx-api=0.34.0,@aws-cdk/region-info=0.34.0,jsii-runtime=node.js/v11.3.0 +Outputs: + MyFargateServiceLoadBalancerDNS704F6391: + Value: + Fn::GetAtt: + - MyFargateServiceLBDE830E97 + - DNSName + From eb444afa577982749a35758b5302313633940fa3 Mon Sep 17 00:00:00 2001 From: Taylor Monacelli Date: Sun, 23 Jun 2019 17:19:00 -0700 Subject: [PATCH 022/655] Update readme to work with CDK 0.35 --- doc_source/ecs_example.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index c4ee95db..4113c0e2 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -97,10 +97,10 @@ Replace the comment at the end of the constructor with the following code\. // Create a load-balanced Fargate service and make it public new ecs.LoadBalancedFargateService(this, 'MyFargateService', { cluster: cluster, // Required - cpu: '512', // Default is 256 + cpu: 512, // Default is 256 desiredCount: 6, // Default is 1 image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"), // Required - memoryMiB: '2048', // Default is 512 + memoryLimitMiB: 2048, // Default is 512 publicLoadBalancer: true // Default is false }); ``` From 08ad70451410edb612f2b03c96c8f03e3fdce485 Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Mon, 24 Jun 2019 13:42:17 -0700 Subject: [PATCH 023/655] Updated CLI and PGP sections with feedback from editor --- doc_source/pgp-keys.md | 14 +++--- doc_source/tools.md | 104 ++++++++++++++++++++++------------------- 2 files changed, 63 insertions(+), 55 deletions(-) diff --git a/doc_source/pgp-keys.md b/doc_source/pgp-keys.md index 44c927fc..645b0ff7 100644 --- a/doc_source/pgp-keys.md +++ b/doc_source/pgp-keys.md @@ -1,14 +1,14 @@ -------- -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(AWS CDK\)\. Releases might lack important features and might have future breaking changes\. -------- -# OpenPGP Keys for the AWS CDK and JSII +# OpenPGP Keys for the AWS CDK and jsii -This topic contains the OpenPGP keys for the CDK and JSII\. +This topic contains the OpenPGP keys for the AWS CDK and `jsii`\. -## CDK OpenPGP Key +## AWS CDK OpenPGP Key | | | @@ -21,7 +21,7 @@ This topic contains the OpenPGP keys for the CDK and JSII\. | User ID: | AWS CDK Team | | Key fingerprint: | E88B E3B6 F0B1 E350 9E36 4F96 0566 A784 E17F 3870 | -Select the "Copy" icon to copy the following OpenPGP key: +Select the **Copy** icon to copy the following OpenPGP key\. ``` -----BEGIN PGP PUBLIC KEY BLOCK----- @@ -54,7 +54,7 @@ EkSlc/RoDqZCpBGgcoy1FFWvV/ZLgNU6OTQlYH6oYOWiylSJnaTDyurrktsxJI6d -----END PGP PUBLIC KEY BLOCK----- ``` -## JSII OpenPGP Key +## jsii OpenPGP Key | | | @@ -67,7 +67,7 @@ EkSlc/RoDqZCpBGgcoy1FFWvV/ZLgNU6OTQlYH6oYOWiylSJnaTDyurrktsxJI6d | User ID: | AWS JSII Team | | Key fingerprint: | 85EF 6522 4CE2 1E8C 72DB 28EC 1C7A CE4C B2A1 B93A | -Select the "Copy" icon to copy the following OpenPGP key: +Select the **Copy** icon to copy the following OpenPGP key\. ``` -----BEGIN PGP PUBLIC KEY BLOCK----- diff --git a/doc_source/tools.md b/doc_source/tools.md index 48018438..a8bf23fd 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -1,71 +1,73 @@ -------- -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(AWS CDK\)\. Releases might lack important features and might have future breaking changes\. -------- -# CDK Toolchain +# AWS CDK Tools -This section contains information about CDK tools\. +This topic describes the tools you can use to work with the AWS CDK\. These tools include the AWS CDK Command Line Interface \(cdk\) and AWS SAM CLI\. ## AWS CDK Command Line Interface \(cdk\) -The CDK Toolkit, cdk, is the main tool you use to interact with your CDK app\. It executes the CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the CDK\. +The AWS CDK CLI, known as the cdk, is your main tool for interacting with your AWS CDK app\. The cdk executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates that the AWS CDK generates\. -There are two ways to tell cdk what command to use to run your CDK app\. The first way is to include an explicit \-\-app option whenever you use a cdk command\. +There are two ways to tell the cdk what command to use to run your AWS CDK app\. + +The first way is to include an explicit \-\-app option whenever you use a cdk command\. ``` -cdk --app 'node bin/main.js' synth +cdk --app "npx ts-node bin/hello-cdk.ts" ls ``` -The second way is to add the following entry to the `cdk.json` file\. +The second way is to add the following entry to the `cdk.json` file \(if you use the cdk init command, the command does this for you\)\. ``` { - "app": "node bin/main.js" + "app": "npx ts-node bin/hello-cdk.ts" } ``` -You can also use the npx cdk instead of just cdk\. +You can also use the npx cdk instead of just the cdk\. -Here are the actions you can take on your CDK app \(this is the output of the cdk \-\-help command\)\. +Here are the actions you can take on your AWS CDK app \(this is the output of the cdk \-\-help command\)\. ``` Usage: cdk -a COMMAND Commands: - cdk list Lists all stacks in the app [aliases: ls] - cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation + cdk list List all stacks in the app [aliases: ls] + cdk synthesize [STACKS..] Synthesize and print the AWS CloudFormation template for this stack [aliases: synth] - cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS + cdk bootstrap [ENVIRONMENTS..] Deploy the CDK toolkit stack into an AWS environment - cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your + cdk deploy [STACKS..] Deploy the stack(s) named STACKS into your AWS account cdk destroy [STACKS..] Destroy the stack(s) named STACKS - cdk diff [STACKS..] Compares the specified stack with the deployed + cdk diff [STACKS..] Compare the specified stack with the deployed stack or a local template file, and returns with status 1 if any difference is found - cdk metadata [STACK] Returns all metadata associated with this + cdk metadata [STACK] Return all metadata associated with this stack cdk init [TEMPLATE] Create a new, empty CDK project from a template. Invoked without TEMPLATE, the app template will be used. cdk context Manage cached context values - cdk docs Opens the reference documentation in a browser + cdk docs Open the reference documentation in a browser [aliases: doc] - cdk doctor Check your set-up for potential problems + cdk doctor Check your setup for potential problems Options: - --app, -a REQUIRED: command-line for executing your app or a cloud - assembly directory (e.g. "node bin/my-app.js") [string] + --app, -a REQUIRED: command line for executing your app or a cloud + assembly directory (e.g., "node bin/my-app.js") [string] --context, -c Add contextual string parameter (KEY=VALUE) [array] - --plugin, -p Name or path of a node package that extend the CDK + --plugin, -p Name or path of a node package that extends the CDK features. Can be specified multiple times [array] --rename Rename stack name if different from the one defined in the cloud executable ([ORIGINAL:]RENAMED) [string] --trace Print trace for stack warnings [boolean] --strict Do not construct stacks with warnings [boolean] - --ignore-errors Ignores synthesis errors, which will likely produce an + --ignore-errors Ignore synthesis errors, which will likely produce an invalid output [boolean] [default: false] --json, -j Use JSON output instead of YAML [boolean] [default: false] @@ -83,14 +85,16 @@ Options: --asset-metadata Include "aws:asset:*" CloudFormation metadata for resources that user assets (enabled by default) [boolean] [default: true] - --role-arn, -r ARN of Role to use when invoking CloudFormation [string] + --role-arn, -r ARN of role to use when invoking AWS CloudFormation [string] --toolkit-stack-name The name of the CDK toolkit stack [string] - --staging copy assets to the output directory (use --no-staging to - disable) [boolean] [default: true] - --output, -o emits the synthesized cloud assembly into a directory + --staging Copy assets to the output directory (use --no-staging to + disable, needed for local debugging of the source files + with SAM CLI) [boolean] [default: true] + --output, -o Emits the synthesized cloud assembly into a directory (default: cdk.out) [string] --ci Force CI detection. Use --no-ci to disable CI autodetection. [boolean] [default: false] + --tags, -t Tags to add to the stack (KEY=VALUE) [array] --version Show version number [boolean] -h, --help Show help [boolean] @@ -102,36 +106,34 @@ as defaults. Settings in cdk.json take precedence. If your app has a single stack, you don't have to specify the stack name\. -If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. - -### Bootstrapping the CDK +### Bootstrapping Your AWS Environment -Before you can use the CDK you must bootstrap the CDK to create the infrastructure that the CDK needs\. Currently the bootstrap command creates only an Amazon S3 bucket\. +Before you can use the AWS CDK, you must create the infrastructure that the AWS CDK CLI \(cdk\) needs to deploy your AWS CDK app\. Currently the bootstrap command creates only an Amazon S3 bucket\. -You incur any charges for what the CDK stores in the bucket\. Because the CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. +You incur any charges for objects that the AWS CDK stores in the bucket\. Because the AWS CDK doesn't remove any objects from the bucket, the bucket accumulates them as you use the AWS CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. ### Security\-Related Changes -To protect you against unintended changes that affect your security posture, the CDK toolkit prompts you to approve security\-related changes before deploying them\. +To protect you against unintended changes that affect your security posture, the AWS CDK command\-line tool prompts you to approve security\-related changes before deploying them\. -You change the level of changes that requires approval by specifying: +You modify the level of changes that require approval by specifying the following\. ``` cdk deploy --require-approval LEVEL ``` -Where *LEVEL* can be one of the following: +*LEVEL* can be one of the following values\. never Approval is never required\. any\-change -Requires approval on any IAM or security\-group related change\. +Requires approval on any AWS Identity and Access Management \(IAM\) or security\-group related change\. broadening \(default\) Requires approval when IAM statements or traffic rules are added\. Removals don't require approval\. -The setting can also be configured in the `cdk.json` file\. +You can also configure the setting in the `cdk.json` file\. ``` { @@ -142,9 +144,9 @@ The setting can also be configured in the `cdk.json` file\. ### Version Reporting -To gain insight into how the CDK is used, the versions of libraries used by CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. +To gain insight into how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. You can also use this information to identify stacks using a package with known serious security or reliability issues, and contact the package users with that important information\. -The CDK reports the name and version of `npm` modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. +The AWS CDK reports the name and version of `npm` modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. The `AWS::CDK::Metadata` resource looks like the following\. @@ -172,11 +174,17 @@ To opt out of version reporting, use one of the following methods: } ``` -## SAM CLI +## AWS SAM CLI + +This topic describes how to use the AWS SAM CLI with the AWS CDK to test an AWS Lambda function locally\.For more information about testing Lambda functions locally, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. + +To install 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)\. + +### AWS SAM Example -This topic describes how to use the SAM CLI with the CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. +The following example walks you through creating an AWS CDK application with a Lambda function and testing that function locally using AWS SAM\. -1. The first step is to create a CDK application and add the Lambda package\. +1. Create an AWS CDK app and add the Lambda package\. ``` mkdir cdk-sam-example @@ -185,13 +193,13 @@ This topic describes how to use the SAM CLI with the CDK to test a Lambda functi npm install @aws-cdk/aws-lambda ``` -1. Add a Lambda reference to `lib/cdk-sam-example-stack.ts`: +1. Add a Lambda reference to `lib/cdk-sam-example-stack.ts`\. ``` import lambda = require('@aws-cdk/aws-lambda'); ``` -1. Replace the comment in `lib/cdk-sam-example-stack.ts` with the following Lambda function: +1. Replace the comment in `lib/cdk-sam-example-stack.ts` with the following Lambda function\. ``` new lambda.Function(this, 'MyFunction', { @@ -201,33 +209,33 @@ This topic describes how to use the SAM CLI with the CDK to test a Lambda functi }); ``` -1. Create the directory `my_function` +1. Create the directory `my_function`\. ``` mkdir my_function ``` -1. Create the file `app.py` in `my_function` with the following content: +1. Create the file `app.py` in `my_function` with the following content\. ``` def lambda_handler(event, context): return "This is a Lambda Function defined through CDK" ``` -1. Compile your CDK app and create a AWS CloudFormation template +1. Compile your AWS CDK app and create an AWS CloudFormation template\. ``` npm run build cdk synth > template.yaml ``` -1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the CDK generates for all resources\. The line right after it should look like: +1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an eight\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like the following\. ``` Type: AWS::Lambda::Function ``` -1. Run the function by executing: +1. Run the function by executing the following code\. ``` sam local invoke MyFunction12345678 --no-event From 53af69a73253aa1654ce479c60a812d530991626 Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Tue, 25 Jun 2019 11:13:57 -0700 Subject: [PATCH 024/655] Updated versioning section with info from Quip doc https://quip-amazon.com/zHjEA5L05v1W/CDK-Versions-API-Stability#BKR9CAmkfUf --- doc_source/aws_construct_lib.md | 55 ++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 7 deletions(-) diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md index 9a621081..79b146ba 100644 --- a/doc_source/aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -1,22 +1,63 @@ -------- -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(AWS CDK\)\. Releases might lack important features and might have future breaking changes\. -------- # AWS Construct Library -The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [Vpc](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your CDK app\. +The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [Vpc](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your AWS CDK app\. -The AWS Construct Library modules are described in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. +The AWS Construct Library modules are described in the [AWS CDK Reference](https://awslabs.github.io/aws-cdk/)\. ## Versioning -The CDK follows the semantic versioning model\. This means that breaking changes are limited to major releases, such as 2\.0\. +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [Semantic Versioning](https://semver.org) model\. This means that breaking changes to stable APIs \(see “The AWS CDK Stability Index”\) are limited to major releases\. Minor and patch releases are backwards\-compatible, meaning that the code written in a previous version with the same major can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. -Minor releases, such as 2\.4, guarantee that any code written in a previous minor version, such as 2\.1, will build, run, and produce the exact same results when built, run, and producing results, as before\. +### AWS CDK Stability Index -## CDK Patterns +However, certain APIs deviate from the semantic versioning model\. The AWS CDK team has added a stability index to help developers determine which APIs deviate from the semantic versioning model\. + +There are three levels of stability in the AWS CDK Construct Library: + +Experimental +The API is still under active development and subject to non\-backward compatible changes or removal in any future version\. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. + +Stable +The API is subject to the semantic versioning model\. We will not introduce non\-backward compatible changes or remove the API in a subsequent patch or feature release\. + +Deprecated +The API may emit warnings\. We do not guarantee backward compatibility\. + +Experimental and stable modules receive the same level of support from AWS\. The only difference is that we might change experimental APIs within a major version\. While we don not recommend using experimental APIs in production, we vet them the same way as we vet stable APIs before we include them in an AWS CDK release\. + +### Identifying the Support Level of an API + +The AWS CDK Developer guide and API Reference for each module starts with a section outlining the module's stability index\. The libraries that include only AWS CloudFormation Resources, and no hand\-curated constructs, are labelled with the maturity indicator **CloudFormation\-only**\. + +The module\-level gives an indication of the stability of the majority of the APIs included in the module, however individual APIs within the module can be annotated with different stability levels: + + +| Stability | TypeScript | JavaScript | Python | C\#/\.NET | Java | +| --- |--- |--- |--- |--- |--- | +| Experimental | @experimental | @stability Experimental | @experimental | Stability: Experimental | Stability: Experimental | +| Stable | @stable | @stability Stable | @stable | Stability: Stable | Stability: Stable | +| Deprecated | @deprecated | @Deprecated | @deprecated | \[Obsolete\] | Stability: Deprecated | + +### Language Binding Stability + +In addition to modules of the AWS CDK Construct Library, language support is also subject to a stability indication\. While the API described in all the languages is the same, the specific programming model and naming of language bindings considered experimental can change as it matures\. + + +| Language | Stability | +| --- |--- | +| TypeScript | Stable | +| JavaScript | Stable | +| Python | Stable | +| Java | Experimental | +| C\#/\.NET | Experimental | + +## AWS CDK Patterns The AWS Construct Library includes many common patterns and capabilities that are designed to enable developers to focus on their application\-specific architectures and reduce the boilerplate and glue logic needed when working with AWS services\. @@ -79,7 +120,7 @@ const stack2 = new StackThatExpectsABucket(app, 'Stack2', { }); ``` -If the resource is in the same account and region, but in a different stack, the CDK creates the relevant information, such as the bucket name, that is necessary to transfer that information from one stack to the other\. +If the resource is in the same account and region, but in a different stack, the AWS CDK creates the relevant information, such as the bucket name, that is necessary to transfer that information from one stack to the other\. ### Passing Resources from a Different Account or Region From 0b3018c0772c36e9d64b41a5dd00c888c60e6ed8 Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Tue, 25 Jun 2019 11:13:57 -0700 Subject: [PATCH 025/655] Updated versioning section with info from Quip doc --- doc_source/aws_construct_lib.md | 55 ++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 7 deletions(-) diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md index 9a621081..79b146ba 100644 --- a/doc_source/aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -1,22 +1,63 @@ -------- -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. +This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(AWS CDK\)\. Releases might lack important features and might have future breaking changes\. -------- # AWS Construct Library -The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [Vpc](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your CDK app\. +The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [Vpc](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your AWS CDK app\. -The AWS Construct Library modules are described in the [CDK Reference](https://awslabs.github.io/aws-cdk/)\. +The AWS Construct Library modules are described in the [AWS CDK Reference](https://awslabs.github.io/aws-cdk/)\. ## Versioning -The CDK follows the semantic versioning model\. This means that breaking changes are limited to major releases, such as 2\.0\. +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [Semantic Versioning](https://semver.org) model\. This means that breaking changes to stable APIs \(see “The AWS CDK Stability Index”\) are limited to major releases\. Minor and patch releases are backwards\-compatible, meaning that the code written in a previous version with the same major can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. -Minor releases, such as 2\.4, guarantee that any code written in a previous minor version, such as 2\.1, will build, run, and produce the exact same results when built, run, and producing results, as before\. +### AWS CDK Stability Index -## CDK Patterns +However, certain APIs deviate from the semantic versioning model\. The AWS CDK team has added a stability index to help developers determine which APIs deviate from the semantic versioning model\. + +There are three levels of stability in the AWS CDK Construct Library: + +Experimental +The API is still under active development and subject to non\-backward compatible changes or removal in any future version\. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. + +Stable +The API is subject to the semantic versioning model\. We will not introduce non\-backward compatible changes or remove the API in a subsequent patch or feature release\. + +Deprecated +The API may emit warnings\. We do not guarantee backward compatibility\. + +Experimental and stable modules receive the same level of support from AWS\. The only difference is that we might change experimental APIs within a major version\. While we don not recommend using experimental APIs in production, we vet them the same way as we vet stable APIs before we include them in an AWS CDK release\. + +### Identifying the Support Level of an API + +The AWS CDK Developer guide and API Reference for each module starts with a section outlining the module's stability index\. The libraries that include only AWS CloudFormation Resources, and no hand\-curated constructs, are labelled with the maturity indicator **CloudFormation\-only**\. + +The module\-level gives an indication of the stability of the majority of the APIs included in the module, however individual APIs within the module can be annotated with different stability levels: + + +| Stability | TypeScript | JavaScript | Python | C\#/\.NET | Java | +| --- |--- |--- |--- |--- |--- | +| Experimental | @experimental | @stability Experimental | @experimental | Stability: Experimental | Stability: Experimental | +| Stable | @stable | @stability Stable | @stable | Stability: Stable | Stability: Stable | +| Deprecated | @deprecated | @Deprecated | @deprecated | \[Obsolete\] | Stability: Deprecated | + +### Language Binding Stability + +In addition to modules of the AWS CDK Construct Library, language support is also subject to a stability indication\. While the API described in all the languages is the same, the specific programming model and naming of language bindings considered experimental can change as it matures\. + + +| Language | Stability | +| --- |--- | +| TypeScript | Stable | +| JavaScript | Stable | +| Python | Stable | +| Java | Experimental | +| C\#/\.NET | Experimental | + +## AWS CDK Patterns The AWS Construct Library includes many common patterns and capabilities that are designed to enable developers to focus on their application\-specific architectures and reduce the boilerplate and glue logic needed when working with AWS services\. @@ -79,7 +120,7 @@ const stack2 = new StackThatExpectsABucket(app, 'Stack2', { }); ``` -If the resource is in the same account and region, but in a different stack, the CDK creates the relevant information, such as the bucket name, that is necessary to transfer that information from one stack to the other\. +If the resource is in the same account and region, but in a different stack, the AWS CDK creates the relevant information, such as the bucket name, that is necessary to transfer that information from one stack to the other\. ### Passing Resources from a Different Account or Region From a6de862b3f4c653d575c48a57ed988e6d56f4cbf Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Thu, 27 Jun 2019 11:34:37 -0700 Subject: [PATCH 026/655] Updated YAML file --- doc_source/my_ecs_construct-stack.yaml | 173 +++++-------------------- 1 file changed, 31 insertions(+), 142 deletions(-) diff --git a/doc_source/my_ecs_construct-stack.yaml b/doc_source/my_ecs_construct-stack.yaml index 2f4ab4d7..5dd8b29d 100644 --- a/doc_source/my_ecs_construct-stack.yaml +++ b/doc_source/my_ecs_construct-stack.yaml @@ -14,10 +14,13 @@ Resources: MyVpcPublicSubnet1SubnetF6608456: Type: AWS::EC2::Subnet Properties: - CidrBlock: 10.0.0.0/19 + CidrBlock: 10.0.0.0/18 VpcId: Ref: MyVpcF9F0CA6F - AvailabilityZone: us-west-2a + AvailabilityZone: + Fn::Select: + - 0 + - Fn::GetAZs: "" MapPublicIpOnLaunch: true Tags: - Key: Name @@ -82,10 +85,13 @@ Resources: MyVpcPublicSubnet2Subnet492B6BFB: Type: AWS::EC2::Subnet Properties: - CidrBlock: 10.0.32.0/19 + CidrBlock: 10.0.64.0/18 VpcId: Ref: MyVpcF9F0CA6F - AvailabilityZone: us-west-2b + AvailabilityZone: + Fn::Select: + - 1 + - Fn::GetAZs: "" MapPublicIpOnLaunch: true Tags: - Key: Name @@ -147,81 +153,16 @@ Resources: Value: MyEcsConstruct/MyVpc/PublicSubnet2 Metadata: aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/NATGateway - MyVpcPublicSubnet3Subnet57EEE236: - Type: AWS::EC2::Subnet - Properties: - CidrBlock: 10.0.64.0/19 - VpcId: - Ref: MyVpcF9F0CA6F - AvailabilityZone: us-west-2c - MapPublicIpOnLaunch: true - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PublicSubnet3 - - Key: aws-cdk:subnet-name - Value: Public - - Key: aws-cdk:subnet-type - Value: Public - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/Subnet - MyVpcPublicSubnet3RouteTable15028F08: - Type: AWS::EC2::RouteTable - Properties: - VpcId: - Ref: MyVpcF9F0CA6F - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PublicSubnet3 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/RouteTable - MyVpcPublicSubnet3RouteTableAssociation5C27DDA4: - Type: AWS::EC2::SubnetRouteTableAssociation - Properties: - RouteTableId: - Ref: MyVpcPublicSubnet3RouteTable15028F08 - SubnetId: - Ref: MyVpcPublicSubnet3Subnet57EEE236 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/RouteTableAssociation - MyVpcPublicSubnet3DefaultRoute3A83AB36: - Type: AWS::EC2::Route - Properties: - RouteTableId: - Ref: MyVpcPublicSubnet3RouteTable15028F08 - DestinationCidrBlock: 0.0.0.0/0 - GatewayId: - Ref: MyVpcIGW5C4A4F63 - DependsOn: - - MyVpcVPCGW488ACE0D - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/DefaultRoute - MyVpcPublicSubnet3EIPC5ACADAB: - Type: AWS::EC2::EIP - Properties: - Domain: vpc - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/EIP - MyVpcPublicSubnet3NATGatewayD4B50EBE: - Type: AWS::EC2::NatGateway - Properties: - AllocationId: - Fn::GetAtt: - - MyVpcPublicSubnet3EIPC5ACADAB - - AllocationId - SubnetId: - Ref: MyVpcPublicSubnet3Subnet57EEE236 - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PublicSubnet3 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet3/NATGateway MyVpcPrivateSubnet1Subnet5057CF7E: Type: AWS::EC2::Subnet Properties: - CidrBlock: 10.0.96.0/19 + CidrBlock: 10.0.128.0/18 VpcId: Ref: MyVpcF9F0CA6F - AvailabilityZone: us-west-2a + AvailabilityZone: + Fn::Select: + - 0 + - Fn::GetAZs: "" MapPublicIpOnLaunch: false Tags: - Key: Name @@ -264,10 +205,13 @@ Resources: MyVpcPrivateSubnet2Subnet0040C983: Type: AWS::EC2::Subnet Properties: - CidrBlock: 10.0.128.0/19 + CidrBlock: 10.0.192.0/18 VpcId: Ref: MyVpcF9F0CA6F - AvailabilityZone: us-west-2b + AvailabilityZone: + Fn::Select: + - 1 + - Fn::GetAZs: "" MapPublicIpOnLaunch: false Tags: - Key: Name @@ -307,52 +251,6 @@ Resources: Ref: MyVpcPublicSubnet2NATGateway91BFBEC9 Metadata: aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/DefaultRoute - MyVpcPrivateSubnet3Subnet772D6AD7: - Type: AWS::EC2::Subnet - Properties: - CidrBlock: 10.0.160.0/19 - VpcId: - Ref: MyVpcF9F0CA6F - AvailabilityZone: us-west-2c - MapPublicIpOnLaunch: false - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PrivateSubnet3 - - Key: aws-cdk:subnet-name - Value: Private - - Key: aws-cdk:subnet-type - Value: Private - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet3/Subnet - MyVpcPrivateSubnet3RouteTableB790927C: - Type: AWS::EC2::RouteTable - Properties: - VpcId: - Ref: MyVpcF9F0CA6F - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PrivateSubnet3 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet3/RouteTable - MyVpcPrivateSubnet3RouteTableAssociationD951741C: - Type: AWS::EC2::SubnetRouteTableAssociation - Properties: - RouteTableId: - Ref: MyVpcPrivateSubnet3RouteTableB790927C - SubnetId: - Ref: MyVpcPrivateSubnet3Subnet772D6AD7 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet3/RouteTableAssociation - MyVpcPrivateSubnet3DefaultRouteEC11C0C5: - Type: AWS::EC2::Route - Properties: - RouteTableId: - Ref: MyVpcPrivateSubnet3RouteTableB790927C - DestinationCidrBlock: 0.0.0.0/0 - NatGatewayId: - Ref: MyVpcPublicSubnet3NATGatewayD4B50EBE - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet3/DefaultRoute MyVpcIGW5C4A4F63: Type: AWS::EC2::InternetGateway Properties: @@ -386,19 +284,16 @@ Resources: Subnets: - Ref: MyVpcPublicSubnet1SubnetF6608456 - Ref: MyVpcPublicSubnet2Subnet492B6BFB - - Ref: MyVpcPublicSubnet3Subnet57EEE236 Type: application DependsOn: - MyVpcPublicSubnet1DefaultRoute95FDF9EB - MyVpcPublicSubnet2DefaultRoute052936F6 - - MyVpcPublicSubnet3DefaultRoute3A83AB36 Metadata: aws:cdk:path: MyEcsConstruct/MyFargateService/LB/Resource MyFargateServiceLBSecurityGroup6FBF16F1: Type: AWS::EC2::SecurityGroup Properties: - GroupDescription: Automatically created Security Group for ELB - MyEcsConstructMyFargateServiceLB5E4E9AE3 + GroupDescription: Automatically created Security Group for ELB MyEcsConstructMyFargateServiceLB5E4E9AE3 SecurityGroupEgress: [] SecurityGroupIngress: - CidrIp: 0.0.0.0/0 @@ -426,8 +321,7 @@ Resources: FromPort: 80 ToPort: 80 Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/LB/SecurityGroup/to - MyEcsConstructMyFargateServiceSecurityGroup67F71DB3:80 + aws:cdk:path: MyEcsConstruct/MyFargateService/LB/SecurityGroup/to MyEcsConstructMyFargateServiceSecurityGroup67F71DB3:80 MyFargateServiceLBPublicListener61A1042F: Type: AWS::ElasticLoadBalancingV2::Listener Properties: @@ -481,7 +375,7 @@ Resources: LogDriver: awslogs Options: awslogs-group: - Ref: MyFargateServiceLoggingLogGroup271A17C2 + Ref: MyFargateServiceTaskDefwebLogGroup4A6C44E8 awslogs-stream-prefix: MyFargateService awslogs-region: Ref: AWS::Region @@ -509,6 +403,11 @@ Resources: Volumes: [] Metadata: aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/Resource + MyFargateServiceTaskDefwebLogGroup4A6C44E8: + Type: AWS::Logs::LogGroup + DeletionPolicy: Retain + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/web/LogGroup/Resource MyFargateServiceTaskDefExecutionRoleD6305504: Type: AWS::IAM::Role Properties: @@ -536,7 +435,7 @@ Resources: Effect: Allow Resource: Fn::GetAtt: - - MyFargateServiceLoggingLogGroup271A17C2 + - MyFargateServiceTaskDefwebLogGroup4A6C44E8 - Arn Version: "2012-10-17" PolicyName: MyFargateServiceTaskDefExecutionRoleDefaultPolicyEC22B20F @@ -544,11 +443,6 @@ Resources: - Ref: MyFargateServiceTaskDefExecutionRoleD6305504 Metadata: aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/ExecutionRole/DefaultPolicy/Resource - MyFargateServiceLoggingLogGroup271A17C2: - Type: AWS::Logs::LogGroup - DeletionPolicy: Retain - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/Logging/LogGroup/Resource MyFargateServiceF490C034: Type: AWS::ECS::Service Properties: @@ -560,6 +454,7 @@ Resources: MaximumPercent: 200 MinimumHealthyPercent: 50 DesiredCount: 6 + HealthCheckGracePeriodSeconds: 60 LaunchType: FARGATE LoadBalancers: - ContainerName: web @@ -576,7 +471,6 @@ Resources: Subnets: - Ref: MyVpcPrivateSubnet1Subnet5057CF7E - Ref: MyVpcPrivateSubnet2Subnet0040C983 - - Ref: MyVpcPrivateSubnet3Subnet772D6AD7 ServiceRegistries: [] DependsOn: - MyFargateServiceLBPublicListenerECSGroup4A3EDF05 @@ -612,12 +506,7 @@ Resources: - GroupId ToPort: 80 Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/Service/SecurityGroup/from - MyEcsConstructMyFargateServiceLBSecurityGroup8793A2F7:80 - CDKMetadata: - Type: AWS::CDK::Metadata - Properties: - Modules: aws-cdk=0.34.0,@aws-cdk/assets=0.34.0,@aws-cdk/assets-docker=0.34.0,@aws-cdk/aws-applicationautoscaling=0.34.0,@aws-cdk/aws-autoscaling=0.34.0,@aws-cdk/aws-autoscaling-common=0.34.0,@aws-cdk/aws-autoscaling-hooktargets=0.34.0,@aws-cdk/aws-cloudformation=0.34.0,@aws-cdk/aws-cloudwatch=0.34.0,@aws-cdk/aws-ec2=0.34.0,@aws-cdk/aws-ecr=0.34.0,@aws-cdk/aws-ecs=0.34.0,@aws-cdk/aws-ecs-patterns=0.34.0,@aws-cdk/aws-elasticloadbalancingv2=0.34.0,@aws-cdk/aws-events=0.34.0,@aws-cdk/aws-events-targets=0.34.0,@aws-cdk/aws-iam=0.34.0,@aws-cdk/aws-kms=0.34.0,@aws-cdk/aws-lambda=0.34.0,@aws-cdk/aws-logs=0.34.0,@aws-cdk/aws-route53=0.34.0,@aws-cdk/aws-route53-targets=0.34.0,@aws-cdk/aws-s3=0.34.0,@aws-cdk/aws-servicediscovery=0.34.0,@aws-cdk/aws-sns=0.34.0,@aws-cdk/aws-sqs=0.34.0,@aws-cdk/cdk=0.34.0,@aws-cdk/cx-api=0.34.0,@aws-cdk/region-info=0.34.0,jsii-runtime=node.js/v11.3.0 + aws:cdk:path: MyEcsConstruct/MyFargateService/Service/SecurityGroup/from MyEcsConstructMyFargateServiceLBSecurityGroup8793A2F7:80 Outputs: MyFargateServiceLoadBalancerDNS704F6391: Value: From 7f6457aaaf5d8e6a8c58ecc57af0da66b584085a Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Thu, 27 Jun 2019 11:35:43 -0700 Subject: [PATCH 027/655] Updated versioning topic based on Elad's feedback --- doc_source/aws_construct_lib.md | 28 +++++++++------------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md index 79b146ba..3bc8f9da 100644 --- a/doc_source/aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -6,26 +6,29 @@ This documentation is for the developer preview release \(public beta\) of the A # AWS Construct Library -The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [Vpc](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html) construct, which makes it easy to define an [Amazon VPC](https://aws.amazon.com/vpc) in your AWS CDK app\. +The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [Vpc](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html) construct, which makes it easy to define an Amazon VPC in your AWS CDK app\. The AWS Construct Library modules are described in the [AWS CDK Reference](https://awslabs.github.io/aws-cdk/)\. ## Versioning -Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [Semantic Versioning](https://semver.org) model\. This means that breaking changes to stable APIs \(see “The AWS CDK Stability Index”\) are limited to major releases\. Minor and patch releases are backwards\-compatible, meaning that the code written in a previous version with the same major can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [Semantic Versioning](https://semver.org) model\. This means that breaking changes to stable APIs \(see “The AWS CDK Stability Index”\) are limited to major releases\. Minor and patch releases are backwards\-compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. ### AWS CDK Stability Index -However, certain APIs deviate from the semantic versioning model\. The AWS CDK team has added a stability index to help developers determine which APIs deviate from the semantic versioning model\. +However, certain APIs do not adher to the semantic versioning model\. The AWS CDK team has added a stability index to help developers determine which APIs deviate from the semantic versioning model\. There are three levels of stability in the AWS CDK Construct Library: -Experimental -The API is still under active development and subject to non\-backward compatible changes or removal in any future version\. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. - Stable The API is subject to the semantic versioning model\. We will not introduce non\-backward compatible changes or remove the API in a subsequent patch or feature release\. +CloudFormation Only +These APIs are automatically built from the AWS CloudFormation resource specification and are subject to any changes introduced by AWS CloudFormation\. + +Experimental +The API is still under active development and subject to non\-backward compatible changes or removal in any future version\. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. + Deprecated The API may emit warnings\. We do not guarantee backward compatibility\. @@ -44,19 +47,6 @@ The module\-level gives an indication of the stability of the majority of the AP | Stable | @stable | @stability Stable | @stable | Stability: Stable | Stability: Stable | | Deprecated | @deprecated | @Deprecated | @deprecated | \[Obsolete\] | Stability: Deprecated | -### Language Binding Stability - -In addition to modules of the AWS CDK Construct Library, language support is also subject to a stability indication\. While the API described in all the languages is the same, the specific programming model and naming of language bindings considered experimental can change as it matures\. - - -| Language | Stability | -| --- |--- | -| TypeScript | Stable | -| JavaScript | Stable | -| Python | Stable | -| Java | Experimental | -| C\#/\.NET | Experimental | - ## AWS CDK Patterns The AWS Construct Library includes many common patterns and capabilities that are designed to enable developers to focus on their application\-specific architectures and reduce the boilerplate and glue logic needed when working with AWS services\. From 7b019e1401c2a356b4fea4cf92b6277ead897e5c Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Mon, 1 Jul 2019 05:59:17 -0700 Subject: [PATCH 028/655] Removed everything after versioning based on Elad's feedback --- doc_source/aws_construct_lib.md | 99 +++------------------------------ 1 file changed, 9 insertions(+), 90 deletions(-) diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md index 3bc8f9da..ad323546 100644 --- a/doc_source/aws_construct_lib.md +++ b/doc_source/aws_construct_lib.md @@ -47,96 +47,15 @@ The module\-level gives an indication of the stability of the majority of the AP | Stable | @stable | @stability Stable | @stable | Stability: Stable | Stability: Stable | | Deprecated | @deprecated | @Deprecated | @deprecated | \[Obsolete\] | Stability: Deprecated | -## AWS CDK Patterns +### Language Binding Stability -The AWS Construct Library includes many common patterns and capabilities that are designed to enable developers to focus on their application\-specific architectures and reduce the boilerplate and glue logic needed when working with AWS services\. +In addition to modules of the AWS CDK Construct Library, language support is also subject to a stability indication\. While the API described in all the languages is the same, the specific programming model and naming of language bindings considered experimental can change as it stabilizes\. -### Grants -AWS Identity and Access Management \(IAM\) policies are automatically defined based on intent\. For example, when subscribing an Amazon Simple Notification Service \(Amazon SNS\) [Topic](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns/topic.html) to an AWS Lambda [Function](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-lambda/function.html), the function's IAM permission policy is automatically modified to allow the specific topic to invoke the function\. - -Also, most AWS constructs expose `grant*` methods that allow intent\-based permission definitions\. For example, the Amazon S3 [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct has a [grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grantreadidentity-objectskeypattern) method\. This method accepts an IAM [IPrincipal](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/iprincipal.html) such as a [User](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/user.html) or a [Role](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-iam/role.html), which modifies the policy to allow the principal to read objects from the bucket\. - -## Metrics - -Many AWS resources emit [Amazon CloudWatch metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html) as part of their normal operation\. Metrics can be used to set up an [Alarm](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-cloudwatch/alarm.html) or can be included in a [Dashboard](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-cloudwatch/dashboard.html)\. - -You can obtain [Metric](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-cloudwatch/metric.html) objects for AWS constructs by using `metricXxx()` methods\. For example, the [metricAllDuration](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-lambda/function.html#aws_lambda_Function_metricAllDuration) method reports the execution time of an AWS Lambda function\. - -For more information, see [CloudWatch](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudwatch-readme.html)\. - -## Events - -Many AWS constructs include `on*` methods, which you can to react to events emitted by the construct\. For example, the CodeCommit [Repository](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-codecommit/repository.html) construct implements the [onCommit](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-codecommit/irepository.html#aws_codecommit_IRepository_onCommit) method\. You can use AWS constructs as targets for various event provider interfaces, such as [IEventRuleTarget](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-events/ieventruletarget.html) \(for the CloudWatch event rule target\), [IAlarmAction](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-cloudwatch/ialarmaction.html) \(for Amazon CloudWatch alarm actions\), and so on\. - -For more information, see [CloudWatch](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudwatch-readme.html) and [Events](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-events-readme.html)\. - -## Referencing Resources - -This section contains information about how to reference other resources, either from within the same app, or across apps\. The only caveat is that the resource must be in the same account and region\. - -Many CDK classes have required properties that are CDK resource objects \(resources\)\. To satisfy these requirements, you can refer to a resource in one of two ways: -+ By passing the resource directly\. -+ By passing the resource's unique identifier\. This is typically an ARN, but it could also be an ID or a name\. - -For example, an Amazon ECS service requires a reference to the cluster on which it runs; a CloudFront distribution requires a reference to the bucket containing source code\. - -In the AWS CDK, all AWS Construct Library resources that expect another resource take a property that is of the interface type of that resource\. For example, the Amazon ECS service takes a property of type `cluster: ICluster;` the CloudFront distribution takes a property of type `sourceBucket: IBucket`\. - -Since every resource implements its corresponding interface, you can directly pass any resources you're defining in the same AWS CDK application, as shown in the following example, which creates a new Amazon ECS cluster\. - -``` -const cluster = new ecs.Cluster(this, 'Cluster', { /* ... */ }); - -const service = new ecs.Service(this, 'Service', { - cluster: cluster, - /* ... */ -}); -``` - -### Passing Resources from a Different Stack - -You can refer to resources in a different stack, but in the same account and region\. If you need to refer to a resource in a different account or region, see the next section\. - -``` -const account = '123456789012'; -const region = 'us-east-1'; - -const stack1 = new StackThatProvidesABucket(app, 'Stack1'); - -// stack2 takes a property of type IBucket -const stack2 = new StackThatExpectsABucket(app, 'Stack2', { - bucket: stack1.bucket -}); -``` - -If the resource is in the same account and region, but in a different stack, the AWS CDK creates the relevant information, such as the bucket name, that is necessary to transfer that information from one stack to the other\. - -### Passing Resources from a Different Account or Region - -You can refer to a resource in a different account or region by using the resource's unique indentifier, such as: -+ `bucketName` for `bucket` -+ `functionArn` for `lambda` -+ `securityGroupId` for `securityGroup` - -The following example shows how to pass a generated bucket name to a Lambda function\. - -``` -const bucket = new s3.Bucket(this, 'Bucket'); - -new lambda.Function(this, 'MyLambda', { - /* ... */, - environment: { - BUCKET_NAME: bucket.bucketName, - }, -}); -``` - -### Turning Unique Identifiers into Objects - -If you have the unique identifier for a resource, such as a bucket ARN, but you need to pass it to a AWS CDK construct that expects an object, you can turn the ARN into a AWS CDK object in the current stack by calling a static factory method on the resource's class\. The following example shows how to create a bucket from an existing bucket ARN\. - -``` -// Construct a resource (bucket) by its full ARN (can be cross account) -Bucket.fromBucketArn(this, 'Bucket', 'arn:aws:s3:::my-bucket-name'); -``` \ No newline at end of file +| Language | Stability | +| --- |--- | +| TypeScript | Stable | +| JavaScript | Stable | +| Python | Stable | +| Java | Experimental | +| C\#/\.NET | Experimental | \ No newline at end of file From 92daa8254d37e55fe86afed3e3cee75e3fd0d0cf Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Thu, 11 Jul 2019 10:30:06 -0700 Subject: [PATCH 029/655] Updated to 1.0.0 release --- doc_source/about_examples.md | 10 +- doc_source/apps.md | 99 +++++++ doc_source/apps_and_stacks.md | 92 ------- doc_source/aspects.md | 52 ++++ doc_source/assets.md | 218 ++++++++++++++- doc_source/cfn_layer.md | 225 +++++----------- doc_source/cloudformation.md | 14 - doc_source/constructs.md | 222 +++++++++------- doc_source/context.md | 114 ++++---- doc_source/core_concepts.md | 10 +- doc_source/doc-history.md | 17 +- doc_source/ecs_example.md | 43 ++- doc_source/environments.md | 31 +++ doc_source/examples.md | 6 - doc_source/get_cfn_param.md | 6 - doc_source/get_context_var.md | 12 +- doc_source/get_env_var.md | 6 - doc_source/get_secrets_manager_value.md | 14 +- doc_source/get_ssm_value.md | 10 +- doc_source/getting_started.md | 57 ++-- doc_source/home.md | 130 ++++----- doc_source/how_to_set_cw_alarm.md | 26 +- doc_source/how_tos.md | 6 - doc_source/identifiers.md | 22 +- doc_source/index.md | 29 +- doc_source/lifecycle.md | 37 --- doc_source/multiple_languages.md | 162 +++++++----- doc_source/permissions.md | 97 +++++++ doc_source/pgp-keys.md | 16 +- doc_source/reference.md | 56 +++- doc_source/resources.md | 250 ++++++++++++++++-- doc_source/serverless_example.md | 26 +- .../stack_how_to_create_multiple_stacks.md | 24 +- doc_source/stacks.md | 82 ++++++ doc_source/tagging.md | 103 ++++++++ doc_source/tokens.md | 131 ++++++++- doc_source/tools.md | 104 ++++---- doc_source/troubleshooting.md | 12 +- doc_source/use_cfn_template.md | 10 +- doc_source/writing_constructs.md | 89 ------- 40 files changed, 1632 insertions(+), 1038 deletions(-) create mode 100644 doc_source/apps.md delete mode 100644 doc_source/apps_and_stacks.md create mode 100644 doc_source/aspects.md delete mode 100644 doc_source/cloudformation.md create mode 100644 doc_source/environments.md delete mode 100644 doc_source/lifecycle.md create mode 100644 doc_source/permissions.md create mode 100644 doc_source/stacks.md create mode 100644 doc_source/tagging.md delete mode 100644 doc_source/writing_constructs.md diff --git a/doc_source/about_examples.md b/doc_source/about_examples.md index ba2663fb..b821270e 100644 --- a/doc_source/about_examples.md +++ b/doc_source/about_examples.md @@ -1,9 +1,3 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # AWS CDK Examples The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitHub includes the following examples\. @@ -18,7 +12,7 @@ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitH | [appsync\-graphql\-dynamodb](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/appsync-graphql-dynamodb/) | Creating a single GraphQL API with an API Key, and four Resolvers doing CRUD operations over a single DynamoDB | | [classic\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/classic-load-balancer/) | Using an AutoScalingGroup with a Classic Load Balancer | | [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) | Shows adding a Custom Resource to your CDK app | -| [elasticbeanstalk](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/elasticbeanstalk/) | Elastic Beanstalk example using L1 with a Blue/Green pipeline \(community contributed\) | +| [elasticbeanstalk](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/elasticbeanstalk/) | Elastic Beanstalk example using CFN resources with a Blue/Green pipeline \(community contributed\) | | [ecs\-cluster](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/cluster/) | Provision an ECS Cluster with custom Autoscaling Group configuration | | [ecs\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-load-balanced-service/) | Starting a container fronted by a load balancer on ECS | | [ecs\-service\-with\-task\-placement](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-task-placement/) | Starting a container ECS with task placement specifications | @@ -31,7 +25,7 @@ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitH | [resource\-overrides](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/resource-overrides/) | Shows how to override generated CloudFormation code | | [static\-site](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/static-site/) | A static site using CloudFront | | [stepfunctions\-job\-poller](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/stepfunctions-job-poller/) | A simple StepFunctions workflow | -| [ecs\-service\-with\-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-logging/) | Starting a container fronted by a load balancer on Fargate | +| [ecs\-service\-with\-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-logging/) | Starting a container fronted by a load balancer on ECS | | [fargate\-service\-with\-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/fargate-service-with-logging/) | Starting a container fronted by a load balancer on Fargate | ## Java examples diff --git a/doc_source/apps.md b/doc_source/apps.md new file mode 100644 index 00000000..8205b823 --- /dev/null +++ b/doc_source/apps.md @@ -0,0 +1,99 @@ +# Apps + +As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/stack.html) construct\. + +The following example declares a stack class named `MyFirstStack` that includes a single Amazon S3 bucket\. However, this only declares a stack\. You still need to define \(also known as to instantiate\) it in some scope to deploy it\. + +``` +class MyFirstStack extends Stack { + constructor(scope: Construct, id: string, props: StackProps) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket'); + } +} +``` + +## App Constructs + +To define the previous stack within some scope, use the [App](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/app.html) construct\. The following example defines a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. + +``` +const app = new App(); +new MyFirstStack(app, 'hello-cdk'); +app.synth(); +``` + +The `App` construct doesn't require any initialization arguments, because it's the only construct that can be used as a root for the construct tree\. You can now use the `App` instance as a scope for defining a single instance of your stack\. + +You can also extend the App construct as follows\. + +``` +class MyApp extends App { + constructor() { + new MyFirstStack(this, 'hello-cdk'); + } +} + +new MyApp().synth(); +``` + +Both options are equivalent\. + +## App Lifecycle + +The following diagram shows the phases that the AWS CDK goes through when you call the cdk deploy\. This command deploys the resources that your app defines\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/Lifecycle.png) + +An AWS CDK app goes through the following phases in its lifecycle\. + +1\. Construction \(or Initialization\) + Your code instantiates all of the defined constructs and then links them together\. In this stage, all of the constructs \(app, stacks, and their child constructs\) are instantiated and the constructor chain is executed\. Most of your app code is executed in this stage\. + +2\. Preparation +All constructs that have implemented the `prepare` method participate in a final round of modifications, to set up their final state\. The preparation phase happens automatically\. As a user, you don't see any feedback from this phase\. It's rare to need to use the “prepare” hook, and generally not recommended\. You should be very careful when mutating the construct tree during this phase, because the order of operations could impact behavior\. + +3\. Validation +All constructs that have implemented the `validate` method can validate themselves to ensure that they're in a state that will correctly deploy\. You will get notified of any validation failures that happen during this phase\. Generally, we recommend that you perform validation as soon as possible \(usually as soon as you get some input\) and throw exceptions as early as possible\. Performing validation early improves diagnosability as stack traces will be more accurate, and ensures that your code can continue to execute safely\. + +4\. Synthesis +This is the final stage of the execution of your AWS CDK app\. It's triggered by a call to `app.synth()`, and it traverses the construct tree and invokes the `synthesize` method on all constructs\. Constructs that implement `synthesize` can participate in synthesis and emit deployment artifacts to the resulting cloud assembly\. These constructs include AWS CloudFormation templates, AWS Lambda application bundles, file and Docker image assets, and other deployment artifacts\. [Cloud Assemblies](#apps_cloud_assembly) describes the output of this phase\. In most cases, you won’t need to implement the `synthesize` method + +5\. Deployment +In this phase, the AWS CDK CLI takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. + +By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: ++ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. ++ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)`\. See [Tokens](tokens.md) for details\. + +### Cloud Assemblies + +The call to `app.synth()` is what tells the AWS CDK to synthesize a cloud assembly from an app\. Typically you don't interact directly with cloud assemblies\. They are files that include everything needed to deploy your app to a cloud environment\. For example, it includes an AWS CloudFormation template for each stack in your app, and a copy of any file assets or Docker images that you reference in your app\. + +To interact with the cloud assembly that your AWS CDK app creates, you typically use the AWS CDK CLI\. But any tool that can read the cloud assembly format can be used to deploy your app\. + +To work with the CDK CLI, you need to let it know how to execute an AWS CDK app\. + +``` +cdk --app executable cdk-command +``` + +The \-\-appoption instructs the CLI to run your AWS CDK app, and its contents depend on the programming language you use\. Eventually it should be a program that the operating system can run\. You can also create the `cdk.json`file and add information to it so that you need to call only `cdk cdk-command`\. For example, for JavaScript apps, the `cdk.json` file might look like the following, where `node bin/my-app.js` executes a Node\.js program\. + +``` +{ + "app": "node bin/my-app.js" +} +``` + +**Note** +Use the `cdk init` command to create a language\-specific project, with a `cdk.json` file containing the correct configuration for the programming language you specify\. + +The *cdk\-command* part of the AWS CDK CLI command represents what you want the AWS CDK to do with the app\. + +The CLI can also interact directly with an already synthesized cloud assembly\. To do that, just pass the directory in which the cloud assembly is stored in `--app`\. The following example lists the stacks defined in the cloud assembly stored under `./my-cloud-assembly`\. + +``` +cdk --app ./my-cloud-assembly ls +``` \ No newline at end of file diff --git a/doc_source/apps_and_stacks.md b/doc_source/apps_and_stacks.md deleted file mode 100644 index bee7e0d6..00000000 --- a/doc_source/apps_and_stacks.md +++ /dev/null @@ -1,92 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Apps, Stacks, and Environments and Authentication - -The main artifact of a CDK program known as a *CDK app*\. This is an executable program that you can use to synthesize deployment artifacts that supporting tools, such as the CDK Toolkit, can deploy, as described in [AWS CDK Command Line Interface \(cdk\)](tools.md#cli)\. - -Stacks are CDK constructs that you can deploy into an AWS environment\. The combination of AWS Region and account becomes the stack's *environment*\. Most production apps consist of multiple stacks of resources that are deployed as a single transaction using a resource provisioning service such as AWS CloudFormation\. Any resources added directly or indirectly as children of a stack are included in the stack's template when it is synthesized by your CDK program\. - -Let's look at apps and stacks from the bottom up\. - -## Stacks - -Define an application stack by extending the [Stack]() class, as shown in the following example\. - -``` -import cdk = require("@aws-cdk/cdk"); -import s3 = require("@aws-cdk/aws-s3"); - -interface MyStackProps extends cdk.StackProps { - enc: boolean; -} - -export class MyStack extends cdk.Stack { - constructor(scope: cdk.App, id: string, props: MyStackProps) { - super(scope, id, props); - - if (props.enc) { - new s3.Bucket(this, "MyGroovyBucket", { - encryption: s3.BucketEncryption.KmsManaged - }); - } else { - new s3.Bucket(this, "MyGroovyBucket"); - } - } -} -``` - -Next we'll show you how to use one or more stacks to create a CDK app\. - -## Apps - -An [app]() is a collection of [stack]() objects, as shown in the following example\. - -``` -import cdk = require("@aws-cdk/cdk"); -import { MyStack } from "../lib/MyApp-stack"; - -const app = new cdk.App(); - -new MyStack(app, "MyWestCdkStack", { - env: { - region: "us-west-2" - }, - enc: false -}); - -new MyStack(app, "MyEastCdkStack", { - env: { - region: "us-east-1" - }, - enc: true -}); -``` - -Use the cdk ls command to list the stacks in this executable, as shown in the following example\. - -``` -MyEastCdkStack -MyWestCdkStack -``` - -Use the cdk deploy command to deploy an individual stack\. - -``` -cdk deploy MyWestCdkStack -``` - -## Environments and Authentication - -When you create a [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/stack.html) instance, you can supply the target deployment environment for the stack using the `env` property, as described in [Specifying Your Credentials and Region](getting_started.md#getting_started_credentials)\. - -We recommend that you use the default environment for development stacks, and explicitly specify accounts and regions using the `env` property for production stacks\. - -You can always find the Region within which your stack is deployed by using the `region` property of the stack, as follows\. - -``` -this.region -``` \ No newline at end of file diff --git a/doc_source/aspects.md b/doc_source/aspects.md new file mode 100644 index 00000000..7d208990 --- /dev/null +++ b/doc_source/aspects.md @@ -0,0 +1,52 @@ +# Aspects + +Aspects are the way to apply an operation to all constructs in a given scope\. The functionality could modify the constructs, such as by adding tags, or it could be verifying something about the state of the constructs, such as ensuring that all buckets are encrypted\. + +To apply an aspect to a construct and all constructs in the same scope, call [node\.applyAspect](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.ConstructNode.html#apply-aspectaspect) with a new aspect, as shown in the following example\. + +``` +myConstruct.node.applyAspect(new SomeAspect(...)); +``` + +The AWS CDK currently uses aspects only to [tag resources](tagging.md), but the framework is extensible and can also be used for other purposes\. For example, you can use it to validate or change the AWS CloudFormation resources that are defined for you\. + +## Aspects in Detail + +The AWS CDK implements tagging using a more generic system, called aspects, which is an instance of the visitor pattern\. An aspect is a class that implements the following interface\. + +``` +interface IAspect { + visit(node: IConstruct): void;} +``` + +When you call `construct.node.applyAspect(aspect)`, the construct adds the aspect to an internal list of aspects\. + +During the [prepare phase](apps.md#lifecycle), the AWS CDK calls the visit method of the object for the construct and each of its children in top\-down order\. + +Although the aspect object is free to change any aspect of the construct object, it only operates on a specific subset of construct types\. After determining the construct type, it can call any method and inspect or assign any property on the construct\. + +## Example + +The following example validates that all buckets created in the stack have versioning enabled\. The aspect adds an error to the constructs that fail the validation, which results in the synth operation failing and prevents deploying the resulting cloud assembly\. + +``` +class BucketVersioningChecker implements IAspect { + public visit(node: IConstruct): void { + // See that we're dealing with a CfnBucket + if (node instanceof s3.CfnBucket) { + + // Check for versioning property, exclude the case where the property + // can be a token (IResolvable). + if (!node.versioningConfiguration + || (!Tokenization.isResolvable(node.versioningConfiguration) + && node.versioningConfiguration.status !== 'Enabled')) { + + node.node.addError('Bucket versioning is not enabled'); + } + } + } +} + +// Apply to the stack +stack.node.applyAspect(new BucketVersioningChecker()); +``` \ No newline at end of file diff --git a/doc_source/assets.md b/doc_source/assets.md index dcb53e83..aefe91ee 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -1,11 +1,217 @@ --------- +# Assets -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. +Assets are local files, directories, or Docker images that can be bundled into AWS CDK libraries and apps; for example, a directory that contains the handler code for an AWS Lambda function\. Assets can represent any artifact that the app needs to operate\. --------- +You typically reference assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html#code) property enables you to pass an [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function’s code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-assetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. -# Assets +## Assets in Detail + +When you refer to an asset in your app, the [cloud assembly](apps.md#apps_cloud_assembly) synthesized from your application includes metadata information with instructions for the AWS CDK CLI on where to find the asset on the local disk, and what type of bundling to perform based on the type of asset, such as a directory to compress \(zip\) or a Docker image to build\. + +The AWS CDK generates a source hash for assets and can be used at construction time to determine whether the contents of an asset have changed\. + +By default, the AWS CDK creates a copy of the asset in the cloud assembly directory, which defaults to `cdk.out`, under the source hash\. This is so that the cloud assembly is self\-contained and moved over to a different host for deployment\. See [Cloud Assemblies](apps.md#apps_cloud_assembly) for details\. + +The AWS CDK also synthesizes AWS CloudFormation parameters that the AWS CDK CLI specifies during deployment\. The AWS CDK uses those parameters to refer to the deploy\-time values of the asset\. + +When the AWS CDK deploys an app that references assets \(either directly by the app code or through a library\), the AWS CDK CLI first prepares and publishes them to Amazon S3 or Amazon ECR, and only then deploys the stack\. The AWS CDK specifies the locations of the published assets as AWS CloudFormation parameters to the relevant stacks, and uses that information to enable referencing these locations within an AWS CDK app\. + +This section describes the low\-level APIs available in the framework\. + +## Asset Types + +The AWS CDK supports the following types of assets: + +Amazon S3 Assets +These are local files and directories that the AWS CDK uploads to Amazon S3\. + +Docker Image +These are Docker images that the AWS CDK uploads to Amazon ECR\. + +These asset types are explained in the following sections\. + +### Amazon S3 Assets + +You can define local files and directories as assets, and the AWS CDK packages and uploads them to Amazon S3 through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-assets-readme.html) module\. + +The following example defines a local directory asset and a file asset\. + +``` +import { Asset } from '@aws-cdk/aws-s3-assets'; + +// Archived and uploaded to Amazon S3 as a .zip file +const directoryAsset = new Asset(this, "SampleAsset", { + path: path.join(__dirname, "sample-asset-directory") +}); + +// Uploaded to Amazon S3 as-is +const fileAsset = new Asset(this, 'SampleAsset', { + path: path.join(__dirname, 'file-asset.txt') +}); +``` + +In most cases, you don’t need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods that enable you to use assets\. For Lambda functions, the [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) property enables you to specify a directory or a \.zip file in the local file system\. + +#### Lambda Function Example + +A common use case is to create AWS Lambda functions with the handler code, which is the entry point for the function, as an Amazon S3 asset\. + +The following example uses an Amazon S3 asset to define a handler in the local directory `handler` and creates a Lambda function with the local directory asset as the `code` property\. + +``` +def lambda_handler(event, context): + message = 'Hello World!' + return { + 'message': message + } +``` + +The code for the main AWS CDK app should look like the following\. + +``` +import cdk = require('@aws-cdk/core'); +import lambda = require('@aws-cdk/aws-lambda'); +import path = require('path'); + +export class HelloAssetStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + new lambda.Function(this, 'myLambdaFunction', { + code: lambda.Code.asset(path.join(__dirname, 'handler')), + runtime: lambda.Runtime.PYTHON_3_6, + handler: 'index.lambda_handler' + }); + } +} +``` + +The `Function` method uses assets to bundle the contents of the directory and use it for the function’s code\. + +#### Deploy\-Time Attributes Example + +Amazon S3 asset types also expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. + +The following example uses deploy\-time attributes to pass the location of an image asset into a Lambda function as environment variables\. + +``` +const imageAsset = new Asset(this, "SampleAsset", { + path: path.join(__dirname, “images/my-image.png") +}); + +new lambda.Function(this, "myLambdaFunction", { + code: lambda.Code.asset(path.join(__dirname, "handler")), + runtime: lambda.Runtime.PYTHON_3_6, + handler: "index.lambda_handler", + environment: { + 'S3_BUCKET_NAME': imageAsset.s3BucketName, + 'S3_OBJECT_KEY': imageAsset.s3ObjectKey, + 'S3_URL': imageAsset.s3Url + } +}); +``` + +#### Permissions + +If you use Amazon S3 assets directly through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-assets-readme.html) module, IAM roles, users, or groups, and need to read assets in runtime, grant those assets IAM permissions through the [asset\.grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3-assets.Asset.html#grant-readgrantee) method\. + +The following example grants an IAM group read permissions on a file asset\. + +``` +const asset = new Asset(this, 'MyFile', { + path: path.join(__dirname, 'my-image.png') +}); + +const group = new iam.Group(this, 'MyUserGroup'); + asset.grantRead(group); +} +``` + +### Docker Image Assets + +The AWS CDK supports bundling local Docker images as assets through the [aws\-ecr\-assets](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecr-assets-readme.html) module\. + +The following example defines a docker image that is built locally and pushed to Amazon ECR\. Images are built from a local Docker context directory \(with a Dockerfile\) and uploaded to Amazon ECR by the AWS CDK CLI or your app's CI/CD pipeline, and can be naturally referenced in your AWS CDK app\. + +``` +import { DockerImageAsset } from '@aws-cdk/aws-ecr-assets'; + +const asset = new DockerImageAsset(this, 'MyBuildImage', { + directory: path.join(__dirname, 'my-image') +}); +``` + +The `my-image` directory must include a Dockerfile\. The AWS CDK CLI builds a Docker image from `my-image`, pushes it to an Amazon ECR repository, and specifies the name of the repository as an AWS CloudFormation parameter to your stack\. Docker image asset types expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. + +#### Amazon ECS Task Definition Example + +A common use case is to create an Amazon ECS [TaskDefinition](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.TaskDefinition.html) to run docker containers\. The following example specifies the location of a Docker image asset that the AWS CDK builds locally and pushes to Amazon ECR\. + +``` +import ecs = require('@aws-cdk/aws-ecs'); +import path = require('path'); + +const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { + memoryLimitMiB: 1024, + cpu: 512 +}); + +taskDefinition.addContainer("my-other-container", { + image: ecs.ContainerImage.fromAsset(path.join(__dirname, "..", "demo-image")) +}); +``` + +#### Deploy\-Time Attributes Example + +The following example shows how to use the deploy\-time attributes `repository` and `imageUri` to create an Amazon ECS task definition with the AWS Fargate launch type\. + +``` +import ecs = require('@aws-cdk/aws-ecs'); +import path = require('path'); +import { DockerImageAsset } from '@aws-cdk/aws-ecr-assets'; + +const asset = new DockerImageAsset(this, 'my-image', { + directory: path.join(__dirname, "..", "demo-image") +}); + +const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { + memoryLimitMiB: 1024, + cpu: 512 +}); + +taskDefinition.addContainer("my-other-container", { + image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri) +}); +``` + +#### Build Arguments Example + +You can provide customized build arguments for the Docker build step through the `buildArgs` property option when the AWS CDK CLI builds the image during deployment\. + +``` +const asset = new DockerImageAsset(this, 'MyBuildImage', { + directory: path.join(__dirname, 'my-image'), + buildArgs: { + HTTP_PROXY: 'http://10.20.30.2:1234' + } +}); +``` + +#### Permissions + +If you use a module that supports Docker image assets, such as [aws\-ecs](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html), the AWS CDK manages permissions for you when you use assets directly or through [ContainerImage\.fromEcrRepository](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-ecr-repositoryrepository-tag)\. If you use Docker image assets directly, you need to ensure that the consuming principal has permissions to pull the image\. + +In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecr.Repository.html#grant-pullgrantee) method\. This modifies the IAM policy of the principal to enable it to pull images from this repository\. If the principal that is pulling the image is not in the same account or is an AWS service, such as AWS CodeBuild, that does not assume a role in your account, you must grant pull permissions on the resource policy and not on the principal's policy\. Use the [asset\.repository\.addToResourcePolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecr.Repository.html#add-to-resource-policystatement) method to grant the appropriate principal permissions\. + +## AWS CloudFormation Resource Metadata + +**Note** +This section is relevant only for construct authors\. In certain situations, tools need to know that a certain CFN resource is using a local asset\. For example, you can use the AWS SAM CLI to invoke Lambda functions locally for debugging purposes\. See [SAM CLI](tools.md#sam) for details\. + +To enable such use cases, external tools consult a set of metadata entries on AWS CloudFormation resources: ++ `aws:asset:path` – Points to the local path of the asset\. ++ `aws:asset:property` – The name of the resource property where the asset is used\. -Assets are local files, directories, or Docker images that can be bundled into CDK constructs and apps\. A common example is a directory that contains the handler code for an AWS Lambda function, however, assets can represent any artifact that the app needs to operate\. +Using these two metadata entries, tools can identify that assets are used by a certain resource, and enable advanced local experiences\. -When deploying a CDK app that includes constructs with assets, the CDK Toolkit first prepares and publishes them to Amazon Simple Storage Service \(Amazon S3\) or Amazon Elastic Container Registry \(Amazon ECR\), and only then deploys the stacks\. The locations of the published assets are passed in as AWS CloudFormation parameters to the relevant stacks\. \ No newline at end of file +To add these metadata entries to a resource, use the `asset.addResourceMetadata` method\. \ No newline at end of file diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 4446913e..e8fd55dd 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -1,193 +1,104 @@ --------- +# Escape Hatches -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. +It's possible that neither the high\-level constructs nor the low\-level CFN Resource constructs have a specific feature you are looking for\. There are three possible reasons for this lack of functionality: ++ The AWS service feature is available through AWS CloudFormation, but there are no Construct classes for the service\. ++ The AWS service feature is available through AWS CloudFormation, and there are Construct classes for the service, but the Construct classes don’t yet expose the feature\. ++ The feature is not yet available through AWS CloudFormation\. --------- +To determine whether a feature is available through AWS CloudFormation, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. -# Work Around Missing AWS CDK Features +## Using AWS CloudFormation Constructs Directly -This topic describes how to modify the underlying AWS CloudFormation resources in the AWS Construct Library\. We also call this technique an "escape hatch" because it allows users to "escape" from the abstraction boundary defined by the AWS construct, and patch the underlying resources\. +If there are no Construct classes available for the service, you can fall back to the automatically generated CFN Resources, which map 1:1 onto all available AWS CloudFormation resources and properties\. These resources can be recognized by their name starting with `Cfn`, such as `CfnBucket` or `CfnRole`\. You instantiate them exactly as you would use the equivalent AWS CloudFormation resource\. For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. -**Important** -We don't recommend this method because it breaks the abstraction layer and might produce unexpected results\. -If you modify an AWS construct in this way, we can't ensure that your code will be compatible with subsequent releases\. - -AWS constructs, such as [Topic](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns/topic.html), encapsulate one or more AWS CloudFormation resources behind their APIs\. These resources are also represented as `CfnXxx` constructs in each library\. For example, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct encapsulates the [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/cfnbucket.html)\. When a stack that includes an AWS construct is synthesized, the AWS CloudFormation definitions of the underlying resources are included in the resulting template\. - -Eventually, we expect the APIs provided by AWS constructs to support all of the services and capabilities offered by AWS\. But we're aware that the library still has many gaps, both at the service level \(some services don't have any constructs yet\) and at the resource level \(an AWS construct exists, but some features are missing\)\. - -**Note** -If you encounter a missing capability in the AWS Construct Library, whether it's an entire library, a specific resource, or a feature, create an [issue](https://github.com/awslabs/aws-cdk/issues/new) on GitHub and let us know\. - -This section describes the following use cases: -+ How to access the low\-level AWS CloudFormation resources encapsulated by an AWS construct -+ How to specify resource options, such as metadata, and dependencies on resources -+ How to add overrides to AWS CloudFormation resources and property definitions -+ How to directly define low\-level AWS CloudFormation resources without an AWS construct - -You can also find more information about how to work directly with the AWS CloudFormation layer in [AWS Construct Library](aws_construct_lib.md)\. - -## Accessing Low\-Level Resources - -Use [construct\.findChild\(\)](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.Construct.findChild) to access any child of a construct by its construct ID\. By convention, the main resource of any AWS construct is named **Resource**\. - -The following example shows how to access the underlying Amazon Simple Storage Service \(Amazon S3\) bucket resource, given a [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct\. +For example, to instantiate a low\-level Amazon S3 bucket CFN Resource with analytics enabled, you would write something like the following\. ``` -// Create an AWS bucket construct -const bucket = new s3.Bucket(this, 'MyBucket'); - -// The main construct is named "Resource" and -// its type is s3.CfnBucket; const -const bucketResource = bucket.node.findChild('Resource') as s3.CfnBucket; +new s3.CfnBucket(this, 'MyBucket', { + analyticsConfigurations: [ + { + id: 'Config', + // ... + } + ] +}); ``` -The `bucketResource` represents the low\-level AWS CloudFormation resource of type [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/cfnbucket.html) that's encapsulated by the bucket\. - -If the child can't be located, [construct\.findChildren\(id\)](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3#@aws-cdk/cdk.Construct.findChild) fails\. This means that if the underlying AWS Construct Library changes the IDs or structure for some reason, synthesis fails\. - -You can also use [construct\.children](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3#@aws-cdk/cdk.Construct.children) for more advanced queries\. For example, you can look for a child that has a certain AWS CloudFormation resource type\. +In the rare case where you want to define a resource that doesn't have a corresponding `CfnXxx` class, such as a new resource that wasn't published yet in the AWS CloudFormation resource specification, you can instantiate the `cdk.CfnResource` directly and specify the resource type and properties\. This is shown in the following example\. ``` -const bucketResource = - bucket.children.find(c => (c as cdk.Resource).resourceType === 'AWS::S3::Bucket') - as s3.CfnBucket; +new cdk.CfnResource(this, 'MyBucket', { + type: 'AWS::S3::Bucket', + properties: { + // Note the PascalCase here! + AnalyticsConfigurations: [ + { + Id: 'Config', + // ... + } + ] + } +}); ``` -Once you have a AWS CloudFormation resource, you are interacting with AWS CloudFormation resource classes, which extend [cdk\.CfnResource](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource)\. - -## Resource Options +For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. -Set resource options using [cdk\.CfnResource](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource) properties such as *Metadata* and *DependsOn*\. +## Modifying the AWS CloudFormation Resource behind AWS Constructs -For example, the following code: +If an Construct is missing a feature or you are trying to work around an issue, you can modify the CFN Resource that is encapsulated by the Construct\. -``` -const bucketResource = bucket.node.findChild('Resource') as s3.CfnBucket; - -bucketResource.options.metadata = { MetadataKey: 'MetadataValue' }; -bucketResource.options.updatePolicy = { - autoScalingRollingUpdate: { - pauseTime: '390' - } -}; - -bucketResource.addDependency(otherBucket.node.findChild('Resource') as cdk.Resource); -``` +All Constructs contain within them the corresponding CFN Resource\. For example, the high\-level `Bucket` construct wraps the low\-level `CfnBucket` construct\. Because the `CfnBucket` corresponds directly to the AWS CloudFormation resource, it exposes all features that are available through AWS CloudFormation\. -Synthesizes into the following template\. +The basic approach to get access to the CFN Resource class is to use `construct.node.defaultChild`, cast it to the right type for the resource, and modify its properties\. Again, let’s take the example of a `Bucket`\. ``` -{ - "Type": "AWS::S3::Bucket", - "DependsOn": [ "Other34654A52" ], - "UpdatePolicy": { - "AutoScalingRollingUpdate": { - "PauseTime": "390" - } - }, - "Metadata": { - "MetadataKey": "MetadataValue" - } -} -``` +// Get the AWS CloudFormation resource +const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; -## Raw Overrides +// Change its properties +cfnBucket.analyticsConfiguration = [ + { + id: 'Config', + // ... + } +]; +``` - Use the [cdk\.CfnResource\.addOverride\(path, value\)](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource.addOverride) method to define an override that is applied to the resource definition during synthesis, as shown in the following example\. +You can also use this object to change AWS CloudFormation options such as `Metadata` and `UpdatePolicy`\. ``` -// Define an override at the resource definition root, you can even modify the "Type" -// of the resource if needed. -bucketResource.addOverride('Type', 'AWS::S3::SpecialBucket'); - -// fine an override for a property (both are equivalent operations): -bucketResource.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); -bucketResource.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); - -// se dot-notation to define overrides in complex structures which will be merged -// with the values set by the higher-level construct -bucketResource.addPropertyOverride('LoggingConfiguration.DestinationBucketName', otherBucket.bucketName); - -// It's also possible to assign a null value -bucketResource.addPropertyOverride('Foo.Bar', null); +cfnBucket.cfnOptions.metadata = { + MetadataKey: 'MetadataValue' +}; ``` -This synthesizes to the following\. +## Raw Overrides -``` -{ - "Type": "AWS::S3::SpecialBucket", - "Properties": { - "Foo": { - "Bar": null - }, - "VersioningConfiguration": { - "Status": "NewStatus" - }, - "LoggingConfiguration": { - "DestinationBucketName": { - "Ref": "Other34654A52" - } - } - } -} -``` +If there are properties that are missing from the CFN Resource, you can bypass all typing using raw overrides\. This also makes it possible to delete synthesized properties\. -Use `undefined`, [cdk\.CfnResource\.addDeletionOverride](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource.addDeletionOverride), or [cdk\.CfnResource\.addPropertyDeletionOverride](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource.addPropertyDeletionOverride) to delete values\. +Use one of the `addOverride` or `addDeletionOverride` methods, as shown in the following example\. ``` -const bucket = new s3.Bucket(this, 'MyBucket', { - versioned: true, - encryption: s3.BucketEncryption.KmsManaged -}); - -const bucketResource = bucket.node.findChild('Resource') as s3.CfnBucket; -bucketResource.addPropertyOverride('BucketEncryption.ServerSideEncryptionConfiguration.0.EncryptEverythingAndAlways', true); -bucketResource.addPropertyDeletionOverride('BucketEncryption.ServerSideEncryptionConfiguration.0.ServerSideEncryptionByDefault'); -``` +// Get the AWS CloudFormation resource +const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; -This synthesizes to the following\. +// Use dot notation to address inside the resource template fragment +cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); +cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); -``` -{ - "MyBucketF68F3FF0": { - "Type": "AWS::S3::Bucket", - "Properties": { - "BucketEncryption": { - "ServerSideEncryptionConfiguration": [ - { - "EncryptEverythingAndAlways": true - } - ] - }, - "VersioningConfiguration": { - "Status": "Enabled" - } - } - } -} +// addPropertyOverride is a convenience function, which implies the +// path starts with "Properties." +cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); +cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); ``` -## Directly Defining AWS CloudFormation Resources +## Custom Resources -You can also explicitly define AWS CloudFormation resources in your stack\. To do this, instantiate one of the `CfnXxx` constructs of the dedicated library\. +If the feature isn't available through AWS CloudFormation, but only through a direct API call, the only solution is to write an AWS CloudFormation Custom Resource to make the API call you need\. Don’t worry, the AWS CDK makes it easier to write these, and wrap them up into a regular construct interface, so from another user’s perspective the feature feels native\. -``` -new s3.CfnBucket(this, 'MyBucket', { - analyticsConfigurations: [ - // ... - ] -}); -``` - -In the rare case where you want to define a resource that doesn't have a corresponding `CfnXxx` class \(such as a new resource that wasn't published yet in the AWS CloudFormation resource specification\), you can instantiate the [cdk\.CfnResource](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk.html#@aws-cdk/cdk.CfnResource)\. +Building a custom resource involves writing a Lambda function that responds to a resource’s CREATE, UPDATE and DELETE lifecycle events\. If your custom resource needs to make only a single API call, consider using the [AwsCustomResource](https://github.com/awslabs/aws-cdk/tree/master/packages/%40aws-cdk/custom-resources)\. This makes it possible to perform arbitrary SDK calls during an AWS CloudFormation deployment\. Otherwise, you should write your own Lambda function to perform the work you need to get done\. -``` -new cdk.Resource(this, 'MyBucket', { - type: 'AWS::S3::Bucket', - properties: { - AnalyticsConfiguration: [ /* ... */ ] // note the PascalCase here - } -}); -``` \ No newline at end of file +The subject is too broad to completely cover here, but the following links should get you started: ++ [Custom Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) ++ [Custom\-Resource Example](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) ++ For a more fully fledged example, see the [DnsValidatedCertificate](https://github.com/awslabs/aws-cdk/blob/master/packages/@aws-cdk/aws-certificatemanager/lib/dns-validated-certificate.ts) class in the CDK standard library\. This is implemented as a custom resource\. \ No newline at end of file diff --git a/doc_source/cloudformation.md b/doc_source/cloudformation.md deleted file mode 100644 index bb708737..00000000 --- a/doc_source/cloudformation.md +++ /dev/null @@ -1,14 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# AWS CloudFormation - -The [AWS Construct Library](aws_construct_lib.md) includes constructs with APIs for defining AWS infrastructure\. For example, you can use the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct to define Amazon Simple Storage Service \(Amazon S3\) buckets, and the [Topic](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sns/topic.html) construct to define Amazon Simple Notification Service \(Amazon SNS\) topics\. - -Under the hood, these constructs are implemented using AWS CloudFormation resources, which are available in the `CfnXxx` classes in each library\. For example, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct uses the [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/cfnbucket.html) resource \(as well as other resources, depending on what bucket APIs are used\)\. - -**Important** -Avoid interacting directly with AWS CloudFormation unless absolutely necessary, such as when a CDK AWS Construct Library does not provide the needed functionality\. \ No newline at end of file diff --git a/doc_source/constructs.md b/doc_source/constructs.md index d8d2e36b..325dc02b 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -1,163 +1,187 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Constructs -You can think of constructs as *cloud components*\. They can represent architectures of any complexity\. They can represent a single resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket or an Amazon Simple Notification Service \(Amazon SNS\) topic\. They can represent reusable components, such as a static website, a part of a specific application, or complex, multistack applications that span multiple accounts and AWS Regions\. Constructs can also include other constructs\. Everything in the AWS CDK is a construct\. +Constructs are the basic building blocks of AWS CDK apps\. A construct represents a "cloud component" and encapsulates everything AWS CloudFormation needs to create the component\. -This composition of constructs means that you can create sharable constructs\. For example, if construct A and construct B use construct C and you make changes to construct C, then and both construct A and construct B get those changes\. +A construct can represent a single resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can represent a higher\-lever component consisting of multiple AWS CDK resources\. Examples of such components include a worker queue with its associated compute capacity, a cron job with monitoring resources and a dashboard, or even an entire app spanning multiple AWS accounts and regions\. -## The AWS CloudFormation Resource Library +## AWS Construct Library -The AWS CDK provides a class library of constructs called the **AWS CloudFormation Resource Library**\. This library consists of constructs that represent all the resources available on AWS\. +The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html), which contains constructs representing AWS resources\. -Each module in the AWS Construct Library includes two types of constructs for each resource: low\-level constructs known as an AWS CloudFormation Resource constructs and high\-level constructs known as an AWS Construct Library constructs\. +This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html)` class represents an Amazon DynamoDB table\. -The CDK creates the low\-level resources from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) on a regular basis\. Low\-level constructs are named **Cfn***Xyz*, where *Xyz* represents the name of the resource\. These constructs provide direct, one\-to\-one access to how a resource is synthesized in the AWS CloudFormation template produced by your CDK app\. Using low\-level resources requires you to explicitly configure all resource properties, IAM policies, and have a deep understanding of the details\. +There are different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources*\. These constructs represent all of the AWS resources that are available in AWS CloudFormation\. CFN Resources are generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) on a regular basis\. They are named **Cfn***Xyz*, where *Xyz* represents the name of the resource\. For example, [s3\.CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) CFN Resource\. When you use CFN constructs, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying resource model\. -High\-level resource constructs are authored by AWS and offer an intent\-based API for using AWS services\. They provide the same functionality as the low\-level resources, but encode much of the details, boilerplate, and glue logic required to use AWS\. High\-level resources offer convenient defaults and additional knowledge about the inner workings of the AWS resources they represent\. +The next level of constructs also represent AWS resources, but with a higher\-level, intent\-based API\. They provide the same functionality, but handle much of the details, boilerplate, and glue logic required by CFN constructs\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#aws_s3_Bucket) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#aws_s3_Bucket_addLifecycleRule), which adds a lifecycle rule to the bucket\. -Similarly to the AWS SDKs and AWS CloudFormation, the AWS Construct Library is organized into modules, one for each AWS service\. For example, the `@aws-cdk/aws-ec2` module includes resources for Amazon EC2 instances and networking\. The `aws-sns` module includes resources such as `Topic` and `Subscription`\. See the [Reference](https://docs.aws.amazon.com/cdk/api/latest) for descriptions of the CDK packages and constructs\. +Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.LoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs-patterns.LoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing Elastic Load Balancing \(ELB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. -AWS Construct Library members are found in the `@aws-cdk/aws-NAMESPACE` packages, where `NAMESPACE` is the short name for the associated service, such as `SQS` for the AWS Construct Library for the Amazon Simple Queue Service \(Amazon SQS\) service\. +For more information about how to navigate the library and discover constructs that can help you build your apps, see the [API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html)\. -## Construct Structure +## Composition -Constructs are represented as normal classes in your code and are defined by instantiating an object of that class\. +The key pattern for defining higher\-level abstractions through constructs is called *composition*\. A high\-level construct can be composed from any number of lower\-level constructs, and in turn, those could be composed from even lower\-level constructs\. To enable this pattern, constructs are always defined within the scope of another construct\. This scoping pattern results in a hierarchy of constructs known as a *construct tree*\. In the AWS CDK, the root of the tree represents your entire **[AWS CDK app](https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#apps)**\. Within the app, you typically define one or more **[stacks](https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#stacks)**, which are the unit of deployment, analogous to AWS CloudFormation stacks\. Within stacks, you define resources, or other constructs that eventually contain resources\. -When constructs are initialized, they are always defined within the *scope* of another construct, and always have an *id* that must be unique within the same scope\. +Composition of constructs means that you can define reusable components and share them like any other code\. For example, a central team can define a construct that implements the company's best practice for a DynamoDB table with backup, global replication, auto\-scaling, and monitoring, and share it with teams across a company or publicly\. Teams can now use this construct as they would any other library package in their favorite programming language to define their tables and comply with their team's best practices\. When the library is updated, developers can pick up the updates and enjoy any bug fixes and improvements through the workflows they already have for their other types of code\. -For example, here's how you would define an Amazon SNS `topic` in your stack with default configuration\. +## Initialization -``` -new sns.Topic(this, 'MyTopic'); -``` +Constructs are implemented in classes that extend the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html) base class\. You define a construct by instantiating the class\. All constructs take three parameters when they are initialized: ++ **scope** – The construct within which this construct is defined\. You should almost always pass `this` for the scope, because it represents the current scope in which you are defining the construct\. ++ **id** – An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's encapsulated within the scope's subtree and is used to allocate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. ++ **props** – A set of properties or keyword arguments, depending upon the supported language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. -The first argument to every construct is always the scope in which it's created, and is almost always `this`, because most constructs are defined within the current scope\. +Iidentifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/tag.html) or for specifying where the constructs will be deployed\. -Scopes enable constructs to be composed together to form higher\-level abstractions\. This is done by enabling the framework to group them together into logical units, allocate globally unique identifiers, and allow them to consult context information, such as the AWS Region in which it's going to be deployed and which availability Zones are available for your account\. +## Apps and Stacks -In most cases, the construct initializer has a third `props` argument that can be used to define the construct's initial configuration\. For example: +We call your CDK application an *app*, which is represented by the AWS CDK class [App](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/app.html)\. The following example defines an app with a single stack that contains a single Amazon S3 bucket with versioning enabled: ``` -new MyConstruct(this, 'Foo', { - favoriteColor: 'green', - timeout: 300 -}); -``` - -Use the `construct.node` property to get the following information about the construct\. - - construct\.node\.scope -Gets the scope in which the construct was defined\. +import { App, Stack, StackProps } from '@aws-cdk/core'; +import s3 = require('@aws-cdk/aws-s3'); - construct\.node\.id -Gets the `id` of the construct\. +class HelloCdkStack extends Stack { + constructor(scope: App, id: string, props?: StackProps) { + super(scope, id, props); - construct\.node\.uniqueId -Gets the app\-wide unique, safe ID of the construct\. This ID encodes the construct's path into a human\-readable portion and a hash of the full path to ensure global uniqueness\. - - construct\.node\.path -Gets the full path of this construct from the root of the scope \(the `App`\)\. + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} -## Construct IDs +const app = new App(); +new HelloCdkStack(app, "HelloCdkStack"); +``` -Every construct in a CDK app must have an `id` that's unique within the scope in which the construct is defined\. The CDK uses IDs to find constructs in the construct hierarchy\. It also uses IDs to allocate logical IDs so that AWS CloudFormation can keep track of the generated resources\. +As you can see, you need a scope within which to define your bucket\. Since resources eventually need to be deployed as part of a AWS CloudFormation stack into an *AWS *[https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#environments](https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#environments), which covers a specific AWS account and AWS region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/stack.html#cdk_Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/stack.html#cdk_Stack)\. -When a construct is created, its ID is specified as the second initializer argument\. +Stacks in AWS CDK apps extend the **Stack** base class, as shown in the previous example\. This is a common pattern when creating a stack within your AWS CDK app: extend the **Stack** class, define a constructor that accepts **scope**, **id**, and **props**, and invoke the base class constructor via `super` with the received **scope**, **id**, and **props**, as shown in the following example\. ``` -const c1 = new MyConstruct(this, 'OneConstruct'); -const c2 = new MyConstruct(this, 'TwoConstruct'); -assert(c1.node.id === 'OneConstruct'); -assert(c2.node.id === 'TwoConstruct'); +class HelloCdkStack extends Stack { + constructor(scope: App, id: string, props?: StackProps) { + super(scope, id, props); + + //... + } +} ``` -Notice that the ID of a construct doesn't directly map to the physical name of the resource when it's created\. To give a physical name to a bucket or table, specify the physical name using the appropriate property, such as `bucketName` or `tableName`, as shown in the following example\. +## Using Constructs + +Once you have defined a stack, you can populate it with resources\. The following example imports the [Amazon S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) module and uses it to define a new Amazon S3 bucket by creating an instance of the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class within the current scope \(`this`\) which, in our case is the `HelloCdkStack` instance\. ``` -new s3.Bucket(this, 'MyBucket', { - bucketName: 'physical-bucket-name' +import s3 = require('@aws-cdk/aws-s3'); + +// "this" is HelloCdkStack +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true }); ``` -We recommend that you avoid specifying physical names\. Instead, let AWS CloudFormation generate names for you\. Use attributes, such as `bucket.bucketName`, to discover the generated names\. +The [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) includes constructs that represent many AWS resources\. -When you synthesize a CDK app into an AWS CloudFormation template, the AWS CloudFormation logical ID for each resource in the template is allocated according to the path of that resource in the scope hierarchy\. +**Note** +`MyFirstBucket` is not the name of the bucket that AWS CloudFormation creates\. It is a logical identifier given to the new construct\. See [Physical Names](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/resource.html#core_Resource_physicalName) for details\. -## Construct Properties +## Configuration -Customize constructs by passing a property object as the third parameter \(*props*\)\. Every construct has its own set of properties, defined as an interface\. You can pass a property object to your construct in two ways: inline, or instantiated as a separate property object\. +Most constructs accept `props` as their third initialization argument\. This is a name/value collection that defines the construct’s configuration\. The following example defines a bucket with AWS Key Management Service \(AWS KMS\) encryption and static website hosting enabled\. Since it does not explicitly specify an encryption key, the `Bucket` construct defines a new `kms.Key` and associates it with the bucket\. ``` -// Inline (recommended) -new sqs.Queue(this, 'MyQueue', { - visibilityTimeout: 300 +new s3.Bucket(this, 'MyEncryptedBucket', { + encryption: s3.BucketEncryption.Kms, + websiteIndexDocument: 'index.html' }); +``` -// Instantiate separate property object -const props: QueueProps = { - visibilityTimeout: 300 -}; + AWS constructs are designed around the concept of "sensible defaults\." Most constructs have a minimal required configuration, enabling you to quickly get started while also providing full control over the configuration when you need it\. -new Queue(this, 'MyQueue', props); -``` +## Interacting with Constructs -## Construct Metadata +Constructs are classes that extend the base [Construct](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/construct.html) class\. After you instantiate a construct, the construct object exposes a set of methods and properties that enable you to interact with the construct and pass it around as a reference to other parts of the system\. The AWS CDK framework doesn't put any restrictions on the APIs of constructs; authors can define any API they wish\. However, the AWS constructs that are included with the AWS Construct Library, such as `s3.Bucket`, follow guidelines and common patterns in order to provide a consistent experience across all AWS resources\. -Attach metadata to a construct using the `addMetadata` method\. Metadata is an AWS CDK\-level annotation, and as such, does not appear in the deployed resources\. Metadata entries automatically include the stack trace from which the metadata entry was added to allow tracing back to your code, even if the entry was defined by a lower\-level library that you don't own\. +For example, almost all AWS constructs have a set of [grant](permissions.md#permissions_grants) methods that you can use to grant AWS Identity and Access Management \(IAM\) permissions on that construct to a principal\. The following example grants the IAM group `data-science` permission to read from the Amazon S3 bucket `raw-data`\. -Use the `addWarning()` method to emit a message when you you synthesis a stack; use the `addError()` method to not only emit a message when you you synthesis a stack, but to also block the deployment of a stack\. +``` +const rawData = new s3.Bucket(this, 'raw-data'); +const dataScience = new iam.Group(this, 'data-science'); +rawData.grantRead(dataScience); +``` -The following example blocks the deployment of `myStack` if it is not in `us-west-2`: +Another common pattern is for AWS constructs to set one of the resource’s attributes, such as its Amazon Resource Name \(ARN\), name, or URL from data supplied elsewhere\. For example, the following code defines an AWS Lambda function and associates it with an Amazon Simple Queue Service \(Amazon SQS\) queue through the queue's URL in an environment variable\. ``` -if (myStack.region !== 'us-west-2') { - myStack.node.addError('myStack is not in us-west-2'); -} +const jobsQueue = new sqs.Queue(this, 'jobs'); +const createJobLambda = new lambda.Function(this, 'create-job', { + runtime: lambda.Runtime.NODEJS_8_10, + handler: 'index.handler', + code: lambda.Code.asset('./create-job-lambda-code'), + environment: { + QUEUE_URL: jobsQueue.queueUrl + } +}); ``` -## Tagging Constructs +For information about the most common API patterns in the AWS Construct Library, see [Resources](https://docs.aws.amazon.com/cdk/latest/guide/resources.html)\. -You can add a tag to any construct to identify the resources you create\. Tags can be applied to any construct\. Tags are inherited, and are based on scope\. If you tag construct `A`, and construct `A` contains construct `B`, construct `B` inherits the tag\. +## Authoring Constructs -There are two tag operations\. +In addition to using existing constructs like `s3.Bucket`, you can also author your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct imported from a third\-party library that someone published on npm or Maven or PyPI—or to your company's internal package repository\. -Tag -Adds \(or applies\) a tag to a set of resources, or to all but a set of resources\. +To declare a new construct, create a class that extends the [Construct](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/construct.html) base class, then follow the pattern for initializer arguments\. -RemoveTag -Removes a tag from a set of resources, or from all but a set of resources\. +For example, you could declare a construct that represents an Amazon S3 bucket which sends an Amazon Simple Notification Service \(Amazon SNS\) notification every time someone uploads a file into it: -The following example adds the tag key\-value pair *StackType*\-*TheBest* to any resource created within the **theBestStack** stack labeled *MarketingSystem*\. +``` +export interface NotifyingBucketProps { + prefix?: string; +} +export class NotifyingBucket extends Construct { + constructor(scope: Construct, id: string, props: NotifyingBucketProps = {}) { + super(scope, id); + const bucket = new s3.Bucket(this, 'bucket'); + const topic = new sns.Topic(this, 'topic'); + bucket.onObjectCreated(topic, { prefix: props.prefix }); + } +} ``` -import cdk = require('@aws-cdk/cdk'); -const app = new cdk.App(); -const theBestStack = new cdk.Stack(app, 'MarketingSystem'); -theBestStack.node.apply(new cdk.Tag('StackType', 'TheBest')); - -// To remove the tag: -theBestStack.node.apply(new cdk.RemoveTag('TheBest')); - -// To remove the tag from all EXCEPT the subnets: -theBestStack.node.apply(new cdk.RemoveTag('TheBest'), {excludeResourceTypes: ['AWS::EC2::Subnet']})); +The `NotifyingBucket` constructor has the same signature as the base `Construct` class: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. This means that you could define an instance of this construct in your app without `props`, for example: + ``` +new NotifyingBucket(this, 'MyNotifyingBucket'); +``` + +Or you could use `props` to specify the path prefix to filter on, for example: -The tag operations include some properties to fine\-tune how tags are applied to or removed from the resources that the construct creates\. +``` +new NotifyingBucket(this, 'MyNotifyingBucket', { prefix: 'images/' }); +``` -applyToLaunchedInstances -Use this Boolean property to set `PropagateAtLaunch` for any Auto Scaling group resource the construct creates\. The default is `true`\. +Typically, you would also want to expose some properties or methods from your constructs\. For example, it's not very useful to have a topic hidden behind your construct, because it wouldn't be possible to subscribe to it\. Adding a `topic` property allows consumers to access the inner topic, as shown in the following example: -includeResourceTypes -Use this array of strings to apply a tag only to those AWS CloudFormation resource types\. The default is an empty array, which means the tag applies to all AWS CloudFormation resource types\. +``` +export class NotifyingBucket extends Construct { + public readonly topic: sns.Topic; + + constructor(scope: Construct, id: string, props: NotifyingBucketProps) { + super(scope, id); + const bucket = new s3.Bucket(this, 'bucket'); + this.topic = new sns.Topic(this, 'topic'); + bucket.onObjectCreated(this.topic, { prefix: props.prefix }); + } +} +``` -excludeResourceTypes -Use this array of strings to exclude a tag from those AWS CloudFormation resource types\. The default is an empty array, which means the tag applies to all AWS CloudFormation resource types\. This property takes precedence over the `includeResourceTypes` property\. +Now, consumers can subscribe to the topic, for example: -priority -Set this integer value to control the precedence of tags\. The default is 0 \(zero\) for `Tag` and 1 for `RemoveTag`\. Higher values take precedence over lower values\. \ No newline at end of file +``` +const queue = new sqs.Queue(this, 'NewImagesQueue'); +const images = new NotificationBucket(this, 'Images'); +images.topic.addSubscription(new sns_sub.QueueSubscription(queue)); +``` \ No newline at end of file diff --git a/doc_source/context.md b/doc_source/context.md index 5e489d7c..a20ce8be 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -1,35 +1,59 @@ --------- +# Runtime Context -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. +The AWS CDK uses context to retrieve information such as the Availability Zones in your account or Amazon Machine Image \(AMI\) IDs used to start your instances\. To avoid unexpected changes to your deployments, such as when a new Amazon Linux AMI is released, thus changing your Auto Scaling group, the AWS CDK stores context values in the `cdk.context.json` file within your project\. This ensures that the AWS CDK retrieves the same value the next time it synthesizes your app\. Don't forget to put this file under version control\. --------- +## Construct Context -# Run\-Time Context +You can provide context values in three different ways: ++ Automatically by the AWS CDK CLI after required information, such as the list of Availability Zones, is looked up from the current AWS account\. ++ Provided by the user through the CLI using the \-\-context option, or in the `context` key of the `cdk.json` file\. ++ Set in code using the `construct.node.setContext` method\. -The CDK uses context to retrieve information such as the Availability Zones in your account or Amazon Machine Image \(AMI\) IDs used to start your instances\. To avoid unexpected changes to your deployments, such as when a new Amazon Linux AMI is released, thus changing your Auto Scaling group, the CDK stores context values in `cdk.context.json`\. This ensures that the CDK retrieves the same value the next time it synthesises your app\. Don't forget to put this file under version control\. +Context entries are scoped to the construct that created them: they are visible to children constructs, but not to siblings\. Context entries that are set by the CLI, either automatically or from the \-\-context option, are implicitly set on the `App` construct, and are visible to the app\. + +You can get context information using the `construct.node.tryGetContext` method, which returns the value set on the current construct if it is present\. Otherwise, it resolves the context from the current construct’s parent, until it has reached the `App` construct\. + +## Context Methods + +The AWS CDK supports several context methods that enable AWS CDK apps to get contextual information\. For example, you can get a list of Availability Zones that are available in a given AWS account and AWS Region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) method\. + +The following are the context methods: + +[HostedZone\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-route53.HostedZone.html#static-from-lookupscope-id-query) +Gets the hosted zones in your account\. + +[stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) +Gets the supported Availability Zones\. + +StringParameter\.valueFromLookup +Gets a value from the current Region's AWS Systems Manager Parameter Store\. + +Vpc\.fromLookup +Gets the existing VPCs in your accounts\. + +If a given context information isn't available, the AWS CDK app notifies the AWS CDK CLI that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. + +Don't forget to add the `cdk.context.json` file to your source control repository to ensure that subsequent synth commands will return the same result, and that your AWS account won’t be needed when synthesizing from your build system\. ## Viewing and Managing Context -Use the cdk context to see context values stored for your application\. The output should be something like the following\. +Use the cdk context command to view and manage the information in your `cdk.context.json` file\. To see this information, use the cdk context command without any options\. The output should be something like the following\. ``` Context found in cdk.json: - -┌───┬────────────────────────────────────────────────────┬────────────────────────────────────────────────────┐ -│ # │ Key │ Value │ -├───┼────────────────────────────────────────────────────┼────────────────────────────────────────────────────┤ -│ 1 │ availability-zones:account=123456789012:region=us- │ [ "us-east-1a", "us-east-1b", "us-east-1c", │ -│ │ east-1 │ "us-east-1d", "us-east-1e", "us-east-1f" ] │ -├───┼────────────────────────────────────────────────────┼────────────────────────────────────────────────────┤ -│ 2 │ ssm:account=123456789012:parameterName=/aws/ │ "ami-013be31976ca2c322" │ -│ │ service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_ │ │ -│ │ 64-gp2:region=us-east-1 │ │ -└───┴────────────────────────────────────────────────────┴────────────────────────────────────────────────────┘ + +┌───────────────────────────────────────────────────────────────────────────| +│ # | Key │ Value | +├───────────────────────────────────────────────────────────────────────────| +│ 1 | availability-zones:account=123456789012:region=eu-central-1 │ [ "eu-central-1a", "eu-central-1b", "eu-central-1c" ] | +├───────────────────────────────────────────────────────────────────────────| +│ 2 | availability-zones:account=123456789012:region=eu-west-1 │ [ "eu-west-1a", "eu-west-1b", "eu-west-1c" ] | +└───────────────────────────────────────────────────────────────────────────| Run cdk context --reset KEY_OR_NUMBER to remove a context key. It will be refreshed on the next CDK synthesis run. ``` -If at some point you want to update to the latest version of the Amazon Linux AMI, do a controlled update of the context value, reset it, and synthesize again\. +To remove a context value, run cdk context \-\-reset, specifying the value's corresponding key number\. The following example removes the value that corresponds to the key value of `2` in the preceding example, which is the Amazon Linux AMI ID\. ``` $ cdk context --reset 2 @@ -37,10 +61,12 @@ $ cdk context --reset 2 ``` Context value -ssm:account=123456789012:parameterName=/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2:region=us-east-1 +availability-zones:account=123456789012:region=eu-west-1 reset. It will be refreshed on the next SDK synthesis run. ``` +Therefore, if you want to update to the latest version of the Amazon Linux AMI, you can use the preceding example to do a controlled update of the context value and reset it, and then synthesize and deploy your app again\. + ``` cdk synth ``` @@ -49,56 +75,8 @@ cdk synth ... ``` -To clear all context values, run cdk context \-\-clear\. +To clear all of the stored context values for your app, run cdk context \-\-clear, as follows\. ``` cdk context --clear -``` - -## Context Providers - -The AWS CDK currently supports the following context providers\. - -[AvailabilityZoneProvider](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/availabilityzoneprovider.html) -Use this provider to get the list of all supported Availability Zones in this context, as shown in the following example\. - -``` -// "this" refers to a Construct scope -const zones: string[] = new AvailabilityZoneProvider(this).availabilityZones; - -for (let zone of zones) { - // Do something for each zone! -} -``` - -[HostedZoneProvider](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-route53/hostedzoneprovider.html) -Use this provider to discover existing hosted zones in your account\. For example, the following code imports an existing hosted zone into your CDK app so you can add records to it\. - -``` -const zone: HostedZoneRef = new HostedZoneProvider(this, { - domainName: 'test.com' -}).findAndImport(this, 'HostedZone'); -``` - -[SSMParameterProvider](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/ssmparameterprovider.html) -Use this provider to read values from the current Region's AWS Systems Manager parameter store\. For example, the following code returns the value of the *my\-awesome\-parameter* key\. - -``` -const ami: string = new SSMParameterProvider(this, { - parameterName: 'my-awesome-parameter' -).parameterValue(); -``` -This is only for reading plain strings, and not recommended for secrets\. For reading secure strings from the Systems Manager Parameter Store, see [Get a Value from a Systems Manager Parameter Store Variable](get_ssm_value.md)\. - -[VpcNetworkProvider](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpcnetworkprovider.html) -Use this provider to look up and reference existing VPCs in your accounts\. For example, the following code imports a VPC by tag name\. - -``` -const provider = new VpcNetworkProvider(this, { - tags: { - "tag:Purpose": 'WebServices' - } -}); - -const vpc = Vpc.import(this, 'VPC', provider.vpcProps); ``` \ No newline at end of file diff --git a/doc_source/core_concepts.md b/doc_source/core_concepts.md index 5533118d..acecfa92 100644 --- a/doc_source/core_concepts.md +++ b/doc_source/core_concepts.md @@ -1,11 +1,5 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Concepts -This topic describes some of the concepts \(the why and how\) behind the CDK\. It also discusses the advantages of using the AWS Construct Library instead of a low\-level AWS CloudFormation Resource\. +This topic describes some of the concepts \(the why and how\) behind the AWS CDK\. It also discusses the AWS Construct Library\. -CDK apps are composed of building blocks known as [Constructs](constructs.md), which are composed together to form stacks \. \ No newline at end of file +AWS CDK apps are composed of building blocks known as [Constructs](constructs.md), which are composed together to form [stacks](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html) and [apps](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.App.html)\. \ No newline at end of file diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index e9a0f243..2c4ca8ee 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -1,18 +1,11 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Document History for the AWS CDK Developer Guide -This document is based on the following release of the AWS Cloud Development Kit \(CDK\)\. -+ **API version: 0\.33\.0** -+ **Latest documentation update:** June 6, 2019 +This document is based on the following release of the AWS Cloud Development Kit \(AWS CDK\)\. ++ **API version: 1\.0\.0** ++ **Latest documentation update:** July 11, 2019 -See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the CDK releases\. +See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the AWS CDK releases\. | Change | Description | Date | | --- |--- |--- | -| [Kindle](#doc-history) | The developer guide is now available as a free Kindle download\. | May 22, 2019 | -| [Identifiers](#doc-history) | The Concepts section now has information about Identifiers\. | May 20, 2019 | \ No newline at end of file +| [Initial Release](#doc-history) | The developer guide is released\. | July 11, 2019 | \ No newline at end of file diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 4113c0e2..c846e84f 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -1,9 +1,3 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Creating an AWS Fargate Service Using the AWS CDK This example walks you through how to create an AWS Fargate service running on an Amazon Elastic Container Service \(Amazon ECS\) cluster that's fronted by an internet\-facing Application Load Balancer from an image on Amazon ECR\. @@ -15,27 +9,27 @@ This tutorial shows you how to launch some services using the Fargate launch typ + [Setting Up with Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/get-set-up-for-amazon-ecs.html) + [Getting Started with Amazon ECS Using Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_GetStarted.html) -This example creates a similar Fargate service in CDK code\. +This example creates a similar Fargate service in AWS CDK code\. The Amazon ECS construct used in this tutorial helps you use AWS services by providing the following benefits: + Automatically configures a load balancer\. + Automatically opens a security group for load balancers\. This enables load balancers to communicate with instances without you explicitly creating a security group\. -+ Automatically orders dependency between the service and the load balancer attaching to a target group, where the CDK enforces the correct order of creating the listener before an instance is created\. ++ Automatically orders dependency between the service and the load balancer attaching to a target group, where the AWS CDK enforces the correct order of creating the listener before an instance is created\. + Automatically configures user data on automatically scaling groups\. This creates the correct configuration to associate a cluster to AMIs\. -+ Validates parameter combinations early\. This exposes AWS CloudFormation issues earlier, thus saving you deployment time\. For example, depending on the task, it's easy to misconfigure the memory settings\. Previously, you would not encounter an error until you deployed your app\. But now the CDK can detect a misconfiguration and emit an error when you synthesize your app\. ++ Validates parameter combinations early\. This exposes AWS CloudFormation issues earlier, thus saving you deployment time\. For example, depending on the task, it's easy to misconfigure the memory settings\. Previously, you would not encounter an error until you deployed your app\. But now the AWS CDK can detect a misconfiguration and emit an error when you synthesize your app\. + Automatically adds permissions for Amazon Elastic Container Registry \(Amazon ECR\) if you use an image from Amazon ECR\. -+ Automatically scales\. The CDK supplies a method so you can autoscalinginstances when you use an Amazon EC2 cluster\. This happens automatically when you use an instance in a Fargate cluster\. ++ Automatically scales\. The AWS CDK supplies a method so you can autoscalinginstances when you use an Amazon EC2 cluster\. This happens automatically when you use an instance in a Fargate cluster\. - In addition, the CDK prevents an instance from being deleted when automatic scaling tries to kill an instance, but either a task is running or is scheduled on that instance\. + In addition, the AWS CDK prevents an instance from being deleted when automatic scaling tries to kill an instance, but either a task is running or is scheduled on that instance\. Previously, you had to create a Lambda function to have this functionality\. + Provides asset support, so that you can deploy a source from your machine to Amazon ECS in one step\. Previously, to use an application source you had to perform several manual steps, such as uploading to Amazon ECR and creating a Docker image\. See [ECS](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html) for details\. -## Creating the Directory and Initializing the CDK +## Creating the Directory and Initializing the AWS CDK -Let's start by creating a directory to hold the CDK code, and then creating a CDK app in that directory\. +Let's start by creating a directory to hold the AWS CDK code, and then creating a AWS CDK app in that directory\. ``` mkdir MyEcsConstruct @@ -74,34 +68,35 @@ There are two different ways to run your container tasks with Amazon ECS: + Use the `Fargate` launch type, where Amazon ECS manages the physical machines that your containers are running on for you\. + Use the `EC2` launch type, where you do the managing, such as specifying automatic scaling\. -The following tutorial creates a Fargate service running on an ECS cluster fronted by an internet\-facing Application ad Balancer\. +The following tutorial creates a Fargate service running on an ECS cluster fronted by an internet\-facing Application load Balancer\. Add the following `import` statements to `lib/my_ecs_construct-stack.ts`\. ``` -import ec2 = require('@aws-cdk/aws-ec2'); -import ecs = require('@aws-cdk/aws-ecs'); +import ec2 = require("@aws-cdk/aws-ec2"); +import ecs = require("@aws-cdk/aws-ecs"); +import ecs_patterns = require("@aws-cdk/aws-ecs-patterns"); ``` Replace the comment at the end of the constructor with the following code\. ``` - const vpc = new ec2.VpcNetwork(this, 'MyVpc', { - maxAZs: 3 // Default is all AZs in region + const vpc = new ec2.Vpc(this, "MyVpc", { + maxAzs: 3 // Default is all AZs in region }); - const cluster = new ecs.Cluster(this, 'MyCluster', { + const cluster = new ecs.Cluster(this, "MyCluster", { vpc: vpc }); // Create a load-balanced Fargate service and make it public - new ecs.LoadBalancedFargateService(this, 'MyFargateService', { - cluster: cluster, // Required + new ecs_patterns.LoadBalancedFargateService(this, "MyFargateService", { + cluster: cluster, // Required cpu: 512, // Default is 256 - desiredCount: 6, // Default is 1 + desiredCount: 6, // Default is 1 image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"), // Required - memoryLimitMiB: 2048, // Default is 512 - publicLoadBalancer: true // Default is false + memoryLimitMiB: 2048, // Default is 512 + publicLoadBalancer: true // Default is false }); ``` diff --git a/doc_source/environments.md b/doc_source/environments.md new file mode 100644 index 00000000..7a83a133 --- /dev/null +++ b/doc_source/environments.md @@ -0,0 +1,31 @@ +# Environments + +Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and AWS Region into which this stack needs to be deployed\. + +By default, if you don’t specify an environment when you define a stack, the stack is said to be environment agnostic\. This means that AWS CloudFormation templates which are synthesized from this stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availablityZones`\. When using cdk deploy to deploy environment\-agnostic stacks, the CLI uses the default CLI environment configuration to determine where to deploy this stack\. The AWS CDK CLI follows a protocol similar to the AWS CLI for determining which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Command Line Interface \(cdk\)](tools.md#cli) for details\. + +For production systems, we recommend that you explicitly specify the environment for each stack in your app using the `env` property\. The following example specifies two environments used in two different stacks\. + +``` +const envEU = { account: '2383838383', region: 'eu-west-1' }; +const envUSA = { account: '8373873873', region: 'us-west-2' }; + +new MyFirstStack(this, 'first-stack-us', { env: envUSA, encryption: false }); +new MyFirstStack(this, 'first-stack-eu', { env: envEU, encryption: true }); +``` + +By explicitly specifying the target account and Region, the AWS CDK CLI ensures that you only deploy this stack to the desired target and deployment if the configured credentials are not aligned\. To deploy stacks to multiple accounts or different Regions, you must set the correct credentials or Region each time you run a cdk deploy *STACK* command\. + +You can use the `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION` environment variables to explicitly associate a stack with the default CLI environment, as shown in the following example\. This is a common practice for development stacks that you want to include in your app, and have each developer use their own account\. + +``` +new MyDevStack(this, 'dev', { + env: { + account: process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEFAULT_REGION + } +}); +``` + +**Note** +There is a distinction between not specifying the `env` property at all and specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. This means that constructs that are defined in such a stack cannot make assumptions about their environment\. For example, you can’t write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html#aws_ec2_Vpc_fromLookup), which need to query your AWS account\. When specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, you tell the stack that it will be deployed in the account and Region as configured in the CLI at the time of synthesis\. This means that the synthesized template could be different on different machines, users, or sessions\. This might be acceptable for use cases like development stacks, but would be an anti\-pattern for production stacks\. \ No newline at end of file diff --git a/doc_source/examples.md b/doc_source/examples.md index 18f24a52..7ff08946 100644 --- a/doc_source/examples.md +++ b/doc_source/examples.md @@ -1,9 +1,3 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Examples This topic contains the following examples: diff --git a/doc_source/get_cfn_param.md b/doc_source/get_cfn_param.md index 28207f3d..fa2731f6 100644 --- a/doc_source/get_cfn_param.md +++ b/doc_source/get_cfn_param.md @@ -1,9 +1,3 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Use an AWS CloudFormation Parameter See [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for information about using the optional *Parameters* section to customize your AWS CloudFormation templates\. diff --git a/doc_source/get_context_var.md b/doc_source/get_context_var.md index fbc01ff4..727a3337 100644 --- a/doc_source/get_context_var.md +++ b/doc_source/get_context_var.md @@ -1,14 +1,8 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Get a Value from a Context Variable -You can specify a context variable either as part of a CDK Toolkit command, or in `cdk.json`\. +You can specify a context variable either as part of an AWS CDK CLI command, or in `cdk.json`\. -To create a command line context variable, use the **\-\-context** \(**\-c**\) option of a CDK Toolkit command, as shown in the following example\. +To create a command line context variable, use the **\-\-context** \(**\-c**\) option, as shown in the following example\. ``` cdk synth -c bucket_name=mygroovybucket @@ -27,5 +21,5 @@ To specify the same context variable and value in the `cdk.json` file, use the f To get the value of a context variable in your app, use code like the following, which gets the value of the context variable **bucket\_name**\. ``` -const bucket_name = this.node.getContext("bucket_name"); +const bucket_name = this.node.tryGetContext("bucket_name"); ``` \ No newline at end of file diff --git a/doc_source/get_env_var.md b/doc_source/get_env_var.md index a32fee3a..d2458a25 100644 --- a/doc_source/get_env_var.md +++ b/doc_source/get_env_var.md @@ -1,9 +1,3 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Get a Value from an Environment Variable To get the value of an environment variable, use code like the following\. This code gets the value of the environment variable `MYBUCKET`\. diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index 7ca4f2de..577d20d5 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -1,9 +1,3 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Get a Value from AWS Secrets Manager To use values from AWS Secrets Manager in your CDK app, use the [fromSecretAttributes](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-secretsmanager/secret.html#aws_secretsmanager_Secret_fromSecretAttributes) method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. @@ -11,15 +5,15 @@ To use values from AWS Secrets Manager in your CDK app, use the [fromSecretAttri ``` import sm = require("@aws-cdk/aws-secretsmanager"); -export class SecretsManagerStack extends cdk.Stack { - constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { +export class SecretsManagerStack extends core.Stack { + constructor(scope: core.App, id: string, props?: core.StackProps) { super(scope, id, props); - const secret = sm.Secret.import(this, "ImportedSecret", { + const secret = sm.Secret.fromSecretAttributes(this, "ImportedSecret", { secretArn: "arn:aws:secretsmanager:::secret:-" // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: - // encryptionKey, + // Key, }); ``` diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index b13bc78b..688b33db 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -1,9 +1,3 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Get a Value from a Systems Manager Parameter Store Variable You can get the value of an AWS Systems Manager Parameter Store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It isn't possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from AWS Secrets Manager \(see [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. @@ -13,7 +7,7 @@ To read a particular version of a Systems Manager Parameter Store plain string v ``` import ssm = require('@aws-cdk/aws-ssm'); -const parameterString = new ssm.ParameterStoreString(this, 'MyParameter', { +const parameterString = new ssm.StringParameter.fromStringParameterAttributes(this, 'MyParameter', { parameterName: 'my-parameter-name', version: 1, }); @@ -26,7 +20,7 @@ To read a particular version of a Systems Manager Parameter Store `SecureString` ``` import ssm = require('@aws-cdk/aws-ssm'); -const secureString = new ssm.ParameterStoreSecureString(this, 'MySecretParameter', { +const secureString = new ssm.StringParameter.fromSecureStringParameterAttributes(this, 'MySecretParameter', { parameterName: 'my-secret-parameter-name', version: 1, }); diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index b50fed93..59ef85bb 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -1,18 +1,12 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Getting Started With the AWS CDK -This topic describes how to install and configure the AWS CDK and create your first CDK app\. +This topic describes how to install and configure the AWS CDK and create your first AWS CDK app\. ## Prerequisites -**CDK command line tools** +**AWS CDK command line tools** + [Node\.js \(>= 8\.11\.x\)](https://nodejs.org/en/download) -+ You must specify both your credentials and an AWS Region to use the CDK Toolkit;, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. ++ You must specify both your credentials and an AWS Region to use the AWS CDK CLI;, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. ------ #### [ TypeScript ] @@ -43,15 +37,15 @@ none ------ -## Installing the CDK +## Installing the AWS CDK -Install the CDK using the following command\. +Install the AWS CDK using the following command\. ``` npm install -g aws-cdk ``` -Run the following command to see the version number of the CDK\. +Run the following command to see the version number of the AWS CDK\. ``` cdk --version @@ -59,7 +53,7 @@ cdk --version ## Updating Your Language Dependencies -If you get an error message that your language framework is out of date, use one of the following commands to update the components that the CDK needs to support the language\. +If you get an error message that your language framework is out of date, use one of the following commands to update the components that the AWS CDK needs to support the language\. ------ #### [ TypeScript ] @@ -105,13 +99,18 @@ You might have to call this multiple times to update all dependencies\. You can use the `env` property on a stack to specify the account and region used when deploying a stack, as shown in the following example, where *REGION* is the region and *ACCOUNT* is the account ID\. ``` -new MyStack(app, { env: { region: 'REGION', account: 'ACCOUNT' } }); +new MyStack(app, { + env: { + region: 'REGION', + account: 'ACCOUNT' + } +}); ``` **Note** -The CDK team recommends that you explicitly set your account and region using the `env` property on a stack when you deploy stacks to production\. +The AWS CDK team recommends that you explicitly set your account and region using the `env` property on a stack when you deploy stacks to production\. -Since you can create any number of stacks in any of your accounts in any region that supports all of the stack's resources, the CDK team recommends that you create your production stacks in one CDK app, and deploy them as necessary\. For example, if you own three accounts, with account IDs *ONE*, *TWO*, and *THREE* and want to be able to deploy each one in **us\-west\-2** and **us\-east\-1**, you might declare them as: +Since you can create any number of stacks in any of your accounts in any region that supports all of the stack's resources, the AWS CDK team recommends that you create your production stacks in one AWS CDK app, and deploy them as necessary\. For example, if you own three accounts, with account IDs *ONE*, *TWO*, and *THREE* and want to be able to deploy each one in **us\-west\-2** and **us\-east\-1**, you might declare them as: ``` new MyStack(app, 'Stack-One-W', { env: { account: 'ONE', region: 'us-west-2' }}); @@ -129,11 +128,11 @@ cdk deploy Stack-Two-E ``` **Note** -If the existing credentials do not have permission to create resources within the account you specify, the CDK returns an AWS CloudFormation error when you attempt to deploy the stack\. +If the existing credentials do not have permission to create resources within the account you specify, the AWS CDK returns an AWS CloudFormation error when you attempt to deploy the stack\. ## Specifying Your Credentials and Region -You must specify your credentials and an AWS Region to use the CDK Toolkit\. The CDK looks for credentials and region in the following order: +You must specify your credentials and an AWS Region to use the AWS CDK CLI\. The CDK looks for credentials and region in the following order: + Using the \-\-profile option to cdk commands\. + Using environment variables\. + Using the default profile as set by the AWS Command Line Interface \(AWS CLI\)\. @@ -398,7 +397,7 @@ npm install @aws-cdk/aws-s3 ------ #### [ Java ] -If necessary, add the following to `pom.xml`, where *CDK\-VERSION* is the version of the CDK\. +If necessary, add the following to `pom.xml`, where *CDK\-VERSION* is the version of the AWS CDK\. ``` @@ -436,11 +435,11 @@ Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represente In `lib/hello-cdk-stack.ts`: ``` -import cdk = require('@aws-cdk/cdk'); +import core = require('@aws-cdk/core'); import s3 = require('@aws-cdk/aws-s3'); -export class HelloCdkStack extends cdk.Stack { - constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { +export class HelloCdkStack extends core.Stack { + constructor(scope: core.App, id: string, props?: core.StackProps) { super(scope, id, props); new s3.Bucket(this, 'MyFirstBucket', { @@ -593,7 +592,7 @@ Synthesize an AWS CloudFormation template for the app, as follows\. If you get a cdk synth ``` -This command executes the CDK app and synthesizes an AWS CloudFormation template for the `HelloCdkStack` stack\. You should see something similar to the following, where *VERSION* is the version of the CDK\. +This command executes the AWS CDK app and synthesizes an AWS CloudFormation template for the `HelloCdkStack` stack\. You should see something similar to the following, where *VERSION* is the version of the AWS CDK\. ``` Resources: @@ -616,7 +615,7 @@ Resources: You can see that the stack contains an `AWS::S3::Bucket` resource with the versioning configuration we want\. **Note** -The toolkit automatically added the **AWS::CDK::Metadata** resource to your template\. The CDK uses metadata to gain insight into how the CDK is used\. One possible benefit is that the CDK team could notify users if a construct is going to be deprecated\. For details, including how to [opt out](tools.md#version_reporting_opt_out) of version reporting, see [Version Reporting](tools.md#version_reporting) \. +The AWS CDK CLI automatically adds the **AWS::CDK::Metadata** resource to your template\. The AWS CDK uses metadata to gain insight into how the AWS CDK is used\. One possible benefit is that the CDK team could notify users if a construct is going to be deprecated\. For details, including how to [opt out](tools.md#version_reporting_opt_out) of version reporting, see [Version Reporting](tools.md#version_reporting) \. ### Deploying the Stack @@ -639,8 +638,8 @@ Update `lib/hello-cdk-stack.ts` ``` new s3.Bucket(this, 'MyFirstBucket', { - versioned: true, - encryption: s3.BucketEncryption.KmsManaged + versioned: true, + encryption: s3.BucketEncryption.KmsManaged }); ``` @@ -734,13 +733,13 @@ Nothing to compile\. ### Preparing for Deployment -Before you deploy the updated app, evaluate the difference between the CDK app and the deployed app\. +Before you deploy the updated app, evaluate the difference between the AWS CDK app and the deployed app\. ``` cdk diff ``` -The toolkit queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares the result with the template synthesized from the app\. The Resources section of the output should look like the following\. +The AWS CDK CLI queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares the result with the template synthesized from the app\. The Resources section of the output should look like the following\. ``` Stack HelloCdkStack @@ -760,7 +759,7 @@ Deploy the changes\. cdk deploy ``` -Enter y to approve the changes and deploy the updated stack\. The CDK Toolkit updates the bucket configuration to enable server\-side AWS KMS encryption for the bucket\. The final output is the ARN of the stack, where *REGION* is your default region, *ACCOUNT\-ID* is your account ID, and *ID* is a unique identifier for the bucket or stack\. +Enter y to approve the changes and deploy the updated stack\. The AWS CDK CLI updates the bucket configuration to enable server\-side AWS KMS encryption for the bucket\. The final output is the ARN of the stack, where *REGION* is your default region, *ACCOUNT\-ID* is your account ID, and *ID* is a unique identifier for the bucket or stack\. ``` HelloCdkStack: deploying... diff --git a/doc_source/home.md b/doc_source/home.md index 980e7d21..485e9dad 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -1,12 +1,6 @@ --------- +# What Is the AWS CDK? -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# What is the AWS Cloud Development Kit? - -Welcome to the *AWS CDK \(CDK\) Developer Guide*\. This document provides information about the CDK, which is a software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. +Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, which is a software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. AWS CloudFormation enables you to: + Create and provision AWS infrastructure deployments predictably and repeatedly\. @@ -14,102 +8,94 @@ AWS CloudFormation enables you to: + Build highly reliable, highly scalable, cost\-effective applications in the cloud without worrying about creating and configuring the underlying AWS infrastructure\. + Use a template file to create and delete a collection of resources together as a single unit \(a stack\)\. -Use the CDK to define your cloud resources using one of the supported programming languages: C\#/\.NET, Java, JavaScript, Python, or TypeScript\. This document does not supply reference information for the CDK\. You can find that information in the [CDK Reference](https://docs.aws.amazon.com/cdk/api/latest)\. +Use the AWS CDK to define your cloud resources in a familiar programming language\. The AWS CDK supports TypeScript, JavaScript, and Python\. The AWS CDK also provides Developer Preview support for C\#/\.NET, and Java\. -Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](apps_and_stacks.md#stacks) and [Apps](apps_and_stacks.md#apps)\. +Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/AppStacks.png) -## Why Use the CDK? +## Why Use the AWS CDK? -Let's look at the power of the CDK\. Here is some TypeScript code in a CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md)\)\. +Let's look at the power of the AWS CDK\. Here is some TypeScript code in an AWS CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md)\)\. ``` -export class MyEcsConstructStack extends cdk.Stack { - constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { +export class MyEcsConstructStack extends core.Stack { + constructor(scope: core.App, id: string, props?: core.StackProps) { super(scope, id, props); - const vpc = new ec2.VpcNetwork(this, 'MyVpc', { - maxAZs: 3 // Default is all AZs in region + const vpc = new ec2.Vpc(this, "MyVpc", { + maxAzs: 3 // Default is all AZs in region }); - const cluster = new ecs.Cluster(this, 'MyCluster', { + const cluster = new ecs.Cluster(this, "MyCluster", { vpc: vpc }); // Create a load-balanced Fargate service and make it public - new ecs.LoadBalancedFargateService(this, 'MyFargateService', { - cluster: cluster, // Required - cpu: '512', // Default is 256 - desiredCount: 6, // Default is 1 + new ecs_patterns.LoadBalancedFargateService(this, "MyFargateService", { + cluster: cluster, // Required + cpu: 512, // Default is 256 + desiredCount: 6, // Default is 1 image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"), // Required - memoryMiB: '2048', // Default is 512 - publicLoadBalancer: true // Default is false + memoryLimitMiB: 2048, // Default is 512 + publicLoadBalancer: true // Default is false }); ``` -This produces an AWS CloudFormation template of over 600 lines\. We'll show the first 25 lines and Outputs of a cdk synth command\. - -``` -Resources: - MyVpcF9F0CA6F: - Type: AWS::EC2::VPC - Properties: - CidrBlock: 10.0.0.0/16 - EnableDnsHostnames: true - EnableDnsSupport: true - InstanceTenancy: default - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/Resource - MyVpcPublicSubnet1SubnetF6608456: - Type: AWS::EC2::Subnet - Properties: - CidrBlock: 10.0.0.0/19 - VpcId: - Ref: MyVpcF9F0CA6F - AvailabilityZone: us-west-2a - MapPublicIpOnLaunch: true - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PublicSubnet1 - - Key: aws-cdk:subnet-name -... - MyFargateServiceLoadBalancerDNS704F6391: - Value: - Fn::GetAtt: - - MyFargateServiceLBDE830E97 - - DNSName -``` - -Another advantage of IAC \(infrastructure as code\) is that you get code completion within your IDE: - +This produces an AWS CloudFormation [template of over 600 lines](https://github.com/awsdocs/aws-cdk-guide/blob/master/doc_source/my_ecs_construct-stack.yaml); deploying the AWS CDK app produces over 50 resources of the following types\. ++ [AWS::EC2::EIP](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html) ++ [AWS::EC2::InternetGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html) ++ [AWS::EC2::NatGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html) ++ [AWS::EC2::Route](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html) ++ [AWS::EC2::RouteTable](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route-table.html) ++ [AWS::EC2::SecurityGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html) ++ [AWS::EC2::Subnet](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html) ++ [AWS::EC2::SubnetRouteTableAssociation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html) ++ [AWS::EC2::VCPGatewayAttachment](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html) ++ [AWS::EC2::VPC](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html) ++ [AWS::ECS::Cluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-cluster.html) ++ [AWS::ECS::Service](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html) ++ [AWS::ECS::TaskDefinition](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-taskdefinition.html) ++ [AWS::ElasticLoadBalancingV2::Listener](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html) ++ [AWS::ElasticLoadBalancingV2::LoadBalancer](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html) ++ [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html) ++ [AWS::IAM::Policy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html) ++ [AWS::IAM::Role](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html) ++ [AWS::Logs::LogGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html) + +Other advantages of the AWS CDK include: ++ Use logic \(if statements, for\-loops, etc\) when defining your infrastructure ++ Use object\-oriented techniques to create a model of your system ++ Define high level abstractions, share them, and publish them to your team, company, or community ++ Organize your project into logical modules ++ Share and reuse your infrastructure as a library ++ Testing your infrastructure code using industry\-standard protocols ++ Use your existing code review workflow ++ Code completion within your IDE ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/CodeCompletion.png) -## Developing With the CDK +## Developing with the AWS CDK -Unless otherwise indicated, the code examples in this guide are in TypeScript\. To aid you in porting a TypeScript example to a supported programming language, see [Multi\-Language Support in the CDK](multiple_languages.md)\. The CDK also includes examples in the supported programming languages\. See [AWS CDK Examples](about_examples.md) for a list of the examples\. +Unless otherwise indicated, the code examples in this guide are in TypeScript\. To aid you in porting a TypeScript example to a supported programming language, see [AWS CDK in Other Languages ](multiple_languages.md)\. The AWS CDK also includes examples in the supported programming languages\. See [AWS CDK Examples](about_examples.md) for a list of the examples\. -The [CDK Toolchain](tools.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. +The [AWS CDK Tools](tools.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. -The [AWS Construct Library](aws_construct_lib.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to create resources for an Amazon or AWS service\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. +The [AWS Construct Library](constructs.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to create resources for an Amazon or AWS service\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. **Note** -There is no charge for using the CDK, however you might incur AWS charges for creating or using AWS [chargeable resources](http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Simple Monthly Calculator](http://calculator.s3.amazonaws.com/index.html) to estimate charges for the use of various AWS resources\. +There is no charge for using the AWS CDK, however you might incur AWS charges for creating or using AWS [chargeable resources](http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Simple Monthly Calculator](http://calculator.s3.amazonaws.com/index.html) to estimate charges for the use of various AWS resources\. -## Contributing to the CDK +## Contributing to the AWS CDK Because the AWS CDK is open source, the team encourages you contribute to make it an even better tool\. For details, see [Contributing](https://github.com/awslabs/aws-cdk/blob/master/CONTRIBUTING.md)\. ## Additional Documentation and Resources -In addition to this guide, the following are other resources available to CDK users: +In addition to this guide, the following are other resources available to AWS CDK users: + [Reference](https://docs.aws.amazon.com/cdk/api/latest) -+ [CDK Demo at re:Invent 2018](https://www.youtube.com/watch?v=Lh-kVC2r2AU) -+ [CDK Workshop](https://cdkworkshop.com/) -+ [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) ++ [AWS CDK Demo at re:Invent 2018](https://www.youtube.com/watch?v=Lh-kVC2r2AU) ++ [AWS CDK Workshop](https://cdkworkshop.com/) ++ [AWS CDK Examples](https://github.com/aws-samples/aws-cdk-examples) + [AWS Developer Blog](https://aws.amazon.com/blogs/developer) + [Gitter Channel](https://gitter.im/awslabs/aws-cdk) + [Stack Overflow](https://stackoverflow.com/questions/tagged/aws-cdk) @@ -119,7 +105,7 @@ In addition to this guide, the following are other resources available to CDK us + [Documentation Source](https://github.com/awsdocs/aws-cdk-user-guide/tree/master/doc_source) + [License](https://github.com/awslabs/aws-cdk/blob/master/LICENSE) + [Releases](https://github.com/awslabs/aws-cdk/releases) - + [CDK OpenPGP Key](pgp-keys.md#cdk_pgp_key) + + [AWS CDK OpenPGP Key](pgp-keys.md#cdk_pgp_key) + [JSII OpenPGP Key](pgp-keys.md#jsii_pgp_key) + [AWS CDK Sample for Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/sample-cdk.html) + [AWS CloudFormation Concepts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html) diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index bd532640..7b61874b 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -1,9 +1,3 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Set a CloudWatch Alarm The **aws\-cloudwatch** package supports setting CloudWatch alarms on CloudWatch metrics\. The syntax is as follows, where *METRIC* is a CloudWatch metric you have created, and the alarm is raised there are more than 100 of the measured metrics in two of the last three seconds: @@ -17,7 +11,7 @@ new cloudwatch.Alarm(this, 'Alarm', { }); ``` -The syntax for creating a metric for a AWS CloudFormation Resource is as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. +The syntax for creating a metric is as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. ``` const metric = new cloudwatch.Metric({ @@ -27,15 +21,15 @@ const metric = new cloudwatch.Metric({ }); ``` -Many CDK packages contain an AWS Construct Library construct with functionality to enable setting an alarm based on an existing metric\. For example, you can create an Amazon SQS alarm for the **ApproximateNumberOfMessagesVisible** metric that raises an alarm if the queue has more than 100 messages available for retrieval in two of the last three seconds\. +Many AWS CDK packages contain functionality to enable setting an alarm based on an existing metric\. For example, you can create an Amazon SQS alarm for the **ApproximateNumberOfMessagesVisible** metric that raises an alarm if the queue has more than 100 messages available for retrieval in two of the last three seconds\. ``` -const qMetric = queue.metric('ApproximateNumberOfMessagesVisible'); - -new cloudwatch.Alarm(this, 'Alarm', { - metric: qMetric, - threshold: 100, - evaluationPeriods: 3, - datapointsToAlarm: 2, -}); + const qMetric = queue.metric("ApproximateNumberOfMessagesVisible"); + + new cloudwatch.Alarm(this, "Alarm", { + metric: qMetric, + threshold: 100, + evaluationPeriods: 3, + datapointsToAlarm: 2 + }); ``` \ No newline at end of file diff --git a/doc_source/how_tos.md b/doc_source/how_tos.md index f11f4008..c2d16c73 100644 --- a/doc_source/how_tos.md +++ b/doc_source/how_tos.md @@ -1,9 +1,3 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # AWS CDK HowTos This section contains short code examples that show you how to accomplish a task using the AWS CDK\. \ No newline at end of file diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index 69133ed1..e91d05b3 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -1,16 +1,10 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Identifiers -The CDK deals with many types of identifiers and names\. To use the AWS CDK effectively and avoid errors, you need to understand the types of identifiers\. +The AWS CDK deals with many types of identifiers and names\. To use the AWS CDK effectively and avoid errors, you need to understand the types of identifiers\. -Identifiers must be unique within the scope in which they are created; they do not need to be globally unique in your CDK application\. +Identifiers must be unique within the scope in which they are created; they do not need to be globally unique in your AWS CDK application\. -If you attempt to create an identifier with the same value within the same scope, the CDK throws an exception\. +If you attempt to create an identifier with the same value within the same scope, the AWS CDK throws an exception\. ## Construct IDs @@ -37,11 +31,11 @@ new MyStack(app, 'Stack2'); ## Paths -As the constructs in an CDK application form a hierarchy, we refer to the collection of ids from a given construct, then of its parent construct, then grandparent construct, and so on up to the root of the construct tree, which is an instance of the `App` class as a *path*\. +As the constructs in an AWS CDK application form a hierarchy, we refer to the collection of ids from a given construct, then of its parent construct, then grandparent construct, and so on up to the root of the construct tree, which is an instance of the `App` class as a *path*\. -The CDK typically displays paths in your templates as a string, with the ids from the levels separated by slashes, starting at the node just below the root `App` instance, which is usually a stack\. For example, the paths of the two Amazon S3 bucket resources in the previous code example are `Stack1/MyBucket` and `Stack2/MyBucket`\. +The AWS CDK typically displays paths in your templates as a string, with the ids from the levels separated by slashes, starting at the node just below the root `App` instance, which is usually a stack\. For example, the paths of the two Amazon S3 bucket resources in the previous code example are `Stack1/MyBucket` and `Stack2/MyBucket`\. -You can access the path of any construct programatically, as shown in the following example, which gets the path of `myConstruct`\. Since ids must be unique within the scope they are created, their paths are always unique within a CDK application\. +You can access the path of any construct programmatically, as shown in the following example, which gets the path of `myConstruct`\. Since ids must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. ``` const path: string = myConstruct.node.path; @@ -49,9 +43,9 @@ const path: string = myConstruct.node.path; ## Unique IDs -Since AWS CloudFormation requires that all logical IDs in a template are unique, the CDK must be able to generate unique identifier for each construct in an application\. Since the CDK already has paths that are globally unique, the CDK generates these unique identifiers by concatenating the elements of the path, and adds an 8\-digit hash\. The hash is necessary, as otherwise two distinct paths, such as `A/B/C` and `A/BC` would result in the same identifier\. The CDK calls this concatenated path elements and hash the *unique ID* of the construct\. +Since AWS CloudFormation requires that all logical IDs in a template are unique, the AWS CDK must be able to generate unique identifier for each construct in an application\. Since the AWS CDK already has paths that are globally unique, the AWS CDK generates these unique identifiers by concatenating the elements of the path, and adds an 8\-digit hash\. The hash is necessary, as otherwise two distinct paths, such as `A/B/C` and `A/BC` would result in the same identifier\. The AWS CDK calls this concatenated path elements and hash the *unique ID* of the construct\. -You can access the unique ID of any construct programatically, as shown in the following example, which gets the unique ID of `myConstruct`\. Since ids must be unique within the scope they are created, their paths are always unique within a CDK application\. +You can access the unique ID of any construct programmatically, as shown in the following example, which gets the unique ID of `myConstruct`\. Since ids must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. ``` const uid: string = myConstruct.node.uniqueId; diff --git a/doc_source/index.md b/doc_source/index.md index 3d0c739d..d0c33a0b 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -1,4 +1,4 @@ -# AWS Cloud Development Kit (CDK) Developer Guide +# AWS Cloud Development Kit (AWS CDK) Developer Guide ----- *****Copyright © 2019 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** @@ -14,22 +14,24 @@ Amazon's trademarks and trade dress may not be used in ----- ## Contents -+ [What is the AWS Cloud Development Kit?](home.md) ++ [What Is the AWS CDK?](home.md) + [Getting Started With the AWS CDK](getting_started.md) + [Concepts](core_concepts.md) + [Constructs](constructs.md) - + [Apps, Stacks, and Environments and Authentication](apps_and_stacks.md) + + [Apps](apps.md) + + [Stacks](stacks.md) + + [Environments](environments.md) + [Resources](resources.md) + [Identifiers](identifiers.md) - + [Run-Time Context](context.md) - + [Assets](assets.md) - + [AWS CloudFormation](cloudformation.md) + [Tokens](tokens.md) - + [AWS CDK Lifecycle](lifecycle.md) -+ [Writing AWS CDK Constructs](writing_constructs.md) - + [Multi-Language Support in the CDK](multiple_languages.md) -+ [AWS Construct Library](aws_construct_lib.md) -+ [About the Reference](reference.md) + + [Tagging](tagging.md) + + [Assets](assets.md) + + [Permissions](permissions.md) + + [Runtime Context](context.md) + + [Aspects](aspects.md) + + [Escape Hatches](cfn_layer.md) ++ [API Reference](reference.md) + + [AWS CDK in Other Languages](multiple_languages.md) + [Examples](examples.md) + [Creating a Serverless Application Using the AWS CDK](serverless_example.md) + [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) @@ -40,11 +42,10 @@ Amazon's trademarks and trade dress may not be used in + [Use an Existing AWS CloudFormation Template](use_cfn_template.md) + [Get a Value from a Systems Manager Parameter Store Variable](get_ssm_value.md) + [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md) - + [Work Around Missing AWS CDK Features](cfn_layer.md) + [Create an App with Multiple Stacks](stack_how_to_create_multiple_stacks.md) + [Set a CloudWatch Alarm](how_to_set_cw_alarm.md) + [Get a Value from a Context Variable](get_context_var.md) -+ [CDK Toolchain](tools.md) -+ [Troubleshooting the CDK](troubleshooting.md) ++ [AWS CDK Tools](tools.md) ++ [Troubleshooting the AWS CDK](troubleshooting.md) + [OpenPGP Keys for the AWS CDK and JSII](pgp-keys.md) + [Document History for the AWS CDK Developer Guide](doc-history.md) \ No newline at end of file diff --git a/doc_source/lifecycle.md b/doc_source/lifecycle.md deleted file mode 100644 index 2d4caef0..00000000 --- a/doc_source/lifecycle.md +++ /dev/null @@ -1,37 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# AWS CDK Lifecycle - -The following illustration shows the phases that the CDK goes through when you call cdk deploy to create the resources defined by your application\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/Lifecycle.png) - -There are three actors at play to create the resources that your CDK application defines\. -+ Your CDK app\. -+ The CDK Toolkit\. -+ AWS CloudFormation, which the CDK Toolkit calls to deploy your application and create the resources\. - -After you use the toolkit to deploy a CDK application, the application goes through the following phases\. - -Construction -Your code instantiates all desired application constructs and links them together\. - -Preparation -All constructs that have implemented the `prepare` method participate in a final round of modifications, to set up any final state they want to\. The preparation phase happens automatically and users do not see any feedback from this phase\. - -Validation -All constructs that have implemented their `validate` method can validate themselves to make sure they've ended up in a state that will correctly deploy\. Users see any validation failures that are detected during this phase\. - -Synthesis -All constructs render themselves to a set of artifacts, representing AWS CloudFormation templates, AWS Lambda application bundles, and other deployment artifacts\. Users do not see any feedback from this phase\. - -Deployment -The toolkit takes the artifacts produced by the synthesis step, uploads them to Amazon S3 or wherever they need to go, and starts an AWS CloudFormation deployment to deploy the application and create the resources\. - -Note that your CDK app has already finished and exited by the time the AWS CloudFormation deployment starts\. This has the following implications\. -+ Your CDK app cannot respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a Custom Resource\. -+ Your CDK app might have to work with values that cannot be known at the time it executes\. For example, if your CDK application defines an Amazon S3 Bucket with an automatically generated name, and you retrieve the `bucket.bucketName` attribute, that value is not the name of the deployed bucket\. Instead, the value of the `bucketName` attribute is a symbolic value, looking like *$\{TOKEN\[Bucket\.Name\.1234\]\}*\. You can pass this value to constructs, or append it to other strings, and the CDK framework will translate that value\. You cannot examine the value and make decisions based on the deployed bucket name, because the bucket name not available until AWS CloudFormation is done deploying, and by that time your program is no longer running\. Call `cdk.unresolved(value)`, which returns `true` if `value` not known until deployment time\. \ No newline at end of file diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 1458bbfc..35b9318e 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -1,98 +1,122 @@ --------- +# AWS CDK in Other Languages -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. +In some cases the example code in the AWS CDK documentation is available only in TypeScript\. This topic describes how to read TypeScript code and translate it into Python\. This is currently the only other [stable](reference.md#aws_construct_lib_versioning_binding) programming language that the AWS CDK supports \(the AWS CDK supports a developer preview version of Java and C\#/\.NET\)\. See [Hello World Tutorial](getting_started.md#hello_world_tutorial) for an example of creating an AWS CDK app in a supported language\. --------- +## Importing a Module -# Multi\-Language Support in the CDK +Both TypeScript and Python support namespaced module imports and selective imports\. Module names in Python look like **aws\_cdk\.***xxx*, where *xxx* represents an AWS service name, such as **s3** for Amazon S3 \(we'll use Amazon S3 for our examples\)\. Replace the dashes in the TypeScript module name with underscores to get the Python module name\. -This section describes the multi\-language support in the CDK, including hints for porting TypeScript to one of the supported languages\. See [Hello World Tutorial](getting_started.md#hello_world_tutorial) for an example of creating a CDK app in a supported language\. +The following is how you import the entire Amazon S3 module or just a `Stack` class in both languages\. -The CDK supports C\#, Java, JavaScript, and TypeScript\. Since the CDK is developed in TypeScript, many code examples are still only available in TypeScript\. This section will help you port those TypeScript examples to one of the other programming languages\. -## Importing a Package +| TypeScript | Python | +| --- |--- | +| // Import entire module | \# Import entire module | +| import s3 = require\('@aws\-cdk/aws\-s3'\) | import aws\_cdk\.aws\_s3 as s3 | +| | | +| // Selective import | \# Selective import | +| import \{ Stack \} from '@aws\-cdk/core'; | from aws\_cdk\.core import Stack | -In TypeScript, you import a package as follows \(we'll use Amazon S3 for our examples\): +## Instantiating a Class -``` -import s3 = require("@aws-cdk/aws-s3"); -``` +Classes have the same name in TypeScript and in Python\. TypeScript uses **new** to instantiate classes, whereas in Python you call the class object directly\. The keyword **this** in TypeScript translates to **self** in Python\. ------- -#### [ C\# ] +The following table shows how you can translate TypeScript class instantiations to Python class instantiations\. -``` -using Amazon.CDK.AWS.S3; -``` ------- -#### [ Java ] +| TypeScript | Python | +| --- |--- | +| // Instantiate Bucket class | \# Instantiate Bucket class | +| new s3\.Bucket\(this, 'Bucket'\); | s3\.Bucket\(self, 'Bucket'\) | -``` -import software.amazon.awscdk.services.s3.*; -``` +## Methods ------- -#### [ JavaScript ] +Methods names and argument names in TypeScript are `camelCased`, whereas in Python they are `snake_cased`\. Props objects at the end of an argument list in TypeScript are translated into keyword\-only arguments in Python\. -``` -const s3 = require('@aws-cdk/aws-s3'); -``` +The following table shows how you can translate TypeScript methods to Python methods\. ------- -#### [ Python ] -``` -from aws_cdk import aws_s3 as s3 -``` +| TypeScript | Python | +| --- |--- | +| // Instantiate Bucket with props | \# Instantiate Bucket with props | +| const bucket = new s3\.Bucket\(this, 'Bucket', \{ | bucket = s3\.Bucket\(self, 'Bucket', | +|   bucketName: 'my\-bucket', |   bucketName='my\-bucket', | +|   versioned: true, |   versioned=True\) | +| \}\); | | +| | | +| // Call method | \# Call method | +| bucket\.addCorsRule\(\{ | bucket\.add\_cors\_rule\( | +|   allowedOrigins: \['\*'\], |   allowed\_origins=\['\*'\], | +|   allowedMethods: \[\], |   allowed\_methods=\[\] | +| \}\); | \) | ------- +## Enum Constants -## Creating a New Object +Enum constants are scoped to a class, and have uppercase names in both languages\. -In TypeScript, you create a new object as follows\. The first argument, `scope`, is always `this`, the second is the `id` of the construct, and the last is a list of properties, often optional\. +The following table shows how you can translate TypeScript enum constants to Python enum constants\. -``` -new s3.Bucket(this, 'MyFirstBucket', { - // options -}); -``` ------- -#### [ C\# ] +| TypeScript | Python | +| --- |--- | +| s3\.BucketEncryption\.KMS\_MANAGED | s3\.BucketEncryption\.KMS\_MANAGED | -``` -new Bucket(this, "MyFirstBucket", new BucketProps -{ - // options -}); -``` +## Defining Constructs ------- -#### [ Java ] +In TypeScript a construct’s props are defined with an interface, whereas in Python you take keyword \(or keyword\-only, see [PEP3102](https://www.python.org/dev/peps/pep-3102/)\) arguments\. -``` -new Bucket(this, "MyFirstBucket", BucketProps.builder() - // options -} -``` +The following table shows how you can translate TypeScript construct definitions to Python construct definitions\. ------- -#### [ JavaScript ] -``` -new s3.Bucket(this, 'MyFirstBucket', { - // options -}); -``` +| TypeScript | Python | +| --- |--- | +| interface MyConstructProps \{ | | +|   prop1: number; | | +|   prop2?: number; | | +| \} | | +| | | +| class MyConstruct extends Construct \{ | class MyConstruct\(Construct\): | +|   constructor\(scope: Construct, id: string, props: MyConstructProps\) \{ |   def \_\_init\_\_\(scope, id, \*, prop1, prop2=10\): | +|     super\(scope, id\); |   super\(\)\.\_\_init\_\_\(scope, id\) | +| | | +|     const prop2 = props\.prop2 \!== undefined ? props\.prop2 : 10; | | +| | | +|     // Construct contents here |   \# Construct contents here | ------- -#### [ Python ] +## Structs \(Interfaces\) -``` -s3.Bucket(self, - "MyFirstBucket", - # options,) -``` +Structs are TypeScript interfaces that represent a set of values\. You can recognize them because their name doesn't start with an `I`, and all of their fields are **read\-only**\. ------- \ No newline at end of file +In TypeScript, structs are passed as object literals\. In Python, if the struct is the last argument to a method, its fields are lifted into the method call itself\. If the argument list contains nested structs, wrap them in a class named after the struct\. + +The following table shows how to call a method with two levels of structs\. + + +| TypeScript | Python | +| --- |--- | +| bucket\.addLifecycleRule\(\{ | bucket\.add\_lifecycle\_rule\( | +|   transitions: \[ |   transitions=\[ | +|     \{ |     Transition\( | +|       storageClass: StorageClass\.GLACIER, |       storage\_class=StorageClass\.GLACIER, | +|       transitionAfter: Duration\.days\(10\) |       transition\_after=Duration\.days\(10\) | +|     \} |     \) | +|   \] |   \] | +| \}\); | \) | + +## Object Interfaces + +The AWS CDK uses TypeScript object interfaces to indicate that a class implements an expected set of methods and properties\. You can recognize an object interface because its name starts with `I`\. + +Typically, Python users don’t explicitly indicate that a class implements an interface\. However, for the AWS CDK you can do this by decorating your class with `@jsii.implements(interface)`\. + + +| TypeScript | Python | +| --- |--- | +| import \{IAspect, IConstruct \} from ‘@aws\-cdk/core’; | from aws\_cdk\.core import IAspect, IConstruct | +| | | +| | @jsii\.implements\(IAspect\) | +| class MyAspect implements IAspect \{ | class MyAspect\(\): | +|   public visit\(node: IConstruct\) \{ |   def visit\(self, node: IConstruct\) \-> None: | +|     console\.log\(‘Visited’, node\.node\.path\); |     print\("Visited”, node\.node\.path\) | +|   \} | | +| \} | | \ No newline at end of file diff --git a/doc_source/permissions.md b/doc_source/permissions.md new file mode 100644 index 00000000..87ce9c2a --- /dev/null +++ b/doc_source/permissions.md @@ -0,0 +1,97 @@ +# Permissions + +The AWS CDK contains an IAM package to help you deal with permissions\. There a few idioms for managing access and permissions that are implemented uniformly across the entire AWS CDK Construct Library\. + +## Roles + +The IAM package contains a `Role` construct that enables you to manage IAM **Role** instances\. The following code creates a new **Role**, trusting the Amazon EC2 Service Principal\. + +``` +import iam = require('@aws-cdk/aws-iam'); + +const role = new iam.Role(this, 'Role', { + assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'), +}); +``` + +You can add permissions to a role by calling methods on it, and passing the appropriate `Policy` statement\. The following example adds a `Deny` statement to the role for the actions `ec2:SomeAction` and `s3:AnotherAction` on the resources `bucket` and `otherRole`, under the condition that the authorized service is AWS CodeBuild\. + +``` +role.addToPolicy(new iam.PolicyStatement(PolicyStatementEffect.Deny) // default is Allow + // there's also addResource() to add one, and addAllResources() to add '*' + .addResources(bucket.bucketArn, otherRole.roleArn) + // there's also addAction() to add one + .addActions('ec2:SomeAction', 's3:AnotherAction') + .addCondition('StringEquals', { + 'ec2:AuthorizedService': 'codebuild.amazonaws.com', + }) +); +``` + +If you're using a construct that requires a role to function correctly, you can either pass in an existing role when instantiating the construct object, or let the construct create a new role for you, trusting the appropriate service principal\. The following example of using such a construct, in this case a CodeBuild project\. + +``` +import codebuild = require('@aws-cdk/aws-codebuild'); + +// imagine roleOrUndefined is a function that might return a Role object +// under some conditions, and undefined under other conditions +const someRole: iam.IRole | undefined = roleOrUndefined(); + +const project = new codebuild.Project(this, 'Project', { + // if someRole is undefined, a new role will be created, + // trusting the codebuild.amazonaws.com service principal + role: someRole, +}); +``` + +In either case, once the object is created, the role is available as the property role on the construct\. That property is not available on imported resources\. Because of that, the constructs have an `addToRolePolicy` method that does nothing if the construct is an imported resource, and calls the `addToPolicy` method of the `role` property \(passing the policy statement it received as argument\) otherwise, saving you from the trouble of handling the undefined case explicitly in your code\. The following example demonstrates the latter case\. + +``` +// project is imported into the CDK application +const project = codebuild.Project.fromProjectName(this, 'Project', 'ProjectName'); + +// project.role is undefined + +// this method call will have no effect +project.addToRolePolicy(new iam.PolicyStatement() + // ... +); +``` + +## Grants + +Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that bestow a given level of access to another entity\. All those methods start with the prefix **grant**\. For example, Amazon S3 buckets have the methods `grantRead` and `grantReadWrite` to enable read and write access, respectively, from an entity to the bucket without having to know which exact Amazon S3 IAM actions are required to perform read or read/write operations\. + +The first argument to the **grant** methods is always of the type `IGrantable`\. This type represents entities that can be granted permissions\. Those include all constructs in the AWS CDK Construct Library that represent resources with roles, such as CodeBuild projects as shown in the previous example, and IAM objects such as `Role`, `User`, and `Group`\. + +## Resource Policies + +A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. In those cases, the construct exposes the `addToResourcePolicy` method, which takes a `PolicyStatement` as its argument, that enables you to modify the policy\. You must specify a `Principal` when dealing with resource policies\. + +In the following example, the Amazon S3 bucket `bucket` grants a role with the `s3:SomeAction` permission to itself\. + +``` +bucket.addToResourcePolicy(new iam.PolicyStatement() + .addAction('s3:SomeAction') + .addResource(bucket.bucketArn) + .addPrincipal(role) +); +``` + +## Principals + +The AWS CDK Construct Library supports many types of principals, including: + +1. IAM resources, such as `Roles`, `Users`, and `Groups` + +1. Service principals \(`new iam.ServicePrincipal('service.amazonaws.com')`\) + +1. Account principals \(`new iam.AccountPrincipal('0123456789012'))` + +1. Canonical user principals \(`new iam.CanonicalUserPrincipal('79a59d[...]7ef2be')`\) + +1. AWS organizations principals \(`new iam.OrganizationPrincipal('org-id')`\) + +1. Arbitrary ARN principals \(`new iam.ArnPrincipal(res.arn)`\) + +1. A `CompositePrincipal(principal1, principal2, ...)` if you need your role to trust multiple principals \ No newline at end of file diff --git a/doc_source/pgp-keys.md b/doc_source/pgp-keys.md index 645b0ff7..cfe975af 100644 --- a/doc_source/pgp-keys.md +++ b/doc_source/pgp-keys.md @@ -1,12 +1,6 @@ --------- +# OpenPGP Keys for the AWS CDK and JSII -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(AWS CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# OpenPGP Keys for the AWS CDK and jsii - -This topic contains the OpenPGP keys for the AWS CDK and `jsii`\. +This topic contains the OpenPGP keys for the AWS CDK and JSII\. ## AWS CDK OpenPGP Key @@ -21,7 +15,7 @@ This topic contains the OpenPGP keys for the AWS CDK and `jsii`\. | User ID: | AWS CDK Team | | Key fingerprint: | E88B E3B6 F0B1 E350 9E36 4F96 0566 A784 E17F 3870 | -Select the **Copy** icon to copy the following OpenPGP key\. +Select the "Copy" icon to copy the following OpenPGP key: ``` -----BEGIN PGP PUBLIC KEY BLOCK----- @@ -54,7 +48,7 @@ EkSlc/RoDqZCpBGgcoy1FFWvV/ZLgNU6OTQlYH6oYOWiylSJnaTDyurrktsxJI6d -----END PGP PUBLIC KEY BLOCK----- ``` -## jsii OpenPGP Key +## JSII OpenPGP Key | | | @@ -67,7 +61,7 @@ EkSlc/RoDqZCpBGgcoy1FFWvV/ZLgNU6OTQlYH6oYOWiylSJnaTDyurrktsxJI6d | User ID: | AWS JSII Team | | Key fingerprint: | 85EF 6522 4CE2 1E8C 72DB 28EC 1C7A CE4C B2A1 B93A | -Select the **Copy** icon to copy the following OpenPGP key\. +Select the "Copy" icon to copy the following OpenPGP key: ``` -----BEGIN PGP PUBLIC KEY BLOCK----- diff --git a/doc_source/reference.md b/doc_source/reference.md index d8f87232..3f98aaf6 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -1,11 +1,55 @@ --------- +# API Reference -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. +The [API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html/) contains information about the AWS CDK libraries\. --------- +Each library contains information about how to use the library\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) library demonstrates how to set default encryption on an Amazon S3 bucket\. -# About the Reference +## Versioning and Stability Model -See the [CDK Reference](https://awslabs.github.io/aws-cdk/) for information about the CDK libraries\. +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs \(see “The AWS CDK Stability Index”\) are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. -Each library contains information about how to use the library\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) library demonstrates how to set default encryption on an Amazon S3 bucket\. \ No newline at end of file +### AWS CDK Stability Index + +However, certain APIs do not adhere to the semantic versioning model\. The AWS CDK team has added a stability index to help developers determine which APIs deviate from the semantic versioning model\. + +There are three levels of stability in the AWS CDK Construct Library: + +Stable +The API is subject to the semantic versioning model\. We will not introduce non\-backward\-compatible changes or remove the API in a subsequent patch or feature release\. + +CloudFormation Only +These APIs are automatically built from the AWS CloudFormation resource specification and are subject to any changes introduced by AWS CloudFormation\. + +Experimental +The API is still under active development and subject to non\-backward\-compatible changes or removal in any future version\. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. + +Deprecated +The API may emit warnings\. We do not guarantee backward compatibility\. + +Experimental and stable modules receive the same level of support from AWS\. The only difference is that we might change experimental APIs within a major version\. Although we don't recommend using experimental APIs in production, we vet them the same way as we vet stable APIs before we include them in an AWS CDK release\. + +### Identifying the Support Level of an API + +The AWS CDK Developer Guide and API Reference for each module starts with a section outlining the module's stability index\. The libraries that include only AWS CloudFormation resources, and no hand\-curated constructs, are labeled with the maturity indicator **CloudFormation\-only**\. + +The module level gives an indication of the stability of the majority of the APIs included in the module, however, individual APIs within the module can be annotated with different stability levels\. + + +| Stability | TypeScript | JavaScript | Python | C\#/\.NET | Java | +| --- |--- |--- |--- |--- |--- | +| Experimental | @experimental | @stability Experimental | @experimental | Stability: Experimental | Stability: Experimental | +| Stable | @stable | @stability Stable | @stable | Stability: Stable | Stability: Stable | +| Deprecated | @deprecated | @Deprecated | @deprecated | \[Obsolete\] | Stability: Deprecated | + +### Language Binding Stability + +In addition to modules of the AWS CDK Construct Library, language support is also subject to a stability indication\. Although the API described in all the languages is the same, the specific programming model and naming of language bindings is considered experimental and can change as it stabilizes\. + + +| Language | Stability | +| --- |--- | +| TypeScript | Stable | +| JavaScript | Stable | +| Python | Stable | +| Java | Experimental | +| C\#/\.NET | Experimental | \ No newline at end of file diff --git a/doc_source/resources.md b/doc_source/resources.md index 3ac510e8..7df2b508 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1,56 +1,248 @@ --------- +# Resources -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. +As described in [Constructs](constructs.md), the AWS CDK provides a rich class library of constructs, called *AWS constructs*, that represent all AWS resources\. This section describes some common patterns and best practices for how to use these constructs\. --------- +Defining AWS resources in your CDK app is exactly like defining any other construct\. You create an instance of the construct class, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here’s how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. -# Resources +``` +import sqs = require('@aws-cdk/aws-sqs'); + +new sqs.Queue(this, 'MyQueue', { + encryption: sqs.QueueEncryption.KmsManaged +}); +``` -The CDK creates the low\-level resources from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) on a regular basis\. The classes are available under the `CfnXxx` classes of each AWS library\. Their API matches 1:1 with how you would use these resources in AWS CloudFormation\. +Some configuration props are optional, and in many cases have default values\. In some cases, all props are optional, and the last argument can be omitted entirely\. -When defining AWS CloudFormation resources, the `props` argument of the class initializer matches 1:1 to the resource's properties in AWS CloudFormation\. +## Resource Attributes -For example, to define an [AWS::SQS::Queue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html) resource encrypted with an AWS managed key, you can directly specify the [KmsMasterKeyId](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-kmsmasterkeyid) property\. +Most resources in the AWS Construct Library expose attributes, which are resolved at deployment time by AWS CloudFormation\. Attributes are exposed in the form of properties on the resource classes with the type name as a prefix\. The following example shows how to get the URL of an Amazon SQS queue using the `queueUrl` property\. ``` import sqs = require('@aws-cdk/aws-sqs'); - -new sqs.CfnQueue(this, 'MyQueueResource', { - kmsMasterKeyId: 'alias/aws/sqs' + +const queue = new sqs.Queue(this, 'MyQueue'); + +queue.queueUrl; // => A string representing a deploy-time value +``` + +See [Tokens](tokens.md) for information about how the AWS CDK encodes deploy\-time attributes as strings\. + +## Referencing Resources + +Many AWS CDK classes require properties that are AWS CDK resource objects \(resources\)\. To satisfy these requirements, you can refer to a resource in one of two ways: ++ By passing the resource directly ++ By passing the resource's unique identifier, which is typically an ARN, but it could also be an ID or a name + +For example, an Amazon ECS service requires a reference to the cluster on which it runs; an Amazon CloudFront distribution requires a reference to the bucket containing source code\. + +If a construct property represents another AWS construct, its type is that of the interface type of that construct\. For example, the Amazon ECS service takes a property `cluster` of type `ecs.ICluster`; the CloudFront distribution takes a property `sourceBucket` of type `s3.IBucket`\. + +Because every resource implements its corresponding interface, you can directly pass any resource object you're defining in the same AWS CDK app\. The following example defines an Amazon ECS cluster and then uses it to define an Amazon ECS service\. + +``` +const cluster = new ecs.Cluster(this, 'Cluster', { /* ... */ }); + +const service = new ecs.Service(this, 'Service', { + cluster: cluster, + /* ... */ }); ``` -For reference, if you use the [Queue](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-sqs/queue.html) construct, you can define managed queue encryption as follows\. +## Accessing Resources in a Different Stack + +You can access resources in a different stack, as long as they are in the same account and AWS Region\. The following example defines the stack `stack1`, which defines an Amazon S3 bucket\. Then it defines a second stack, `stack2`, which takes the bucket from `stack1` as a constructor property\. ``` -import sqs = require('@aws-cdk/aws-sqs'); - -new sqs.Queue(this, 'MyQueue', { - encryption: sqs.QueueEncryption.KmsManaged +const prod = { account: '123456789012', region: 'us-east-1' }; + +const stack1 = new StackThatProvidesABucket(app, 'Stack1' , { env: prod }); + +// stack2 will take a property { bucket: IBucket } +const stack2 = new StackThatExpectsABucket(app, 'Stack2', { + bucket: stack1.bucket, + env: prod +}); +``` + +If the AWS CDK determines that the resource is in the same account and Region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. + +## Physical Names + +The logical names of resources in AWS CloudFormation are different from the names of resources that are shown in the AWS Management Console after AWS CloudFormation has deployed the resources\. The AWS CDK calls these final names *physical names*\. + +For example, AWS CloudFormation might create the Amazon S3 bucket with the logical ID **Stack2MyBucket4DD88B4F** from the previous example with the physical name **stack2mybucket4dd88b4f\-iuv1rbv9z3to**\. + +You can specify a physical name when creating constructs that represent resources by using the property Name\. The following example creates an Amazon S3 bucket with the physical name **my\-bucket\-name**\. + +``` +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket-name', +}); +``` + +Assigning physical names to resources has some disadvantages in AWS CloudFormation\. Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource's properties that are immutable after creation, will fail if a resource has a physical name assigned\. If you end up in a state like that, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again\. See the [AWS CloudFormation documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) for details\. + +In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value `PhysicalName.GENERATE_IF_NEEDED,`, as follows\. + +``` +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: PhysicalName.GENERATE_IF_NEEDED, +}); +``` + +## Passing Unique Identifiers + +Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. For example, when you are using the low\-level AWS CloudFormation resources, or need to expose resources to the runtime components of an AWS CDK application, such as when referring to Λ functions through environment variables\. + +These identifiers are available as attributes on the resources, such as the following\. + +``` +bucket.bucketName +lambda.functionArn +securityGroup.securityGroupId +``` + +The following example shows how to pass a generated bucket name to an AWS Lambda function\. + +``` +const bucket = new s3.Bucket(this, 'Bucket'); + +new lambda.Function(this, 'MyLambda', { + /* ... */, + environment: { + BUCKET_NAME: bucket.bucketName, + }, +}); +``` + +## Importing Existing External Resources + +Sometimes you already have a resource in your AWS account and want to use it in your AWS CDK app, for example, a resource that was defined through the console, the AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource’s ARN \(or another identifying attribute, or group of attributes\) into an AWS CDK object in the current stack by calling a static factory method on the resource's class\. + +The following example shows how to define a bucket based on the existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a VPC based on the existing VPC with the resource name `booh`\. + +``` +// Construct a resource (bucket) just by its name (must be same account) +Bucket.fromName(this, 'Bucket', 'my-bucket-name'); + +// Construct a resource (bucket) by its full ARN (can be cross account) +Bucket.fromArn(this, 'Bucket', 'arn:aws:s3:::my-bucket-name'); + +// Construct a resource by giving more than one attribute (complex resources) +Resource.fromAttributes(this, 'MyResource', { + resourceName: 'booh', + vpc: vpc +}); +``` + +Because the `ec2.Vpc` construct is composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables\), the complexity makes it difficult to import those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future usage in `cdk.context.json`\. + +The following example shows how to get the default VPC of a stack’s environment\. + +``` +ec2.Vpc.fromLookup(this, 'DefaultVpc’, { + isDefault: true }); ``` -## Resource Object Properties +Note that this approach works only for stacks that are defined with an explicit **account** and **region** in their `env` property\. If this is called from an [environment\-agnostic stack](stacks.md#stack_api), the CLI does not know which environment to query for the VPC\. + +Although you can use an imported resource anywhere, you cannot modify the imported resource\. For example, calling `addToResourcePolicy` on an imported `s3.IBucket` does nothing\. + +## Permission Grants + +AWS constructs make least\-privilege permissions easy to achieve by offering simple, intent\-based APIs to express permission requirements\. Many AWS constructs offer grant methods that enable you to easily grant an entity, such as an IAM role or a user, permission to work with the resource without having to manually craft one or more IAM permission statements\. + +The following example creates the permissions to allow a Lambda function’s execution role to read and write objects to a particular Amazon S3 bucket\. If the Amazon S3 bucket is encrypted using an AWS KMS key, this method also grants the Lambda function's execution role permissions to decrypt using this key\. + +``` +bucket.grantReadWrite(lambda); +``` + +The grant methods return an `iam.Grant` object\. Use the success attribute of the `Grant` object to determine whether the grant was effectively applied \(for example, it may not have been applied on [imported resources](#resources_referencing)\)\. You can also use the `assertSuccess` method of the `Grant` object to enforce that the grant was successfully applied\. -Use resource object properties to get a runtime attribute of an AWS CloudFormation resource\. +If a specific grant method isn't available for the particular use case, you can use a generic grant method to define a new grant with a specified list of actions\. -The following example configures the dead letter queue of an AWS Lambda function to use the Amazon Resource Name \(ARN\) of an Amazon SQS queue resource\. +The following example shows how to grant a Lambda function access to the Amazon DynamoDB `CreateBackup` action\. ``` +table.grant(lambda, 'dynamodb:CreateBackup'); +``` + +Many resources, such as Lambda functions, require a role to be assumed when executing code\. A configuration property enables you to specify an `iam.IRole`\. If no role is specified, the function automatically creates a role specifically for this use\. You can then use grant methods on the resources to add statements to the role\. + +The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-iam-readme.html) objects\. Add statements directly to roles \(or a construct’s attached role\) using the `addToRolePolicy` method, or to a resource’s policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` method\. + +## Metrics and Alarms + +Many resources emit CloudWatch metrics that can be used to set up monitoring dashboards and alarms\. AWS constructs have metric methods that allow easy access to the metrics without having to look up the correct name to use\. + +The following example shows how to define an alarm when the `ApproximateNumberOfMessagesNotVisible` of an Amazon SQS queue exceeds 100\. + +``` +import cw = require('@aws-cdk/aws-cloudwatch'); import sqs = require('@aws-cdk/aws-sqs'); -import lambda = require('@aws-cdk/aws-lambda'); - -const dlq = new sqs.CfnQueue(this, { name: 'DLQ' }); - -new lambda.CfnFunction(this, { - deadLetterConfig: { - targetArn: dlq.queueArn - } +import { Duration } from '@aws-cdk/core'; + +const queue = new sqs.Queue(this, 'MyQueue'); + +const metric = queue.metricApproximateNumberOfMessagesNotVisible({ + label: 'Messages Visible (Approx)', + period: Duration.minutes(5), + // ... +}); +metric.createAlarm(this, 'TooManyMessagesAlarm', { + comparisonOperator: cw.ComparisonOperator.GreaterThan, + threshold: 100, + // ... }); ``` -The [cdk\.CfnReference](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/cfnreference.html) attribute represents the AWS CloudFormation resource's intrinsic reference \(or *return value*\)\. For example, *dlq\.ref* also [refers](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-properties-sqs-queues-ref) to the queue's ARN\. When possible, use an explicitly named attribute instead of *ref*\. +If there is no method for a particular metric, you can use the general metric method to specify the metric name manually\. + +Metrics can also be added to CloudWatch dashboards\. See [CloudWatch](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudwatch-readme.html)\. + +## Network Traffic + +In many cases, you must enable permissions on a network for an application to work, such as when the compute infrastructure needs to access the persistence layer\. Resources that establish or listen for connections expose methods that enable traffic flows, including setting security group rules or network ACLs\. + +[IConnectable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Iconnectable.html) resources have a `connections` property that is the gateway to network traffic rules configuration\. + +You enable data to flow on a given network path by using `allow` methods\. The following example enables HTTPS connections to the web and incoming connections from the Amazon EC2 Auto Scaling group `fleet2`\. + +``` +import asg = require('@aws-cdk/aws-autoscaling'); +import ec2 = require('@aws-cdk/aws-ec2'); -## Resource Options +const fleet: asg.AutoScalingGroup = /*…*/ -For resources, the [CfnResource\.options](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/cfnresource.html#cdk_CfnResource_options) object includes AWS CloudFormation options, such as `condition`, `updatePolicy`, `createPolicy`, and `metadata`\. \ No newline at end of file +// Allow surfing the (secure) web +fleet.connections.allowTo(new ec2.AnyIpv4(), new ec2.Port(443)); + +const fleet2: asg.AutoScalingGroup = this.newASG(); +fleet.connections.allowFrom(fleet2); +``` + +Certain resources have default ports associated with them, for example, the listener of a load balancer on the public port, and the ports on which the database engine accepts connections for instances of an Amazon RDS database\. In such cases, you can enforce tight network control without having to manually specify the port by using the `allowDefaultPortFrom` and `allowToDefaultPort` methods\. + +The following example shows how to enable connections from any IPV4 address, and a connection from an Auto Scaling group to access a database\. + +``` +listener.connections.allowDefaultPortFromAnyIpv4('Allow public access'); + +fleet.connections.allowToDefaultPort(rdsDatabase, 'Fleet can access database'); +``` + +## Amazon CloudWatch Events + +Some resources can act as event sources\. Use the `addEventNotification` method to register an event target to a particular event type emitted by the resource\. In addition to this, `addXxxNotification` methods offer a simplified way to register a handler for a common event type\. + +The following example shows how to trigger a Lambda function when an object is added to an Amazon S3 bucket\. + +``` +Import targets = require('@aws-cdk/aws-events-targets'); +const handler = new lambda.Function(this, 'Handler', { /*…*/ }); +const bucket = new s3.Bucket(this, 'Bucket'); +bucket.addObjectCreatedNotification(new targets.LambdaFunction(hanlder)); +``` \ No newline at end of file diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 85adae74..6b8324d0 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -1,9 +1,3 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Creating a Serverless Application Using the AWS CDK This example walks you through how to create the resources for a simple widget dispensing service\. It includes: @@ -13,13 +7,13 @@ This example walks you through how to create the resources for a simple widget d This tutorial contains the following steps\. -1. Creates a CDK app +1. Creates a AWS CDK app 1. Creates a Lambda function that gets a list of widgets with: GET / 1. Creates the service that calls the Lambda function -1. Adds the service to the CDK app +1. Adds the service to the AWS CDK app 1. Tests the app @@ -28,7 +22,7 @@ This tutorial contains the following steps\. + Get a widget by name with GET /\{name\} + Delete a widget by name with DELETE /\{name\} -## Create a CDK App +## Create a AWS CDK App Create the TypeScript app **MyWidgetService** in the current folder\. @@ -47,7 +41,7 @@ npm run build cdk synth ``` -You should see a stack like the following, where *CDK\-VERSION* is the version of the CDK\. +You should see a stack like the following, where *CDK\-VERSION* is the version of the AWS CDK\. ``` Resources: @@ -128,20 +122,20 @@ npm install @aws-cdk/aws-apigateway @aws-cdk/aws-lambda @aws-cdk/aws-s3 Create the TypeScript file `widget_service.ts` in the `lib` directory\. ``` -import cdk = require("@aws-cdk/cdk"); +import core = require("@aws-cdk/core"); import apigateway = require("@aws-cdk/aws-apigateway"); import lambda = require("@aws-cdk/aws-lambda"); import s3 = require("@aws-cdk/aws-s3"); -export class WidgetService extends cdk.Construct { - constructor(scope: cdk.Construct, id: string) { +export class WidgetService extends core.Construct { + constructor(scope: core.Construct, id: string) { super(scope, id); const bucket = new s3.Bucket(this, "WidgetStore"); const handler = new lambda.Function(this, "WidgetHandler", { - runtime: lambda.Runtime.NodeJS810, // So we can use async in widget.js - code: lambda.Code.directory("resources"), + runtime: lambda.Runtime.NODEJS_8_10, // So we can use async in widget.js + code: lambda.Code.asset("resources"), handler: "widgets.main", environment: { BUCKET: bucket.bucketName @@ -209,7 +203,7 @@ cdk synth ## Deploy and Test the App -Before you can deploy your first CDK app, you must bootstrap your deployment\. This creates some AWS infrastructure that the CDK needs\. For details, see the **bootstrap** section of the [CDK Toolchain](tools.md)\(if you've already bootstrapped a CDK app, you'll get a warning and nothing will change\)\. +Before you can deploy your first AWS CDK app, you must bootstrap your deployment\. This creates some AWS infrastructure that the AWS CDK needs\. For details, see the **bootstrap** section of the [AWS CDK Tools](tools.md)\(if you've already bootstrapped a AWS CDK app, you'll get a warning and nothing will change\)\. ``` cdk bootstrap diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index 7fe83c55..efeb64d6 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -1,30 +1,22 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Create an App with Multiple Stacks -The following example shows one solution to parameterizing how you create a stack\. It creates one stack with a `t2.micro` AMI for development, and three stacks with the more expensive `c5.2xlarge` AMI\. The development stack and one of the production stacks use the same account to create the stack in `us-east-1`; the other two production stacks use different account IDs and regions\. - -The file `MyApp-stack.ts` defines a property set that extends the `cdk.StackProps` class to add one additional property, `enc`, which specifies whether to set encryption on the Amazon S3 bucket in the stack\. +The following example shows one solution to parameterizing how you create a stack\. It defines a property set that extends the `cdk.StackProps` class to add one additional property, `enc`, which specifies whether to set encryption on the Amazon S3 bucket in the stack\. ``` -import cdk = require("@aws-cdk/cdk"); +import core = require("@aws-cdk/core"); import s3 = require("@aws-cdk/aws-s3"); -interface MyStackProps extends cdk.StackProps { +interface MyStackProps extends core.StackProps { enc: boolean; } -export class MyStack extends cdk.Stack { - constructor(scope: cdk.App, id: string, props: MyStackProps) { +export class MyStack extends core.Stack { + constructor(scope: core.App, id: string, props: MyStackProps) { super(scope, id, props); if (props.enc) { new s3.Bucket(this, "MyGroovyBucket", { - encryption: s3.BucketEncryption.KmsManaged + encryption: s3.BucketEncryption.KMS_MANAGED }); } else { new s3.Bucket(this, "MyGroovyBucket"); @@ -36,10 +28,10 @@ export class MyStack extends cdk.Stack { The file `MyApp.ts` creates two stacks\. One with an unencrypted bucket in the `us-west-2` region; the other with an encrypted bucket in the `us-east-1` region\. ``` -import cdk = require("@aws-cdk/cdk"); +import core = require("@aws-cdk/core"); import { MyStack } from "../lib/MyApp-stack"; -const app = new cdk.App(); +const app = new core.App(); new MyStack(app, "MyWestCdkStack", { env: { diff --git a/doc_source/stacks.md b/doc_source/stacks.md new file mode 100644 index 00000000..ff10929b --- /dev/null +++ b/doc_source/stacks.md @@ -0,0 +1,82 @@ +# Stacks + +The unit of deployment in the AWS CDK is called a *stack*\. All AWS resources defined within the scope of a stack, either directly or indirectly, are provisioned as a single unit\. + +Because AWS CDK stacks are implemented through AWS CloudFormation stacks, they have the same limitations as in [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html)\. + +You can define any number of stacks in your AWS CDK app\. Any instance of the `Stack` construct represents a stack, and can be either defined directly within the scope of the app, like the `MyFirstStack` example shown previously, or indirectly by any construct within the tree\. + +For example, the following code defines an AWS CDK app with two stacks\. + +``` +const app = new App(); + +new MyFirstStack(app, 'stack1'); +new MySecondStack(app, 'stack2'); + +app.run(); +``` + +To list all the stacks in an AWS CDK app, run the cdk ls command, which for the previous AWS CDK app would have the following output\. + +``` +stack1 +stack2 +``` + +When you run the cdk synth command for an app with multiple stacks, the cloud assembly includes a separate template for each stack instance\. Even if the two stacks are instances of the same class, the AWS CDK emits them as two individual templates\. + +You can synthesize each template by specifying the stack name in the cdk synth command\. The following example synthesizes the template for **stack1**\. + +``` +cdk synth stack1 +``` + +This approach is conceptually different from how AWS CloudFormation templates are normally used, where a template can be deployed multiple times and parameterized through [AWS CloudFormation parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html)\. Although AWS CloudFormation parameters can be defined in the AWS CDK, they are generally discouraged because AWS CloudFormation parameters are resolved only during deployment\. This means that you cannot determine their value in your code\. For example, to conditionally include a resource in your app based on the value of a parameter, you must set up an [AWS CloudFormation condition](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) and tag the resource with this condition\. Because the AWS CDK takes an approach where concrete templates are resolved at synthesis time, you can use an **if** statement to check the value to determine whether a resource should be defined or some behavior should be applied\. + +**Note** +The AWS CDK provides as much resolution as possible during synthesis time to enable idiomatic and natural usage of your programming language\. + +Like any other construct, stacks can be composed together into groups\. The following pseudocode shows an example of a service that consists of three stacks: a control plane, a data plane, and monitoring stacks\. The service construct is defined twice: once for the beta environment and once for the production environment\. + +``` +class ControlPlane extends Stack { ... } +class DataPlane extends Stack { ... } +class Monitoring extends Stack { ... } + +class MyService extends Construct { + constructor(...) { + new ControlPlane(this, ...); + new DataPlane(this, ...); + new Monitoring(this, ...); + } +} + +const app = new App(); +new MyService(app, 'beta'); +new MyService(app, 'prod', { prod: true }); +app.run(); +``` + +This AWS CDK app eventually consists of six stacks, three for each environment\. + +The physical names of the AWS CloudFormation stacks are automatically determined by the AWS CDK based on the stack's construct path in the tree\. By default, a stack's name is derived from the construct ID of the `Stack` object, but you can specify an explicit name using the `stackName` prop, as follows\. + +``` +new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name' }); +``` + +## Stack API + +The [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/stack.html) object provides a rich API, including the following: ++ `Stack.of(construct)` – A static method that returns the **Stack** in which a construct is defined\. This is useful if you need to interact with a stack from within a reusable construct\. The call fails if a stack cannot be found in scope\. ++ `stack.stackName` – Returns the physical name of the stack\. As mentioned previously, all AWS CDK stacks have a physical name that the AWS CDK can resolve during synthesis\. ++ `stack.region` and `stack.account` – Return the AWS Region and account, respectively, into which this stack will be deployed\. These properties return either the account or Region explicitly specified when the stack was defined, or a string\-encoded token that resolves to the AWS CloudFormation pseudo\-parameters for account and Region to indicate that this stack is environment agnostic\. See [Environments](environments.md) for information about how environments are determined for stacks\. ++ `stack.account` – Returns the AWS account into which this stack will be deployed\. Similarly to Region, this property returns either an explicit account ID or a token that resolves to \{ Ref: AWS::AccountId \}\. Use `Token.isUnresolved` method to determine whether the value is a token before reading the value returned from this property\. ++ `stack.addDependency(stack)` – Can be used to explicitly define dependency order between two stacks\. This order is respected by the cdk deploy command when deploying multiple stacks at once\. ++ `stack.tags` – Returns a [TagManager](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/tagmanager.html#core_TagManager) that you can use to add or remove stack\-level tags\. This tag manager tags all resources within the stack, and also tags the stack itself when it’s created through AWS CloudFormation\. ++ `stack.partition`, `stack.urlSuffix`, `stack.stackId`, and `stack.notificationArn` – Return tokens that resolve to the respective AWS CloudFormation pseudo\-parameters, such as \{ "Ref": "AWS::Partition" \}\. These tokens are associated with this specific stack object, so the framework can identify cross\-stack references\. ++ `stack.availabilityZones` – Returns the set of Availability Zones available in the environment in which this stack is deployed\. For environment\-agnostic stacks, this always returns an array with two Availability Zones, but for environment\-specific stacks, the AWS CDK queries the environment and returns the exact set of Availability Zones that are available\. ++ `stack.parseArn(arn)` and `stack.formatArn(comps)` – Can be used to work with Amazon Resource Names \(ARNs\)\. ++ `stack.toJsonString(obj)` – Can be used to format an arbitrary object as a JSON string that can be embedded in an AWS CloudFormation template\. The object can include tokens, attributes, and references, which are only resolved during deployment\. ++ `stack.templateOptions` – Enables you to specify AWS CloudFormation template options, such as Transform, `Description`, and Metadata, for your stack\. \ No newline at end of file diff --git a/doc_source/tagging.md b/doc_source/tagging.md new file mode 100644 index 00000000..d988dc51 --- /dev/null +++ b/doc_source/tagging.md @@ -0,0 +1,103 @@ +# Tagging + +The AWS CDK includes two classes that you can use to create and delete tags: ++ [Tag](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html) applies a new tag to a construct and all of its children\. ++ [RemoveTag](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.RemoveTag.html) removes a tag from a construct and any of its children, including tags a child construct may have applied to itself\. + +Let's look at a couple of examples\. + +The following example applies the tag **key** with the value **value** to `myConstruct`\. + +``` +myConstruct.node.applyAspect(new Tag('key', 'value')); +``` + +The following example deletes the tag **key** from `myConstruct`\. + +``` +myConstruct.node.applyAspect(new RemoveTag('key')); +``` + +The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. If the priorities are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 and removing a tag has a priority of 200\. To change the priority of applying a tag, pass a `priority` option to `Tag` or `RemoveTag`\. + +The following applies a tag with a priority of 300 to `myConstruct`\. + +``` +myConstruct.node.applyAspect(new Tag('key', 'value', { + priority: 300 +})); +``` + +## Tag + +The `Tag` operation includes some properties to fine\-tune how tags are applied from the resources that the construct creates, all of which are optional\. + +The following example applies the tag **tagname** with the value **value** and priority **100** to resources of type **AWS::Xxx::Yzz** in `myConstruct`, but not to instances launched in an Amazon EC2 Auto Scaling group or to resources of type **AWS::Xxx::Zss**\. + +``` +myConstruct.node.applyAspect(new Tag('tagname', 'value', { + applyToLaunchedInstances: false, + includeResourceTypes: ['AWS::Xxx::Yyy'], + excludeResourceTypes: ['AWS::Xxx::Zzz'], + priority: 100, +})); +``` + +These properties have the following meanings\. + +applyToLaunchedInstances +By default, tags are applied to instances launched in an Auto Scaling group\. Set this property to **false** to not apply tags to instances launched in an Auto Scaling group\. + +includeResourceTypes/excludeResourceTypes +Use these to apply tags only to a subset of resources, based on AWS CloudFormation resource types\. By default, the tag is applied to all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. + +priority +Use this to set the priority of this operation with respect to other `Tag` and `RemoveTag` operations\. Higher values take precedence over lower values\. The default is 100\. + +## RemoveTag + +The `RemoveTag` class includes properties to fine\-tune how tags are removed, all of which are optional\. + +The following example removes the tag **tagname** with priority **200** from resources of type **AWS::Xxx::Yzz** in `myConstruct`, but not to resources of type **AWS::Xxx::Zzz**\. + +``` +myConstruct.node.applyAspect(new RemoveTag('tagname', { + includeResourceTypes: ['AWS::Xxx::Yyy'], + excludeResourceTypes: ['AWS::Xxx::Zzz'], + priority: 200, +})); +``` + +These properties have the following meanings\. + +includeResourceTypes/excludeResourceTypes +Use these properties to remove tags only from subset of resources based on AWS CloudFormation resource types\. By default, the tag is removed from all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. + +priority +Use this property to specify the priority of this operation with respect to other `Tag` and `RemoveTag` operations\. Higher values take precedence over lower values\. The default is 200\. + +## Example + +The following example adds the tag key **StackType** with value **TheBest** to any resource created within the Stack named `MarketingSystem`\. Then it removes it again from all resources except Amazon EC2 VPC subnets\. The result is that only the subnets have the tag applied\. + +``` +import { App, RemoveTag, Stack, Tag } from require('@aws-cdk/cdk'); + +const app = new App(); +const theBestStack = new Stack(app, 'MarketingSystem'); + +// Add a tag to all constructs in the stack +theBestStack.node.applyAspect(new Tag('StackType', 'TheBest')); + +// Remove the tag from all resources except subnet resources +theBestStack.node.applyAspect(new RemoveTag('StackType'), { + exludeResourceTypes: ['AWS::EC2::Subnet'] +})); +``` + +**Note** +You can achieve the same result by using the following\. + +``` +theBestStack.node.applyAspect(new Tag('StackType', 'TheBest', { includeResourceTypes: [‘AWS::EC2::Subnet’]})); +``` \ No newline at end of file diff --git a/doc_source/tokens.md b/doc_source/tokens.md index 3b5c286c..63df4d4d 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -1,9 +1,130 @@ --------- +# Tokens -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. +Tokens represent values that can only be resolved at a later time in the lifecycle of an app \(see [App Lifecycle](apps.md#lifecycle)\)\. For example, the name of an Amazon S3 bucket that you define in your AWS CDK app is only allocated by AWS CloudFormation when you deploy your app\. If you print the `bucket.bucketName` attribute, which is a string, you see it contains something like the following\. --------- +``` +${TOKEN[Bucket.Name.1234]} +``` -# Tokens +This is how the AWS CDK encodes a token whose value is not yet known at construction time, but will become available later\. The AWS CDK calls these placeholders *tokens*\. In this case, it’s a token encoded as a string\. + +You can pass this string around as if it was the name of the bucket, such as in the following example, where the bucket name is specified as an environment variable to an AWS Lambda function\. + +``` +const bucket = new s3.Bucket(this, 'Bucket'); + +const fn = new lambda.Function(stack, 'MyLambda', { + // ... + environment: { + BUCKET_NAME: bucket.bucketName, + } +}); +``` + +When the AWS CloudFormation template is finally synthesized, the token is rendered as the AWS CloudFormation intrinsic `{ "Ref": "MyBucket" }`\. At deployment time, AWS CloudFormation replaces this intrinsic with the actual name of the bucket that was created\. + +## Tokens and Token Encodings + +Tokens are objects that implement the [IResolvable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.IResolvable.html) interface, which contains a single `resolve` method\. The AWS CDK calls this method during synthesis to produce the final value for the AWS CloudFormation template\. Tokens participate in the synthesis process to produce arbitrary values of any type\. + +**Note** +You’ll hardly ever work directly with the `IResolvable` interface\. You will most likely only see string\-encoded versions of tokens\. + +Other functions typically only accept arguments of basic types, such as `string` or `number`\. To use tokens in these cases, you can encode them into one of three types using static methods on the [core\.Token](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html) class\. ++ Strings using [Token\.asString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) ++ List of strings using [Token\.asList](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) ++ Number \(float\) using [Token\.asNumber](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) + +These take an arbitrary value, which can also be an `IResolvable` interface, and encode them into a primitive value of the appropriate type\. + +**Important** +Because any one of the previous types can potentially be an encoded token, be careful when you parse or try to read their contents\. For example, if you attempt to parse a string to extract a value from it, and the string is an encoded token, your parsing will fail\. Similarly, if you attempt to query the length of an array, or perform math operations with a number, you must first verify that they are not encoded tokens\. + +To check whether a value has an unresolved token in it, call the `Token.isUnresolved` method\. + +The following example validates that the length of a value, which could be a token, is no more than 10 characters\. + +``` +if (!Token.isUnresolved(name) && name.length > 10) { + throw new Error(`Maximum length for name is 10 characters`); +} +``` + +If **name** is a token, validation is not be performed, and the error could occur in a later stage in the lifecycle, such as during deployment\. + +**Note** +You can use token encodings to escape the type system\. For example, you could string\-encode a token that produces a number value at synthesis time\. If you use these functions, it’s your responsibility to ensure that your template resolves to a usable state after synthesis\. + +## String\-Encoded Tokens + +String\-encoded tokens look like the following\. + +``` +${TOKEN[Bucket.Name.1234]} +``` + +They can be passed around like regular strings, and can be concatenated, as shown in the following example\. + +``` +const functionName = bucket.bucketName + 'Function'; +``` + +In languages that support it, you can also use string interpolation, as shown in the following example\. + +``` +const functionName = `${bucket.bucketName}Function`; +``` + +Concatenation is safe, but avoid manipulating the string in other ways\. For example, taking a substring of a string is likely to break the string token\. + +## List\-Encoded Tokens + +List\-encoded tokens look like the following + +``` +["#{TOKEN[Stack.NotificationArns.1234]}"] +``` + +The only safe thing to do with these lists is pass them directly to other constructs\. Tokens in string list form cannot be concatenated, nor can an element be taken from the token\. The only safe way to manipulate them is by using AWS CloudFormation intrinsic functions like [Fn\.select](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-select.html)\. + +## Number\-Encoded Tokens + +Number\-encoded tokens are a set of very tiny negative floating\-point numbers that look like the following\. + +``` +-1.8881545897087626e+289 +``` + +As with list tokens, you cannot modify the number value, as doing so is likely to break the number token\. The only allowed operation is to pass the value around to another construct\. + +## Lazy Values + +In addition to representing deploy\-time values, such as AWS CloudFormation attributes\), Tokens are also commonly used to represent synthesis\-time lazy values\. These are values for which the final value will be determined before synthesis has completed, just not at the point where the value is constructed\. Use tokens to pass a literal string or number value to another construct, while the actual value at synthesis time may depend on some calculation that has yet to occur\. + +You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.stringValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-string-valueproducer-options) and [Lazy\.numberValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-number-valueproducer)\. For following example creates an Auto Scaling group whose capacity is determined after its creation\. + +``` +let actualValue: number; + +new AutoScalingGroup(this, ‘Group’, { + desiredCapacity: Lazy.numberValue({ + produce() { + return actualValue; + } + }) +}); + +// At some later point +actualValue = 10; +``` + +## Converting to JSON + +Sometimes you have to produce a JSON string of arbitrary data, and you may not know whether the data contains tokens\. To properly JSON\-encode any data structure, regardless of whether it contains tokens, use the [stack\.toJsonString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#to-json-stringobj-space), as shown in the following example\. -Tokens represent instrinsic AWS CloudFormation values or values that not are known until deployment\. \ No newline at end of file +``` +const stack = Stack.of(this); + const str = stack.toJsonString({ + value: bucket.bucketName + }); +``` \ No newline at end of file diff --git a/doc_source/tools.md b/doc_source/tools.md index a8bf23fd..80e0699c 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -1,20 +1,12 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(AWS CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # AWS CDK Tools -This topic describes the tools you can use to work with the AWS CDK\. These tools include the AWS CDK Command Line Interface \(cdk\) and AWS SAM CLI\. +This section contains information about AWS CDK tools\. ## AWS CDK Command Line Interface \(cdk\) -The AWS CDK CLI, known as the cdk, is your main tool for interacting with your AWS CDK app\. The cdk executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates that the AWS CDK generates\. - -There are two ways to tell the cdk what command to use to run your AWS CDK app\. +The AWS CDK CLI, cdk, is the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. -The first way is to include an explicit \-\-app option whenever you use a cdk command\. +There are two ways to tell cdk what command to use to run your AWS CDK app\. The first way is to include an explicit \-\-app option whenever you use a cdk command\. ``` cdk --app "npx ts-node bin/hello-cdk.ts" ls @@ -28,7 +20,7 @@ The second way is to add the following entry to the `cdk.json` file \(if you use } ``` -You can also use the npx cdk instead of just the cdk\. +You can also use the npx cdk instead of just cdk\. Here are the actions you can take on your AWS CDK app \(this is the output of the cdk \-\-help command\)\. @@ -36,41 +28,39 @@ Here are the actions you can take on your AWS CDK app \(this is the output of th Usage: cdk -a COMMAND Commands: - cdk list List all stacks in the app [aliases: ls] - cdk synthesize [STACKS..] Synthesize and print the AWS CloudFormation + cdk list [STACKS..] Lists all stacks in the app [aliases: ls] + cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation template for this stack [aliases: synth] - cdk bootstrap [ENVIRONMENTS..] Deploy the CDK toolkit stack into an AWS + cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS environment - cdk deploy [STACKS..] Deploy the stack(s) named STACKS into your + cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your AWS account cdk destroy [STACKS..] Destroy the stack(s) named STACKS - cdk diff [STACKS..] Compare the specified stack with the deployed + cdk diff [STACKS..] Compares the specified stack with the deployed stack or a local template file, and returns with status 1 if any difference is found - cdk metadata [STACK] Return all metadata associated with this + cdk metadata [STACK] Returns all metadata associated with this stack cdk init [TEMPLATE] Create a new, empty CDK project from a template. Invoked without TEMPLATE, the app template will be used. cdk context Manage cached context values - cdk docs Open the reference documentation in a browser + cdk docs Opens the reference documentation in a browser [aliases: doc] - cdk doctor Check your setup for potential problems + cdk doctor Check your set-up for potential problems Options: - --app, -a REQUIRED: command line for executing your app or a cloud - assembly directory (e.g., "node bin/my-app.js") [string] + --app, -a REQUIRED: command-line for executing your app or a cloud + assembly directory (e.g. "node bin/my-app.js") [string] --context, -c Add contextual string parameter (KEY=VALUE) [array] - --plugin, -p Name or path of a node package that extends the CDK + --plugin, -p Name or path of a node package that extend the CDK features. Can be specified multiple times [array] - --rename Rename stack name if different from the one defined in - the cloud executable ([ORIGINAL:]RENAMED) [string] --trace Print trace for stack warnings [boolean] --strict Do not construct stacks with warnings [boolean] - --ignore-errors Ignore synthesis errors, which will likely produce an + --ignore-errors Ignores synthesis errors, which will likely produce an invalid output [boolean] [default: false] - --json, -j Use JSON output instead of YAML - [boolean] [default: false] + --json, -j Use JSON output instead of YAML when templates are + printed to STDOUT [boolean] [default: false] --verbose, -v Show debug logs [boolean] [default: false] --profile Use the indicated AWS profile as the default environment [string] @@ -85,16 +75,16 @@ Options: --asset-metadata Include "aws:asset:*" CloudFormation metadata for resources that user assets (enabled by default) [boolean] [default: true] - --role-arn, -r ARN of role to use when invoking AWS CloudFormation [string] + --role-arn, -r ARN of Role to use when invoking CloudFormation [string] --toolkit-stack-name The name of the CDK toolkit stack [string] - --staging Copy assets to the output directory (use --no-staging to - disable, needed for local debugging of the source files + --staging copy assets to the output directory (use --no-staging to + disable, needed for local debugging the source files with SAM CLI) [boolean] [default: true] - --output, -o Emits the synthesized cloud assembly into a directory + --output, -o emits the synthesized cloud assembly into a directory (default: cdk.out) [string] --ci Force CI detection. Use --no-ci to disable CI autodetection. [boolean] [default: false] - --tags, -t Tags to add to the stack (KEY=VALUE) [array] + --tags, -t tags to add to the stack (KEY=VALUE) [array] --version Show version number [boolean] -h, --help Show help [boolean] @@ -106,34 +96,36 @@ as defaults. Settings in cdk.json take precedence. If your app has a single stack, you don't have to specify the stack name\. -### Bootstrapping Your AWS Environment +If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. -Before you can use the AWS CDK, you must create the infrastructure that the AWS CDK CLI \(cdk\) needs to deploy your AWS CDK app\. Currently the bootstrap command creates only an Amazon S3 bucket\. +### Bootstrapping your AWS Environment -You incur any charges for objects that the AWS CDK stores in the bucket\. Because the AWS CDK doesn't remove any objects from the bucket, the bucket accumulates them as you use the AWS CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. +Before you can use the AWS CDK you must bootstrap your AWS environment to create the infrastructure that the AWS CDK CLI needs to deploy your AWS CDK app\. Currently the bootstrap command creates only an Amazon S3 bucket\. + +You incur any charges for what the AWS CDK stores in the bucket\. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. ### Security\-Related Changes -To protect you against unintended changes that affect your security posture, the AWS CDK command\-line tool prompts you to approve security\-related changes before deploying them\. +To protect you against unintended changes that affect your security posture, the AWS CDK toolkit prompts you to approve security\-related changes before deploying them\. -You modify the level of changes that require approval by specifying the following\. +You change the level of changes that requires approval by specifying: ``` cdk deploy --require-approval LEVEL ``` -*LEVEL* can be one of the following values\. +Where *LEVEL* can be one of the following: never Approval is never required\. any\-change -Requires approval on any AWS Identity and Access Management \(IAM\) or security\-group related change\. +Requires approval on any IAM or security\-group related change\. broadening \(default\) Requires approval when IAM statements or traffic rules are added\. Removals don't require approval\. -You can also configure the setting in the `cdk.json` file\. +The setting can also be configured in the `cdk.json` file\. ``` { @@ -144,7 +136,7 @@ You can also configure the setting in the `cdk.json` file\. ### Version Reporting -To gain insight into how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. You can also use this information to identify stacks using a package with known serious security or reliability issues, and contact the package users with that important information\. +To gain insight into how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. The AWS CDK reports the name and version of `npm` modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. @@ -174,17 +166,11 @@ To opt out of version reporting, use one of the following methods: } ``` -## AWS SAM CLI - -This topic describes how to use the AWS SAM CLI with the AWS CDK to test an AWS Lambda function locally\.For more information about testing Lambda functions locally, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. - -To install 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)\. - -### AWS SAM Example +## SAM CLI -The following example walks you through creating an AWS CDK application with a Lambda function and testing that function locally using AWS SAM\. +This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. -1. Create an AWS CDK app and add the Lambda package\. +1. The first step is to create a AWS CDK application and add the Lambda package\. ``` mkdir cdk-sam-example @@ -193,13 +179,13 @@ The following example walks you through creating an AWS CDK application with a L npm install @aws-cdk/aws-lambda ``` -1. Add a Lambda reference to `lib/cdk-sam-example-stack.ts`\. +1. Add a Lambda reference to `lib/cdk-sam-example-stack.ts`: ``` import lambda = require('@aws-cdk/aws-lambda'); ``` -1. Replace the comment in `lib/cdk-sam-example-stack.ts` with the following Lambda function\. +1. Replace the comment in `lib/cdk-sam-example-stack.ts` with the following Lambda function: ``` new lambda.Function(this, 'MyFunction', { @@ -209,33 +195,33 @@ The following example walks you through creating an AWS CDK application with a L }); ``` -1. Create the directory `my_function`\. +1. Create the directory `my_function` ``` mkdir my_function ``` -1. Create the file `app.py` in `my_function` with the following content\. +1. Create the file `app.py` in `my_function` with the following content: ``` def lambda_handler(event, context): return "This is a Lambda Function defined through CDK" ``` -1. Compile your AWS CDK app and create an AWS CloudFormation template\. +1. Compile your AWS CDK app and create a AWS CloudFormation template ``` npm run build - cdk synth > template.yaml + cdk synth --no-staging > template.yaml ``` -1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an eight\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like the following\. +1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: ``` Type: AWS::Lambda::Function ``` -1. Run the function by executing the following code\. +1. Run the function by executing: ``` sam local invoke MyFunction12345678 --no-event diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 1fa6d5e3..04c0cd39 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -1,12 +1,6 @@ --------- +# Troubleshooting the AWS CDK -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Troubleshooting the CDK - -This section describes how to troubleshoot problems with your CDK app\. +This section describes how to troubleshoot problems with your AWS CDK app\. ## Inconsistent Module Versions @@ -27,7 +21,7 @@ lib/my_ecs_construct-stack.ts:56:49 - error TS2345: Argument of type 'this' is n 'root' is declared here. ``` -The solution is to delete the `node_modules` directory and re\-install your CDK modules: +The solution is to delete the `node_modules` directory and re\-install your AWS CDK modules: ``` rm -rf node_modules diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 87c45b13..c67fec21 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -1,12 +1,6 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - # Use an Existing AWS CloudFormation Template -The CDK provides a mechanism that you can use to incorporate resources from an existing AWS CloudFormation template into your CDK app\. For example, suppose you have a template, `my-template.json`, with the following resource, where *S3Bucket* is the logical ID of the bucket in your template: +The AWS CDK provides a mechanism that you can use to incorporate resources from an existing AWS CloudFormation template into your AWS CDK app\. For example, suppose you have a template, `my-template.json`, with the following resource, where *S3Bucket* is the logical ID of the bucket in your template: ``` { @@ -19,7 +13,7 @@ The CDK provides a mechanism that you can use to incorporate resources from an e } ``` -You can include this bucket in your CDK app, as shown in the following example \(note that you cannot use this method in an AWS Construct Library construct\): +You can include this bucket in your AWS CDK app, as shown in the following example: ``` import cdk = require("@amp;aws-cdk/cdk"); diff --git a/doc_source/writing_constructs.md b/doc_source/writing_constructs.md deleted file mode 100644 index 4645fd0d..00000000 --- a/doc_source/writing_constructs.md +++ /dev/null @@ -1,89 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# Writing AWS CDK Constructs - -This topic provides some tips for writing idiomatic new constructs for the CDK\. These tips apply equally to constructs written for inclusion in the AWS Construct Library, purpose\-built constructs to achieve a well\-defined goal, or constructs that serve as building blocks for assembling your cloud applications\. - -## General Design Principles -+ Favor composition over inheritance\. Most of the constructs should directly extend the `Construct` class instead of some other construct\. Use inheritance mainly to allow polymorphism\. Typically, you define a construct within your scope and expose any of its APIs and properties in the enclosing construct\. -+ Provide defaults for everything that a reasonable guess can be made for\. Ideally, `props` should be optional and `new MyAwesomeConstruct(this, "Foo")` should be enough to set up a reasonable variant of the construct\. This doesn't mean that the user should not have the opportunity to customize\! Instead, it means that the specific parameter should be optional and set to a reasonable value if it's not supplied\. This might involve creating other resources as part of initializing this construct\. For example, all resources that require a role allow passing in a `Role` object \(specifically, a `RoleRef` object\), but if the user doesn't supply one, an appropriate `Role` object is defined in place\. -+ Use contextual defaulting between properties\. The value of one property might affect sensible defaults for other properties\. For example: `enableDnsHostnames` and `enableDnsSupport`\. `dnsHostnames` require `dnsSupport`, so only throw an error if the user has explicitly disabled DNS Support, but tried to enable DNS ostnames\. A user expects things to just work\. -+ Make the user think about intent, not implementation detail\. For example, if establishing an association between two resources \(such as a `Topic` and a `Queue`\) requires multiple steps \(in this case, creating a `Subscription` but also setting appropriate IAM permissions\), make both things happen in a single call \(to `subscribeQueue()`\)\. -+ Don't rename concepts or terminology\. For example don't rename the Amazon SQS `dataKeyReusePeriod` to `keyRotation` because it will be hard for people to diagnose problems\. They won't be able to search for *sqs dataKeyReuse* and find topics on it\. It's permissible to introduce a concept if a counterpart doesn't exist in AWS CloudFormation, especially if it directly maps onto the mental model that users already have about a service\. -+ Optimize for the common case\. For example, `AutoScalingGroup` accepts a `VPC` and deploys in the private subnet by default because that's the common case, but has an option to `placementOptions` for special cases\. -+ If a class can have multiple modes or behaviors, prefer values over polymorphism\. Try switching behavior on property values first\. Switch to multiple classes with a shared base class or interface only if there's value to be had from having multiple classes \(type safety, maybe one mode has different featuresor required parameters\)\. - -## Implementation Details -+ Every construct consists of an exported class \(`MyConstruct`\) and an exported interface \(`MyConstructProps`\) that defines the parameters for these classes\. The `props` argument is the third to the construct \(after the mandatory `scope` and `id` arguments\), and the entire parameter should be optional if all of the properties on the `props` object are optional\. -+ Most of the logic happens in the constructor\. The constructor builds up the state of the construct \(what children it has, which ones are always there and which are optional, and so on\)\. -+ Validate as early as possible\. Throw an `Error` in the constructor if the parameters don't make sense\. Override the `validate()` method to validate mutations that can occur after construction time\. Validation has the following hierarchy: - + Best – Incorrect code won't compile, because of type safety guarantees\. - + Good – Runtime check everything the type checker can't enforce and fail early \(error in the constructor\)\. - + Okay – Validate everything that can't be checked at construction time at synth time \(error in `validate()`\)\. - + Not great – Fail with an error in AWS CloudFormation \(bad because the AWS CloudFormation deploy operation can take a long time, and the error can take several minutes to surface\)\. - + Very bad – Fail with a timeout during AWS CloudFormation deployment\. \(It can take up to an hour for resource stabilization to timeout\!\) - + Worst – Don't fail the deployment at all, but fail at runtime\. -+ Avoid unneeded hierarchy in `props`\. Try to keep the `props` interface flat to help discoverability\. -+ Constructs are classes that have a set of invariants they maintain over their lifetime \(such as which members are initialized, and relationships between properties as members that are mutated\)\. -+ Constructs mostly have write\-only scalar properties that are passed in the constructor, but mutating functions for collections \(for example, there will be `construct.addElement()` or `construct.onEvent()` functions, but not `construct.setProperty()`\)\. It's perfectly fine to deviate from this convention when it makes sense for your own constructs\. -+ Don't expose `Tokens` to your consumers\. Tokens are an implementation mechanism for one of two purposes: representing AWS CloudFormation intrinsic values, or representing lazily evaluated values\. You can use them for implementation purposes, but use more specific types as part of your public API\. -+ `Tokens` are \(mostly\) used only in the implementation of an AWS Construct Library to pass lazy values to other constructs\. For example, if you have an array that can be mutated during the lifetime of your class, you pass it to an AWS CloudFormation Resourceconstruct like so: `new cdk.Token(() => this.myList)`\. -+ Be aware that you might not be able to usefully inspect all strings\. Any string passed into your construct may contain special markers that represent values that will only be known at deploy time \(for example, the ARN of a resource that will be created during deployment\)\. Those are *stringified Tokens* and they look like `"${TOKEN[Token.123]}"`\. You will not be able to validate those against a regular expression, for example, as their real values are not known yet\. To determine whether your string contains a special marker, use `cdk.unresolved(string)`\. -+ Indicate units of measurement in property names that don't use a strong type\. For example, use **milli**, **sec**, **min**, **hr**, **Bytes**, **KiB**, **MiB**, and **GiB**\. -+ Be sure to define an `IMyResource` interface for your resources that defines the API area that other constructs will use\. Typical capabilities on this interface are querying for a resource ARN and adding resource permissions\. -+ Accept objects instead of ARNs or names\. When accepting other resources as parameters, declare your property as `resource: IMyResource` instead of `resourceArn: string`\. This makes snapping objects together feel natural to consumers, and allows you to query or modify the incoming resource as well\. For example, the latter is particularly useful if something about IAM permissions needs to be set\. -+ If your construct wraps a single \(or most prominent\) other construct, give it an ID of either **"Resource"** or **"Default"**\. The main resource that an AWS construct represents should use the ID **"Resource"** For higher\-level wrapping resources, you will generally use **"Default"** \(resources named **"Default"** will inherit their scope's logical ID, while resources named **"Resource"** will have a distinct logical ID, but the human\-readable part of it won't show the **"Resource"** part\)\. - -## Implementation Language - -For construct libraries to be reusable across programming languages, they need to be authored in a language that can compile to a `jsii` assembly\. - -Author in TypeScript unless you plan to isolate your constructs to a single programming language\. - -## Code Organization - -Your package should look like the following\. - -``` -your-package -├── package.json -├── README.md -├── lib -│   ├── index.ts -│   ├── some-resource.ts -│   └── some-other-resource.ts -└── test -  ├── integ.everything.lit.ts -   ├── test.some-resource.ts -   └── test.some-other-resource.ts -``` -+ If it represents the canonical AWS Construct Library for this service, name your package is named `@aws-cdk/aws-xxx`\. We recommend starting with `cdk-`, but you are otherwise free to choose the name\. -+ Put code under `lib/`, and tests under `test/`\. -+ The entry point should be `lib/index.ts` and should only contain `export`s for other files\. -+ You don't need to put every class in a separate file\. Try to think of a reader\-friendly organization of your source files\. -+ To make package\-private utility functions, put them in a file that isn't exported from `index.ts`\. -+ Free\-floating functions \(functions that are not part of a class definition\) cannot be accessed through jsii \(that is, from languages other than TypeScript and JavaScript\)\. Don't use them for public features of your construct library\. -+ Document all public APIs with doc comments \(`JSdoc` syntax\)\. Document defaults using the **@default** marker in doc comments\. - -## Testing -+ Add unit tests for every construct \(`test.xxx.ts`\), relating the construct's properties to the AWS CloudFormation that is generated\. Use the `@aws-cdk/assert` library to make it easier to write assertions on the AWS CloudFormation output\. -+ Try to test one concern per unit test\. Even if you could test more than one feature of the construct per test, it's better to write multiple tests, one for each feature\. A test should have one reason to break\. -+ Add integration tests \(`integ.xxx.ts`\) that are CDK apps that exercise the features of the construct, then load your shell with credentials and run npm run integ to exercise them\. You will also have to run this if the AWS CloudFormation output of the construct changes\. -+ If there are packages that you depend on only for testing, add them to `devDependencies` \(instead of regular `dependencies`\)\. You're still not allowed to create dependency cycles this way \(from the root, run scripts/find\-cycles\.sh to determine whether you have created any cycles\)\. -+ If possible, try to make your integ test literate \(`integ.xxx.lit.ts`\) and link to it from the `README`\. - -## README -+ Header should include maturity level\. -+ Header should start at `H2`, not `H1`\. -+ Include some example code for the simple use case near the very top\. -+ If there are multiple common use cases, provide an example for each one and describe what happens under the hood at a high level \(for example, which resources are created\)\. -+ Reference docs are not needed\. -+ Use literate \(`.lit.ts`\) integration tests in the `README` file\. - -## Construct IDs - -All child construct IDs are part of your public contract\. Those IDs are used to generate AWS CloudFormation logical names for resources\. If they change, AWS CloudFormation will replace the resource\. Technically, this means that if you change any ID of a child construct you will have to major\-version\-bump your library\. \ No newline at end of file From 288adb727d6d43c629562e58e831776d16e1fc52 Mon Sep 17 00:00:00 2001 From: Doug-AWS Date: Fri, 12 Jul 2019 14:43:28 -0700 Subject: [PATCH 030/655] Updated for 1.0.0 release --- doc_source/aws_construct_lib.md | 61 -------- doc_source/codepipeline_example.md | 242 +++++++++++++++++++++++++++++ doc_source/examples.md | 3 +- doc_source/home.md | 2 +- doc_source/index.md | 1 + doc_source/reference.md | 6 +- doc_source/tagging.md | 2 +- 7 files changed, 250 insertions(+), 67 deletions(-) delete mode 100644 doc_source/aws_construct_lib.md create mode 100644 doc_source/codepipeline_example.md diff --git a/doc_source/aws_construct_lib.md b/doc_source/aws_construct_lib.md deleted file mode 100644 index ad323546..00000000 --- a/doc_source/aws_construct_lib.md +++ /dev/null @@ -1,61 +0,0 @@ --------- - -This documentation is for the developer preview release \(public beta\) of the AWS Cloud Development Kit \(AWS CDK\)\. Releases might lack important features and might have future breaking changes\. - --------- - -# AWS Construct Library - -The AWS Construct Library is a set of modules that expose APIs for defining AWS resources in AWS CDK apps\. Each module is based on the AWS service to which the resource belongs\. For example, [EC2](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ec2-readme.html) includes the [Vpc](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html) construct, which makes it easy to define an Amazon VPC in your AWS CDK app\. - -The AWS Construct Library modules are described in the [AWS CDK Reference](https://awslabs.github.io/aws-cdk/)\. - -## Versioning - -Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [Semantic Versioning](https://semver.org) model\. This means that breaking changes to stable APIs \(see “The AWS CDK Stability Index”\) are limited to major releases\. Minor and patch releases are backwards\-compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. - -### AWS CDK Stability Index - -However, certain APIs do not adher to the semantic versioning model\. The AWS CDK team has added a stability index to help developers determine which APIs deviate from the semantic versioning model\. - -There are three levels of stability in the AWS CDK Construct Library: - -Stable -The API is subject to the semantic versioning model\. We will not introduce non\-backward compatible changes or remove the API in a subsequent patch or feature release\. - -CloudFormation Only -These APIs are automatically built from the AWS CloudFormation resource specification and are subject to any changes introduced by AWS CloudFormation\. - -Experimental -The API is still under active development and subject to non\-backward compatible changes or removal in any future version\. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. - -Deprecated -The API may emit warnings\. We do not guarantee backward compatibility\. - -Experimental and stable modules receive the same level of support from AWS\. The only difference is that we might change experimental APIs within a major version\. While we don not recommend using experimental APIs in production, we vet them the same way as we vet stable APIs before we include them in an AWS CDK release\. - -### Identifying the Support Level of an API - -The AWS CDK Developer guide and API Reference for each module starts with a section outlining the module's stability index\. The libraries that include only AWS CloudFormation Resources, and no hand\-curated constructs, are labelled with the maturity indicator **CloudFormation\-only**\. - -The module\-level gives an indication of the stability of the majority of the APIs included in the module, however individual APIs within the module can be annotated with different stability levels: - - -| Stability | TypeScript | JavaScript | Python | C\#/\.NET | Java | -| --- |--- |--- |--- |--- |--- | -| Experimental | @experimental | @stability Experimental | @experimental | Stability: Experimental | Stability: Experimental | -| Stable | @stable | @stability Stable | @stable | Stability: Stable | Stability: Stable | -| Deprecated | @deprecated | @Deprecated | @deprecated | \[Obsolete\] | Stability: Deprecated | - -### Language Binding Stability - -In addition to modules of the AWS CDK Construct Library, language support is also subject to a stability indication\. While the API described in all the languages is the same, the specific programming model and naming of language bindings considered experimental can change as it stabilizes\. - - -| Language | Stability | -| --- |--- | -| TypeScript | Stable | -| JavaScript | Stable | -| Python | Stable | -| Java | Experimental | -| C\#/\.NET | Experimental | \ No newline at end of file diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md new file mode 100644 index 00000000..d29bcf38 --- /dev/null +++ b/doc_source/codepipeline_example.md @@ -0,0 +1,242 @@ +# Creating a Code Pipeline Using the AWS CDK + +This example creates a code pipeline using the AWS CDK\. + +The AWS CDK enables you to easily create applications running in the AWS Cloud\. But creating the application is just the start of the journey\. You also want to make changes to it, test those changes, and finally deploy them to your stack\. The AWS CDK enables this workflow by using the **Code\*** suite of AWS tools: AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline\. Together, they allow you to build what’s called a [deployment pipeline](https://aws.amazon.com/getting-started/tutorials/continuous-deployment-pipeline/) for your application\. + +The following example shows how to deploy an AWS Lambda function in a pipeline\. In this example, your AWS CDK code and your Lambda code are in the same repository\. The Lambda code is in the `Lambda` directory, while your CDK code is in the `bin` and `lib` directories that the `cdk init` command sets up for your CDK code\. + +## Lambda Stack + +The first step is to create the file `lambda-stack.ts` in which we define the class `LambdaStack`\. This class defines the AWS CloudFormation stack for the Lambda function\. This is the stack that is deployed in our pipeline\. + +This class includes the `lambdaCode` property, which is an instance of the `CfnParametersCode` class\. This property represents the code that is supplied later by the pipeline\. Because the pipeline needs access to the object, we expose it as a public, read\-only property on our class\. + +The example also uses the CodeDeploy support for blue\-green deployments to Lambda, and the deployment increases the traffic to the new version in 10\-percent increments every minute\. As blue\-green deployment can only operate on aliases, not on the function directly, we create an alias for our function, named `Prod`\. + +The alias uses a Lambda version, which is named after the date when the code executed\. This ensures that every invocation of the AWS CDK code publishes a new version of the function\. + +If the Lambda function needs any other resources when executing, such as an Amazon S3 bucket, Amazon DynamoDB table, or Amazon API Gateway, declare those resources here\. + +``` +// file: lib/lambda-stack.ts + + import codedeploy = require('@aws-cdk/aws-codedeploy'); + import lambda = require('@aws-cdk/aws-lambda'); + import { App, Stack, StackProps } from '@aws-cdk/core'; + + export class LambdaStack extends Stack { + public readonly lambdaCode: lambda.CfnParametersCode; + + constructor(app: App, id: string, props?: StackProps) { + super(app, id, props); + + this.lambdaCode = lambda.Code.cfnParameters(); + + const func = new lambda.Function(this, 'Lambda', { + code: this.lambdaCode, + handler: 'index.handler', + runtime: lambda.Runtime.NODEJS_8_10, + }); + + const version = func.addVersion(new Date().toISOString()); + const alias = new lambda.Alias(this, 'LambdaAlias', { + aliasName: 'Prod', + version, + }); + + new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', { + alias, + deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE, + }); + } + } +``` + +## Pipeline Stack + +The second class, `PipelineStack`, is the stack that contains our pipeline\. + +First it needs a reference to the Lambda code it’s deploying\. For that, we define a new props interface for it, `PipelineStackProps`\. This extends the standard `StackProps`, and use it in its constructor signature\. This is how clients of this class pass the Lambda code that the class needs\. + +Then comes the Git repository used to store the source code\. In the example, it’s hosted by CodeCommit\. The `Repository.fromRepositoryName` method is a standard AWS CDK idiom for referencing a resource, such as a CodeCommit repository, that lives outside the AWS CDK code\. Replace *NameOfYourCodeCommitRepository* with the name of your repository\. + +The example has two CodeBuild projects\. The first project obtains the AWS CloudFormation template from the AWS CDK code\. To do that, it calls the standard install and build targets for Node\.js, and then calls the cdk synth command\. This produces AWS CloudFormation templates in the target directory `dist`\. Finally, it uses the `dist/LambdaStack.template.json` file as its output\. + +The second project does a similar thing, except for the Lambda code\. Because of that, it starts by changing the current directory to `lambda`, which is where we said the Lambda code lives in the repository\. It then invokes the same install and build Node\.js targets as before\. The output is the contents of the node\_modules directory, plus the `index.js` file\. Because `index.handler` is the entry point to the Lambda code, `index.js` must exist, and must export a `handler` function\. This function is called by the Lambda runtime to handle requests\. If your Lambda code uses more files than just `index.js`, add them here\. + +Finally, we create our pipeline\. It has a source Action targeting the CodeCommit repository, two build Actions using the previously defined projects, and finally a deploy Action that uses AWS CloudFormation\. It takes the template generated by the AWS CDK build Project \(stored in the `LambdaStack.template.json` file, same as the build specified\), and then uses the Lambda code that was passed in its props to reference the output of the build of our Lambda function\. The deployed Lambda function uses the output of that build as its code\. We have to make sure that the Lambda build output is an input to the AWS CloudFormation action though, and that’s why we pass it in the `extraInputs` property\. + +We also change the name of the stack that will be deployed, from `LambdaStack` to `LambdaDeploymentStack`\. The name change isn't required\. We could have left it the same\. + +``` +// lib/pipeline-stack.ts + +import codebuild = require('@aws-cdk/aws-codebuild'); +import codecommit = require('@aws-cdk/aws-codecommit'); +import codepipeline = require('@aws-cdk/aws-codepipeline'); +import codepipeline_actions = require('@aws-cdk/aws-codepipeline-actions'); +import lambda = require('@aws-cdk/aws-lambda'); +import s3 = require('@aws-cdk/aws-s3'); +import { App, Stack, StackProps } from '@aws-cdk/core'; + +export interface PipelineStackProps extends StackProps { + readonly lambdaCode: lambda.CfnParametersCode; +} + +export class PipelineStack extends Stack { + constructor(app: App, id: string, props: PipelineStackProps) { + super(app, id, props); + + const code = codecommit.Repository.fromRepositoryName(this, 'ImportedRepo', + 'NameOfYourCodeCommitRepository'); + + const cdkBuild = new codebuild.PipelineProject(this, 'CdkBuild', { + buildSpec: codebuild.BuildSpec.fromObject({ + version: '0.2', + phases: { + install: { + commands: 'npm install', + }, + build: { + commands: [ + 'npm run build', + 'npm run cdk synth -- -o dist' + ], + }, + }, + artifacts: { + 'base-directory': 'dist', + files: [ + 'LambdaStack.template.json', + ], + }, + }), + environment: { + buildImage: codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_8_11_0, + }, + }); + const lambdaBuild = new codebuild.PipelineProject(this, 'LambdaBuild', { + buildSpec: codebuild.BuildSpec.fromObject({ + version: '0.2', + phases: { + install: { + commands: [ + 'cd lambda', + 'npm install', + ], + }, + build: { + commands: 'npm run build', + }, + }, + artifacts: { + 'base-directory': 'lambda', + files: [ + 'index.js', + 'node_modules/**/*', + ], + }, + }), + environment: { + buildImage: codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_8_11_0, + }, + }); + + const sourceOutput = new codepipeline.Artifact(); + const cdkBuildOutput = new codepipeline.Artifact('CdkBuildOutput'); + const lambdaBuildOutput = new codepipeline.Artifact('LambdaBuildOutput'); + new codepipeline.Pipeline(this, 'Pipeline', { + stages: [ + { + stageName: 'Source', + actions: [ + new codepipeline_actions.CodeCommitSourceAction({ + actionName: 'CodeCommit_Source', + repository: code, + output: sourceOutput, + }), + ], + }, + { + stageName: 'Build', + actions: [ + new codepipeline_actions.CodeBuildAction({ + actionName: 'Lambda_Build', + project: lambdaBuild, + input: sourceOutput, + outputs: [lambdaBuildOutput], + }), + new codepipeline_actions.CodeBuildAction({ + actionName: 'CDK_Build', + project: cdkBuild, + input: sourceOutput, + outputs: [cdkBuildOutput], + }), + ], + }, + { + stageName: 'Deploy', + actions: [ + new codepipeline_actions.CloudFormationCreateUpdateStackAction({ + actionName: 'Lambda_CFN_Deploy', + templatePath: cdkBuildOutput.atPath('LambdaStack.template.json'), + stackName: 'LambdaDeploymentStack', + adminPermissions: true, + parameterOverrides: { + ...props.lambdaCode.assign(lambdaBuildOutput.s3Location), + }, + extraInputs: [lambdaBuildOutput], + }), + ], + }, + ], + }); + } +} +``` + +## Main Program + +Finally, we have our main AWS CDK entry point file, `pipeline.ts`, in the `bin` directory\. It’s simple: it first instantiates the `LambdaStack` class as `LambdaStack`, which is what the AWS CDK build in the pipeline expects\. Then it instantiates the `PipelineStack` class, passing the required Lambda code from the `LambdaStack` object\. + +``` +#!/usr/bin/env node + +// bin/pipeline.ts + +import { App } from '@aws-cdk/core'; +import { LambdaStack } from '../lib/lambda-stack'; +import { PipelineStack } from '../lib/pipeline-stack'; + +const app = new App(); + +const lambdaStack = new LambdaStack(app, 'LambdaStack'); +new PipelineStack(app, 'PipelineDeployingLambdaStack', { + lambdaCode: lambdaStack.lambdaCode, +}); + +app.synth(); +``` + +## Creating the Pipeline + +The final steps are building the code and deploying the pipeline\. Use the following command to build the TypeScript code\. + +``` +npm run build +``` + +Use the following command to deploy the pipeline stack\. + +``` +npm run cdk deploy PipelineDeployingLambdaStack +``` + +The name, **PipelineDeployingLambdaStack**, is the name we used when we instantiated `PipelineStack` in `pipeline.ts`\. + +After the deployment finishes, you should have a three\-stage pipeline that looks something like the following\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/pipeline.jpg) + +Try making a change, such as to your `LambdaStack` AWS CDK code or to your Lambda function code, and push it to the repository\. The pipeline should pick up your change, build it, and deploy it automatically, without any human intervention\. \ No newline at end of file diff --git a/doc_source/examples.md b/doc_source/examples.md index 7ff08946..ca68f8be 100644 --- a/doc_source/examples.md +++ b/doc_source/examples.md @@ -2,4 +2,5 @@ This topic contains the following examples: + [Creating a Serverless Application Using the AWS CDK](serverless_example.md) Creates a serverless application using Lambda, API Gateway, and Amazon S3\. -+ [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. \ No newline at end of file ++ [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. ++ [Creating a Code Pipeline Using the AWS CDK](codepipeline_example.md) Creates a CI/CD pipeline\. \ No newline at end of file diff --git a/doc_source/home.md b/doc_source/home.md index 485e9dad..fa14a290 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -92,7 +92,7 @@ Because the AWS CDK is open source, the team encourages you contribute to make i ## Additional Documentation and Resources In addition to this guide, the following are other resources available to AWS CDK users: -+ [Reference](https://docs.aws.amazon.com/cdk/api/latest) ++ [API Reference](https://docs.aws.amazon.com/cdk/api/latest) + [AWS CDK Demo at re:Invent 2018](https://www.youtube.com/watch?v=Lh-kVC2r2AU) + [AWS CDK Workshop](https://cdkworkshop.com/) + [AWS CDK Examples](https://github.com/aws-samples/aws-cdk-examples) diff --git a/doc_source/index.md b/doc_source/index.md index d0c33a0b..f4d5198d 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -35,6 +35,7 @@ Amazon's trademarks and trade dress may not be used in + [Examples](examples.md) + [Creating a Serverless Application Using the AWS CDK](serverless_example.md) + [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) + + [Creating a Code Pipeline Using the AWS CDK](codepipeline_example.md) + [AWS CDK Examples](about_examples.md) + [AWS CDK HowTos](how_tos.md) + [Get a Value from an Environment Variable](get_env_var.md) diff --git a/doc_source/reference.md b/doc_source/reference.md index 3f98aaf6..4ca9626c 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -1,12 +1,12 @@ # API Reference -The [API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html/) contains information about the AWS CDK libraries\. +The [API Reference](https://docs.aws.amazon.com/cdk/api/latest) contains information about the AWS CDK libraries\. Each library contains information about how to use the library\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) library demonstrates how to set default encryption on an Amazon S3 bucket\. ## Versioning and Stability Model -Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs \(see “The AWS CDK Stability Index”\) are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs, which is described in the next section, are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. ### AWS CDK Stability Index @@ -30,7 +30,7 @@ Experimental and stable modules receive the same level of support from AWS\. The ### Identifying the Support Level of an API -The AWS CDK Developer Guide and API Reference for each module starts with a section outlining the module's stability index\. The libraries that include only AWS CloudFormation resources, and no hand\-curated constructs, are labeled with the maturity indicator **CloudFormation\-only**\. +Each module in the [API Reference](https://docs.aws.amazon.com/cdk/api/latest) starts with a section outlining the module's stability index\. The libraries that include only AWS CloudFormation resources, and no hand\-curated constructs, are labeled with the maturity indicator **CloudFormation\-only**\. The module level gives an indication of the stability of the majority of the APIs included in the module, however, individual APIs within the module can be annotated with different stability levels\. diff --git a/doc_source/tagging.md b/doc_source/tagging.md index d988dc51..e6d300fa 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -58,7 +58,7 @@ Use this to set the priority of this operation with respect to other `Tag` and ` The `RemoveTag` class includes properties to fine\-tune how tags are removed, all of which are optional\. -The following example removes the tag **tagname** with priority **200** from resources of type **AWS::Xxx::Yzz** in `myConstruct`, but not to resources of type **AWS::Xxx::Zzz**\. +The following example removes the tag **tagname** with priority **200** from resources of type **AWS::Xxx::Yzz** in `myConstruct`, but not from resources of type **AWS::Xxx::Zzz**\. ``` myConstruct.node.applyAspect(new RemoveTag('tagname', { From ce5a19f8cec6ea860c36de0d490933b4319d5545 Mon Sep 17 00:00:00 2001 From: shlo Date: Fri, 19 Jul 2019 15:17:25 +0800 Subject: [PATCH 031/655] patch spaces between words --- doc_source/apps.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index 8205b823..a34d16a6 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -79,7 +79,7 @@ To work with the CDK CLI, you need to let it know how to execute an AWS CDK app\ cdk --app executable cdk-command ``` -The \-\-appoption instructs the CLI to run your AWS CDK app, and its contents depend on the programming language you use\. Eventually it should be a program that the operating system can run\. You can also create the `cdk.json`file and add information to it so that you need to call only `cdk cdk-command`\. For example, for JavaScript apps, the `cdk.json` file might look like the following, where `node bin/my-app.js` executes a Node\.js program\. +The \-\-app option instructs the CLI to run your AWS CDK app, and its contents depend on the programming language you use\. Eventually it should be a program that the operating system can run\. You can also create the `cdk.json` file and add information to it so that you need to call only `cdk cdk-command`\. For example, for JavaScript apps, the `cdk.json` file might look like the following, where `node bin/my-app.js` executes a Node\.js program\. ``` { @@ -96,4 +96,4 @@ The CLI can also interact directly with an already synthesized cloud assembly\. ``` cdk --app ./my-cloud-assembly ls -``` \ No newline at end of file +``` From 718d3e6d81bfd38de84e5f4a317d74966231979c Mon Sep 17 00:00:00 2001 From: shlo Date: Fri, 19 Jul 2019 17:14:13 +0800 Subject: [PATCH 032/655] fix grammar --- doc_source/permissions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/permissions.md b/doc_source/permissions.md index 87ce9c2a..d7d7cd48 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -1,6 +1,6 @@ # Permissions -The AWS CDK contains an IAM package to help you deal with permissions\. There a few idioms for managing access and permissions that are implemented uniformly across the entire AWS CDK Construct Library\. +The AWS CDK contains an IAM package to help you deal with permissions\. There are a few idioms for managing access and permissions that are implemented uniformly across the entire AWS CDK Construct Library\. ## Roles @@ -94,4 +94,4 @@ The AWS CDK Construct Library supports many types of principals, including: 1. Arbitrary ARN principals \(`new iam.ArnPrincipal(res.arn)`\) -1. A `CompositePrincipal(principal1, principal2, ...)` if you need your role to trust multiple principals \ No newline at end of file +1. A `CompositePrincipal(principal1, principal2, ...)` if you need your role to trust multiple principals From bcf605a7c87f8e2872d1dbab5d31d3eb5096685f Mon Sep 17 00:00:00 2001 From: Chad Schmutzer Date: Fri, 19 Jul 2019 22:22:17 -0700 Subject: [PATCH 033/655] fixing minor typo --- doc_source/constructs.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 325dc02b..92636290 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -31,7 +31,7 @@ Constructs are implemented in classes that extend the [https://docs.aws.amazon.c + **id** – An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's encapsulated within the scope's subtree and is used to allocate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. + **props** – A set of properties or keyword arguments, depending upon the supported language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. -Iidentifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/tag.html) or for specifying where the constructs will be deployed\. +Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/tag.html) or for specifying where the constructs will be deployed\. ## Apps and Stacks @@ -184,4 +184,4 @@ Now, consumers can subscribe to the topic, for example: const queue = new sqs.Queue(this, 'NewImagesQueue'); const images = new NotificationBucket(this, 'Images'); images.topic.addSubscription(new sns_sub.QueueSubscription(queue)); -``` \ No newline at end of file +``` From 4ea1913ea339c1529ea16cf309e273289b3318d7 Mon Sep 17 00:00:00 2001 From: Michael Gilliland Date: Mon, 22 Jul 2019 15:05:47 -0400 Subject: [PATCH 034/655] Add ending curly braces. Also add language annotation to enable syntax highlighting in github. --- doc_source/home.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/doc_source/home.md b/doc_source/home.md index fa14a290..9f7ff719 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -18,7 +18,7 @@ Developers can use one of the supported programming languages to define reusable Let's look at the power of the AWS CDK\. Here is some TypeScript code in an AWS CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md)\)\. -``` +``` typescript export class MyEcsConstructStack extends core.Stack { constructor(scope: core.App, id: string, props?: core.StackProps) { super(scope, id, props); @@ -40,6 +40,8 @@ export class MyEcsConstructStack extends core.Stack { memoryLimitMiB: 2048, // Default is 512 publicLoadBalancer: true // Default is false }); + } +} ``` This produces an AWS CloudFormation [template of over 600 lines](https://github.com/awsdocs/aws-cdk-guide/blob/master/doc_source/my_ecs_construct-stack.yaml); deploying the AWS CDK app produces over 50 resources of the following types\. @@ -117,4 +119,4 @@ Amazon Web Services \(AWS\) is a collection of digital infrastructure services t AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. -To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file +To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. From 53700a03c229a710ce7c435ce8b6021dd8853420 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 31 Jul 2019 22:50:39 +0000 Subject: [PATCH 035/655] update Markdown files with post-GA changes to CDK Developer Guide --- doc_source/apps.md | 18 ++++---- doc_source/assets.md | 12 +++--- doc_source/cfn_layer.md | 8 ++-- doc_source/codepipeline_example.md | 10 ++--- doc_source/constructs.md | 10 ++--- doc_source/context.md | 4 +- doc_source/ecs_example.md | 2 +- doc_source/environments.md | 4 +- doc_source/getting_started.md | 39 +++++++++++------ doc_source/home.md | 8 ++-- doc_source/multiple_languages.md | 69 ++++++------------------------ doc_source/permissions.md | 2 +- doc_source/resources.md | 14 +++--- doc_source/serverless_example.md | 39 ++++++----------- doc_source/stacks.md | 4 +- doc_source/tagging.md | 2 +- doc_source/tokens.md | 10 ++--- doc_source/use_cfn_template.md | 2 +- 18 files changed, 106 insertions(+), 151 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index a34d16a6..b884d182 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -1,6 +1,6 @@ # Apps -As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/stack.html) construct\. +As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html) construct\. The following example declares a stack class named `MyFirstStack` that includes a single Amazon S3 bucket\. However, this only declares a stack\. You still need to define \(also known as to instantiate\) it in some scope to deploy it\. @@ -14,9 +14,9 @@ class MyFirstStack extends Stack { } ``` -## App Constructs +## The App Construct -To define the previous stack within some scope, use the [App](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/app.html) construct\. The following example defines a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. +To define the previous stack within some scope, use the [App](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/app.html) construct\. The following example defines a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. ``` const app = new App(); @@ -52,13 +52,13 @@ An AWS CDK app goes through the following phases in its lifecycle\. Your code instantiates all of the defined constructs and then links them together\. In this stage, all of the constructs \(app, stacks, and their child constructs\) are instantiated and the constructor chain is executed\. Most of your app code is executed in this stage\. 2\. Preparation -All constructs that have implemented the `prepare` method participate in a final round of modifications, to set up their final state\. The preparation phase happens automatically\. As a user, you don't see any feedback from this phase\. It's rare to need to use the “prepare” hook, and generally not recommended\. You should be very careful when mutating the construct tree during this phase, because the order of operations could impact behavior\. +All constructs that have implemented the `prepare` method participate in a final round of modifications, to set up their final state\. The preparation phase happens automatically\. As a user, you don't see any feedback from this phase\. It's rare to need to use the "prepare" hook, and generally not recommended\. You should be very careful when mutating the construct tree during this phase, because the order of operations could impact behavior\. 3\. Validation All constructs that have implemented the `validate` method can validate themselves to ensure that they're in a state that will correctly deploy\. You will get notified of any validation failures that happen during this phase\. Generally, we recommend that you perform validation as soon as possible \(usually as soon as you get some input\) and throw exceptions as early as possible\. Performing validation early improves diagnosability as stack traces will be more accurate, and ensures that your code can continue to execute safely\. 4\. Synthesis -This is the final stage of the execution of your AWS CDK app\. It's triggered by a call to `app.synth()`, and it traverses the construct tree and invokes the `synthesize` method on all constructs\. Constructs that implement `synthesize` can participate in synthesis and emit deployment artifacts to the resulting cloud assembly\. These constructs include AWS CloudFormation templates, AWS Lambda application bundles, file and Docker image assets, and other deployment artifacts\. [Cloud Assemblies](#apps_cloud_assembly) describes the output of this phase\. In most cases, you won’t need to implement the `synthesize` method +This is the final stage of the execution of your AWS CDK app\. It's triggered by a call to `app.synth()`, and it traverses the construct tree and invokes the `synthesize` method on all constructs\. Constructs that implement `synthesize` can participate in synthesis and emit deployment artifacts to the resulting cloud assembly\. These constructs include AWS CloudFormation templates, AWS Lambda application bundles, file and Docker image assets, and other deployment artifacts\. [Cloud Assemblies](#apps_cloud_assembly) describes the output of this phase\. In most cases, you won't need to implement the `synthesize` method 5\. Deployment In this phase, the AWS CDK CLI takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. @@ -67,10 +67,12 @@ By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS + The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. + The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)`\. See [Tokens](tokens.md) for details\. -### Cloud Assemblies +## Cloud Assemblies The call to `app.synth()` is what tells the AWS CDK to synthesize a cloud assembly from an app\. Typically you don't interact directly with cloud assemblies\. They are files that include everything needed to deploy your app to a cloud environment\. For example, it includes an AWS CloudFormation template for each stack in your app, and a copy of any file assets or Docker images that you reference in your app\. +See the [cloud assembly specification](https://github.com/aws/aws-cdk/blob/master/design/cloud-assembly.md) for details on how cloud assemblies are formatted\. + To interact with the cloud assembly that your AWS CDK app creates, you typically use the AWS CDK CLI\. But any tool that can read the cloud assembly format can be used to deploy your app\. To work with the CDK CLI, you need to let it know how to execute an AWS CDK app\. @@ -79,7 +81,7 @@ To work with the CDK CLI, you need to let it know how to execute an AWS CDK app\ cdk --app executable cdk-command ``` -The \-\-app option instructs the CLI to run your AWS CDK app, and its contents depend on the programming language you use\. Eventually it should be a program that the operating system can run\. You can also create the `cdk.json` file and add information to it so that you need to call only `cdk cdk-command`\. For example, for JavaScript apps, the `cdk.json` file might look like the following, where `node bin/my-app.js` executes a Node\.js program\. +The \-\-app option instructs the CLI to run your AWS CDK app, and its contents depend on the programming language you use\. Eventually it should be a program that the operating system can run\. You can also create the `cdk.json`file and add information to it so that you need to call only `cdk cdk-command`\. For example, for JavaScript apps, the `cdk.json` file might look like the following, where `node bin/my-app.js` executes a Node\.js program\. ``` { @@ -96,4 +98,4 @@ The CLI can also interact directly with an already synthesized cloud assembly\. ``` cdk --app ./my-cloud-assembly ls -``` +``` \ No newline at end of file diff --git a/doc_source/assets.md b/doc_source/assets.md index aefe91ee..6c4a931e 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -2,7 +2,7 @@ Assets are local files, directories, or Docker images that can be bundled into AWS CDK libraries and apps; for example, a directory that contains the handler code for an AWS Lambda function\. Assets can represent any artifact that the app needs to operate\. -You typically reference assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html#code) property enables you to pass an [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function’s code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-assetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. +You typically reference assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html#code) property enables you to pass an [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function's code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-assetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. ## Assets in Detail @@ -40,17 +40,17 @@ The following example defines a local directory asset and a file asset\. import { Asset } from '@aws-cdk/aws-s3-assets'; // Archived and uploaded to Amazon S3 as a .zip file -const directoryAsset = new Asset(this, "SampleAsset", { +const directoryAsset = new Asset(this, "SampleZippedDirAsset", { path: path.join(__dirname, "sample-asset-directory") }); // Uploaded to Amazon S3 as-is -const fileAsset = new Asset(this, 'SampleAsset', { +const fileAsset = new Asset(this, 'SampleSingleFileAsset', { path: path.join(__dirname, 'file-asset.txt') }); ``` -In most cases, you don’t need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods that enable you to use assets\. For Lambda functions, the [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) property enables you to specify a directory or a \.zip file in the local file system\. +In most cases, you don't need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods that enable you to use assets\. For Lambda functions, the [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) property enables you to specify a directory or a \.zip file in the local file system\. #### Lambda Function Example @@ -86,7 +86,7 @@ export class HelloAssetStack extends cdk.Stack { } ``` -The `Function` method uses assets to bundle the contents of the directory and use it for the function’s code\. +The `Function` method uses assets to bundle the contents of the directory and use it for the function's code\. #### Deploy\-Time Attributes Example @@ -96,7 +96,7 @@ The following example uses deploy\-time attributes to pass the location of an im ``` const imageAsset = new Asset(this, "SampleAsset", { - path: path.join(__dirname, “images/my-image.png") + path: path.join(__dirname, "images/my-image.png") }); new lambda.Function(this, "myLambdaFunction", { diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index e8fd55dd..e2994edd 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -2,7 +2,7 @@ It's possible that neither the high\-level constructs nor the low\-level CFN Resource constructs have a specific feature you are looking for\. There are three possible reasons for this lack of functionality: + The AWS service feature is available through AWS CloudFormation, but there are no Construct classes for the service\. -+ The AWS service feature is available through AWS CloudFormation, and there are Construct classes for the service, but the Construct classes don’t yet expose the feature\. ++ The AWS service feature is available through AWS CloudFormation, and there are Construct classes for the service, but the Construct classes don't yet expose the feature\. + The feature is not yet available through AWS CloudFormation\. To determine whether a feature is available through AWS CloudFormation, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. @@ -49,7 +49,7 @@ If an Construct is missing a feature or you are trying to work around an issue, All Constructs contain within them the corresponding CFN Resource\. For example, the high\-level `Bucket` construct wraps the low\-level `CfnBucket` construct\. Because the `CfnBucket` corresponds directly to the AWS CloudFormation resource, it exposes all features that are available through AWS CloudFormation\. -The basic approach to get access to the CFN Resource class is to use `construct.node.defaultChild`, cast it to the right type for the resource, and modify its properties\. Again, let’s take the example of a `Bucket`\. +The basic approach to get access to the CFN Resource class is to use `construct.node.defaultChild`, cast it to the right type for the resource, and modify its properties\. Again, let's take the example of a `Bucket`\. ``` // Get the AWS CloudFormation resource @@ -94,9 +94,9 @@ cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); ## Custom Resources -If the feature isn't available through AWS CloudFormation, but only through a direct API call, the only solution is to write an AWS CloudFormation Custom Resource to make the API call you need\. Don’t worry, the AWS CDK makes it easier to write these, and wrap them up into a regular construct interface, so from another user’s perspective the feature feels native\. +If the feature isn't available through AWS CloudFormation, but only through a direct API call, the only solution is to write an AWS CloudFormation Custom Resource to make the API call you need\. Don't worry, the AWS CDK makes it easier to write these, and wrap them up into a regular construct interface, so from another user's perspective the feature feels native\. -Building a custom resource involves writing a Lambda function that responds to a resource’s CREATE, UPDATE and DELETE lifecycle events\. If your custom resource needs to make only a single API call, consider using the [AwsCustomResource](https://github.com/awslabs/aws-cdk/tree/master/packages/%40aws-cdk/custom-resources)\. This makes it possible to perform arbitrary SDK calls during an AWS CloudFormation deployment\. Otherwise, you should write your own Lambda function to perform the work you need to get done\. +Building a custom resource involves writing a Lambda function that responds to a resource's CREATE, UPDATE and DELETE lifecycle events\. If your custom resource needs to make only a single API call, consider using the [AwsCustomResource](https://github.com/awslabs/aws-cdk/tree/master/packages/%40aws-cdk/custom-resources)\. This makes it possible to perform arbitrary SDK calls during an AWS CloudFormation deployment\. Otherwise, you should write your own Lambda function to perform the work you need to get done\. The subject is too broad to completely cover here, but the following links should get you started: + [Custom Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index d29bcf38..efde4d2c 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -2,7 +2,7 @@ This example creates a code pipeline using the AWS CDK\. -The AWS CDK enables you to easily create applications running in the AWS Cloud\. But creating the application is just the start of the journey\. You also want to make changes to it, test those changes, and finally deploy them to your stack\. The AWS CDK enables this workflow by using the **Code\*** suite of AWS tools: AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline\. Together, they allow you to build what’s called a [deployment pipeline](https://aws.amazon.com/getting-started/tutorials/continuous-deployment-pipeline/) for your application\. +The AWS CDK enables you to easily create applications running in the AWS Cloud\. But creating the application is just the start of the journey\. You also want to make changes to it, test those changes, and finally deploy them to your stack\. The AWS CDK enables this workflow by using the **Code\*** suite of AWS tools: AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline\. Together, they allow you to build what's called a [deployment pipeline](https://aws.amazon.com/getting-started/tutorials/continuous-deployment-pipeline/) for your application\. The following example shows how to deploy an AWS Lambda function in a pipeline\. In this example, your AWS CDK code and your Lambda code are in the same repository\. The Lambda code is in the `Lambda` directory, while your CDK code is in the `bin` and `lib` directories that the `cdk init` command sets up for your CDK code\. @@ -57,15 +57,15 @@ If the Lambda function needs any other resources when executing, such as an Amaz The second class, `PipelineStack`, is the stack that contains our pipeline\. -First it needs a reference to the Lambda code it’s deploying\. For that, we define a new props interface for it, `PipelineStackProps`\. This extends the standard `StackProps`, and use it in its constructor signature\. This is how clients of this class pass the Lambda code that the class needs\. +First it needs a reference to the Lambda code it's deploying\. For that, we define a new props interface for it, `PipelineStackProps`\. This extends the standard `StackProps`, and use it in its constructor signature\. This is how clients of this class pass the Lambda code that the class needs\. -Then comes the Git repository used to store the source code\. In the example, it’s hosted by CodeCommit\. The `Repository.fromRepositoryName` method is a standard AWS CDK idiom for referencing a resource, such as a CodeCommit repository, that lives outside the AWS CDK code\. Replace *NameOfYourCodeCommitRepository* with the name of your repository\. +Then comes the Git repository used to store the source code\. In the example, it's hosted by CodeCommit\. The `Repository.fromRepositoryName` method is a standard AWS CDK idiom for referencing a resource, such as a CodeCommit repository, that lives outside the AWS CDK code\. Replace *NameOfYourCodeCommitRepository* with the name of your repository\. The example has two CodeBuild projects\. The first project obtains the AWS CloudFormation template from the AWS CDK code\. To do that, it calls the standard install and build targets for Node\.js, and then calls the cdk synth command\. This produces AWS CloudFormation templates in the target directory `dist`\. Finally, it uses the `dist/LambdaStack.template.json` file as its output\. The second project does a similar thing, except for the Lambda code\. Because of that, it starts by changing the current directory to `lambda`, which is where we said the Lambda code lives in the repository\. It then invokes the same install and build Node\.js targets as before\. The output is the contents of the node\_modules directory, plus the `index.js` file\. Because `index.handler` is the entry point to the Lambda code, `index.js` must exist, and must export a `handler` function\. This function is called by the Lambda runtime to handle requests\. If your Lambda code uses more files than just `index.js`, add them here\. -Finally, we create our pipeline\. It has a source Action targeting the CodeCommit repository, two build Actions using the previously defined projects, and finally a deploy Action that uses AWS CloudFormation\. It takes the template generated by the AWS CDK build Project \(stored in the `LambdaStack.template.json` file, same as the build specified\), and then uses the Lambda code that was passed in its props to reference the output of the build of our Lambda function\. The deployed Lambda function uses the output of that build as its code\. We have to make sure that the Lambda build output is an input to the AWS CloudFormation action though, and that’s why we pass it in the `extraInputs` property\. +Finally, we create our pipeline\. It has a source Action targeting the CodeCommit repository, two build Actions using the previously defined projects, and finally a deploy Action that uses AWS CloudFormation\. It takes the template generated by the AWS CDK build Project \(stored in the `LambdaStack.template.json` file, same as the build specified\), and then uses the Lambda code that was passed in its props to reference the output of the build of our Lambda function\. The deployed Lambda function uses the output of that build as its code\. We have to make sure that the Lambda build output is an input to the AWS CloudFormation action though, and that's why we pass it in the `extraInputs` property\. We also change the name of the stack that will be deployed, from `LambdaStack` to `LambdaDeploymentStack`\. The name change isn't required\. We could have left it the same\. @@ -198,7 +198,7 @@ export class PipelineStack extends Stack { ## Main Program -Finally, we have our main AWS CDK entry point file, `pipeline.ts`, in the `bin` directory\. It’s simple: it first instantiates the `LambdaStack` class as `LambdaStack`, which is what the AWS CDK build in the pipeline expects\. Then it instantiates the `PipelineStack` class, passing the required Lambda code from the `LambdaStack` object\. +Finally, we have our main AWS CDK entry point file, `pipeline.ts`, in the `bin` directory\. It's simple: it first instantiates the `LambdaStack` class as `LambdaStack`, which is what the AWS CDK build in the pipeline expects\. Then it instantiates the `PipelineStack` class, passing the required Lambda code from the `LambdaStack` object\. ``` #!/usr/bin/env node diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 92636290..87b34300 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -10,7 +10,7 @@ The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html)` class represents an Amazon DynamoDB table\. -There are different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources*\. These constructs represent all of the AWS resources that are available in AWS CloudFormation\. CFN Resources are generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) on a regular basis\. They are named **Cfn***Xyz*, where *Xyz* represents the name of the resource\. For example, [s3\.CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) CFN Resource\. When you use CFN constructs, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying resource model\. +There are different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources*\. These constructs represent all of the AWS resources that are available in AWS CloudFormation\. CFN Resources are generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) on a regular basis\. They are named **Cfn***Xyz*, where *Xyz* represents the name of the resource\. For example, [s3\.CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) CFN Resource\. When you use CFN resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying resource model\. The next level of constructs also represent AWS resources, but with a higher\-level, intent\-based API\. They provide the same functionality, but handle much of the details, boilerplate, and glue logic required by CFN constructs\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#aws_s3_Bucket) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#aws_s3_Bucket_addLifecycleRule), which adds a lifecycle rule to the bucket\. @@ -55,7 +55,7 @@ const app = new App(); new HelloCdkStack(app, "HelloCdkStack"); ``` -As you can see, you need a scope within which to define your bucket\. Since resources eventually need to be deployed as part of a AWS CloudFormation stack into an *AWS *[https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#environments](https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#environments), which covers a specific AWS account and AWS region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/stack.html#cdk_Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/stack.html#cdk_Stack)\. +As you can see, you need a scope within which to define your bucket\. Since resources eventually need to be deployed as part of a AWS CloudFormation stack into an *AWS *[https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#environments](https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#environments), which covers a specific AWS account and AWS region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html)\. Stacks in AWS CDK apps extend the **Stack** base class, as shown in the previous example\. This is a common pattern when creating a stack within your AWS CDK app: extend the **Stack** class, define a constructor that accepts **scope**, **id**, and **props**, and invoke the base class constructor via `super` with the received **scope**, **id**, and **props**, as shown in the following example\. @@ -89,7 +89,7 @@ The [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/latest/docs/aws- ## Configuration -Most constructs accept `props` as their third initialization argument\. This is a name/value collection that defines the construct’s configuration\. The following example defines a bucket with AWS Key Management Service \(AWS KMS\) encryption and static website hosting enabled\. Since it does not explicitly specify an encryption key, the `Bucket` construct defines a new `kms.Key` and associates it with the bucket\. +Most constructs accept `props` as their third initialization argument\. This is a name/value collection that defines the construct's configuration\. The following example defines a bucket with AWS Key Management Service \(AWS KMS\) encryption and static website hosting enabled\. Since it does not explicitly specify an encryption key, the `Bucket` construct defines a new `kms.Key` and associates it with the bucket\. ``` new s3.Bucket(this, 'MyEncryptedBucket', { @@ -112,7 +112,7 @@ const dataScience = new iam.Group(this, 'data-science'); rawData.grantRead(dataScience); ``` -Another common pattern is for AWS constructs to set one of the resource’s attributes, such as its Amazon Resource Name \(ARN\), name, or URL from data supplied elsewhere\. For example, the following code defines an AWS Lambda function and associates it with an Amazon Simple Queue Service \(Amazon SQS\) queue through the queue's URL in an environment variable\. +Another common pattern is for AWS constructs to set one of the resource's attributes, such as its Amazon Resource Name \(ARN\), name, or URL from data supplied elsewhere\. For example, the following code defines an AWS Lambda function and associates it with an Amazon Simple Queue Service \(Amazon SQS\) queue through the queue's URL in an environment variable\. ``` const jobsQueue = new sqs.Queue(this, 'jobs'); @@ -184,4 +184,4 @@ Now, consumers can subscribe to the topic, for example: const queue = new sqs.Queue(this, 'NewImagesQueue'); const images = new NotificationBucket(this, 'Images'); images.topic.addSubscription(new sns_sub.QueueSubscription(queue)); -``` +``` \ No newline at end of file diff --git a/doc_source/context.md b/doc_source/context.md index a20ce8be..2abe28c8 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -11,7 +11,7 @@ You can provide context values in three different ways: Context entries are scoped to the construct that created them: they are visible to children constructs, but not to siblings\. Context entries that are set by the CLI, either automatically or from the \-\-context option, are implicitly set on the `App` construct, and are visible to the app\. -You can get context information using the `construct.node.tryGetContext` method, which returns the value set on the current construct if it is present\. Otherwise, it resolves the context from the current construct’s parent, until it has reached the `App` construct\. +You can get context information using the `construct.node.tryGetContext` method, which returns the value set on the current construct if it is present\. Otherwise, it resolves the context from the current construct's parent, until it has reached the `App` construct\. ## Context Methods @@ -33,7 +33,7 @@ Gets the existing VPCs in your accounts\. If a given context information isn't available, the AWS CDK app notifies the AWS CDK CLI that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. -Don't forget to add the `cdk.context.json` file to your source control repository to ensure that subsequent synth commands will return the same result, and that your AWS account won’t be needed when synthesizing from your build system\. +Don't forget to add the `cdk.context.json` file to your source control repository to ensure that subsequent synth commands will return the same result, and that your AWS account won't be needed when synthesizing from your build system\. ## Viewing and Managing Context diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index c846e84f..1845b11b 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -59,7 +59,7 @@ Resources: Install support for Amazon EC2 and Amazon ECS\. ``` -npm install @aws-cdk/aws-ec2 @aws-cdk/aws-ecs +npm install @aws-cdk/aws-ec2 @aws-cdk/aws-ecs @aws-cdk/aws-ecs-patterns ``` ## Create a Fargate Service diff --git a/doc_source/environments.md b/doc_source/environments.md index 7a83a133..c023de57 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -2,7 +2,7 @@ Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and AWS Region into which this stack needs to be deployed\. -By default, if you don’t specify an environment when you define a stack, the stack is said to be environment agnostic\. This means that AWS CloudFormation templates which are synthesized from this stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availablityZones`\. When using cdk deploy to deploy environment\-agnostic stacks, the CLI uses the default CLI environment configuration to determine where to deploy this stack\. The AWS CDK CLI follows a protocol similar to the AWS CLI for determining which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Command Line Interface \(cdk\)](tools.md#cli) for details\. +By default, if you don't specify an environment when you define a stack, the stack is said to be environment agnostic\. This means that AWS CloudFormation templates which are synthesized from this stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availablityZones`\. When using cdk deploy to deploy environment\-agnostic stacks, the CLI uses the default CLI environment configuration to determine where to deploy this stack\. The AWS CDK CLI follows a protocol similar to the AWS CLI for determining which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Command Line Interface \(cdk\)](tools.md#cli) for details\. For production systems, we recommend that you explicitly specify the environment for each stack in your app using the `env` property\. The following example specifies two environments used in two different stacks\. @@ -28,4 +28,4 @@ new MyDevStack(this, 'dev', { ``` **Note** -There is a distinction between not specifying the `env` property at all and specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. This means that constructs that are defined in such a stack cannot make assumptions about their environment\. For example, you can’t write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html#aws_ec2_Vpc_fromLookup), which need to query your AWS account\. When specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, you tell the stack that it will be deployed in the account and Region as configured in the CLI at the time of synthesis\. This means that the synthesized template could be different on different machines, users, or sessions\. This might be acceptable for use cases like development stacks, but would be an anti\-pattern for production stacks\. \ No newline at end of file +There is a distinction between not specifying the `env` property at all and specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. This means that constructs that are defined in such a stack cannot make assumptions about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html#aws_ec2_Vpc_fromLookup), which need to query your AWS account\. When specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, you tell the stack that it will be deployed in the account and Region as configured in the CLI at the time of synthesis\. This means that the synthesized template could be different on different machines, users, or sessions\. This might be acceptable for use cases like development stacks, but would be an anti\-pattern for production stacks\. \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 59ef85bb..1b70b627 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -2,12 +2,18 @@ This topic describes how to install and configure the AWS CDK and create your first AWS CDK app\. +**Note** +Looking for more than just the basics? Try the [CDK Workshop](https://cdkworkshop.com/)\. + ## Prerequisites **AWS CDK command line tools** + [Node\.js \(>= 8\.11\.x\)](https://nodejs.org/en/download) + You must specify both your credentials and an AWS Region to use the AWS CDK CLI;, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. +**Note** + Why do you need Node\.js if you're a not a JavaScript developer? The AWS CDK is developed in TypeScript and transpiled to JavaScript\. Bindings for the other supported languages make use of the AWS CDK back\-end running on Node\.js, as does the `cdk` command\-line tool\. + ------ #### [ TypeScript ] @@ -217,6 +223,9 @@ mkdir hello-cdk cd hello-cdk ``` +**Note** + Be sure to use the name `hello-cdk` for your project directory\. The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, you'll need to change some of the code in this article\. + ### Initializing the App Initialize an app, where *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), **python** \(Python\), or **typescript** \(TypeScript\) and *TEMPLATE* is an optional template that creates an app with different resources than the default app that cdk init creates for the language\. @@ -410,7 +419,7 @@ If necessary, add the following to `pom.xml`, where *CDK\-VERSION* is the versio ------ #### [ C\# ] -Run the following command in the src/HelloCdk directory\. +Run the following command in the `src/HelloCdk` directory\. ``` dotnet add package Amazon.CDK.AWS.S3 @@ -452,13 +461,13 @@ export class HelloCdkStack extends core.Stack { ------ #### [ JavaScript ] -In `index.js`: +In `lib/hello-cdk-stack.js`: ``` -const cdk = require('@aws-cdk/cdk'); +const cdk = require('@aws-cdk/core'); const s3 = require('@aws-cdk/aws-s3'); -class MyStack extends cdk.Stack { +class HelloCdkStack extends cdk.Stack { constructor(scope, id, props) { super(scope, id, props); @@ -467,6 +476,8 @@ class MyStack extends cdk.Stack { }); } } + +module.exports = { HelloCdkStack } ``` ------ @@ -525,12 +536,12 @@ namespace HelloCdk ------ #### [ Python ] -Replace the import statement in `hello_cdk_stack.py` in the `hello_cdk` directory with the following code\. +Replace the first import statement in `hello_cdk_stack.py` in the `hello_cdk` directory with the following code\. ``` from aws_cdk import ( aws_s3 as s3, - cdk + core ) ``` @@ -545,8 +556,8 @@ bucket = s3.Bucket(self, ------ Notice a few things: -+ [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) is a construct\. This means it's initialization signature has `scope`, `id`, and `props` and it is a child of the stack\. -+ `MyFirstBucket` is the **id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. To specify a physical name for your bucket, set the [bucketName](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#bucketname) property when you define your bucket\. ++ [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) is a construct\. This means its initialization signature has `scope`, `id`, and `props` and it is a child of the stack\. ++ `MyFirstBucket` is the **id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. To specify a physical name for your bucket, set the [bucketName](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#bucketname) property \(`bucket_name` in Python\) when you define your bucket\. + Because the bucket's [versioned](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. Compile your program, as follows\. @@ -639,19 +650,19 @@ Update `lib/hello-cdk-stack.ts` ``` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, - encryption: s3.BucketEncryption.KmsManaged + encryption: s3.BucketEncryption.KMS_MANAGED }); ``` ------ #### [ JavaScript ] -Update `index.js`\. +Update `lib/hello-cdk-stack.js`\. ``` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, - encryption: s3.BucketEncryption.KmsManaged + encryption: s3.BucketEncryption.KMS_MANAGED }); ``` @@ -667,7 +678,7 @@ import software.amazon.awscdk.services.s3.BucketEncryption; ``` new Bucket(this, "MyFirstBucket", BucketProps.builder() .withVersioned(true) - .withEncryption(BucketEncryption.KmsManaged) + .withEncryption(BucketEncryption.KMS_MANAGED) .build()); ``` @@ -680,7 +691,7 @@ Update `HelloStack.cs`\. new Bucket(this, "MyFirstBucket", new BucketProps { Versioned = true, - Encryption = BucketEncryption.KmsManaged + Encryption = BucketEncryption.KMS_MANAGED }); ``` @@ -691,7 +702,7 @@ new Bucket(this, "MyFirstBucket", new BucketProps bucket = s3.Bucket(self, "MyFirstBucket", versioned=True, - encryption=s3.BucketEncryption.KmsManaged,) + encryption=s3.BucketEncryption.KMS_MANAGED,) ``` ------ diff --git a/doc_source/home.md b/doc_source/home.md index 9f7ff719..99ecd5e2 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -18,7 +18,7 @@ Developers can use one of the supported programming languages to define reusable Let's look at the power of the AWS CDK\. Here is some TypeScript code in an AWS CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md)\)\. -``` typescript +``` export class MyEcsConstructStack extends core.Stack { constructor(scope: core.App, id: string, props?: core.StackProps) { super(scope, id, props); @@ -40,11 +40,9 @@ export class MyEcsConstructStack extends core.Stack { memoryLimitMiB: 2048, // Default is 512 publicLoadBalancer: true // Default is false }); - } -} ``` -This produces an AWS CloudFormation [template of over 600 lines](https://github.com/awsdocs/aws-cdk-guide/blob/master/doc_source/my_ecs_construct-stack.yaml); deploying the AWS CDK app produces over 50 resources of the following types\. +This produces an AWS CloudFormation [template of more than 500 lines](https://github.com/awsdocs/aws-cdk-guide/blob/master/doc_source/my_ecs_construct-stack.yaml); deploying the AWS CDK app produces more than 50 resources of the following types\. + [AWS::EC2::EIP](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html) + [AWS::EC2::InternetGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html) + [AWS::EC2::NatGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html) @@ -119,4 +117,4 @@ Amazon Web Services \(AWS\) is a collection of digital infrastructure services t AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. -To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. +To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 35b9318e..4b91492f 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -11,77 +11,50 @@ The following is how you import the entire Amazon S3 module or just a `Stack` cl | TypeScript | Python | | --- |--- | -| // Import entire module | \# Import entire module | -| import s3 = require\('@aws\-cdk/aws\-s3'\) | import aws\_cdk\.aws\_s3 as s3 | -| | | -| // Selective import | \# Selective import | -| import \{ Stack \} from '@aws\-cdk/core'; | from aws\_cdk\.core import Stack | +|
// Import entire module
import s3 = require('@aws-cdk/aws-s3')

// Selective import
import { Stack } from '@aws-cdk/core';
|
# Import entire module
import aws_cdk.aws_s3 as s3

# Selective import
from aws_cdk.core import Stack
| ## Instantiating a Class -Classes have the same name in TypeScript and in Python\. TypeScript uses **new** to instantiate classes, whereas in Python you call the class object directly\. The keyword **this** in TypeScript translates to **self** in Python\. +Classes have the same name in TypeScript and in Python\. TypeScript uses **new** to instantiate classes, whereas in Python you call the class object directly, like a function\. Props objects at the end of an argument list become keyword\-only arguments in Python, and their names become `snake_case`\. The keyword **this** in TypeScript translates to **self** in Python\. The following table shows how you can translate TypeScript class instantiations to Python class instantiations\. | TypeScript | Python | | --- |--- | -| // Instantiate Bucket class | \# Instantiate Bucket class | -| new s3\.Bucket\(this, 'Bucket'\); | s3\.Bucket\(self, 'Bucket'\) | +|
// Instantiate Bucket class
const bucket = new s3.Bucket(this, 'Bucket');
|
# Instantiate Bucket class
bucket = s3.Bucket(self, 'Bucket')
| +|
// Instantiate Bucket with props
const bucket = new s3.Bucket(this, 'Bucket', {
bucketName: 'my-bucket',
versioned: true,
});
|
# Instantiate Bucket with props
bucket = s3.Bucket(self, 'Bucket',
bucket_name='my-bucket',
versioned=True)
| ## Methods -Methods names and argument names in TypeScript are `camelCased`, whereas in Python they are `snake_cased`\. Props objects at the end of an argument list in TypeScript are translated into keyword\-only arguments in Python\. +Methods names and argument names in TypeScript are `camelCased`, whereas in Python they are `snake_cased`\. Props objects at the end of an argument list in TypeScript are translated into keyword\-only arguments in Python, and their names become `snake_case`\. The following table shows how you can translate TypeScript methods to Python methods\. | TypeScript | Python | | --- |--- | -| // Instantiate Bucket with props | \# Instantiate Bucket with props | -| const bucket = new s3\.Bucket\(this, 'Bucket', \{ | bucket = s3\.Bucket\(self, 'Bucket', | -|   bucketName: 'my\-bucket', |   bucketName='my\-bucket', | -|   versioned: true, |   versioned=True\) | -| \}\); | | -| | | -| // Call method | \# Call method | -| bucket\.addCorsRule\(\{ | bucket\.add\_cors\_rule\( | -|   allowedOrigins: \['\*'\], |   allowed\_origins=\['\*'\], | -|   allowedMethods: \[\], |   allowed\_methods=\[\] | -| \}\); | \) | +|
// Call method
bucket.addCorsRule({
allowedOrigins: ['*'],
allowedMethods: [],
});
|
# Call method
bucket.add_cors_rule(
allowed_origins=['*'],
allowed_methods=[]
)
| ## Enum Constants -Enum constants are scoped to a class, and have uppercase names in both languages\. - -The following table shows how you can translate TypeScript enum constants to Python enum constants\. +Enum constants are scoped to a class, and have uppercase names with underscores in both languages \(sometimes referred to as `SCREAMING_SNAKE_CASE`\)\. TypeScript enum constants and Python enum constants are identical\. | TypeScript | Python | | --- |--- | -| s3\.BucketEncryption\.KMS\_MANAGED | s3\.BucketEncryption\.KMS\_MANAGED | +|
s3.BucketEncryption.KMS_MANAGED
|
s3.BucketEncryption.KMS_MANAGED
| ## Defining Constructs -In TypeScript a construct’s props are defined with an interface, whereas in Python you take keyword \(or keyword\-only, see [PEP3102](https://www.python.org/dev/peps/pep-3102/)\) arguments\. +In TypeScript, a construct's props are defined with a shape\-based interface, whereas Python takes keyword \(or keyword\-only, see [PEP3102](https://www.python.org/dev/peps/pep-3102/)\) arguments\. -The following table shows how you can translate TypeScript construct definitions to Python construct definitions\. +The following table shows how TypeScript construct definitions translate to Python construct definitions\. | TypeScript | Python | | --- |--- | -| interface MyConstructProps \{ | | -|   prop1: number; | | -|   prop2?: number; | | -| \} | | -| | | -| class MyConstruct extends Construct \{ | class MyConstruct\(Construct\): | -|   constructor\(scope: Construct, id: string, props: MyConstructProps\) \{ |   def \_\_init\_\_\(scope, id, \*, prop1, prop2=10\): | -|     super\(scope, id\); |   super\(\)\.\_\_init\_\_\(scope, id\) | -| | | -|     const prop2 = props\.prop2 \!== undefined ? props\.prop2 : 10; | | -| | | -|     // Construct contents here |   \# Construct contents here | +|
interface MyConstructProps {
prop1: number;
prop2?: number;
}

class MyConstruct extends Construct {
constructor(scope: Construct, id: string, props: MyConstructProps) {
super(scope, id);
const prop2 = props.prop2 !== undefined ? props.prop2 : 10;

// Construct contents here

}
}
|
class MyConstruct(Construct):

def __init__(scope, id, *, prop1, prop2=10):
super().__init__(scope, id)

# Construct contents here
| ## Structs \(Interfaces\) @@ -94,29 +67,15 @@ The following table shows how to call a method with two levels of structs\. | TypeScript | Python | | --- |--- | -| bucket\.addLifecycleRule\(\{ | bucket\.add\_lifecycle\_rule\( | -|   transitions: \[ |   transitions=\[ | -|     \{ |     Transition\( | -|       storageClass: StorageClass\.GLACIER, |       storage\_class=StorageClass\.GLACIER, | -|       transitionAfter: Duration\.days\(10\) |       transition\_after=Duration\.days\(10\) | -|     \} |     \) | -|   \] |   \] | -| \}\); | \) | +|
bucket.addLifecycleRule({
transitions: [
{
storageClass: StorageClass.GLACIER,
transitionAfter: Duration.days(10)
}
]
});
|
bucket.add_lifecycle_rule(
transitions=[
Transition(
storage_class=StorageClass.GLACIER,
transition_after=Duration.days(10)
)
]
)
| ## Object Interfaces The AWS CDK uses TypeScript object interfaces to indicate that a class implements an expected set of methods and properties\. You can recognize an object interface because its name starts with `I`\. -Typically, Python users don’t explicitly indicate that a class implements an interface\. However, for the AWS CDK you can do this by decorating your class with `@jsii.implements(interface)`\. +Typically, Python users don't explicitly indicate that a class implements an interface\. However, for the AWS CDK you can do this by decorating your class with `@jsii.implements(interface)`\. | TypeScript | Python | | --- |--- | -| import \{IAspect, IConstruct \} from ‘@aws\-cdk/core’; | from aws\_cdk\.core import IAspect, IConstruct | -| | | -| | @jsii\.implements\(IAspect\) | -| class MyAspect implements IAspect \{ | class MyAspect\(\): | -|   public visit\(node: IConstruct\) \{ |   def visit\(self, node: IConstruct\) \-> None: | -|     console\.log\(‘Visited’, node\.node\.path\); |     print\("Visited”, node\.node\.path\) | -|   \} | | -| \} | | \ No newline at end of file +|
import {IAspect, IConstruct } from '@aws-cdk/core';

class MyAspect implements IAspect {
public visit(node: IConstruct) {
console.log('Visited', node.node.path);
}
}
|
from aws_cdk.core import IAspect, IConstruct

@jsii.implements(IAspect)
class MyAspect():
def visit(self, node: IConstruct) -> None:
print("Visited", node.node.path)
| \ No newline at end of file diff --git a/doc_source/permissions.md b/doc_source/permissions.md index d7d7cd48..61b2cf7d 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -94,4 +94,4 @@ The AWS CDK Construct Library supports many types of principals, including: 1. Arbitrary ARN principals \(`new iam.ArnPrincipal(res.arn)`\) -1. A `CompositePrincipal(principal1, principal2, ...)` if you need your role to trust multiple principals +1. A `CompositePrincipal(principal1, principal2, ...)` if you need your role to trust multiple principals \ No newline at end of file diff --git a/doc_source/resources.md b/doc_source/resources.md index 7df2b508..8a734b79 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -2,7 +2,7 @@ As described in [Constructs](constructs.md), the AWS CDK provides a rich class library of constructs, called *AWS constructs*, that represent all AWS resources\. This section describes some common patterns and best practices for how to use these constructs\. -Defining AWS resources in your CDK app is exactly like defining any other construct\. You create an instance of the construct class, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here’s how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. +Defining AWS resources in your CDK app is exactly like defining any other construct\. You create an instance of the construct class, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here's how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. ``` import sqs = require('@aws-cdk/aws-sqs'); @@ -118,7 +118,7 @@ new lambda.Function(this, 'MyLambda', { ## Importing Existing External Resources -Sometimes you already have a resource in your AWS account and want to use it in your AWS CDK app, for example, a resource that was defined through the console, the AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource’s ARN \(or another identifying attribute, or group of attributes\) into an AWS CDK object in the current stack by calling a static factory method on the resource's class\. +Sometimes you already have a resource in your AWS account and want to use it in your AWS CDK app, for example, a resource that was defined through the console, the AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into an AWS CDK object in the current stack by calling a static factory method on the resource's class\. The following example shows how to define a bucket based on the existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a VPC based on the existing VPC with the resource name `booh`\. @@ -138,10 +138,10 @@ Resource.fromAttributes(this, 'MyResource', { Because the `ec2.Vpc` construct is composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables\), the complexity makes it difficult to import those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future usage in `cdk.context.json`\. -The following example shows how to get the default VPC of a stack’s environment\. +The following example shows how to get the default VPC of a stack's environment\. ``` -ec2.Vpc.fromLookup(this, 'DefaultVpc’, { +ec2.Vpc.fromLookup(this, 'DefaultVpc', { isDefault: true }); ``` @@ -154,7 +154,7 @@ Although you can use an imported resource anywhere, you cannot modify the import AWS constructs make least\-privilege permissions easy to achieve by offering simple, intent\-based APIs to express permission requirements\. Many AWS constructs offer grant methods that enable you to easily grant an entity, such as an IAM role or a user, permission to work with the resource without having to manually craft one or more IAM permission statements\. -The following example creates the permissions to allow a Lambda function’s execution role to read and write objects to a particular Amazon S3 bucket\. If the Amazon S3 bucket is encrypted using an AWS KMS key, this method also grants the Lambda function's execution role permissions to decrypt using this key\. +The following example creates the permissions to allow a Lambda function's execution role to read and write objects to a particular Amazon S3 bucket\. If the Amazon S3 bucket is encrypted using an AWS KMS key, this method also grants the Lambda function's execution role permissions to decrypt using this key\. ``` bucket.grantReadWrite(lambda); @@ -172,7 +172,7 @@ table.grant(lambda, 'dynamodb:CreateBackup'); Many resources, such as Lambda functions, require a role to be assumed when executing code\. A configuration property enables you to specify an `iam.IRole`\. If no role is specified, the function automatically creates a role specifically for this use\. You can then use grant methods on the resources to add statements to the role\. -The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-iam-readme.html) objects\. Add statements directly to roles \(or a construct’s attached role\) using the `addToRolePolicy` method, or to a resource’s policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` method\. +The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-iam-readme.html) objects\. Add statements directly to roles \(or a construct's attached role\) using the `addToRolePolicy` method, or to a resource's policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` method\. ## Metrics and Alarms @@ -207,7 +207,7 @@ Metrics can also be added to CloudWatch dashboards\. See [CloudWatch](https://do In many cases, you must enable permissions on a network for an application to work, such as when the compute infrastructure needs to access the persistence layer\. Resources that establish or listen for connections expose methods that enable traffic flows, including setting security group rules or network ACLs\. -[IConnectable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Iconnectable.html) resources have a `connections` property that is the gateway to network traffic rules configuration\. +[IConnectable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.IConnectable.html) resources have a `connections` property that is the gateway to network traffic rules configuration\. You enable data to flow on a given network path by using `allow` methods\. The following example enables HTTPS connections to the web and incoming connections from the Amazon EC2 Auto Scaling group `fleet2`\. diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 6b8324d0..e1678a4f 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -154,21 +154,6 @@ export class WidgetService extends core.Construct { }); api.root.addMethod("GET", getWidgetsIntegration); // GET / - - const widget = api.root.addResource("{id}"); - - // Add new widget to bucket with: POST /{id} - const postWidgetIntegration = new apigateway.LambdaIntegration(handler); - - // Get a specific widget from bucket with: GET /{id} - const getWidgetIntegration = new apigateway.LambdaIntegration(handler); - - // Remove a specific widget from the bucket with: DELETE /{id} - const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); - - widget.addMethod("POST", postWidgetIntegration); // POST /{id} - widget.addMethod("GET", getWidgetIntegration); // GET /{id} - widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} } } ``` @@ -182,7 +167,7 @@ cdk synth ## Add the Service to the App -To add the service to the app, first modify `my_widget_service-stack.ts`\. Add the following line of code after the existing `import` statement\. +To add the service to the app, first modify `my_widget_service-stack.ts` in the `lib` directory\. Add the following line of code after the existing `import` statement\. ``` import widget_service = require('../lib/widget_service'); @@ -247,7 +232,7 @@ Because we haven't stored any widgets yet, the output should be similar to the f The next step is to create Lambda functions to create, show, and delete individual widgets\. -Replace the existing `exports.main` function in `widgets.js` with the following code\. +Replace the existing `exports.main` function in `widgets.js` \(in `resources`\) with the following code\. ``` exports.main = async function(event, context) { @@ -356,20 +341,20 @@ exports.main = async function(event, context) { Wire up these functions to your API Gateway code in `widget_service.ts` by adding the following code at the end of the constructor\. ``` -const widget = api.root.addResource('{name}'); + const widget = api.root.addResource("{id}"); -// Add new widget to bucket with: POST /{name} -const postWidgetIntegration = new apigateway.LambdaIntegration(handler); + // Add new widget to bucket with: POST /{id} + const postWidgetIntegration = new apigateway.LambdaIntegration(handler); -// Get a specific widget from bucket with: GET /{name} -const getWidgetIntegration = new apigateway.LambdaIntegration(handler); + // Get a specific widget from bucket with: GET /{id} + const getWidgetIntegration = new apigateway.LambdaIntegration(handler); -// Remove a specific widget from the bucket with: DELETE /{name} -const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); + // Remove a specific widget from the bucket with: DELETE /{id} + const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); -widget.addMethod('POST', postWidgetIntegration); // POST /{name} -widget.addMethod('GET', getWidgetIntegration); // GET /{name} -widget.addMethod('DELETE', deleteWidgetIntegration); // DELETE /{name} + widget.addMethod("POST", postWidgetIntegration); // POST /{id} + widget.addMethod("GET", getWidgetIntegration); // GET /{id} + widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} ``` Save, build, and deploy the app\. diff --git a/doc_source/stacks.md b/doc_source/stacks.md index ff10929b..a7255c36 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -68,13 +68,13 @@ new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name' }); ## Stack API -The [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/cdk/stack.html) object provides a rich API, including the following: +The [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html) object provides a rich API, including the following: + `Stack.of(construct)` – A static method that returns the **Stack** in which a construct is defined\. This is useful if you need to interact with a stack from within a reusable construct\. The call fails if a stack cannot be found in scope\. + `stack.stackName` – Returns the physical name of the stack\. As mentioned previously, all AWS CDK stacks have a physical name that the AWS CDK can resolve during synthesis\. + `stack.region` and `stack.account` – Return the AWS Region and account, respectively, into which this stack will be deployed\. These properties return either the account or Region explicitly specified when the stack was defined, or a string\-encoded token that resolves to the AWS CloudFormation pseudo\-parameters for account and Region to indicate that this stack is environment agnostic\. See [Environments](environments.md) for information about how environments are determined for stacks\. + `stack.account` – Returns the AWS account into which this stack will be deployed\. Similarly to Region, this property returns either an explicit account ID or a token that resolves to \{ Ref: AWS::AccountId \}\. Use `Token.isUnresolved` method to determine whether the value is a token before reading the value returned from this property\. + `stack.addDependency(stack)` – Can be used to explicitly define dependency order between two stacks\. This order is respected by the cdk deploy command when deploying multiple stacks at once\. -+ `stack.tags` – Returns a [TagManager](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/tagmanager.html#core_TagManager) that you can use to add or remove stack\-level tags\. This tag manager tags all resources within the stack, and also tags the stack itself when it’s created through AWS CloudFormation\. ++ `stack.tags` – Returns a [TagManager](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/tagmanager.html#core_TagManager) that you can use to add or remove stack\-level tags\. This tag manager tags all resources within the stack, and also tags the stack itself when it's created through AWS CloudFormation\. + `stack.partition`, `stack.urlSuffix`, `stack.stackId`, and `stack.notificationArn` – Return tokens that resolve to the respective AWS CloudFormation pseudo\-parameters, such as \{ "Ref": "AWS::Partition" \}\. These tokens are associated with this specific stack object, so the framework can identify cross\-stack references\. + `stack.availabilityZones` – Returns the set of Availability Zones available in the environment in which this stack is deployed\. For environment\-agnostic stacks, this always returns an array with two Availability Zones, but for environment\-specific stacks, the AWS CDK queries the environment and returns the exact set of Availability Zones that are available\. + `stack.parseArn(arn)` and `stack.formatArn(comps)` – Can be used to work with Amazon Resource Names \(ARNs\)\. diff --git a/doc_source/tagging.md b/doc_source/tagging.md index e6d300fa..5a571a68 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -99,5 +99,5 @@ theBestStack.node.applyAspect(new RemoveTag('StackType'), { You can achieve the same result by using the following\. ``` -theBestStack.node.applyAspect(new Tag('StackType', 'TheBest', { includeResourceTypes: [‘AWS::EC2::Subnet’]})); +theBestStack.node.applyAspect(new Tag('StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet'']})); ``` \ No newline at end of file diff --git a/doc_source/tokens.md b/doc_source/tokens.md index 63df4d4d..90001381 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -6,12 +6,12 @@ Tokens represent values that can only be resolved at a later time in the lifecyc ${TOKEN[Bucket.Name.1234]} ``` -This is how the AWS CDK encodes a token whose value is not yet known at construction time, but will become available later\. The AWS CDK calls these placeholders *tokens*\. In this case, it’s a token encoded as a string\. +This is how the AWS CDK encodes a token whose value is not yet known at construction time, but will become available later\. The AWS CDK calls these placeholders *tokens*\. In this case, it's a token encoded as a string\. You can pass this string around as if it was the name of the bucket, such as in the following example, where the bucket name is specified as an environment variable to an AWS Lambda function\. ``` -const bucket = new s3.Bucket(this, 'Bucket'); +const bucket = new s3.Bucket(this, 'MyBucket'); const fn = new lambda.Function(stack, 'MyLambda', { // ... @@ -28,7 +28,7 @@ When the AWS CloudFormation template is finally synthesized, the token is render Tokens are objects that implement the [IResolvable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.IResolvable.html) interface, which contains a single `resolve` method\. The AWS CDK calls this method during synthesis to produce the final value for the AWS CloudFormation template\. Tokens participate in the synthesis process to produce arbitrary values of any type\. **Note** -You’ll hardly ever work directly with the `IResolvable` interface\. You will most likely only see string\-encoded versions of tokens\. +You'll hardly ever work directly with the `IResolvable` interface\. You will most likely only see string\-encoded versions of tokens\. Other functions typically only accept arguments of basic types, such as `string` or `number`\. To use tokens in these cases, you can encode them into one of three types using static methods on the [core\.Token](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html) class\. + Strings using [Token\.asString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) @@ -53,7 +53,7 @@ if (!Token.isUnresolved(name) && name.length > 10) { If **name** is a token, validation is not be performed, and the error could occur in a later stage in the lifecycle, such as during deployment\. **Note** -You can use token encodings to escape the type system\. For example, you could string\-encode a token that produces a number value at synthesis time\. If you use these functions, it’s your responsibility to ensure that your template resolves to a usable state after synthesis\. +You can use token encodings to escape the type system\. For example, you could string\-encode a token that produces a number value at synthesis time\. If you use these functions, it's your responsibility to ensure that your template resolves to a usable state after synthesis\. ## String\-Encoded Tokens @@ -106,7 +106,7 @@ You can construct tokens representing synth\-time lazy values using static metho ``` let actualValue: number; -new AutoScalingGroup(this, ‘Group’, { +new AutoScalingGroup(this, 'Group', { desiredCapacity: Lazy.numberValue({ produce() { return actualValue; diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index c67fec21..b3cd9175 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -16,7 +16,7 @@ The AWS CDK provides a mechanism that you can use to incorporate resources from You can include this bucket in your AWS CDK app, as shown in the following example: ``` -import cdk = require("@amp;aws-cdk/cdk"); +import cdk = require("@aws-cdk/core"); import fs = require("fs"); new cdk.Include(this, "ExistingInfrastructure", { From 0e7e607d9ef99c25f369815ee87800b31e2ff8a0 Mon Sep 17 00:00:00 2001 From: Bernard Paques Date: Sat, 3 Aug 2019 11:27:06 +0200 Subject: [PATCH 036/655] fix small typo --- doc_source/resources.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index 8a734b79..c2344623 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -244,5 +244,5 @@ The following example shows how to trigger a Lambda function when an object is a Import targets = require('@aws-cdk/aws-events-targets'); const handler = new lambda.Function(this, 'Handler', { /*…*/ }); const bucket = new s3.Bucket(this, 'Bucket'); -bucket.addObjectCreatedNotification(new targets.LambdaFunction(hanlder)); -``` \ No newline at end of file +bucket.addObjectCreatedNotification(new targets.LambdaFunction(handler)); +``` From 3b9dd9fd8f7876e197ac37375c155e0145675d48 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 5 Aug 2019 18:26:37 +0000 Subject: [PATCH 037/655] Updates for SSM, tagging, permissions, minor typos --- doc_source/get_ssm_value.md | 52 ++++++++++++++++++++++++++++--------- doc_source/index.md | 2 +- doc_source/permissions.md | 40 ++++++++++++++-------------- doc_source/resources.md | 2 +- doc_source/tagging.md | 52 ++++++++++++++++++------------------- 5 files changed, 88 insertions(+), 60 deletions(-) diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 688b33db..7d8f04ca 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -1,37 +1,65 @@ -# Get a Value from a Systems Manager Parameter Store Variable +# Get a Value from the Systems Manager Parameter Store -You can get the value of an AWS Systems Manager Parameter Store variable, depending on whether you want the latest version of a plain string, a particular version of a plain string, or a particular version of a secret string\. It isn't possible to retrieve the latest version of a secure string\. To read the latest version of a secret, you have to read the secret from AWS Secrets Manager \(see [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. +The AWS CDK can retrieve the value of AWS Systems Manager Parameter Store attribute at synthesis time \(as the AWS CloudFormation template is being generated\) or at deployment time \(when the synthesized template is being deployed by AWS CloudFormation\)\. In the latter case, the AWS CDK provides a [token](tokens.md) that is later resolved by AWS CloudFormation\. -To read a particular version of a Systems Manager Parameter Store plain string value at AWS CloudFormation deployment time, use [ParameterStoreString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.ParameterStoreString.html)\. If you don't supply a `version` value, you get the latest version\. +The AWS CDK supports retrieving both plain and secure values\. You may request a specific version of either kind of value\. For plain values only, you may omit the version from your request to receive the latest version\. You must always specify the version when requesting the value of a secure attribute\. + +**Note** + This topic shows how to read attributes from the AWS Systems Manager Parameter Store\. You can also read secrets from the AWS Secrets Manager \(see [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. + +## Reading Values at Synthesis Time + +To read a particular version of a Systems Manager Parameter Store plain string value at synthesis time, use the [fromStringParameterAttributes](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-from-string-parameter-attributesscope-id-attrs) method\. If you don't supply a `version` value, you get the latest version\. ``` import ssm = require('@aws-cdk/aws-ssm'); const parameterString = new ssm.StringParameter.fromStringParameterAttributes(this, 'MyParameter', { - parameterName: 'my-parameter-name', - version: 1, + parameterName: 'my-plain-parameter-name', + version: 1, // omit to get latest version }); -const myvalue = parameterString.stringValue; +const myValue = parameterString.stringValue; ``` -To read a particular version of a Systems Manager Parameter Store `SecureString` value at AWS CloudFormation deployment time, use [ParameterStoreSecureString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.ParameterStoreSecureString.html)\. You must supply a `version` value\. +To read a particular version of a Systems Manager Parameter Store secure string value at synthesis time, use [fromSecureStringParameterAttributes](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-from-secure-string-parameter-attributesscope-id-attrs)\. You must supply a `version` value for secure strings\. ``` import ssm = require('@aws-cdk/aws-ssm'); const secureString = new ssm.StringParameter.fromSecureStringParameterAttributes(this, 'MySecretParameter', { - parameterName: 'my-secret-parameter-name', + parameterName: 'my-secure-parameter-name', version: 1, }); -const myvalue = secureString.stringValue; +const myValue = secureString.stringValue; ``` -Use the [put\-parameter](https://docs.aws.amazon.com/cli/latest/reference/ssm/put-parameter.html) CLI command to add a string parameter to the system, such as when testing: +## Reading Values at Deployment Time + +To read values from the Systems Manager Parameter Store at deployment time, use the [fromStringParameterAttributes](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-string-parameterscope-parametername-version) and [fromSecureStringParameterAttributes](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-secure-string-parameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md) that are later resolved by AWS CloudFormation during deployment\. + +``` +import ssm = require('@aws-cdk/aws-ssm'); + +// Get latest version of specified version of plain string attribute +const latestStringToken = ssm.StringParameter.valueForStringParameter( + this, 'my-plain-parameter-name'); // latest version +const versionOfStringToken = ssm.StringParameter.valueForStringParameter( + this, 'my-plain-parameter-name', 1); // version 1 + +// Get specified version of secure string attribute +const secureStringToken = new ssm.StringParameter.valueForSecureStringParameter( + this, 'my-secure-parameter-name', 1); // must specify version +``` + +## Writing Values to Systems Manager + +Use the [ssm put\-parameter](https://docs.aws.amazon.com/cli/latest/reference/ssm/put-parameter.html) CLI command to add a string parameter to the Systems Manager, such as when testing: ``` -aws ssm put-parameter --name "my-parameter-name" --type "String" --value "my-parameter-value" +aws ssm put-parameter --name "parameter-name" --type "String" --value "parameter-value" + aws ssm put-parameter --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" ``` -The command returns an ARN you can use for the example\. \ No newline at end of file +This command returns an ARN that you can use to retrieve the value in your AWS CDK code\. \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index f4d5198d..65bf4247 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -41,7 +41,7 @@ Amazon's trademarks and trade dress may not be used in + [Get a Value from an Environment Variable](get_env_var.md) + [Use an AWS CloudFormation Parameter](get_cfn_param.md) + [Use an Existing AWS CloudFormation Template](use_cfn_template.md) - + [Get a Value from a Systems Manager Parameter Store Variable](get_ssm_value.md) + + [Get a Value from the Systems Manager Parameter Store](get_ssm_value.md) + [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md) + [Create an App with Multiple Stacks](stack_how_to_create_multiple_stacks.md) + [Set a CloudWatch Alarm](how_to_set_cw_alarm.md) diff --git a/doc_source/permissions.md b/doc_source/permissions.md index 61b2cf7d..0d017336 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -17,18 +17,18 @@ const role = new iam.Role(this, 'Role', { You can add permissions to a role by calling methods on it, and passing the appropriate `Policy` statement\. The following example adds a `Deny` statement to the role for the actions `ec2:SomeAction` and `s3:AnotherAction` on the resources `bucket` and `otherRole`, under the condition that the authorized service is AWS CodeBuild\. ``` -role.addToPolicy(new iam.PolicyStatement(PolicyStatementEffect.Deny) // default is Allow - // there's also addResource() to add one, and addAllResources() to add '*' - .addResources(bucket.bucketArn, otherRole.roleArn) - // there's also addAction() to add one - .addActions('ec2:SomeAction', 's3:AnotherAction') - .addCondition('StringEquals', { - 'ec2:AuthorizedService': 'codebuild.amazonaws.com', - }) -); +const policyStatement = new iam.PolicyStatement(PolicyStatementEffect.Deny) // default is Allow + +policyStatement.addResources(bucket.bucketArn, otherRole.roleArn); +policyStatement.addActions('ec2:SomeAction', 's3:AnotherAction'); +policyStatement.addCondition('StringEquals', { + 'ec2:AuthorizedService': 'codebuild.amazonaws.com', +}); + +role.addToPolicy(policyStatement); ``` -If you're using a construct that requires a role to function correctly, you can either pass in an existing role when instantiating the construct object, or let the construct create a new role for you, trusting the appropriate service principal\. The following example of using such a construct, in this case a CodeBuild project\. +If you're using a construct that requires a role to function correctly, you can either pass in an existing role when instantiating the construct object, or let the construct create a new role for you, trusting the appropriate service principal\. The following example uses such a construct: a CodeBuild project\. ``` import codebuild = require('@aws-cdk/aws-codebuild'); @@ -50,12 +50,11 @@ In either case, once the object is created, the role is available as the propert // project is imported into the CDK application const project = codebuild.Project.fromProjectName(this, 'Project', 'ProjectName'); -// project.role is undefined +const policyStatement = new iam.PolicyStatement(); +// set up your policyStatement here using addResources, addActions, addCondition, etc. -// this method call will have no effect -project.addToRolePolicy(new iam.PolicyStatement() - // ... -); +// project.role is undefined, so this method call will have no effect +project.addToRolePolicy(policyStatement); ``` ## Grants @@ -71,10 +70,13 @@ A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a res In the following example, the Amazon S3 bucket `bucket` grants a role with the `s3:SomeAction` permission to itself\. ``` -bucket.addToResourcePolicy(new iam.PolicyStatement() - .addAction('s3:SomeAction') - .addResource(bucket.bucketArn) - .addPrincipal(role) +const policyStatement = new iam.PolicyStatement(); + +policyStatement.addAction('s3:SomeAction'); +policyStatement.addResource(bucket.bucketArn); +policyStatement.addPrincipal(role); + +bucket.addToResourcePolicy(policyStatement); ); ``` diff --git a/doc_source/resources.md b/doc_source/resources.md index c2344623..127decc2 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -245,4 +245,4 @@ Import targets = require('@aws-cdk/aws-events-targets'); const handler = new lambda.Function(this, 'Handler', { /*…*/ }); const bucket = new s3.Bucket(this, 'Bucket'); bucket.addObjectCreatedNotification(new targets.LambdaFunction(handler)); -``` +``` \ No newline at end of file diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 5a571a68..8e72509a 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -1,46 +1,44 @@ # Tagging -The AWS CDK includes two classes that you can use to create and delete tags: -+ [Tag](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html) applies a new tag to a construct and all of its children\. -+ [RemoveTag](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.RemoveTag.html) removes a tag from a construct and any of its children, including tags a child construct may have applied to itself\. +The `Tag` class includes two methods that you can use to create and delete tags: ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props) applies a new tag to a construct and all of its children\. ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props) removes a tag from a construct and any of its children, including tags a child construct may have applied to itself\. -Let's look at a couple of examples\. - -The following example applies the tag **key** with the value **value** to `myConstruct`\. +Let's look at a couple of examples\. The following example applies the tag **key** with the value **value** to `myConstruct`\. ``` -myConstruct.node.applyAspect(new Tag('key', 'value')); +Tag.add(myConstruct, 'key', 'value'); ``` The following example deletes the tag **key** from `myConstruct`\. ``` -myConstruct.node.applyAspect(new RemoveTag('key')); +tag.remove(myConstruct, 'key'); ``` -The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. If the priorities are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 and removing a tag has a priority of 200\. To change the priority of applying a tag, pass a `priority` option to `Tag` or `RemoveTag`\. +The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. If the priorities are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 and removing a tag has a priority of 200\. To change the priority of applying a tag, pass a `priority` property to `Tag.add()` or `Tag.remove()`\. The following applies a tag with a priority of 300 to `myConstruct`\. ``` -myConstruct.node.applyAspect(new Tag('key', 'value', { +Tag.add(myConstruct, 'key', 'value', { priority: 300 -})); +}); ``` -## Tag +## Tag\.add\(\) -The `Tag` operation includes some properties to fine\-tune how tags are applied from the resources that the construct creates, all of which are optional\. +`Tag.add()` supports properties that fine\-tune how tags are applied to resources\. All properties are optional\. The following example applies the tag **tagname** with the value **value** and priority **100** to resources of type **AWS::Xxx::Yzz** in `myConstruct`, but not to instances launched in an Amazon EC2 Auto Scaling group or to resources of type **AWS::Xxx::Zss**\. ``` -myConstruct.node.applyAspect(new Tag('tagname', 'value', { +Tag.add(myConstruct, 'tagname', 'value', { applyToLaunchedInstances: false, includeResourceTypes: ['AWS::Xxx::Yyy'], excludeResourceTypes: ['AWS::Xxx::Zzz'], priority: 100, -})); +}); ``` These properties have the following meanings\. @@ -52,20 +50,20 @@ includeResourceTypes/excludeResourceTypes Use these to apply tags only to a subset of resources, based on AWS CloudFormation resource types\. By default, the tag is applied to all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. priority -Use this to set the priority of this operation with respect to other `Tag` and `RemoveTag` operations\. Higher values take precedence over lower values\. The default is 100\. +Use this to set the priority of this operation with respect to other `Tag.add()` and `Tag.remove()` operations\. Higher values take precedence over lower values\. The default is 100\. -## RemoveTag +## Tag\.remove\(\) -The `RemoveTag` class includes properties to fine\-tune how tags are removed, all of which are optional\. + `Tag.remove()` supports properties to fine\-tune how tags are removed from resources\. All properties are optional\. The following example removes the tag **tagname** with priority **200** from resources of type **AWS::Xxx::Yzz** in `myConstruct`, but not from resources of type **AWS::Xxx::Zzz**\. ``` -myConstruct.node.applyAspect(new RemoveTag('tagname', { +Tag.remove(myConstruct, 'tagname', { includeResourceTypes: ['AWS::Xxx::Yyy'], excludeResourceTypes: ['AWS::Xxx::Zzz'], priority: 200, -})); +}); ``` These properties have the following meanings\. @@ -74,30 +72,30 @@ includeResourceTypes/excludeResourceTypes Use these properties to remove tags only from subset of resources based on AWS CloudFormation resource types\. By default, the tag is removed from all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. priority -Use this property to specify the priority of this operation with respect to other `Tag` and `RemoveTag` operations\. Higher values take precedence over lower values\. The default is 200\. +Use this property to specify the priority of this operation with respect to other `Tag.add()` and `Tag.remove()` operations\. Higher values take precedence over lower values\. The default is 200\. ## Example The following example adds the tag key **StackType** with value **TheBest** to any resource created within the Stack named `MarketingSystem`\. Then it removes it again from all resources except Amazon EC2 VPC subnets\. The result is that only the subnets have the tag applied\. ``` -import { App, RemoveTag, Stack, Tag } from require('@aws-cdk/cdk'); +import { App, Stack, Tag } from require('@aws-cdk/cdk'); const app = new App(); const theBestStack = new Stack(app, 'MarketingSystem'); // Add a tag to all constructs in the stack -theBestStack.node.applyAspect(new Tag('StackType', 'TheBest')); +Tag.add(theBestStack, 'StackType', 'TheBest'); // Remove the tag from all resources except subnet resources -theBestStack.node.applyAspect(new RemoveTag('StackType'), { +Tag.remove(theBestStack, 'StackType'), { exludeResourceTypes: ['AWS::EC2::Subnet'] -})); +}); ``` **Note** -You can achieve the same result by using the following\. +The following code achieves the same result\. Consider which approach \(inclusion or exclusion\) makes your intent clearer\. ``` -theBestStack.node.applyAspect(new Tag('StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet'']})); + Tag.add(theBestStack, 'StackType', 'TheBest', { includeResourceTypes: [‘AWS::EC2::Subnet’]}); ``` \ No newline at end of file From 26477792da49df2a2ce6cc1e95f229c167c24539 Mon Sep 17 00:00:00 2001 From: Elliot Murphy Date: Tue, 6 Aug 2019 11:36:36 -0400 Subject: [PATCH 038/655] Fix typo on reading SSM values at deploy time. Now the link title matches the link and the code example. Signed-off-by: Elliot Murphy --- doc_source/get_ssm_value.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 7d8f04ca..4228c245 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -37,7 +37,7 @@ const myValue = secureString.stringValue; ## Reading Values at Deployment Time -To read values from the Systems Manager Parameter Store at deployment time, use the [fromStringParameterAttributes](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-string-parameterscope-parametername-version) and [fromSecureStringParameterAttributes](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-secure-string-parameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md) that are later resolved by AWS CloudFormation during deployment\. +To read values from the Systems Manager Parameter Store at deployment time, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-string-parameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-secure-string-parameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md) that are later resolved by AWS CloudFormation during deployment\. ``` import ssm = require('@aws-cdk/aws-ssm'); From 32ac77f0d525c21eb121e4141f6a680c20a7fbce Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Wed, 7 Aug 2019 12:02:42 -0700 Subject: [PATCH 039/655] Create README with contributor info and link to project board --- README.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..3961747f --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# Welcome to the AWS CDK Developer Guide + +This is the GitHub repository for the [AWS CDK Developer Guide](https://docs.aws.amazon.com/cdk/latest/guide/home.html). +You're welcome to report issues with the documentation here or, if you have a moment, to submit a Pull Request with your +suggested changes. + +Issues reported through the Feedback link at the bottom of the individual pages of the AWS CDK Developer Guide go to an internal +Amazon issue tracker and may not appear here. However, we try to track most substantive AWS CDK Developer Guide work on GitHub +so the community can see and comment. + +> **NOTE** +> +> The Markdown files in this repository are an *output* of the AWS CDK Developer Guide build process, not the actual source files. +Periodically, we update the Markdown files here from our builds. This means that changes may appear on docs.aws.amazon.com before they appear +here. Also, sometimes we may close a PR instead of merging it, even if we have in fact integrated your submission into the Guide. + +## Project Board + +Have a look at the AWS CDK Developer Guide [Project Board](https://github.com/awsdocs/aws-cdk-guide/projects/1) +to see what we're working on at the moment. Note that items on the Wishlist may not be in any particular order. + +## Contributor Grant of License + +By submitting a Pull Request against this repo, you grant Amazon the right to use use, modify, copy, and redistribute your contribution +under any license we choose. From f74ed5c08729ac7c74a8146ae69eb03d9970cfe9 Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Thu, 8 Aug 2019 11:34:47 -0700 Subject: [PATCH 040/655] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3961747f..dcbc41d9 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ suggested changes. Issues reported through the Feedback link at the bottom of the individual pages of the AWS CDK Developer Guide go to an internal Amazon issue tracker and may not appear here. However, we try to track most substantive AWS CDK Developer Guide work on GitHub -so the community can see and comment. +so the community can see, comment, and contribute. > **NOTE** > From 69941b87ad0b252dada0ae845a058ac6e63d1a79 Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Fri, 9 Aug 2019 03:26:08 +0000 Subject: [PATCH 041/655] fix type of page constructs.md --- doc_source/constructs.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 87b34300..12dfdcbe 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -2,7 +2,7 @@ Constructs are the basic building blocks of AWS CDK apps\. A construct represents a "cloud component" and encapsulates everything AWS CloudFormation needs to create the component\. -A construct can represent a single resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can represent a higher\-lever component consisting of multiple AWS CDK resources\. Examples of such components include a worker queue with its associated compute capacity, a cron job with monitoring resources and a dashboard, or even an entire app spanning multiple AWS accounts and regions\. +A construct can represent a single resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can represent a higher\-level component consisting of multiple AWS CDK resources\. Examples of such components include a worker queue with its associated compute capacity, a cron job with monitoring resources and a dashboard, or even an entire app spanning multiple AWS accounts and regions\. ## AWS Construct Library @@ -184,4 +184,4 @@ Now, consumers can subscribe to the topic, for example: const queue = new sqs.Queue(this, 'NewImagesQueue'); const images = new NotificationBucket(this, 'Images'); images.topic.addSubscription(new sns_sub.QueueSubscription(queue)); -``` \ No newline at end of file +``` From 29088ed9ffe6a3eb13fcc076033ae66b165d1d64 Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Fri, 9 Aug 2019 04:18:32 +0000 Subject: [PATCH 042/655] fix a example code of tagging --- doc_source/tagging.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 8e72509a..d8df21a5 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -79,7 +79,7 @@ Use this property to specify the priority of this operation with respect to othe The following example adds the tag key **StackType** with value **TheBest** to any resource created within the Stack named `MarketingSystem`\. Then it removes it again from all resources except Amazon EC2 VPC subnets\. The result is that only the subnets have the tag applied\. ``` -import { App, Stack, Tag } from require('@aws-cdk/cdk'); +import { App, Stack, Tag } from '@aws-cdk/core'; const app = new App(); const theBestStack = new Stack(app, 'MarketingSystem'); @@ -88,8 +88,8 @@ const theBestStack = new Stack(app, 'MarketingSystem'); Tag.add(theBestStack, 'StackType', 'TheBest'); // Remove the tag from all resources except subnet resources -Tag.remove(theBestStack, 'StackType'), { - exludeResourceTypes: ['AWS::EC2::Subnet'] +Tag.remove(theBestStack, 'StackType', { + excludeResourceTypes: ['AWS::EC2::Subnet'] }); ``` @@ -98,4 +98,4 @@ The following code achieves the same result\. Consider which approach \(inclusio ``` Tag.add(theBestStack, 'StackType', 'TheBest', { includeResourceTypes: [‘AWS::EC2::Subnet’]}); -``` \ No newline at end of file +``` From 2bb339dfce3bf42083806338def118177f1e6061 Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Thu, 15 Aug 2019 11:37:17 -0700 Subject: [PATCH 043/655] Add links to CDK and CDK Workshop repos for issues with API Ref and Workshop --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index dcbc41d9..ac0b1c1c 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,11 @@ so the community can see, comment, and contribute. Periodically, we update the Markdown files here from our builds. This means that changes may appear on docs.aws.amazon.com before they appear here. Also, sometimes we may close a PR instead of merging it, even if we have in fact integrated your submission into the Guide. +## Other Documentation Issues + +* Issues with the [API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) should be [filed](https://github.com/aws/aws-cdk/issues/new/choose) against the [AWS CDK repo](https://github.com/aws/aws-cdk/). +* Issues with the [CDK Workshop](https://cdkworkshop.com/) should be [filed](https://github.com/aws-samples/aws-cdk-intro-workshop/issues/new/choose) against the [CDK Workshop](https://github.com/aws-samples/aws-cdk-intro-workshop) repo. + ## Project Board Have a look at the AWS CDK Developer Guide [Project Board](https://github.com/awsdocs/aws-cdk-guide/projects/1) From 912f68799079122dcdcd60b5070400ab82243643 Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Thu, 15 Aug 2019 11:37:59 -0700 Subject: [PATCH 044/655] Put another word inside a link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ac0b1c1c..8f23ff8d 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ here. Also, sometimes we may close a PR instead of merging it, even if we have i ## Other Documentation Issues * Issues with the [API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) should be [filed](https://github.com/aws/aws-cdk/issues/new/choose) against the [AWS CDK repo](https://github.com/aws/aws-cdk/). -* Issues with the [CDK Workshop](https://cdkworkshop.com/) should be [filed](https://github.com/aws-samples/aws-cdk-intro-workshop/issues/new/choose) against the [CDK Workshop](https://github.com/aws-samples/aws-cdk-intro-workshop) repo. +* Issues with the [CDK Workshop](https://cdkworkshop.com/) should be [filed](https://github.com/aws-samples/aws-cdk-intro-workshop/issues/new/choose) against the [CDK Workshop repo](https://github.com/aws-samples/aws-cdk-intro-workshop). ## Project Board From 70a237b8b1b070a45c0e766b74c447cd5f363d35 Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Thu, 15 Aug 2019 11:42:33 -0700 Subject: [PATCH 045/655] Add suggestion to +1 issues --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8f23ff8d..7db61437 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ here. Also, sometimes we may close a PR instead of merging it, even if we have i ## Project Board Have a look at the AWS CDK Developer Guide [Project Board](https://github.com/awsdocs/aws-cdk-guide/projects/1) -to see what we're working on at the moment. Note that items on the Wishlist may not be in any particular order. +to see what we're working on at the moment. Note that items on the Wishlist may not be in any particular order. You can help us prioritize our work by +1'ing issues that are important to you. ## Contributor Grant of License From 0b36a6043f158a93f9cdc2a2778905b76922d224 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 15 Aug 2019 20:35:50 +0000 Subject: [PATCH 046/655] Update Markdown files from latest Developer Guide --- doc_source/constructs.md | 2 +- doc_source/doc-history.md | 10 +- doc_source/get_ssm_value.md | 4 +- doc_source/getting_started.md | 230 ++++++++++++++++--------------- doc_source/home.md | 2 +- doc_source/multiple_languages.md | 2 +- doc_source/permissions.md | 90 ++++++------ doc_source/reference.md | 4 +- doc_source/tagging.md | 9 +- 9 files changed, 185 insertions(+), 168 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 12dfdcbe..d27474b1 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -184,4 +184,4 @@ Now, consumers can subscribe to the topic, for example: const queue = new sqs.Queue(this, 'NewImagesQueue'); const images = new NotificationBucket(this, 'Images'); images.topic.addSubscription(new sns_sub.QueueSubscription(queue)); -``` +``` \ No newline at end of file diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 2c4ca8ee..89d13d49 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -1,11 +1,15 @@ # Document History for the AWS CDK Developer Guide This document is based on the following release of the AWS Cloud Development Kit \(AWS CDK\)\. -+ **API version: 1\.0\.0** -+ **Latest documentation update:** July 11, 2019 ++ **API version: 1\.3\.0** ++ **Latest documentation update:** August 13, 2019 See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the AWS CDK releases\. +**Note** +The table below represents significant milestones\. We fix errors and improve content on an ongoing basis\. + | Change | Description | Date | | --- |--- |--- | -| [Initial Release](#doc-history) | The developer guide is released\. | July 11, 2019 | \ No newline at end of file +| [Version 1\.3\.0](#doc-history) | Update tagging topic to use new API\. | August 13, 2019 | +| [Version 1\.0\.0](#doc-history) | The AWS CDK Developer Guide is released\. | July 11, 2019 | \ No newline at end of file diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 4228c245..a8e80b8a 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -42,7 +42,7 @@ To read values from the Systems Manager Parameter Store at deployment time, use ``` import ssm = require('@aws-cdk/aws-ssm'); -// Get latest version of specified version of plain string attribute +// Get latest version or specified version of plain string attribute const latestStringToken = ssm.StringParameter.valueForStringParameter( this, 'my-plain-parameter-name'); // latest version const versionOfStringToken = ssm.StringParameter.valueForStringParameter( @@ -59,7 +59,7 @@ Use the [ssm put\-parameter](https://docs.aws.amazon.com/cli/latest/reference/ss ``` aws ssm put-parameter --name "parameter-name" --type "String" --value "parameter-value" - aws ssm put-parameter --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" +aws ssm put-parameter --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" ``` This command returns an ARN that you can use to retrieve the value in your AWS CDK code\. \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 1b70b627..82fa3389 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -3,7 +3,7 @@ This topic describes how to install and configure the AWS CDK and create your first AWS CDK app\. **Note** -Looking for more than just the basics? Try the [CDK Workshop](https://cdkworkshop.com/)\. +Want to dig deeper? Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour of a real\-world project\. ## Prerequisites @@ -12,7 +12,7 @@ Looking for more than just the basics? Try the [CDK Workshop](https://cdkworksho + You must specify both your credentials and an AWS Region to use the AWS CDK CLI;, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. **Note** - Why do you need Node\.js if you're a not a JavaScript developer? The AWS CDK is developed in TypeScript and transpiled to JavaScript\. Bindings for the other supported languages make use of the AWS CDK back\-end running on Node\.js, as does the `cdk` command\-line tool\. +Why do you need Node\.js when you're a Python, C♯, or Java developer? The AWS CDK is developed in TypeScript and transpiled to JavaScript\. Bindings for the other supported languages make use of the AWS CDK engine running on Node\.js, as does the `cdk` command\-line tool\. ------ #### [ TypeScript ] @@ -24,23 +24,23 @@ TypeScript >= 2\.7 none +------ +#### [ Python ] ++ Python >= 3\.6 + ------ #### [ Java ] + Maven 3\.5\.4 and Java 8 + Set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine ------ -#### [ C\# ] +#### [ C♯ ] \.NET standard 2\.0 compatible implementation: + \.NET Core >= 2\.0 + \.NET Framework >= 4\.6\.1 + Mono >= 5\.4 ------- -#### [ Python ] -+ Python >= 3\.6 - ------ ## Installing the AWS CDK @@ -76,28 +76,28 @@ npx npm-check-updates -u ``` ------ -#### [ Java ] +#### [ Python ] ``` -mvn versions:use-latest-versions +pip install --upgrade aws-cdk.core ``` +You might have to issue this command multiple times to update all dependencies\. + ------ -#### [ C\# ] +#### [ Java ] ``` -nuget update +mvn versions:use-latest-versions ``` ------ -#### [ Python ] +#### [ C♯ ] ``` -pip install --upgrade aws-cdk.cdk +nuget update ``` -You might have to call this multiple times to update all dependencies\. - ------ ## Using the env Property to Specify Account and Region @@ -228,16 +228,22 @@ cd hello-cdk ### Initializing the App -Initialize an app, where *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), **python** \(Python\), or **typescript** \(TypeScript\) and *TEMPLATE* is an optional template that creates an app with different resources than the default app that cdk init creates for the language\. +To initialize your new AWS CDK app, you use the `cdk init` command\. ``` cdk init --language LANGUAGE [TEMPLATE] ``` -The following table describes the templates provided by the supported languages\. +Where: ++ *LANGUAGE* is one of the supported programming languages: **csharp** \(C♯\), **java** \(Java\), **javascript** \(JavaScript\), **python** \(Python\), or **typescript** \(TypeScript\) ++ *TEMPLATE* is an optional template\. If the desired template is *app*, the default, you may omit it\. + +The following table describes the templates available with the supported languages\. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) +For Hello World, you can just use the default template\. + ------ #### [ TypeScript ] @@ -252,6 +258,40 @@ cdk init --language typescript cdk init --language javascript ``` +------ +#### [ Python ] + +``` +cdk init --language python +``` + +Once the init command finishes, your prompt should show **\(\.env\)**, indicating you are running under virtualenv\. If not, you must perform one or two more tasks, depending upon your operating system\. + +On Linux/MacOS: + +``` +python3 -m venv .env +source .env/bin/activate +``` + +On Windows: + +``` +.env\Scripts\activate.bat +``` + +Once you've got your virtualenv running, run the following command to install the required dependencies\. + +``` +pip install -r requirements.txt +``` + +Change the instantiation of **HelloCdkStack** in `app.py` to the following\. + +``` +HelloCdkStack(app, "HelloCdkStack") +``` + ------ #### [ Java ] @@ -268,7 +308,7 @@ Once the init command finishes, we need to modify the template's output\. ``` ------ -#### [ C\# ] +#### [ C♯ ] ``` cdk init --language csharp @@ -289,40 +329,6 @@ Once the init command finishes, we need to modify the template's output\. ``` + Delete everything from the constructor\. ------- -#### [ Python ] - -``` -cdk init --language python -``` - -Once the init command finishes, your prompt should show **\(\.env\)**, indicating you are running under virtualenv\. If not, you must perform one or two more tasks, depending upon your operating system\. - -On Linux/MacOS: - -``` -python3 -m venv .env -source .env/bin/activate -``` - -On Windows: - -``` -.env\Scripts\activate.bat -``` - -Once you've got your virtualenv running, run the following command to install the required dependencies\. - -``` -pip install -r requirements.txt -``` - -Change the instantiation of **HelloCdkStack** in `app.py` to the following\. - -``` -HelloCdkStack(app, "HelloCdkStack") -``` - ------ ### Compiling the App @@ -341,6 +347,11 @@ npm run build Nothing to compile\. +------ +#### [ Python ] + +Nothing to compile\. + ------ #### [ Java ] @@ -349,17 +360,12 @@ mvn compile ``` ------ -#### [ C\# ] +#### [ C♯ ] ``` dotnet build src ``` ------- -#### [ Python ] - -Nothing to compile\. - ------ **Note** @@ -403,6 +409,15 @@ npm install @aws-cdk/aws-s3 npm install @aws-cdk/aws-s3 ``` +------ +#### [ Python ] + +``` +pip install aws-cdk.aws-s3 +``` + +You might have to execute this command multiple times to resolve dependencies\. + ------ #### [ Java ] @@ -417,7 +432,7 @@ If necessary, add the following to `pom.xml`, where *CDK\-VERSION* is the versio ``` ------ -#### [ C\# ] +#### [ C♯ ] Run the following command in the `src/HelloCdk` directory\. @@ -425,15 +440,6 @@ Run the following command in the `src/HelloCdk` directory\. dotnet add package Amazon.CDK.AWS.S3 ``` ------- -#### [ Python ] - -``` -pip install aws-cdk.aws-s3 -``` - -You might have to execute this command multiple times to resolve dependencies\. - ------ Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represented by the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) class\. @@ -480,6 +486,26 @@ class HelloCdkStack extends cdk.Stack { module.exports = { HelloCdkStack } ``` +------ +#### [ Python ] + +Replace the first import statement in `hello_cdk_stack.py` in the `hello_cdk` directory with the following code\. + +``` +from aws_cdk import ( + aws_s3 as s3, + core +) +``` + +Replace the comment with the following code\. + +``` +bucket = s3.Bucket(self, + "MyFirstBucket", + versioned=True,) +``` + ------ #### [ Java ] @@ -510,7 +536,7 @@ public class HelloStack extends Stack { ``` ------ -#### [ C\# ] +#### [ C♯ ] Update `HelloStack.cs` to include a Amazon S3 bucket with versioning enabled\. @@ -533,26 +559,6 @@ namespace HelloCdk } ``` ------- -#### [ Python ] - -Replace the first import statement in `hello_cdk_stack.py` in the `hello_cdk` directory with the following code\. - -``` -from aws_cdk import ( - aws_s3 as s3, - core -) -``` - -Replace the comment with the following code\. - -``` -bucket = s3.Bucket(self, - "MyFirstBucket", - versioned=True,) -``` - ------ Notice a few things: @@ -574,6 +580,11 @@ npm run build Nothing to compile\. +------ +#### [ Python ] + +Nothing to compile\. + ------ #### [ Java ] @@ -582,17 +593,12 @@ mvn compile ``` ------ -#### [ C\# ] +#### [ C♯ ] ``` dotnet build src ``` ------- -#### [ Python ] - -Nothing to compile\. - ------ ### Synthesizing an AWS CloudFormation Template @@ -666,6 +672,16 @@ new s3.Bucket(this, 'MyFirstBucket', { }); ``` +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, + "MyFirstBucket", + versioned=True, + encryption=s3.BucketEncryption.KMS_MANAGED,) +``` + ------ #### [ Java ] @@ -683,7 +699,7 @@ new Bucket(this, "MyFirstBucket", BucketProps.builder() ``` ------ -#### [ C\# ] +#### [ C♯ ] Update `HelloStack.cs`\. @@ -695,16 +711,6 @@ new Bucket(this, "MyFirstBucket", new BucketProps }); ``` ------- -#### [ Python ] - -``` -bucket = s3.Bucket(self, - "MyFirstBucket", - versioned=True, - encryption=s3.BucketEncryption.KMS_MANAGED,) -``` - ------ Compile your program, as follows\. @@ -721,6 +727,11 @@ npm run build Nothing to compile\. +------ +#### [ Python ] + +Nothing to compile\. + ------ #### [ Java ] @@ -729,17 +740,12 @@ mvn compile ``` ------ -#### [ C\# ] +#### [ C♯ ] ``` dotnet build src ``` ------- -#### [ Python ] - -Nothing to compile\. - ------ ### Preparing for Deployment diff --git a/doc_source/home.md b/doc_source/home.md index 99ecd5e2..ef515d1d 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -8,7 +8,7 @@ AWS CloudFormation enables you to: + Build highly reliable, highly scalable, cost\-effective applications in the cloud without worrying about creating and configuring the underlying AWS infrastructure\. + Use a template file to create and delete a collection of resources together as a single unit \(a stack\)\. -Use the AWS CDK to define your cloud resources in a familiar programming language\. The AWS CDK supports TypeScript, JavaScript, and Python\. The AWS CDK also provides Developer Preview support for C\#/\.NET, and Java\. +Use the AWS CDK to define your cloud resources in a familiar programming language\. The AWS CDK supports TypeScript, JavaScript, and Python\. The AWS CDK also provides Developer Preview support for C♯/\.NET, and Java\. Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 4b91492f..8d9fa7be 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -1,6 +1,6 @@ # AWS CDK in Other Languages -In some cases the example code in the AWS CDK documentation is available only in TypeScript\. This topic describes how to read TypeScript code and translate it into Python\. This is currently the only other [stable](reference.md#aws_construct_lib_versioning_binding) programming language that the AWS CDK supports \(the AWS CDK supports a developer preview version of Java and C\#/\.NET\)\. See [Hello World Tutorial](getting_started.md#hello_world_tutorial) for an example of creating an AWS CDK app in a supported language\. +In some cases the example code in the AWS CDK documentation is available only in TypeScript\. This topic describes how to read TypeScript code and translate it into Python\. This is currently the only other [stable](reference.md#aws_construct_lib_versioning_binding) programming language that the AWS CDK supports \(the AWS CDK supports a developer preview version of Java and C♯/\.NET\)\. See [Hello World Tutorial](getting_started.md#hello_world_tutorial) for an example of creating an AWS CDK app in a supported language\. ## Importing a Module diff --git a/doc_source/permissions.md b/doc_source/permissions.md index 0d017336..e61c490d 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -1,33 +1,46 @@ # Permissions -The AWS CDK contains an IAM package to help you deal with permissions\. There are a few idioms for managing access and permissions that are implemented uniformly across the entire AWS CDK Construct Library\. +The AWS Construct Library uses a few common, widely\-implemented idioms to manage access and permissions\. The IAM module provides you with the tools you need to use these idioms\. + +## Grants + +Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. + +The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)`\. + +Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other enttites that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. + +Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly \(`bucket.grantRead(lambda)`\) instead of granting access to their role \(`bucket.grantRead(lambda.role)`\)\. ## Roles -The IAM package contains a `Role` construct that enables you to manage IAM **Role** instances\. The following code creates a new **Role**, trusting the Amazon EC2 Service Principal\. +The IAM package contains a `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)` construct that represents IAM roles\. The following code creates a new role, trusting the Amazon EC2 Service Principal\. ``` import iam = require('@aws-cdk/aws-iam'); const role = new iam.Role(this, 'Role', { - assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'), + assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'), // required }); ``` -You can add permissions to a role by calling methods on it, and passing the appropriate `Policy` statement\. The following example adds a `Deny` statement to the role for the actions `ec2:SomeAction` and `s3:AnotherAction` on the resources `bucket` and `otherRole`, under the condition that the authorized service is AWS CodeBuild\. +You can add permissions to a role by calling the role's `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` method, passing in a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. -``` -const policyStatement = new iam.PolicyStatement(PolicyStatementEffect.Deny) // default is Allow + The following example adds a `Deny` policy statement to the role for the actions `ec2:SomeAction` and `s3:AnotherAction` on the resources `bucket` and `otherRole`, under the condition that the authorized service is AWS CodeBuild\. -policyStatement.addResources(bucket.bucketArn, otherRole.roleArn); -policyStatement.addActions('ec2:SomeAction', 's3:AnotherAction'); -policyStatement.addCondition('StringEquals', { - 'ec2:AuthorizedService': 'codebuild.amazonaws.com', -}); - -role.addToPolicy(policyStatement); +``` +role.addToPolicy(new iam.PolicyStatement({ + effect: iam.Effect.DENY, + resources: [bucket.bucketArn, otherRole.roleArn], + actions: ['ec2:SomeAction', 's3:AnotherAction'], + conditions: {StringEquals: { + 'ec2:AuthorizedService': 'codebuild.amazonaws.com', +}}})); ``` +**Note** + In our example above, we've created a new `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` inline with the `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. + If you're using a construct that requires a role to function correctly, you can either pass in an existing role when instantiating the construct object, or let the construct create a new role for you, trusting the appropriate service principal\. The following example uses such a construct: a CodeBuild project\. ``` @@ -38,62 +51,53 @@ import codebuild = require('@aws-cdk/aws-codebuild'); const someRole: iam.IRole | undefined = roleOrUndefined(); const project = new codebuild.Project(this, 'Project', { - // if someRole is undefined, a new role will be created, + // if someRole is undefined, the Project creates a new default role, // trusting the codebuild.amazonaws.com service principal role: someRole, }); ``` -In either case, once the object is created, the role is available as the property role on the construct\. That property is not available on imported resources\. Because of that, the constructs have an `addToRolePolicy` method that does nothing if the construct is an imported resource, and calls the `addToPolicy` method of the `role` property \(passing the policy statement it received as argument\) otherwise, saving you from the trouble of handling the undefined case explicitly in your code\. The following example demonstrates the latter case\. +Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. This property is not available on imported resources, however, so the constructs have an `addToRolePolicy` method that does nothing if the construct is an imported resource, and calls the `addToPolicy` method of the `role` property otherwise, saving you the trouble of handling the undefined case explicitly\. The following example demonstrates: ``` // project is imported into the CDK application const project = codebuild.Project.fromProjectName(this, 'Project', 'ProjectName'); -const policyStatement = new iam.PolicyStatement(); -// set up your policyStatement here using addResources, addActions, addCondition, etc. - -// project.role is undefined, so this method call will have no effect -project.addToRolePolicy(policyStatement); +// project is imported, so project.role is undefined, and this call has no effect +project.addToRolePolicy(new iam.PolicyStatement({ + effect: iam.Effect.ALLOW, // ... and so on defining the policy +})); ``` -## Grants - -Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that bestow a given level of access to another entity\. All those methods start with the prefix **grant**\. For example, Amazon S3 buckets have the methods `grantRead` and `grantReadWrite` to enable read and write access, respectively, from an entity to the bucket without having to know which exact Amazon S3 IAM actions are required to perform read or read/write operations\. - -The first argument to the **grant** methods is always of the type `IGrantable`\. This type represents entities that can be granted permissions\. Those include all constructs in the AWS CDK Construct Library that represent resources with roles, such as CodeBuild projects as shown in the previous example, and IAM objects such as `Role`, `User`, and `Group`\. - ## Resource Policies -A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. In those cases, the construct exposes the `addToResourcePolicy` method, which takes a `PolicyStatement` as its argument, that enables you to modify the policy\. You must specify a `Principal` when dealing with resource policies\. +A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. These constructs have an `addToResourcePolicy` method, which takes a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` as its argument\. Every policy statement added to a resource policy must specify at least one principal\. -In the following example, the Amazon S3 bucket `bucket` grants a role with the `s3:SomeAction` permission to itself\. +In the following example, the [Amazon S3 bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) `bucket` grants a role with the `s3:SomeAction` permission to itself\. ``` -const policyStatement = new iam.PolicyStatement(); - -policyStatement.addAction('s3:SomeAction'); -policyStatement.addResource(bucket.bucketArn); -policyStatement.addPrincipal(role); - -bucket.addToResourcePolicy(policyStatement); -); +bucket.addToResourcePolicy(new iam.PolicyStatement({ + effect: iam.Effect.ALLOW, + actions: ['s3:SomeAction'], + resources: [bucket.bucketArn], + principals: [role] +})); ``` ## Principals The AWS CDK Construct Library supports many types of principals, including: -1. IAM resources, such as `Roles`, `Users`, and `Groups` +1. IAM resources such as `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)` -1. Service principals \(`new iam.ServicePrincipal('service.amazonaws.com')`\) +1. Service principals \(`new iam.[ServicePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ServicePrincipal.html)('service.amazonaws.com')`\) -1. Account principals \(`new iam.AccountPrincipal('0123456789012'))` +1. Account principals \(`new iam.[AccountPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.AccountPrincipal.html)('0123456789012'))` -1. Canonical user principals \(`new iam.CanonicalUserPrincipal('79a59d[...]7ef2be')`\) +1. Canonical user principals \(`new iam.[CanonicalUserPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CanonicalUserPrincipal.html)('79a59d[...]7ef2be')`\) -1. AWS organizations principals \(`new iam.OrganizationPrincipal('org-id')`\) +1. AWS organizations principals \(`new iam.[OrganizationPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.OrganizationPrincipal.html)('org-id')`\) -1. Arbitrary ARN principals \(`new iam.ArnPrincipal(res.arn)`\) +1. Arbitrary ARN principals \(`new iam.[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ArnPrincipal.html)(res.arn)`\) -1. A `CompositePrincipal(principal1, principal2, ...)` if you need your role to trust multiple principals \ No newline at end of file +1. An `iam.[CompositePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CompositePrincipal.html)(principal1, principal2, ...)` to trust multiple principals \ No newline at end of file diff --git a/doc_source/reference.md b/doc_source/reference.md index 4ca9626c..b126c76f 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -35,7 +35,7 @@ Each module in the [API Reference](https://docs.aws.amazon.com/cdk/api/latest) s The module level gives an indication of the stability of the majority of the APIs included in the module, however, individual APIs within the module can be annotated with different stability levels\. -| Stability | TypeScript | JavaScript | Python | C\#/\.NET | Java | +| Stability | TypeScript | JavaScript | Python | C♯/\.NET | Java | | --- |--- |--- |--- |--- |--- | | Experimental | @experimental | @stability Experimental | @experimental | Stability: Experimental | Stability: Experimental | | Stable | @stable | @stability Stable | @stable | Stability: Stable | Stability: Stable | @@ -52,4 +52,4 @@ In addition to modules of the AWS CDK Construct Library, language support is als | JavaScript | Stable | | Python | Stable | | Java | Experimental | -| C\#/\.NET | Experimental | \ No newline at end of file +| C♯/\.NET | Experimental | \ No newline at end of file diff --git a/doc_source/tagging.md b/doc_source/tagging.md index d8df21a5..66834bfe 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -4,6 +4,9 @@ The `Tag` class includes two methods that you can use to create and delete tags: + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props) applies a new tag to a construct and all of its children\. + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props) removes a tag from a construct and any of its children, including tags a child construct may have applied to itself\. +**Note** +Tagging is implemented using [Aspects](aspects.md)\. Aspects are a way to apply an operation \(such as tagging\) to all constructs in a given scope\. + Let's look at a couple of examples\. The following example applies the tag **key** with the value **value** to `myConstruct`\. ``` @@ -79,7 +82,7 @@ Use this property to specify the priority of this operation with respect to othe The following example adds the tag key **StackType** with value **TheBest** to any resource created within the Stack named `MarketingSystem`\. Then it removes it again from all resources except Amazon EC2 VPC subnets\. The result is that only the subnets have the tag applied\. ``` -import { App, Stack, Tag } from '@aws-cdk/core'; +import { App, Stack, Tag } from require('@aws-cdk/core'); const app = new App(); const theBestStack = new Stack(app, 'MarketingSystem'); @@ -97,5 +100,5 @@ Tag.remove(theBestStack, 'StackType', { The following code achieves the same result\. Consider which approach \(inclusion or exclusion\) makes your intent clearer\. ``` - Tag.add(theBestStack, 'StackType', 'TheBest', { includeResourceTypes: [‘AWS::EC2::Subnet’]}); -``` + Tag.add(theBestStack, 'StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet']}); +``` \ No newline at end of file From 862ee5dd715fcdcb3f79a72c0133129cdda78626 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 15 Aug 2019 20:54:22 +0000 Subject: [PATCH 047/655] Update Markdown files from latest Developer Guide --- doc_source/permissions.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/doc_source/permissions.md b/doc_source/permissions.md index e61c490d..e07389f3 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -4,17 +4,17 @@ The AWS Construct Library uses a few common, widely\-implemented idioms to manag ## Grants -Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. +Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with with **grant**\. For example, Amazon S3 buckets have the methods [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern) and [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. -The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)`\. +The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html), [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html), and [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)\. Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other enttites that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. -Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly \(`bucket.grantRead(lambda)`\) instead of granting access to their role \(`bucket.grantRead(lambda.role)`\)\. +Resources that use execution roles, such as [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html), also implement `IGrantable`, so you can grant them access directly \(`bucket.grantRead(lambda)`\) instead of granting access to their role \(`bucket.grantRead(lambda.role)`\)\. ## Roles -The IAM package contains a `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)` construct that represents IAM roles\. The following code creates a new role, trusting the Amazon EC2 Service Principal\. +The IAM package contains a [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html) construct that represents IAM roles\. The following code creates a new role, trusting the Amazon EC2 Service Principal\. ``` import iam = require('@aws-cdk/aws-iam'); @@ -24,7 +24,7 @@ const role = new iam.Role(this, 'Role', { }); ``` -You can add permissions to a role by calling the role's `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` method, passing in a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. +You can add permissions to a role by calling the role's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.htm#add-to-policystatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.htm#add-to-policystatement) method, passing in a [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. The following example adds a `Deny` policy statement to the role for the actions `ec2:SomeAction` and `s3:AnotherAction` on the resources `bucket` and `otherRole`, under the condition that the authorized service is AWS CodeBuild\. @@ -39,7 +39,7 @@ role.addToPolicy(new iam.PolicyStatement({ ``` **Note** - In our example above, we've created a new `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` inline with the `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. + In our example above, we've created a new [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) inline with the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement) call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. If you're using a construct that requires a role to function correctly, you can either pass in an existing role when instantiating the construct object, or let the construct create a new role for you, trusting the appropriate service principal\. The following example uses such a construct: a CodeBuild project\. @@ -71,7 +71,7 @@ project.addToRolePolicy(new iam.PolicyStatement({ ## Resource Policies -A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. These constructs have an `addToResourcePolicy` method, which takes a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` as its argument\. Every policy statement added to a resource policy must specify at least one principal\. +A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. These constructs have an `addToResourcePolicy` method, which takes a [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) as its argument\. Every policy statement added to a resource policy must specify at least one principal\. In the following example, the [Amazon S3 bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) `bucket` grants a role with the `s3:SomeAction` permission to itself\. @@ -88,7 +88,7 @@ bucket.addToResourcePolicy(new iam.PolicyStatement({ The AWS CDK Construct Library supports many types of principals, including: -1. IAM resources such as `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)` +1. IAM resources such as [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html), [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html), and [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html) 1. Service principals \(`new iam.[ServicePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ServicePrincipal.html)('service.amazonaws.com')`\) From 13b73f8edc24ca10d063707595cef5b740006c81 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 15 Aug 2019 21:01:46 +0000 Subject: [PATCH 048/655] Update Markdown files from latest Developer Guide - 08/15/19 --- doc_source/permissions.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/doc_source/permissions.md b/doc_source/permissions.md index e07389f3..18f0baa2 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -4,17 +4,17 @@ The AWS Construct Library uses a few common, widely\-implemented idioms to manag ## Grants -Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with with **grant**\. For example, Amazon S3 buckets have the methods [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern) and [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. +Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. -The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html), [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html), and [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)\. +The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)`\. Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other enttites that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. -Resources that use execution roles, such as [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html), also implement `IGrantable`, so you can grant them access directly \(`bucket.grantRead(lambda)`\) instead of granting access to their role \(`bucket.grantRead(lambda.role)`\)\. +Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly \(`bucket.grantRead(lambda)`\) instead of granting access to their role \(`bucket.grantRead(lambda.role)`\)\. ## Roles -The IAM package contains a [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html) construct that represents IAM roles\. The following code creates a new role, trusting the Amazon EC2 Service Principal\. +The IAM package contains a `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)` construct that represents IAM roles\. The following code creates a new role, trusting the Amazon EC2 Service Principal\. ``` import iam = require('@aws-cdk/aws-iam'); @@ -24,7 +24,7 @@ const role = new iam.Role(this, 'Role', { }); ``` -You can add permissions to a role by calling the role's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.htm#add-to-policystatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.htm#add-to-policystatement) method, passing in a [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. +You can add permissions to a role by calling the role's `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.htm#add-to-policystatement)` method, passing in a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. The following example adds a `Deny` policy statement to the role for the actions `ec2:SomeAction` and `s3:AnotherAction` on the resources `bucket` and `otherRole`, under the condition that the authorized service is AWS CodeBuild\. @@ -39,7 +39,7 @@ role.addToPolicy(new iam.PolicyStatement({ ``` **Note** - In our example above, we've created a new [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) inline with the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement) call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. + In our example above, we've created a new `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` inline with the `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. If you're using a construct that requires a role to function correctly, you can either pass in an existing role when instantiating the construct object, or let the construct create a new role for you, trusting the appropriate service principal\. The following example uses such a construct: a CodeBuild project\. @@ -71,7 +71,7 @@ project.addToRolePolicy(new iam.PolicyStatement({ ## Resource Policies -A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. These constructs have an `addToResourcePolicy` method, which takes a [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) as its argument\. Every policy statement added to a resource policy must specify at least one principal\. +A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. These constructs have an `addToResourcePolicy` method, which takes a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` as its argument\. Every policy statement added to a resource policy must specify at least one principal\. In the following example, the [Amazon S3 bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) `bucket` grants a role with the `s3:SomeAction` permission to itself\. @@ -88,7 +88,7 @@ bucket.addToResourcePolicy(new iam.PolicyStatement({ The AWS CDK Construct Library supports many types of principals, including: -1. IAM resources such as [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html), [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html), and [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html) +1. IAM resources such as `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)` 1. Service principals \(`new iam.[ServicePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ServicePrincipal.html)('service.amazonaws.com')`\) From 7380d23ec5d9889280d20675b3232cdc14a81915 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Aug 2019 21:40:58 +0000 Subject: [PATCH 049/655] Update Markdown files from latest Developer Guide - 08/19/19 --- doc_source/constructs.md | 2 +- doc_source/getting_started.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index d27474b1..57121143 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -182,6 +182,6 @@ Now, consumers can subscribe to the topic, for example: ``` const queue = new sqs.Queue(this, 'NewImagesQueue'); -const images = new NotificationBucket(this, 'Images'); +const images = new NotifyingBucket(this, 'Images'); images.topic.addSubscription(new sns_sub.QueueSubscription(queue)); ``` \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 82fa3389..1a76b127 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -105,7 +105,7 @@ nuget update You can use the `env` property on a stack to specify the account and region used when deploying a stack, as shown in the following example, where *REGION* is the region and *ACCOUNT* is the account ID\. ``` -new MyStack(app, { +new MyStack(app, 'MyStack', { env: { region: 'REGION', account: 'ACCOUNT' From 454c275e5862956b4bad354f848ea7129018044d Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Wed, 21 Aug 2019 04:50:05 +0000 Subject: [PATCH 050/655] fix example code --- doc_source/stacks.md | 52 +++++++++++++++++++++++++++++++------------- 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/doc_source/stacks.md b/doc_source/stacks.md index a7255c36..eccfb0ee 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -14,7 +14,7 @@ const app = new App(); new MyFirstStack(app, 'stack1'); new MySecondStack(app, 'stack2'); -app.run(); +app.synth(); ``` To list all the stacks in an AWS CDK app, run the cdk ls command, which for the previous AWS CDK app would have the following output\. @@ -40,26 +40,48 @@ The AWS CDK provides as much resolution as possible during synthesis time to ena Like any other construct, stacks can be composed together into groups\. The following pseudocode shows an example of a service that consists of three stacks: a control plane, a data plane, and monitoring stacks\. The service construct is defined twice: once for the beta environment and once for the production environment\. ``` -class ControlPlane extends Stack { ... } -class DataPlane extends Stack { ... } -class Monitoring extends Stack { ... } - -class MyService extends Construct { - constructor(...) { - new ControlPlane(this, ...); - new DataPlane(this, ...); - new Monitoring(this, ...); +import cdk = require("@aws-cdk/core"); +import { Construct, Stack } from "@aws-cdk/core"; + +interface EnvProps { + prod: boolean; +} +class ControlPlane extends Stack {} +class Dataplane extends Stack {} +class Monitoring extends Stack {} + +class MyService extends cdk.Construct { + constructor(scop: Construct, id: string, props?: EnvProps) { + super(scop, id); + + new ControlPlane(this, "cp", {}); + new Dataplane(this, "data", {}); + new Monitoring(this, "mon", {}); } } -const app = new App(); -new MyService(app, 'beta'); -new MyService(app, 'prod', { prod: true }); -app.run(); +const app = new cdk.App(); +new MyService(app, "beta"); +new MyService(app, "prod", { prod: true }); + +app.synth(); ``` This AWS CDK app eventually consists of six stacks, three for each environment\. +``` +cdk ls +``` + +``` +betacpDA8372D3 +betadataE23DB2BA +betamon632BD457 +prodcp187264CE +proddataF7378CE5 +prodmon631A1083 +``` + The physical names of the AWS CloudFormation stacks are automatically determined by the AWS CDK based on the stack's construct path in the tree\. By default, a stack's name is derived from the construct ID of the `Stack` object, but you can specify an explicit name using the `stackName` prop, as follows\. ``` @@ -79,4 +101,4 @@ The [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack + `stack.availabilityZones` – Returns the set of Availability Zones available in the environment in which this stack is deployed\. For environment\-agnostic stacks, this always returns an array with two Availability Zones, but for environment\-specific stacks, the AWS CDK queries the environment and returns the exact set of Availability Zones that are available\. + `stack.parseArn(arn)` and `stack.formatArn(comps)` – Can be used to work with Amazon Resource Names \(ARNs\)\. + `stack.toJsonString(obj)` – Can be used to format an arbitrary object as a JSON string that can be embedded in an AWS CloudFormation template\. The object can include tokens, attributes, and references, which are only resolved during deployment\. -+ `stack.templateOptions` – Enables you to specify AWS CloudFormation template options, such as Transform, `Description`, and Metadata, for your stack\. \ No newline at end of file ++ `stack.templateOptions` – Enables you to specify AWS CloudFormation template options, such as Transform, `Description`, and Metadata, for your stack\. From e7e5981be31cce847a85498f5280a699e0b5b4a4 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Aug 2019 16:28:14 +0000 Subject: [PATCH 051/655] Update Markdown files from latest Developer Guide - 08/21/19 --- doc_source/codepipeline_example.md | 19 +++++++++++++++++-- doc_source/tools.md | 2 +- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index efde4d2c..a73fbba5 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -6,6 +6,16 @@ The AWS CDK enables you to easily create applications running in the AWS Cloud\. The following example shows how to deploy an AWS Lambda function in a pipeline\. In this example, your AWS CDK code and your Lambda code are in the same repository\. The Lambda code is in the `Lambda` directory, while your CDK code is in the `bin` and `lib` directories that the `cdk init` command sets up for your CDK code\. +**Note** +If you are setting up a new project using `cdk init` for the sake of trying this example, be sure to name your project folder `pipeline`\. For example: + +``` +mkdir pipeline +cd pipeline +cdk init --language=typescript +``` +The `cdk init` command uses a template that creates classes and files based on your project name, and some of the instructions in this example rely on these names\. + ## Lambda Stack The first step is to create the file `lambda-stack.ts` in which we define the class `LambdaStack`\. This class defines the AWS CloudFormation stack for the Lambda function\. This is the stack that is deployed in our pipeline\. @@ -198,7 +208,12 @@ export class PipelineStack extends Stack { ## Main Program -Finally, we have our main AWS CDK entry point file, `pipeline.ts`, in the `bin` directory\. It's simple: it first instantiates the `LambdaStack` class as `LambdaStack`, which is what the AWS CDK build in the pipeline expects\. Then it instantiates the `PipelineStack` class, passing the required Lambda code from the `LambdaStack` object\. +Finally, we have our main AWS CDK entry point file, `pipeline.ts`, in the `bin` directory\. + +**Note** +This file may have a different name\. Check your `package.json` file if you're not sure which file is your main entry point\. + +This code is straightforward: it first instantiates the `LambdaStack` class as `LambdaStack`, which is what the AWS CDK build in the pipeline expects\. Then it instantiates the `PipelineStack` class, passing the required Lambda code from the `LambdaStack` object\. ``` #!/usr/bin/env node @@ -230,7 +245,7 @@ npm run build Use the following command to deploy the pipeline stack\. ``` -npm run cdk deploy PipelineDeployingLambdaStack +cdk deploy PipelineDeployingLambdaStack ``` The name, **PipelineDeployingLambdaStack**, is the name we used when we instantiated `PipelineStack` in `pipeline.ts`\. diff --git a/doc_source/tools.md b/doc_source/tools.md index 80e0699c..f1790efd 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -189,7 +189,7 @@ This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda fu ``` new lambda.Function(this, 'MyFunction', { - runtime: lambda.Runtime.Python37, + runtime: lambda.Runtime.PYTHON_3_7, handler: 'app.lambda_handler', code: lambda.Code.asset('./my_function'), }); From 119deabbf6949d1352b33f6cb72d52a56d12fd78 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 4 Sep 2019 18:10:49 +0000 Subject: [PATCH 052/655] Update Markdown files from latest Developer Guide - 09/04/19 --- doc_source/getting_started.md | 2 +- doc_source/serverless_example.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 1a76b127..2514e360 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -9,7 +9,7 @@ Want to dig deeper? Try the [CDK Workshop](https://cdkworkshop.com/) for a more **AWS CDK command line tools** + [Node\.js \(>= 8\.11\.x\)](https://nodejs.org/en/download) -+ You must specify both your credentials and an AWS Region to use the AWS CDK CLI;, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. ++ You must specify both your credentials and an AWS Region to use the AWS CDK CLI, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. **Note** Why do you need Node\.js when you're a Python, C♯, or Java developer? The AWS CDK is developed in TypeScript and transpiled to JavaScript\. Bindings for the other supported languages make use of the AWS CDK engine running on Node\.js, as does the `cdk` command\-line tool\. diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index e1678a4f..f8184748 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -188,7 +188,7 @@ cdk synth ## Deploy and Test the App -Before you can deploy your first AWS CDK app, you must bootstrap your deployment\. This creates some AWS infrastructure that the AWS CDK needs\. For details, see the **bootstrap** section of the [AWS CDK Tools](tools.md)\(if you've already bootstrapped a AWS CDK app, you'll get a warning and nothing will change\)\. +Before you can deploy your first AWS CDK app, you must bootstrap your deployment\. This creates some AWS infrastructure that the AWS CDK needs\. For details, see the **bootstrap** section of the [AWS CDK Tools](tools.md) \(if you've already bootstrapped a AWS CDK app, you'll get a warning and nothing will change\)\. ``` cdk bootstrap From 8ff596443ef95193d7a07c6a0dcf68bc58a0f4ab Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 5 Sep 2019 20:56:38 +0000 Subject: [PATCH 053/655] Update Markdown files from latest Developer Guide - 09/05/19 --- doc_source/context.md | 8 ++++---- doc_source/stacks.md | 20 ++++++++++---------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/doc_source/context.md b/doc_source/context.md index 2abe28c8..4e56f2bd 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -43,17 +43,17 @@ Use the cdk context command to view and manage the information in your `cdk.cont Context found in cdk.json: ┌───────────────────────────────────────────────────────────────────────────| -│ # | Key │ Value | +│ # | Key │ Value | ├───────────────────────────────────────────────────────────────────────────| -│ 1 | availability-zones:account=123456789012:region=eu-central-1 │ [ "eu-central-1a", "eu-central-1b", "eu-central-1c" ] | +│ 1 | availability-zones:account=123456789012:region=eu-central-1 │ [ "eu-central-1a", "eu-central-1b", "eu-central-1c" ] | ├───────────────────────────────────────────────────────────────────────────| -│ 2 | availability-zones:account=123456789012:region=eu-west-1 │ [ "eu-west-1a", "eu-west-1b", "eu-west-1c" ] | +│ 2 | availability-zones:account=123456789012:region=eu-west-1 │ [ "eu-west-1a", "eu-west-1b", "eu-west-1c" ] | └───────────────────────────────────────────────────────────────────────────| Run cdk context --reset KEY_OR_NUMBER to remove a context key. It will be refreshed on the next CDK synthesis run. ``` -To remove a context value, run cdk context \-\-reset, specifying the value's corresponding key number\. The following example removes the value that corresponds to the key value of `2` in the preceding example, which is the Amazon Linux AMI ID\. +To remove a context value, run cdk context \-\-reset, specifying the value's corresponding key number\. The following example removes the value that corresponds to the key value of `2` in the preceding example, which is the list of availability zones in the Ireland region\. ``` $ cdk context --reset 2 diff --git a/doc_source/stacks.md b/doc_source/stacks.md index eccfb0ee..c0ab4afd 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -46,18 +46,20 @@ import { Construct, Stack } from "@aws-cdk/core"; interface EnvProps { prod: boolean; } + class ControlPlane extends Stack {} class Dataplane extends Stack {} class Monitoring extends Stack {} class MyService extends cdk.Construct { - constructor(scop: Construct, id: string, props?: EnvProps) { - super(scop, id); + constructor(scope: Construct, id: string, props?: EnvProps) { + + super(scope, id); + new ControlPlane(this, "cp", {}); new Dataplane(this, "data", {}); - new Monitoring(this, "mon", {}); - } + new Monitoring(this, "mon", {}); } } const app = new cdk.App(); @@ -67,13 +69,11 @@ new MyService(app, "prod", { prod: true }); app.synth(); ``` -This AWS CDK app eventually consists of six stacks, three for each environment\. - -``` -cdk ls -``` +This AWS CDK app eventually consists of six stacks, three for each environment: ``` +$ cdk ls + betacpDA8372D3 betadataE23DB2BA betamon632BD457 @@ -101,4 +101,4 @@ The [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack + `stack.availabilityZones` – Returns the set of Availability Zones available in the environment in which this stack is deployed\. For environment\-agnostic stacks, this always returns an array with two Availability Zones, but for environment\-specific stacks, the AWS CDK queries the environment and returns the exact set of Availability Zones that are available\. + `stack.parseArn(arn)` and `stack.formatArn(comps)` – Can be used to work with Amazon Resource Names \(ARNs\)\. + `stack.toJsonString(obj)` – Can be used to format an arbitrary object as a JSON string that can be embedded in an AWS CloudFormation template\. The object can include tokens, attributes, and references, which are only resolved during deployment\. -+ `stack.templateOptions` – Enables you to specify AWS CloudFormation template options, such as Transform, `Description`, and Metadata, for your stack\. ++ `stack.templateOptions` – Enables you to specify AWS CloudFormation template options, such as Transform, Description, and Metadata, for your stack\. \ No newline at end of file From 6157f05856be9acc6f6b1ff37b323b344e0a2016 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 11 Sep 2019 00:53:48 +0000 Subject: [PATCH 054/655] remove unnecessary new keywords --- doc_source/get_ssm_value.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index a8e80b8a..77b4dbc8 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -14,7 +14,7 @@ To read a particular version of a Systems Manager Parameter Store plain string v ``` import ssm = require('@aws-cdk/aws-ssm'); -const parameterString = new ssm.StringParameter.fromStringParameterAttributes(this, 'MyParameter', { +const parameterString = ssm.StringParameter.fromStringParameterAttributes(this, 'MyParameter', { parameterName: 'my-plain-parameter-name', version: 1, // omit to get latest version }); @@ -27,7 +27,7 @@ To read a particular version of a Systems Manager Parameter Store secure string ``` import ssm = require('@aws-cdk/aws-ssm'); -const secureString = new ssm.StringParameter.fromSecureStringParameterAttributes(this, 'MySecretParameter', { +const secureString = ssm.StringParameter.fromSecureStringParameterAttributes(this, 'MySecretParameter', { parameterName: 'my-secure-parameter-name', version: 1, }); @@ -49,7 +49,7 @@ const versionOfStringToken = ssm.StringParameter.valueForStringParameter( this, 'my-plain-parameter-name', 1); // version 1 // Get specified version of secure string attribute -const secureStringToken = new ssm.StringParameter.valueForSecureStringParameter( +const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` From 19f63c7acf6942709dbd5fb0d8e1eca88c5bb7f3 Mon Sep 17 00:00:00 2001 From: Raoni Timo de Castro Cambiaghi Date: Wed, 11 Sep 2019 17:27:14 +1000 Subject: [PATCH 055/655] Update ECS Fargate example Updating example to use ApplicationLoadBalancedFargateService instead of LoadBalancedFargateService as it's deprecated --- doc_source/ecs_example.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 1845b11b..6ca40387 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -90,7 +90,7 @@ Replace the comment at the end of the constructor with the following code\. }); // Create a load-balanced Fargate service and make it public - new ecs_patterns.LoadBalancedFargateService(this, "MyFargateService", { + new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { cluster: cluster, // Required cpu: 512, // Default is 256 desiredCount: 6, // Default is 1 @@ -117,4 +117,4 @@ cdk deploy AWS CloudFormation displays information about the dozens of steps that it takes as it deploys your app\. -That's how easy it is to create a Fargate service to run a Docker image\. \ No newline at end of file +That's how easy it is to create a Fargate service to run a Docker image\. From 3f3836b9fc4edff417992b3da9da7150d5d73765 Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Thu, 12 Sep 2019 05:52:43 +0000 Subject: [PATCH 056/655] Fix and add example code Context --- doc_source/context.md | 103 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 84 insertions(+), 19 deletions(-) diff --git a/doc_source/context.md b/doc_source/context.md index 4e56f2bd..db213d18 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -5,9 +5,10 @@ The AWS CDK uses context to retrieve information such as the Availability Zones ## Construct Context You can provide context values in three different ways: -+ Automatically by the AWS CDK CLI after required information, such as the list of Availability Zones, is looked up from the current AWS account\. -+ Provided by the user through the CLI using the \-\-context option, or in the `context` key of the `cdk.json` file\. -+ Set in code using the `construct.node.setContext` method\. + +- Automatically by the AWS CDK CLI after required information, such as the list of Availability Zones, is looked up from the current AWS account\. +- Provided by the user through the CLI using the \-\-context option, or in the `context` key of the `cdk.json` file\. +- Set in code using the `construct.node.setContext` method\. Context entries are scoped to the construct that created them: they are visible to children constructs, but not to siblings\. Context entries that are set by the CLI, either automatically or from the \-\-context option, are implicitly set on the `App` construct, and are visible to the app\. @@ -19,16 +20,16 @@ The AWS CDK supports several context methods that enable AWS CDK apps to get con The following are the context methods: -[HostedZone\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-route53.HostedZone.html#static-from-lookupscope-id-query) +[HostedZone\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-route53.HostedZone.html#static-from-wbr-lookupscope-id-query) Gets the hosted zones in your account\. -[stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) +[stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-route53.HostedZone.html#static-from-wbr-lookupscope-id-query) Gets the supported Availability Zones\. -StringParameter\.valueFromLookup +[StringParameter\.valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) Gets a value from the current Region's AWS Systems Manager Parameter Store\. -Vpc\.fromLookup +[Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options) Gets the existing VPCs in your accounts\. If a given context information isn't available, the AWS CDK app notifies the AWS CDK CLI that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. @@ -41,14 +42,14 @@ Use the cdk context command to view and manage the information in your `cdk.cont ``` Context found in cdk.json: - -┌───────────────────────────────────────────────────────────────────────────| -│ # | Key │ Value | -├───────────────────────────────────────────────────────────────────────────| -│ 1 | availability-zones:account=123456789012:region=eu-central-1 │ [ "eu-central-1a", "eu-central-1b", "eu-central-1c" ] | -├───────────────────────────────────────────────────────────────────────────| -│ 2 | availability-zones:account=123456789012:region=eu-west-1 │ [ "eu-west-1a", "eu-west-1b", "eu-west-1c" ] | -└───────────────────────────────────────────────────────────────────────────| + +┌───┬─────────────────────────────────────────────────────────────┬──────────────────────────────────────────────────────────────┐ +│ # | Key │ Value │ +├───┼─────────────────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────│ +│ 1 | availability-zones:account=123456789012:region=eu-central-1 │ [ "eu-central-1a", "eu-central-1b", "eu-central-1c" ] │ +├───┼─────────────────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────│ +│ 2 | availability-zones:account=123456789012:region=eu-west-1 │ [ "eu-west-1a", "eu-west-1b", "eu-west-1c" ] │ +└───┴─────────────────────────────────────────────────────────────┴──────────────────────────────────────────────────────────────┘ Run cdk context --reset KEY_OR_NUMBER to remove a context key. It will be refreshed on the next CDK synthesis run. ``` @@ -71,12 +72,76 @@ Therefore, if you want to update to the latest version of the Amazon Linux AMI, cdk synth ``` +To clear all of the stored context values for your app, run cdk context \-\-clear, as follows\. + ``` -... +cdk context --clear ``` -To clear all of the stored context values for your app, run cdk context \-\-clear, as follows\. +The following is an example of importing an existing vpc using cdk context. ``` -cdk context --clear -``` \ No newline at end of file +import cdk = require('@aws-cdk/core'); +import ec2 = require('@aws-cdk/aws-ec2'); + +export class ExistsvpcStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const vpcid = this.node.tryGetContext('vpcid'); + + const vpc = ec2.Vpc.fromLookup(this, 'VPC', { + vpcId: vpcid, + }); + + const pubsubnets = vpc.selectSubnets({subnetType: ec2.SubnetType.PUBLIC}); + + new cdk.CfnOutput(this, 'publicsubnets', { + value: pubsubnets.subnetIds.toString(), + }); + } +} +``` + +``` +$ cdk diff -c vpcid=vpc-0cb9c31031d0d3e22 +Stack ExistsvpcStack +Outputs +[+] Output publicsubnets publicsubnets: {"Value":"subnet-06e0ea7dd302d3e8f,subnet-01fc0acfb58f3128f"} +``` + +``` +$ cdk context -j + +{ + "vpc-provider:account=123456789012:filter.vpc-id=vpc-0cb9c31031d0d3e22:region=us-east-1": { + "vpcId": "vpc-0cb9c31031d0d3e22", + "availabilityZones": [ + "us-east-1a", + "us-east-1b" + ], + "privateSubnetIds": [ + "subnet-03ecfc033225be285", + "subnet-0cded5da53180ebfa" + ], + "privateSubnetNames": [ + "Private" + ], + "privateSubnetRouteTableIds": [ + "rtb-0e955393ced0ada04", + "rtb-05602e7b9f310e5b0" + ], + "publicSubnetIds": [ + "subnet-06e0ea7dd302d3e8f", + "subnet-01fc0acfb58f3128f" + ], + "publicSubnetNames": [ + "Public" + ], + "publicSubnetRouteTableIds": [ + "rtb-00d1fdfd823c82289", + "rtb-04bb1969b42969bcb" + ] + } +} +``` From 4ff41cdef07b9f6d7c8093fdb5b0a5cd6fb0aa16 Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Thu, 12 Sep 2019 11:13:46 -0700 Subject: [PATCH 057/655] Add link for submitting an issue --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7db61437..40aaf21c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Welcome to the AWS CDK Developer Guide This is the GitHub repository for the [AWS CDK Developer Guide](https://docs.aws.amazon.com/cdk/latest/guide/home.html). -You're welcome to report issues with the documentation here or, if you have a moment, to submit a Pull Request with your +You're welcome to [report issues](https://github.com/awsdocs/aws-cdk-guide/issues/new) with the documentation here or, if you have a moment, to submit a Pull Request with your suggested changes. Issues reported through the Feedback link at the bottom of the individual pages of the AWS CDK Developer Guide go to an internal From d5607b1ff8786bea97e7a4caa8d905db94fd69b5 Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Thu, 12 Sep 2019 11:19:05 -0700 Subject: [PATCH 058/655] Update appearance of Note block --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 40aaf21c..af1b0163 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,7 @@ Issues reported through the Feedback link at the bottom of the individual pages Amazon issue tracker and may not appear here. However, we try to track most substantive AWS CDK Developer Guide work on GitHub so the community can see, comment, and contribute. -> **NOTE** -> +> :memo: **NOTE** - > The Markdown files in this repository are an *output* of the AWS CDK Developer Guide build process, not the actual source files. Periodically, we update the Markdown files here from our builds. This means that changes may appear on docs.aws.amazon.com before they appear here. Also, sometimes we may close a PR instead of merging it, even if we have in fact integrated your submission into the Guide. From baabab0a71e96a217934c6d1c47ce9f0d5c4ee71 Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Fri, 13 Sep 2019 00:10:55 +0000 Subject: [PATCH 059/655] Fix wrong fix link of availabilityZones --- doc_source/context.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/context.md b/doc_source/context.md index db213d18..d5bacc5f 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -23,7 +23,7 @@ The following are the context methods: [HostedZone\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-route53.HostedZone.html#static-from-wbr-lookupscope-id-query) Gets the hosted zones in your account\. -[stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-route53.HostedZone.html#static-from-wbr-lookupscope-id-query) +[stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) Gets the supported Availability Zones\. [StringParameter\.valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) From 2ba3e45bbba5f84e46a083b91b5a5082ad5ac0dc Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Fri, 13 Sep 2019 04:31:07 +0000 Subject: [PATCH 060/655] Fix wrong fix new line --- doc_source/context.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/context.md b/doc_source/context.md index d5bacc5f..069322f2 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -26,7 +26,7 @@ Gets the hosted zones in your account\. [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) Gets the supported Availability Zones\. -[StringParameter\.valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) +[StringParameter\.valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) Gets a value from the current Region's AWS Systems Manager Parameter Store\. [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options) From 656c2f70dae8b41c926fad700ae14f418691cfd0 Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Fri, 13 Sep 2019 04:36:01 +0000 Subject: [PATCH 061/655] Fix prompt string --- doc_source/context.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/context.md b/doc_source/context.md index 069322f2..16c6a4cc 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -69,13 +69,13 @@ reset. It will be refreshed on the next SDK synthesis run. Therefore, if you want to update to the latest version of the Amazon Linux AMI, you can use the preceding example to do a controlled update of the context value and reset it, and then synthesize and deploy your app again\. ``` -cdk synth +$ cdk synth ``` To clear all of the stored context values for your app, run cdk context \-\-clear, as follows\. ``` -cdk context --clear +$ cdk context --clear ``` The following is an example of importing an existing vpc using cdk context. From 432d27db06e98f445f51af99ba7aec5a3683ba6e Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Fri, 13 Sep 2019 06:21:44 +0000 Subject: [PATCH 062/655] Add all options to tools #123 --- doc_source/tools.md | 96 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 87 insertions(+), 9 deletions(-) diff --git a/doc_source/tools.md b/doc_source/tools.md index f1790efd..bcf000bb 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -1,4 +1,4 @@ -# AWS CDK Tools + # AWS CDK Tools This section contains information about AWS CDK tools\. @@ -98,11 +98,87 @@ If your app has a single stack, you don't have to specify the stack name\. If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. +Commands and individual options as follows. + +**cdk list | ls [STACKS..]** +Lists all stacks in the app + +- --long, -l (boolean) + display environment information for each stack + default: false + +**cdk synthesize | synth [STACKS..]** +Synthesizes and prints the CloudFormation template for this stack + +- --exclusively, -e (boolean) + only deploy requested stacks, don\'t include dependencies + +**cdk bootstrap [ENVIRONMENTS..]** +Deploys the CDK toolkit stack into an AWS environment + +- --bootstrap-bucket-name, -b (string) + The name of the CDK toolkit bucket + default: undefined +- --bootstrap-kms-key-id (string) + AWS KMS master key ID used for the SSE-KMS encryption + default: undefined + +**cdk deploy [STACKS..]** +Deploys the stack(s) named STACKS into your AWS account + +- --build-exclude, -E (array) + do not rebuild asset with the given ID. Can be specified multiple times. + default: [] +- --exclusively, -e (boolean) + only deploy requested stacks, don\'t include dependencies +- --require-approval (string) + what security-sensitive changes need manual approval + [Never,AnyChange,Broadening] +- --ci (boolean) + Force CI detection. Use --no-ci to disable CI autodetection. + default: process.env.CI !== undefined +- --tags, -t (array) + tags to add to the stack (KEY=VALUE) + +**cdk destroy [STACKS..]** +Destroy the stack(s) named STACKS + +- --exclusively, -e (boolean) + only deploy requested stacks, don\'t include dependencies +- --force, -f (boolean) + Do not ask for confirmation before destroying the stacks + +**cdk diff [STACKS..]** +Compares the specified stack with the deployed stack or a local template file, and returns with status 1 if any difference is found + +- --exclusively, -e (boolean) + only deploy requested stacks, don\'t include dependencies +- --context-lines (number) + number of context lines to include in arbitrary JSON diff rendering + default: 3 +- --template (string) + the path to the CloudFormation template to compare with +- --strict (boolean) + do not filter out AWS::CDK::Metadata resources + default: false + +**cdk metadata [STACK]** +Returns all metadata associated with this stack + +**cdk init [TEMPLATE]** +Create a new, empty CDK project from a template. Invoked without TEMPLATE, the app template will be used. + +- --language, -l (string) + the language to be used for the new project (default can be configured in ~/.cdk.json) + +- --list (boolean) + list the available templates + ### Bootstrapping your AWS Environment Before you can use the AWS CDK you must bootstrap your AWS environment to create the infrastructure that the AWS CDK CLI needs to deploy your AWS CDK app\. Currently the bootstrap command creates only an Amazon S3 bucket\. -You incur any charges for what the AWS CDK stores in the bucket\. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. +You incur any charges for what the AWS CDK stores in the bucket\. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. ### Security\-Related Changes @@ -114,7 +190,7 @@ You change the level of changes that requires approval by specifying: cdk deploy --require-approval LEVEL ``` -Where *LEVEL* can be one of the following: +Where _LEVEL_ can be one of the following: never Approval is never required\. @@ -152,12 +228,14 @@ CDKMetadata: ### Opting Out from Version Reporting To opt out of version reporting, use one of the following methods: -+ Use the cdk command with the \-\-no\-version\-reporting argument\. + +- Use the cdk command with the \-\-no\-version\-reporting argument\. ``` cdk --no-version-reporting synth ``` -+ Set versionReporting to **false** in `./cdk.json` or `~/cdk.json`\. + +- Set versionReporting to **false** in `./cdk.json` or `~/cdk.json`\. ``` { @@ -215,7 +293,7 @@ This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda fu cdk synth --no-staging > template.yaml ``` -1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: +1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`_12345678_, where _12345678_ represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: ``` Type: AWS::Lambda::Function @@ -232,12 +310,12 @@ This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda fu ``` 2019-04-01 12:22:41 Found credentials in shared credentials file: ~/.aws/credentials 2019-04-01 12:22:41 Invoking app.lambda_handler (python3.7) - + Fetching lambci/lambda:python3.7 Docker container image...... 2019-04-01 12:22:43 Mounting D:\cdk-sam-example\.cdk.staging\a57f59883918e662ab3c46b964d2faa5 as /var/task:ro,delegated inside runtime container START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB - + "This is a Lambda Function defined through CDK" - ``` \ No newline at end of file + ``` From a5cd13ad3cc302f05e867033ff262497b626460d Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Tue, 17 Sep 2019 03:03:31 +0000 Subject: [PATCH 063/655] Fix prettier auto format --- doc_source/tools.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/tools.md b/doc_source/tools.md index bcf000bb..62f3ae51 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -1,4 +1,4 @@ - # AWS CDK Tools +# AWS CDK Tools This section contains information about AWS CDK tools\. @@ -190,7 +190,7 @@ You change the level of changes that requires approval by specifying: cdk deploy --require-approval LEVEL ``` -Where _LEVEL_ can be one of the following: +Where *LEVEL* can be one of the following: never Approval is never required\. @@ -293,7 +293,7 @@ This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda fu cdk synth --no-staging > template.yaml ``` -1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`_12345678_, where _12345678_ represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: +1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: ``` Type: AWS::Lambda::Function From 357c8eb5a06975b6ad9f594c368d7097e68f4fd9 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 17 Sep 2019 19:48:30 +0000 Subject: [PATCH 064/655] show correct stack output, update Include to CfnInclude, update LoadBalancedFargateService to ApplicationLoadBalancedFargateService --- doc_source/constructs.md | 2 +- doc_source/ecs_example.md | 6 +++--- doc_source/use_cfn_template.md | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 57121143..e9e6fbbb 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -14,7 +14,7 @@ There are different levels of constructs in this library, beginning with low\-le The next level of constructs also represent AWS resources, but with a higher\-level, intent\-based API\. They provide the same functionality, but handle much of the details, boilerplate, and glue logic required by CFN constructs\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#aws_s3_Bucket) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#aws_s3_Bucket_addLifecycleRule), which adds a lifecycle rule to the bucket\. -Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.LoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs-patterns.LoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing Elastic Load Balancing \(ELB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. +Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs-patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. For more information about how to navigate the library and discover constructs that can help you build your apps, see the [API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html)\. diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 6ca40387..15dc0a9f 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -44,14 +44,14 @@ npm run build cdk synth ``` -You should see a stack like the following, where *CDK\-VERSION* is the version of the CDK\. +You should see a stack like the following, where *CDK\-VERSION* is the version of the CDK and *NODE\-VERSION* is the version of Node\.js\. \(Your output may differ slightly from what's shown here\.\) ``` Resources: CDKMetadata: - Type: 'AWS::CDK::Metadata' + Type: AWS::CDK::Metadata Properties: - Modules: @aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_ecs_construct=0.1.0 + Modules: aws-cdk=CDK-VERSION,@aws-cdk/core=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,jsii-runtime=node.js/NODE-VERSION ``` ## Add the Amazon EC2 and Amazon ECS Packages diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index b3cd9175..8f9386be 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -19,7 +19,7 @@ You can include this bucket in your AWS CDK app, as shown in the following examp import cdk = require("@aws-cdk/core"); import fs = require("fs"); -new cdk.Include(this, "ExistingInfrastructure", { +new cdk.CfnInclude(this, "ExistingInfrastructure", { template: JSON.parse(fs.readFileSync("my-template.json").toString()) }); ``` From c4e4d48e24933f0d377239781e2f4481b760e4e8 Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Wed, 18 Sep 2019 03:00:52 +0000 Subject: [PATCH 065/655] Fix example code of constructs --- doc_source/constructs.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index e9e6fbbb..13725527 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -93,7 +93,7 @@ Most constructs accept `props` as their third initialization argument\. This is ``` new s3.Bucket(this, 'MyEncryptedBucket', { - encryption: s3.BucketEncryption.Kms, + encryption: s3.BucketEncryption.KMS, websiteIndexDocument: 'index.html' }); ``` @@ -119,7 +119,7 @@ const jobsQueue = new sqs.Queue(this, 'jobs'); const createJobLambda = new lambda.Function(this, 'create-job', { runtime: lambda.Runtime.NODEJS_8_10, handler: 'index.handler', - code: lambda.Code.asset('./create-job-lambda-code'), + code: lambda.Code.fromAsset('./create-job-lambda-code'), environment: { QUEUE_URL: jobsQueue.queueUrl } @@ -146,7 +146,7 @@ export class NotifyingBucket extends Construct { super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); const topic = new sns.Topic(this, 'topic'); - bucket.onObjectCreated(topic, { prefix: props.prefix }); + bucket.addObjectCreatedNotification(topic, { prefix: props.prefix }); } } ``` @@ -173,7 +173,7 @@ export class NotifyingBucket extends Construct { super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); this.topic = new sns.Topic(this, 'topic'); - bucket.onObjectCreated(this.topic, { prefix: props.prefix }); + bucket.addObjectCreatedNotification(this.topic, { prefix: props.prefix }); } } ``` @@ -184,4 +184,4 @@ Now, consumers can subscribe to the topic, for example: const queue = new sqs.Queue(this, 'NewImagesQueue'); const images = new NotifyingBucket(this, 'Images'); images.topic.addSubscription(new sns_sub.QueueSubscription(queue)); -``` \ No newline at end of file +``` From 8e418fe643fb52421314a7f0b340462853dcbbb4 Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Thu, 26 Sep 2019 03:23:02 +0000 Subject: [PATCH 066/655] update cli --help output --- doc_source/tools.md | 62 +++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 36 deletions(-) diff --git a/doc_source/tools.md b/doc_source/tools.md index 62f3ae51..6ab0b9db 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -77,14 +77,13 @@ Options: [boolean] [default: true] --role-arn, -r ARN of Role to use when invoking CloudFormation [string] --toolkit-stack-name The name of the CDK toolkit stack [string] - --staging copy assets to the output directory (use --no-staging to + --staging Copy assets to the output directory (use --no-staging to disable, needed for local debugging the source files with SAM CLI) [boolean] [default: true] - --output, -o emits the synthesized cloud assembly into a directory + --output, -o Emits the synthesized cloud assembly into a directory (default: cdk.out) [string] - --ci Force CI detection. Use --no-ci to disable CI - autodetection. [boolean] [default: false] - --tags, -t tags to add to the stack (KEY=VALUE) [array] + --no-color Removes colors and other style from console output + [boolean] [default: false] --version Show version number [boolean] -h, --help Show help [boolean] @@ -100,21 +99,18 @@ If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used a Commands and individual options as follows. -**cdk list | ls [STACKS..]** -Lists all stacks in the app +**cdk list | ls** - --long, -l (boolean) - display environment information for each stack + Display environment information for each stack default: false -**cdk synthesize | synth [STACKS..]** -Synthesizes and prints the CloudFormation template for this stack +**cdk synthesize | synth** - --exclusively, -e (boolean) - only deploy requested stacks, don\'t include dependencies + Only deploy requested stacks, don\'t include dependencies -**cdk bootstrap [ENVIRONMENTS..]** -Deploys the CDK toolkit stack into an AWS environment +**cdk bootstrap** - --bootstrap-bucket-name, -b (string) The name of the CDK toolkit bucket @@ -123,56 +119,50 @@ Deploys the CDK toolkit stack into an AWS environment AWS KMS master key ID used for the SSE-KMS encryption default: undefined -**cdk deploy [STACKS..]** -Deploys the stack(s) named STACKS into your AWS account +**cdk deploy** - --build-exclude, -E (array) - do not rebuild asset with the given ID. Can be specified multiple times. + Do not rebuild asset with the given ID. Can be specified multiple times. default: [] - --exclusively, -e (boolean) - only deploy requested stacks, don\'t include dependencies + Only deploy requested stacks, don\'t include dependencies - --require-approval (string) - what security-sensitive changes need manual approval + What security-sensitive changes need manual approval [Never,AnyChange,Broadening] - --ci (boolean) Force CI detection. Use --no-ci to disable CI autodetection. default: process.env.CI !== undefined - --tags, -t (array) - tags to add to the stack (KEY=VALUE) + Tags to add to the stack (KEY=VALUE) -**cdk destroy [STACKS..]** -Destroy the stack(s) named STACKS +**cdk destroy** - --exclusively, -e (boolean) - only deploy requested stacks, don\'t include dependencies + Only deploy requested stacks, don\'t include dependencies - --force, -f (boolean) Do not ask for confirmation before destroying the stacks -**cdk diff [STACKS..]** -Compares the specified stack with the deployed stack or a local template file, and returns with status 1 if any difference is found +**cdk diff** - --exclusively, -e (boolean) - only deploy requested stacks, don\'t include dependencies + Only deploy requested stacks, don\'t include dependencies - --context-lines (number) - number of context lines to include in arbitrary JSON diff rendering + Number of context lines to include in arbitrary JSON diff rendering default: 3 - --template (string) - the path to the CloudFormation template to compare with + The path to the CloudFormation template to compare with - --strict (boolean) - do not filter out AWS::CDK::Metadata resources + Do not filter out AWS::CDK::Metadata resources default: false -**cdk metadata [STACK]** -Returns all metadata associated with this stack -**cdk init [TEMPLATE]** -Create a new, empty CDK project from a template. Invoked without TEMPLATE, the app template will be used. +**cdk init** - --language, -l (string) - the language to be used for the new project (default can be configured in ~/.cdk.json) + The language to be used for the new project (default can be configured in ~/.cdk.json) - --list (boolean) - list the available templates + List the available templates ### Bootstrapping your AWS Environment @@ -190,7 +180,7 @@ You change the level of changes that requires approval by specifying: cdk deploy --require-approval LEVEL ``` -Where *LEVEL* can be one of the following: +Where _LEVEL_ can be one of the following: never Approval is never required\. @@ -293,7 +283,7 @@ This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda fu cdk synth --no-staging > template.yaml ``` -1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: +1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`_12345678_, where _12345678_ represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: ``` Type: AWS::Lambda::Function From 719ae8de71a9c84fd7febc95d1d583722b6201c6 Mon Sep 17 00:00:00 2001 From: Elad Ben-Israel Date: Thu, 10 Oct 2019 10:02:02 +0300 Subject: [PATCH 067/655] Indicate that process.env needs @types/node See https://github.com/aws/aws-cdk/issues/4372 --- doc_source/environments.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index c023de57..78e4184a 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -27,5 +27,11 @@ new MyDevStack(this, 'dev', { }); ``` +NOTE: In order to refer to use `process.env` in TypeScript, you will need to install the `@types/node` module: + +``` +npm install -D @types/node +``` + **Note** -There is a distinction between not specifying the `env` property at all and specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. This means that constructs that are defined in such a stack cannot make assumptions about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html#aws_ec2_Vpc_fromLookup), which need to query your AWS account\. When specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, you tell the stack that it will be deployed in the account and Region as configured in the CLI at the time of synthesis\. This means that the synthesized template could be different on different machines, users, or sessions\. This might be acceptable for use cases like development stacks, but would be an anti\-pattern for production stacks\. \ No newline at end of file +There is a distinction between not specifying the `env` property at all and specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. This means that constructs that are defined in such a stack cannot make assumptions about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html#aws_ec2_Vpc_fromLookup), which need to query your AWS account\. When specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, you tell the stack that it will be deployed in the account and Region as configured in the CLI at the time of synthesis\. This means that the synthesized template could be different on different machines, users, or sessions\. This might be acceptable for use cases like development stacks, but would be an anti\-pattern for production stacks\. From be8279d8ba19bfa606e76f080d414a21097250e1 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 11 Oct 2019 22:44:30 +0000 Subject: [PATCH 068/655] sync with recent CDK Developer Guide changes --- doc_source/constructs.md | 4 +- doc_source/context.md | 64 +++++--- doc_source/doc-history.md | 5 +- doc_source/ecs_example.md | 2 +- doc_source/environments.md | 8 +- doc_source/get_ssm_value.md | 55 +++---- doc_source/getting_started.md | 22 +-- doc_source/home.md | 6 +- doc_source/multiple_languages.md | 2 +- doc_source/reference.md | 4 +- .../stack_how_to_create_multiple_stacks.md | 152 ++++++++++++++---- 11 files changed, 210 insertions(+), 114 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 13725527..d84904ea 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -146,7 +146,7 @@ export class NotifyingBucket extends Construct { super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); const topic = new sns.Topic(this, 'topic'); - bucket.addObjectCreatedNotification(topic, { prefix: props.prefix }); + bucket.addObjectCreatedNotification(topic, { prefix: props.prefix }); } } ``` @@ -184,4 +184,4 @@ Now, consumers can subscribe to the topic, for example: const queue = new sqs.Queue(this, 'NewImagesQueue'); const images = new NotifyingBucket(this, 'Images'); images.topic.addSubscription(new sns_sub.QueueSubscription(queue)); -``` +``` \ No newline at end of file diff --git a/doc_source/context.md b/doc_source/context.md index 16c6a4cc..726a1f1e 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -1,18 +1,21 @@ # Runtime Context -The AWS CDK uses context to retrieve information such as the Availability Zones in your account or Amazon Machine Image \(AMI\) IDs used to start your instances\. To avoid unexpected changes to your deployments, such as when a new Amazon Linux AMI is released, thus changing your Auto Scaling group, the AWS CDK stores context values in the `cdk.context.json` file within your project\. This ensures that the AWS CDK retrieves the same value the next time it synthesizes your app\. Don't forget to put this file under version control\. +The AWS CDK uses *context* to retrieve information such as the Availability Zones in your account or Amazon Machine Image \(AMI\) IDs used to start your instances\. Context entries are key\-value pairs\. -## Construct Context +To avoid unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, thus changing your Auto Scaling group, the AWS CDK stores context values in the `cdk.context.json` file within your project\. This ensures that the AWS CDK uses the same context values the next time it synthesizes your app\. Don't forget to put this file under version control\. -You can provide context values in three different ways: +## Construct Context -- Automatically by the AWS CDK CLI after required information, such as the list of Availability Zones, is looked up from the current AWS account\. -- Provided by the user through the CLI using the \-\-context option, or in the `context` key of the `cdk.json` file\. -- Set in code using the `construct.node.setContext` method\. +Context values are made available to your AWS CDK app in five different ways: ++ Automatically from the current AWS account\. ++ Through the \-\-context option to the cdk command\. ++ In the `context` key of the project's `cdk.json` file\. ++ In the `context` key of a `~/cdk.json` file\. ++ In code using the `construct.node.setContext` method\. -Context entries are scoped to the construct that created them: they are visible to children constructs, but not to siblings\. Context entries that are set by the CLI, either automatically or from the \-\-context option, are implicitly set on the `App` construct, and are visible to the app\. +Context values are scoped to the construct that created them; they are visible to child constructs, but not to siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), either automatically or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in the app\. -You can get context information using the `construct.node.tryGetContext` method, which returns the value set on the current construct if it is present\. Otherwise, it resolves the context from the current construct's parent, until it has reached the `App` construct\. +You can get a context value using the `construct.node.tryGetContext` method\. If the requested entry is not found on the current construct or any of its parents, the result is `undefined` \(or your language's equivalent, such as `None` in Python\)\. ## Context Methods @@ -42,14 +45,14 @@ Use the cdk context command to view and manage the information in your `cdk.cont ``` Context found in cdk.json: - -┌───┬─────────────────────────────────────────────────────────────┬──────────────────────────────────────────────────────────────┐ -│ # | Key │ Value │ -├───┼─────────────────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────│ -│ 1 | availability-zones:account=123456789012:region=eu-central-1 │ [ "eu-central-1a", "eu-central-1b", "eu-central-1c" ] │ -├───┼─────────────────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────│ -│ 2 | availability-zones:account=123456789012:region=eu-west-1 │ [ "eu-west-1a", "eu-west-1b", "eu-west-1c" ] │ -└───┴─────────────────────────────────────────────────────────────┴──────────────────────────────────────────────────────────────┘ + +┌───┬─────────────────────────────────────────────────────────────┬─────────────────────────────────────────────────────────┐ +│ # │ Key │ Value │ +├───┼─────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤ +│ 1 │ availability-zones:account=123456789012:region=eu-central-1 │ [ "eu-central-1a", "eu-central-1b", "eu-central-1c" ] │ +├───┼─────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤ +│ 2 │ availability-zones:account=123456789012:region=eu-west-1 │ [ "eu-west-1a", "eu-west-1b", "eu-west-1c" ] │ +└───┴─────────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────────┘ Run cdk context --reset KEY_OR_NUMBER to remove a context key. It will be refreshed on the next CDK synthesis run. ``` @@ -72,30 +75,36 @@ Therefore, if you want to update to the latest version of the Amazon Linux AMI, $ cdk synth ``` +``` +... +``` + To clear all of the stored context values for your app, run cdk context \-\-clear, as follows\. ``` $ cdk context --clear ``` -The following is an example of importing an existing vpc using cdk context. +## Example + +Below is an example of importing an existing Amazon VPC using AWS CDK context\. ``` import cdk = require('@aws-cdk/core'); import ec2 = require('@aws-cdk/aws-ec2'); - export class ExistsvpcStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); - + const vpcid = this.node.tryGetContext('vpcid'); - const vpc = ec2.Vpc.fromLookup(this, 'VPC', { vpcId: vpcid, }); - + const pubsubnets = vpc.selectSubnets({subnetType: ec2.SubnetType.PUBLIC}); - + new cdk.CfnOutput(this, 'publicsubnets', { value: pubsubnets.subnetIds.toString(), }); @@ -103,16 +112,25 @@ export class ExistsvpcStack extends cdk.Stack { } ``` +You can use cdk diff to see the effects of passing in a context value on the command line: + ``` $ cdk diff -c vpcid=vpc-0cb9c31031d0d3e22 +``` + +``` Stack ExistsvpcStack Outputs [+] Output publicsubnets publicsubnets: {"Value":"subnet-06e0ea7dd302d3e8f,subnet-01fc0acfb58f3128f"} ``` +The resulting context values can be viewed as shown here\. + ``` $ cdk context -j +``` +``` { "vpc-provider:account=123456789012:filter.vpc-id=vpc-0cb9c31031d0d3e22:region=us-east-1": { "vpcId": "vpc-0cb9c31031d0d3e22", @@ -144,4 +162,4 @@ $ cdk context -j ] } } -``` +``` \ No newline at end of file diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 89d13d49..75082b26 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -1,8 +1,8 @@ # Document History for the AWS CDK Developer Guide This document is based on the following release of the AWS Cloud Development Kit \(AWS CDK\)\. -+ **API version: 1\.3\.0** -+ **Latest documentation update:** August 13, 2019 ++ **API version: 1\.8\.0** ++ **Latest documentation update:** September 17, 2019 See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the AWS CDK releases\. @@ -11,5 +11,6 @@ The table below represents significant milestones\. We fix errors and improve co | Change | Description | Date | | --- |--- |--- | +| [Version 1\.8\.0](#doc-history) | Updates to reflect improvements to ECS Patterns module\. | September 17, 2019 | | [Version 1\.3\.0](#doc-history) | Update tagging topic to use new API\. | August 13, 2019 | | [Version 1\.0\.0](#doc-history) | The AWS CDK Developer Guide is released\. | July 11, 2019 | \ No newline at end of file diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 15dc0a9f..88150586 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -117,4 +117,4 @@ cdk deploy AWS CloudFormation displays information about the dozens of steps that it takes as it deploys your app\. -That's how easy it is to create a Fargate service to run a Docker image\. +That's how easy it is to create a Fargate service to run a Docker image\. \ No newline at end of file diff --git a/doc_source/environments.md b/doc_source/environments.md index 78e4184a..c023de57 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -27,11 +27,5 @@ new MyDevStack(this, 'dev', { }); ``` -NOTE: In order to refer to use `process.env` in TypeScript, you will need to install the `@types/node` module: - -``` -npm install -D @types/node -``` - **Note** -There is a distinction between not specifying the `env` property at all and specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. This means that constructs that are defined in such a stack cannot make assumptions about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html#aws_ec2_Vpc_fromLookup), which need to query your AWS account\. When specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, you tell the stack that it will be deployed in the account and Region as configured in the CLI at the time of synthesis\. This means that the synthesized template could be different on different machines, users, or sessions\. This might be acceptable for use cases like development stacks, but would be an anti\-pattern for production stacks\. +There is a distinction between not specifying the `env` property at all and specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. This means that constructs that are defined in such a stack cannot make assumptions about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html#aws_ec2_Vpc_fromLookup), which need to query your AWS account\. When specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, you tell the stack that it will be deployed in the account and Region as configured in the CLI at the time of synthesis\. This means that the synthesized template could be different on different machines, users, or sessions\. This might be acceptable for use cases like development stacks, but would be an anti\-pattern for production stacks\. \ No newline at end of file diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 77b4dbc8..01378b62 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -1,43 +1,15 @@ # Get a Value from the Systems Manager Parameter Store -The AWS CDK can retrieve the value of AWS Systems Manager Parameter Store attribute at synthesis time \(as the AWS CloudFormation template is being generated\) or at deployment time \(when the synthesized template is being deployed by AWS CloudFormation\)\. In the latter case, the AWS CDK provides a [token](tokens.md) that is later resolved by AWS CloudFormation\. +The AWS CDK can retrieve the value of AWS Systems Manager Parameter Store attributes\. During synthesis, the AWS CDK produces a [token](tokens.md) that is resolved by AWS CloudFormation during deployment\. The AWS CDK supports retrieving both plain and secure values\. You may request a specific version of either kind of value\. For plain values only, you may omit the version from your request to receive the latest version\. You must always specify the version when requesting the value of a secure attribute\. **Note** This topic shows how to read attributes from the AWS Systems Manager Parameter Store\. You can also read secrets from the AWS Secrets Manager \(see [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. -## Reading Values at Synthesis Time +## Reading Systems Manager Values at Deployment Time -To read a particular version of a Systems Manager Parameter Store plain string value at synthesis time, use the [fromStringParameterAttributes](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-from-string-parameter-attributesscope-id-attrs) method\. If you don't supply a `version` value, you get the latest version\. - -``` -import ssm = require('@aws-cdk/aws-ssm'); - -const parameterString = ssm.StringParameter.fromStringParameterAttributes(this, 'MyParameter', { - parameterName: 'my-plain-parameter-name', - version: 1, // omit to get latest version -}); - -const myValue = parameterString.stringValue; -``` - -To read a particular version of a Systems Manager Parameter Store secure string value at synthesis time, use [fromSecureStringParameterAttributes](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-from-secure-string-parameter-attributesscope-id-attrs)\. You must supply a `version` value for secure strings\. - -``` -import ssm = require('@aws-cdk/aws-ssm'); - -const secureString = ssm.StringParameter.fromSecureStringParameterAttributes(this, 'MySecretParameter', { - parameterName: 'my-secure-parameter-name', - version: 1, -}); - -const myValue = secureString.stringValue; -``` - -## Reading Values at Deployment Time - -To read values from the Systems Manager Parameter Store at deployment time, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-string-parameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-secure-string-parameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md) that are later resolved by AWS CloudFormation during deployment\. +To read values from the Systems Manager Parameter Store, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-string-parameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-secure-string-parameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md), not the actual value\. The value is resolved by AWS CloudFormation during deployment\. ``` import ssm = require('@aws-cdk/aws-ssm'); @@ -53,13 +25,30 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` +## Reading Systems Manager Values at Synthesis Time + +It is sometimes useful to "bake in" a parameter at synthesis time, so that the resulting AWS CloudFormation template always uses the same value, rather than resolving the value during deployment\. + +To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method\. This method returns the actual value of the parameter as a [Runtime Context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. + +``` +import ssm = require('@aws-cdk/aws-ssm'); + +// ... later ... +const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); +``` + +**Note** +Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. + ## Writing Values to Systems Manager -Use the [ssm put\-parameter](https://docs.aws.amazon.com/cli/latest/reference/ssm/put-parameter.html) CLI command to add a string parameter to the Systems Manager, such as when testing: +You can use the AWS CLI, the AWS Management Console, or an AWS SDK to set Systems Manager parameter values\. The following examples use the [ssm put\-parameter](https://docs.aws.amazon.com/cli/latest/reference/ssm/put-parameter.html) CLI command\. ``` aws ssm put-parameter --name "parameter-name" --type "String" --value "parameter-value" aws ssm put-parameter --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" ``` -This command returns an ARN that you can use to retrieve the value in your AWS CDK code\. \ No newline at end of file +**Note** +When updating an SSM value that already exists, also include the `--overwrite` option\. \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 2514e360..317ced9c 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -12,7 +12,7 @@ Want to dig deeper? Try the [CDK Workshop](https://cdkworkshop.com/) for a more + You must specify both your credentials and an AWS Region to use the AWS CDK CLI, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. **Note** -Why do you need Node\.js when you're a Python, C♯, or Java developer? The AWS CDK is developed in TypeScript and transpiled to JavaScript\. Bindings for the other supported languages make use of the AWS CDK engine running on Node\.js, as does the `cdk` command\-line tool\. +Why do you need Node\.js when you're a Python, C\#, or Java developer? The AWS CDK is developed in TypeScript and transpiled to JavaScript\. Bindings for the other supported languages make use of the AWS CDK engine running on Node\.js, as does the `cdk` command\-line tool\. ------ #### [ TypeScript ] @@ -34,7 +34,7 @@ none + Set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine ------ -#### [ C♯ ] +#### [ C\# ] \.NET standard 2\.0 compatible implementation: + \.NET Core >= 2\.0 @@ -92,7 +92,7 @@ mvn versions:use-latest-versions ``` ------ -#### [ C♯ ] +#### [ C\# ] ``` nuget update @@ -235,7 +235,7 @@ cdk init --language LANGUAGE [TEMPLATE] ``` Where: -+ *LANGUAGE* is one of the supported programming languages: **csharp** \(C♯\), **java** \(Java\), **javascript** \(JavaScript\), **python** \(Python\), or **typescript** \(TypeScript\) ++ *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), **javascript** \(JavaScript\), **python** \(Python\), or **typescript** \(TypeScript\) + *TEMPLATE* is an optional template\. If the desired template is *app*, the default, you may omit it\. The following table describes the templates available with the supported languages\. @@ -308,7 +308,7 @@ Once the init command finishes, we need to modify the template's output\. ``` ------ -#### [ C♯ ] +#### [ C\# ] ``` cdk init --language csharp @@ -432,7 +432,7 @@ If necessary, add the following to `pom.xml`, where *CDK\-VERSION* is the versio ``` ------ -#### [ C♯ ] +#### [ C\# ] Run the following command in the `src/HelloCdk` directory\. @@ -529,14 +529,14 @@ public class HelloStack extends Stack { super(parent, id, props); new Bucket(this, "MyFirstBucket", BucketProps.builder() - .withVersioned(true) + .versioned(true) .build()); } } ``` ------ -#### [ C♯ ] +#### [ C\# ] Update `HelloStack.cs` to include a Amazon S3 bucket with versioning enabled\. @@ -693,13 +693,13 @@ import software.amazon.awscdk.services.s3.BucketEncryption; ``` new Bucket(this, "MyFirstBucket", BucketProps.builder() - .withVersioned(true) - .withEncryption(BucketEncryption.KMS_MANAGED) + .versioned(true) + .encrypted(BucketEncryption.KMS_MANAGED) .build()); ``` ------ -#### [ C♯ ] +#### [ C\# ] Update `HelloStack.cs`\. diff --git a/doc_source/home.md b/doc_source/home.md index ef515d1d..940caed0 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -8,7 +8,7 @@ AWS CloudFormation enables you to: + Build highly reliable, highly scalable, cost\-effective applications in the cloud without worrying about creating and configuring the underlying AWS infrastructure\. + Use a template file to create and delete a collection of resources together as a single unit \(a stack\)\. -Use the AWS CDK to define your cloud resources in a familiar programming language\. The AWS CDK supports TypeScript, JavaScript, and Python\. The AWS CDK also provides Developer Preview support for C♯/\.NET, and Java\. +Use the AWS CDK to define your cloud resources in a familiar programming language\. The AWS CDK supports TypeScript, JavaScript, and Python\. The AWS CDK also provides Developer Preview support for C\#/\.NET, and Java\. Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. @@ -32,7 +32,7 @@ export class MyEcsConstructStack extends core.Stack { }); // Create a load-balanced Fargate service and make it public - new ecs_patterns.LoadBalancedFargateService(this, "MyFargateService", { + new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { cluster: cluster, // Required cpu: 512, // Default is 256 desiredCount: 6, // Default is 1 @@ -40,6 +40,8 @@ export class MyEcsConstructStack extends core.Stack { memoryLimitMiB: 2048, // Default is 512 publicLoadBalancer: true // Default is false }); + } +} ``` This produces an AWS CloudFormation [template of more than 500 lines](https://github.com/awsdocs/aws-cdk-guide/blob/master/doc_source/my_ecs_construct-stack.yaml); deploying the AWS CDK app produces more than 50 resources of the following types\. diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 8d9fa7be..4b91492f 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -1,6 +1,6 @@ # AWS CDK in Other Languages -In some cases the example code in the AWS CDK documentation is available only in TypeScript\. This topic describes how to read TypeScript code and translate it into Python\. This is currently the only other [stable](reference.md#aws_construct_lib_versioning_binding) programming language that the AWS CDK supports \(the AWS CDK supports a developer preview version of Java and C♯/\.NET\)\. See [Hello World Tutorial](getting_started.md#hello_world_tutorial) for an example of creating an AWS CDK app in a supported language\. +In some cases the example code in the AWS CDK documentation is available only in TypeScript\. This topic describes how to read TypeScript code and translate it into Python\. This is currently the only other [stable](reference.md#aws_construct_lib_versioning_binding) programming language that the AWS CDK supports \(the AWS CDK supports a developer preview version of Java and C\#/\.NET\)\. See [Hello World Tutorial](getting_started.md#hello_world_tutorial) for an example of creating an AWS CDK app in a supported language\. ## Importing a Module diff --git a/doc_source/reference.md b/doc_source/reference.md index b126c76f..4ca9626c 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -35,7 +35,7 @@ Each module in the [API Reference](https://docs.aws.amazon.com/cdk/api/latest) s The module level gives an indication of the stability of the majority of the APIs included in the module, however, individual APIs within the module can be annotated with different stability levels\. -| Stability | TypeScript | JavaScript | Python | C♯/\.NET | Java | +| Stability | TypeScript | JavaScript | Python | C\#/\.NET | Java | | --- |--- |--- |--- |--- |--- | | Experimental | @experimental | @stability Experimental | @experimental | Stability: Experimental | Stability: Experimental | | Stable | @stable | @stability Stable | @stable | Stability: Stable | Stability: Stable | @@ -52,4 +52,4 @@ In addition to modules of the AWS CDK Construct Library, language support is als | JavaScript | Stable | | Python | Stable | | Java | Experimental | -| C♯/\.NET | Experimental | \ No newline at end of file +| C\#/\.NET | Experimental | \ No newline at end of file diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index efeb64d6..512c2edd 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -1,62 +1,130 @@ # Create an App with Multiple Stacks -The following example shows one solution to parameterizing how you create a stack\. It defines a property set that extends the `cdk.StackProps` class to add one additional property, `enc`, which specifies whether to set encryption on the Amazon S3 bucket in the stack\. +Most of the other code examples in the *AWS CDK Developer Guide* involve only a single stack\. However, you can create apps containing any number of stacks\. Each stack results in its own AWS CloudFormation template\. Stacks are the *unit of deployment:* each stack in an app can be synthesized and deployed individually using the `cdk deploy` command\. + +This topic shows how to create a simple stack that contains an Amazon S3 bucket\. The stack uses a Boolean property, named `encryptBucket`, to indicate whether the bucket should be encrypted\. If so, the stack enables encryption, using a key managed by AWS Key Management Service \(AWS KMS\)\. The app creates two instances of this stack, one with encryption and one without\. + +## Prerequisites + +To complete this example, first do the following: ++ Install Node\.js and the AWS CDK command line tools, if you haven't already\. See [Getting Started With the AWS CDK](getting_started.md) for details\. ++ Create a TypeScript AWS CDK project by entering the following commands at the command line\. + + ``` + mkdir multistack && cd multistack + cdk init --language=typescript + ``` ++ Install the `core` and `s3` AWS Construct Library modules\. We use these modules in our app\. + + ``` + npm install @aws-cdk/core + npm install @aws-cdk/aws-s3 + ``` + +## Extend `StackProps` + +The `props` argument of the `Stack` constructor fulfills the interface `StackProps`\. Because we want our stack to accept an additional property to tell us whether to encrypt the Amazon S3 bucket, we should create an interface that includes that property\. This allows TypeScript to make sure the property has a Boolean value and enables autocompletion for it in your IDE\. + +1. Open `lib/multistack-stack.ts` in your IDE or editor\. + +1. Add the new interface definition\. The code in `multistack-stack.ts` should now look like this\. The lines we added are shown in boldface\. + + ``` + import cdk = require('@aws-cdk/core'); + import s3 = require('@aws-cdk/aws-s3'); + + interface MyStackProps extends cdk.StackProps { + encryptBucket?: boolean; + } + + export class MultistackStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + // The code that defines your stack goes here + } + } + ``` + +We've declared the new property as optional\. If `encryptBucket` is not present, its value is `undefined`, which is false in a Boolean context\. In other words, the bucket will be unencrypted by default\. + +## Define the Stack Class + + Now let's define our stack class, using our new property\. Still working in `multistack-stack.ts`, make the code look like the following\. The code that you need to add or change is shown in boldface\. ``` -import core = require("@aws-cdk/core"); -import s3 = require("@aws-cdk/aws-s3"); +import cdk = require('@aws-cdk/core'); +import s3 = require('@aws-cdk/aws-s3'); -interface MyStackProps extends core.StackProps { - enc: boolean; +interface MultistackProps extends cdk.StackProps { + encryptBucket?: boolean; } -export class MyStack extends core.Stack { - constructor(scope: core.App, id: string, props: MyStackProps) { +export class MultistackStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: MultistackProps) { super(scope, id, props); - - if (props.enc) { + + // Add a Boolean property "encryptBucket" to the StackProps constructor. + // If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. + // Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). + if (props && props.encryptBucket) { new s3.Bucket(this, "MyGroovyBucket", { - encryption: s3.BucketEncryption.KMS_MANAGED + encryption: s3.BucketEncryption.KMS_MANAGED, + removalPolicy: RemovalPolicy.DESTROY }); } else { - new s3.Bucket(this, "MyGroovyBucket"); + new s3.Bucket(this, "MyGroovyBucket", { + removalPolicy: RemovalPolicy.DESTROY}); } } } ``` -The file `MyApp.ts` creates two stacks\. One with an unencrypted bucket in the `us-west-2` region; the other with an encrypted bucket in the `us-east-1` region\. +## Create Two Stack Instances + +Open the file `bin/multistack.ts` and add the code to instantiate two stacks\. As before, the lines of code shown in boldface are the ones you need to add\. Delete the existing `new MultistackStack` definition\. ``` -import core = require("@aws-cdk/core"); -import { MyStack } from "../lib/MyApp-stack"; +#!/usr/bin/env node +import 'source-map-support/register'; +import cdk = require('@aws-cdk/core'); +import { MultistackStack } from '../lib/multistack-stack'; -const app = new core.App(); +const app = new cdk.App(); -new MyStack(app, "MyWestCdkStack", { - env: { - region: "us-west-2" - }, - enc: false +new MultistackStack(app, "MyWestCdkStack", { + env: {region: "us-west-2"}, + encryptBucket: false }); - -new MyStack(app, "MyEastCdkStack", { - env: { - region: "us-east-1" - }, - enc: true + +new MultistackStack(app, "MyEastCdkStack", { + env: {region: "us-east-1"}, + encryptBucket: true }); ``` -The following example shows how to deploy a stack with an encrypted bucket to the `us-east-1` region\. + This code uses the new `encryptBucket` property on the `MultistackStack` class to create the following: ++ One stack with an encrypted Amazon S3 bucket in the `us-east-1` AWS Region\. ++ One stack with an unencrypted Amazon S3 bucket in the `us-west-1` AWS Region\. + +## Define the Stack Class + +Now you can build the app\. The TypeScript compiler converts your code to JavaScript\. + +``` +npm run build +``` + +Next, synthesize an AWS CloudFormation template for `MyEastCdkStack`—, the stack in `us-east-1`\. This is the stack with the encrypted S3 bucket\. ``` -cdk deploy MyEastCdkStack +$ cdk synth MyEastCdkStack ``` -If you look at the stack using cdk synth MyEastCdkStack, you should see a bucket similar to the following: +The output should look similar to the following AWS CloudFormation template \(there might be slight differences\)\. ``` +Resources: MyGroovyBucketFD9882AC: Type: AWS::S3::Bucket Properties: @@ -64,4 +132,28 @@ If you look at the stack using cdk synth MyEastCdkStack, you should see a bucket ServerSideEncryptionConfiguration: - ServerSideEncryptionByDefault: SSEAlgorithm: aws:kms -``` \ No newline at end of file + UpdateReplacePolicy: Retain + DeletionPolicy: Retain + Metadata: + aws:cdk:path: MyEastCdkStack/MyGroovyBucket/Resource + CDKMetadata: + Type: AWS::CDK::Metadata + Properties: + Modules: aws-cdk=1.10.0,@aws-cdk/aws-events=1.10.0,@aws-cdk/aws-iam=1.10.0,@aws-cdk/aws-kms=1.10.0,@aws-cdk/aws-s3=1.10.0,@aws-cdk/core=1.10.0,@aws-cdk/cx-api=1.10.0,@aws-cdk/region-info=1.10.0,jsii-runtime=node.js/v10.16.2 +``` + +To deploy this stack to your AWS account, issue the following command\. For *PROFILE\_NAME*, substitute the name of an AWS CLI profile that contains appropriate credentials for deploying to the `us-east-1` AWS Region\. + +``` +cdk deploy MyEastCdkStack --profile=PROFILE_NAME +``` + +## Clean Up + +To avoid charges for resources that you deployed, destroy the stack using the following command\. + +``` +cdk destroy MyEastCdkStack +``` + +The destroy operation fails if there is anything stored in the bucket\. There shouldn't be anything stored if you've only followed the instructions in this topic\. But if you put something in the bucket yourself, you must delete it using the AWS Management Console or the AWS CLI before destroying the stack\. \ No newline at end of file From dd59b781b256ebf67fd17e5420fafe0e355d8846 Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Wed, 16 Oct 2019 05:15:26 +0000 Subject: [PATCH 069/655] Update cli usage (fetch from upstream) --- doc_source/tools.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/doc_source/tools.md b/doc_source/tools.md index 6ab0b9db..1e676c1f 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -118,6 +118,9 @@ Commands and individual options as follows. - --bootstrap-kms-key-id (string) AWS KMS master key ID used for the SSE-KMS encryption default: undefined +- --tags, -t (array) + Tags to add for the stack (KEY=VALUE) + default: [] **cdk deploy** @@ -132,6 +135,8 @@ Commands and individual options as follows. - --ci (boolean) Force CI detection. Use --no-ci to disable CI autodetection. default: process.env.CI !== undefined +- --notification-arns (array) + ARNs of SNS topics that CloudFormation will notify with stack related events - --tags, -t (array) Tags to add to the stack (KEY=VALUE) @@ -146,7 +151,7 @@ Commands and individual options as follows. - --exclusively, -e (boolean) Only deploy requested stacks, don\'t include dependencies -- --context-lines (number) +- --context-lines (number) Number of context lines to include in arbitrary JSON diff rendering default: 3 - --template (string) @@ -155,12 +160,14 @@ Commands and individual options as follows. Do not filter out AWS::CDK::Metadata resources default: false +**cdk metadata** + +no option **cdk init** - --language, -l (string) The language to be used for the new project (default can be configured in ~/.cdk.json) - - --list (boolean) List the available templates From dad08d1bd66348ed4bc78b9735cd7b583edec994 Mon Sep 17 00:00:00 2001 From: Cliff Chao-kuan Lu Date: Wed, 16 Oct 2019 17:32:15 +0800 Subject: [PATCH 070/655] fix: braces in example --- doc_source/assets.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/doc_source/assets.md b/doc_source/assets.md index 6c4a931e..3db37ae7 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -123,8 +123,7 @@ const asset = new Asset(this, 'MyFile', { }); const group = new iam.Group(this, 'MyUserGroup'); - asset.grantRead(group); -} +asset.grantRead(group); ``` ### Docker Image Assets @@ -214,4 +213,4 @@ To enable such use cases, external tools consult a set of metadata entries on AW Using these two metadata entries, tools can identify that assets are used by a certain resource, and enable advanced local experiences\. -To add these metadata entries to a resource, use the `asset.addResourceMetadata` method\. \ No newline at end of file +To add these metadata entries to a resource, use the `asset.addResourceMetadata` method\. From 63c7c478d424f2d45146ae20351a01400cd1ac13 Mon Sep 17 00:00:00 2001 From: Dan Clayton Date: Wed, 16 Oct 2019 07:27:39 -0700 Subject: [PATCH 071/655] [docs] fix optional param in apps --- doc_source/apps.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index b884d182..4a9eee3a 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -6,7 +6,7 @@ The following example declares a stack class named `MyFirstStack` that includes ``` class MyFirstStack extends Stack { - constructor(scope: Construct, id: string, props: StackProps) { + constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); new s3.Bucket(this, 'MyFirstBucket'); @@ -98,4 +98,4 @@ The CLI can also interact directly with an already synthesized cloud assembly\. ``` cdk --app ./my-cloud-assembly ls -``` \ No newline at end of file +``` From 66b2c868ce25d064a6794c8b655dda22b1cf263d Mon Sep 17 00:00:00 2001 From: hacker65536 Date: Thu, 17 Oct 2019 01:08:05 +0000 Subject: [PATCH 072/655] upgrade node version --- doc_source/getting_started.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 317ced9c..589b4bcd 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -8,7 +8,7 @@ Want to dig deeper? Try the [CDK Workshop](https://cdkworkshop.com/) for a more ## Prerequisites **AWS CDK command line tools** -+ [Node\.js \(>= 8\.11\.x\)](https://nodejs.org/en/download) ++ [Node\.js \(>= 10\.3\.0\)](https://nodejs.org/en/download) + You must specify both your credentials and an AWS Region to use the AWS CDK CLI, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. **Note** From 730fa9e0105cf1f4e0f892eb8c88932869bae5ef Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 2 Dec 2019 20:14:23 +0000 Subject: [PATCH 073/655] Sync with recent changes to CDK Dev Guide source --- doc_source/about_examples.md | 63 +- doc_source/apps.md | 184 +++- doc_source/aspects.md | 137 ++- doc_source/assets.md | 537 +++++++++++- doc_source/cfn_layer.md | 227 ++++- doc_source/codepipeline_example.md | 822 ++++++++++++++++-- doc_source/constructs.md | 533 +++++++++++- doc_source/context.md | 99 ++- doc_source/doc-history.md | 7 +- doc_source/ecs_example.md | 283 +++++- doc_source/environments.md | 331 ++++++- doc_source/get_cfn_param.md | 2 +- doc_source/get_context_var.md | 70 +- doc_source/get_env_var.md | 52 +- doc_source/get_secrets_manager_value.md | 66 +- doc_source/get_ssm_value.md | 100 ++- doc_source/getting_started.md | 319 ++++--- doc_source/home.md | 104 ++- doc_source/how_to_set_cw_alarm.md | 136 ++- doc_source/identifiers.md | 149 +++- doc_source/index.md | 3 +- doc_source/multiple_languages.md | 4 +- doc_source/permissions.md | 247 +++++- doc_source/reference.md | 6 +- doc_source/resources.md | 741 +++++++++++++++- doc_source/serverless_example.md | 581 ++++++++++++- .../stack_how_to_create_multiple_stacks.md | 521 +++++++++-- doc_source/stacks.md | 244 +++++- doc_source/tagging.md | 272 +++++- doc_source/testing.md | 354 ++++++++ doc_source/tokens.md | 258 +++++- doc_source/tools.md | 4 + doc_source/troubleshooting.md | 270 +++++- doc_source/use_cfn_template.md | 75 +- 34 files changed, 7280 insertions(+), 521 deletions(-) create mode 100644 doc_source/testing.md diff --git a/doc_source/about_examples.md b/doc_source/about_examples.md index b821270e..af8a112e 100644 --- a/doc_source/about_examples.md +++ b/doc_source/about_examples.md @@ -1,62 +1,5 @@ # AWS CDK Examples -The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repo on GitHub includes the following examples\. - -## TypeScript examples - - -| Example | Description | -| --- |--- | -| [api\-cors\-lambda\-crud\-dynamodb](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/api-cors-lambda-crud-dynamodb/) | Creating a single API with CORS, and five Lambdas doing CRUD operations over a single DynamoDB | -| [application\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/application-load-balancer/) | Using an AutoScalingGroup with an Application Load Balancer | -| [appsync\-graphql\-dynamodb](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/appsync-graphql-dynamodb/) | Creating a single GraphQL API with an API Key, and four Resolvers doing CRUD operations over a single DynamoDB | -| [classic\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/classic-load-balancer/) | Using an AutoScalingGroup with a Classic Load Balancer | -| [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) | Shows adding a Custom Resource to your CDK app | -| [elasticbeanstalk](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/elasticbeanstalk/) | Elastic Beanstalk example using CFN resources with a Blue/Green pipeline \(community contributed\) | -| [ecs\-cluster](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/cluster/) | Provision an ECS Cluster with custom Autoscaling Group configuration | -| [ecs\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-load-balanced-service/) | Starting a container fronted by a load balancer on ECS | -| [ecs\-service\-with\-task\-placement](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-task-placement/) | Starting a container ECS with task placement specifications | -| [ecs\-service\-with\-advanced\-alb\-config](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-advanced-alb-config/) | Starting a container fronted by a load balancer on ECS with added load balancer configuration | -| [ecs\-service\-with\-task\-networking](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-task-networking/) | Starting an ECS service with task networking, allowing ingress traffic to the task but blocking for the instance | -| [fargate\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/fargate-load-balanced-service/) | Starting a container fronted by a load balancer on Fargate | -| [fargate\-service\-with\-auto\-scaling](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/fargate-service-with-auto-scaling/) | Starting an ECS service of FARGATE launch type that auto scales based on average CPU Utilization | -| [lambda\-cron](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/lambda-cron/) | Running a Lambda on a schedule | -| [my\-widget\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/my-widget-service/) | Use Lambda to serve up widgets | -| [resource\-overrides](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/resource-overrides/) | Shows how to override generated CloudFormation code | -| [static\-site](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/static-site/) | A static site using CloudFront | -| [stepfunctions\-job\-poller](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/stepfunctions-job-poller/) | A simple StepFunctions workflow | -| [ecs\-service\-with\-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-logging/) | Starting a container fronted by a load balancer on ECS | -| [fargate\-service\-with\-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/fargate-service-with-logging/) | Starting a container fronted by a load balancer on Fargate | - -## Java examples - - -| Example | Description | -| --- |--- | -| [hello\-world](https://github.com/aws-samples/aws-cdk-examples/tree/master/java/hello-world/) | A demo application that uses the CDK in Java | -| [lambda\-cron](https://github.com/aws-samples/aws-cdk-examples/tree/master/java/lambda-cron/) | Running a Lambda on a schedule | - -## Python examples - - -| Example | Description | -| --- |--- | -| [application\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/application-load-balancer/) | Using an AutoScalingGroup with an Application Load Balancer | -| [classic\-load\-balancer](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/classic-load-balancer/) | Using an AutoScalingGroup with a Classic Load Balancer | -| [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/custom-resource/) | Shows adding a Custom Resource to your CDK app | -| [ecs\-cluster](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/cluster/) | Provision an ECS Cluster with custom Autoscaling Group configuration | -| [ecs\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/ecs-load-balanced-service/) | Starting a container fronted by a load balancer on ECS | -| [ecs\-service\-with\-task\-placement](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/ecs-service-with-task-placement/) | Starting a container ECS with task placement specifications | -| [ecs\-service\-with\-advanced\-alb\-config](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/ecs-service-with-advanced-alb-config/) | Starting a container fronted by a load balancer on ECS with added load balancer configuration | -| [ecs\-service\-with\-task\-networking](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/ecs-service-with-task-networking/) | Starting an ECS service with task networking, allowing ingress traffic to the task but blocking for the instance | -| [fargate\-load\-balanced\-service](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/fargate-load-balanced-service/) | Starting a container fronted by a load balancer on Fargate | -| [fargate\-service\-with\-autoscaling](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/ecs/fargate-service-with-autoscaling/) | Starting an ECS service of FARGATE launch type that auto scales based on average CPU Utilization | -| [lambda\-cron](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/lambda-cron/) | Running a Lambda on a schedule | -| [stepfunctions](https://github.com/aws-samples/aws-cdk-examples/tree/master/python/stepfunctions/) | A simple StepFunctions workflow | - -## JavaScript examples - - -| Example | Description | -| --- |--- | -| [aws\-cdk\-changelogs\-demo](https://github.com/aws-samples/aws-cdk-changelogs-demo) | A full serverless Node\.js application stack deployed using CDK\. It uses AWS Lambda, AWS Fargate, DynamoDB, Elasticache, S3, and CloudFront\. | \ No newline at end of file +For more examples of AWS CDK stacks and apps in your favorite supported programming language, see: ++ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repository on GitHub ++ The [AWS Code Sample Catalog](https://docs.aws.amazon.com/code-samples/latest/catalog/welcome.html)\. \ No newline at end of file diff --git a/doc_source/apps.md b/doc_source/apps.md index 4a9eee3a..bf2a38b9 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -4,6 +4,9 @@ As described in [Constructs](constructs.md), to provision infrastructure resourc The following example declares a stack class named `MyFirstStack` that includes a single Amazon S3 bucket\. However, this only declares a stack\. You still need to define \(also known as to instantiate\) it in some scope to deploy it\. +------ +#### [ TypeScript ] + ``` class MyFirstStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { @@ -14,9 +17,56 @@ class MyFirstStack extends Stack { } ``` +------ +#### [ Python ] + +``` +class MyFirstStack(Stack): + + def __init__(self, scope: Construct, id: str, **kwargs): + super().__init__(scope, id, **kwargs) + + s3.Bucket(self, "MyFirstBucket") +``` + +------ +#### [ Java ] + +``` +public class MyFirstStack extends Stack { + public MyFirstStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyFirstStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + new Bucket(this, "MyFirstBucket"); + } +} +``` + +------ +#### [ C\# ] + +``` +public class MyFirstStack : Stack +{ + public MyFirstStack(Stack scope, string id, StackProps props = null) : base(scope, id, props) + { + new Bucket(this, "MyFirstBucket"); + } +} +``` + +------ + ## The App Construct -To define the previous stack within some scope, use the [App](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/app.html) construct\. The following example defines a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. +To define the previous stack within the scope of an application, use the [App](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/app.html) construct\. The following example app instantiates a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. + +------ +#### [ TypeScript ] ``` const app = new App(); @@ -24,9 +74,41 @@ new MyFirstStack(app, 'hello-cdk'); app.synth(); ``` +------ +#### [ Python ] + +``` +app = App() +MyFirstStack(app, "hello-cdk") +app.synth() +``` + +------ +#### [ Java ] + +``` +App app = new App(); +new MyFirstStack(app, "hello-cdk"); +app.synth(); +``` + +------ +#### [ C\# ] + +``` +var app = new App(); +new MyFirstStack(app, "hello-cdk"); +app.Synth(); +``` + +------ + The `App` construct doesn't require any initialization arguments, because it's the only construct that can be used as a root for the construct tree\. You can now use the `App` instance as a scope for defining a single instance of your stack\. -You can also extend the App construct as follows\. +You can also define construccts within an App\-derived class as follows\. + +------ +#### [ TypeScript ] ``` class MyApp extends App { @@ -38,7 +120,67 @@ class MyApp extends App { new MyApp().synth(); ``` -Both options are equivalent\. +------ +#### [ Python ] + +``` +class MyApp(App): + def __init__(self): + MyFirstStack(self, "hello-cdk") + +MyApp().synth() +``` + +------ +#### [ Java ] + +``` +// MyApp.java +package com.myorg; + +import software.amazon.awscdk.core.App; + +public class MyApp extends App{ + public MyApp() { + new MyFirstStack(this, "hello-cdk"); + } +} + +// Main.java +package com.myorg; + +public class Main { + public static void main(String[] args) { + new MyApp().synth(); + } +} +``` + +------ +#### [ C\# ] + +``` +public class MyApp : App +{ + public MyApp(AppProps props = null) : base(props) + { + new MyFirstStack(this, "hello-cdk"); + + } +} + +class Program +{ + static void Main(string[] args) + { + new MyApp().Synth(); + } +} +``` + +------ + +These two methods are equivalent\. ## App Lifecycle @@ -65,7 +207,7 @@ In this phase, the AWS CDK CLI takes the deployment artifacts cloud assembly pro By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: + The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. -+ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)`\. See [Tokens](tokens.md) for details\. ++ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)` \(Python: `is_token`\)\. See [Tokens](tokens.md) for details\. ## Cloud Assemblies @@ -83,12 +225,44 @@ cdk --app executable cdk-command The \-\-app option instructs the CLI to run your AWS CDK app, and its contents depend on the programming language you use\. Eventually it should be a program that the operating system can run\. You can also create the `cdk.json`file and add information to it so that you need to call only `cdk cdk-command`\. For example, for JavaScript apps, the `cdk.json` file might look like the following, where `node bin/my-app.js` executes a Node\.js program\. +------ +#### [ TypeScript ] + ``` { "app": "node bin/my-app.js" } ``` +------ +#### [ Python ] + +``` +{ + "app": "python app.py" +} +``` + +------ +#### [ Java ] + +``` +{ + "app": "mvn -q exec:java", +} +``` + +------ +#### [ C\# ] + +``` +{ + "app": "dotnet run -p src/project-name/project-name.csproj" +} +``` + +------ + **Note** Use the `cdk init` command to create a language\-specific project, with a `cdk.json` file containing the correct configuration for the programming language you specify\. @@ -98,4 +272,4 @@ The CLI can also interact directly with an already synthesized cloud assembly\. ``` cdk --app ./my-cloud-assembly ls -``` +``` \ No newline at end of file diff --git a/doc_source/aspects.md b/doc_source/aspects.md index 7d208990..4f5a6182 100644 --- a/doc_source/aspects.md +++ b/doc_source/aspects.md @@ -2,26 +2,81 @@ Aspects are the way to apply an operation to all constructs in a given scope\. The functionality could modify the constructs, such as by adding tags, or it could be verifying something about the state of the constructs, such as ensuring that all buckets are encrypted\. -To apply an aspect to a construct and all constructs in the same scope, call [node\.applyAspect](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.ConstructNode.html#apply-aspectaspect) with a new aspect, as shown in the following example\. +To apply an aspect to a construct and all constructs in the same scope, call [node\.applyAspect](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.ConstructNode.html#apply-aspectaspect) \(Python: `apply_aspect`\) with a new aspect, as shown in the following example\. + +------ +#### [ TypeScript ] ``` myConstruct.node.applyAspect(new SomeAspect(...)); ``` +------ +#### [ Python ] + +``` +my_construct.node.apply_aspect(SomeAspect(...)) +``` + +------ +#### [ Java ] + +``` +myConstruct.getNode().applyAspect(new SomeAspect(...)); +``` + +------ +#### [ C\# ] + +``` +myConstruct.Node.ApplyAspect(new SomeAspect(...)); +``` + +------ + The AWS CDK currently uses aspects only to [tag resources](tagging.md), but the framework is extensible and can also be used for other purposes\. For example, you can use it to validate or change the AWS CloudFormation resources that are defined for you\. ## Aspects in Detail -The AWS CDK implements tagging using a more generic system, called aspects, which is an instance of the visitor pattern\. An aspect is a class that implements the following interface\. +The AWS CDK implements tagging using a more generic system, called *aspects*, which is an instance of the visitor pattern\. An aspect is a class that implements the following interface\. + +------ +#### [ TypeScript ] ``` interface IAspect { visit(node: IConstruct): void;} ``` -When you call `construct.node.applyAspect(aspect)`, the construct adds the aspect to an internal list of aspects\. +------ +#### [ Python ] + + Python doesn't have interfaces as a language feature, so an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. + +------ +#### [ Java ] + +``` +public interface IAspect { + public void visit(Construct node); +} +``` + +------ +#### [ C\# ] + +``` +public interface IAspect +{ + void Visit(IConstruct node); +} +``` + +------ -During the [prepare phase](apps.md#lifecycle), the AWS CDK calls the visit method of the object for the construct and each of its children in top\-down order\. +When you call `construct.node.applyAspect(aspect)` \(Python: `apply_aspect`\) the construct adds the aspect to an internal list of aspects\. + +During the [prepare phase](apps.md#lifecycle), the AWS CDK calls the `visit` method of the object for the construct and each of its children in top\-down order\. Although the aspect object is free to change any aspect of the construct object, it only operates on a specific subset of construct types\. After determining the construct type, it can call any method and inspect or assign any property on the construct\. @@ -29,6 +84,9 @@ Although the aspect object is free to change any aspect of the construct object, The following example validates that all buckets created in the stack have versioning enabled\. The aspect adds an error to the constructs that fail the validation, which results in the synth operation failing and prevents deploying the resulting cloud assembly\. +------ +#### [ TypeScript ] + ``` class BucketVersioningChecker implements IAspect { public visit(node: IConstruct): void { @@ -49,4 +107,73 @@ class BucketVersioningChecker implements IAspect { // Apply to the stack stack.node.applyAspect(new BucketVersioningChecker()); -``` \ No newline at end of file +``` + +------ +#### [ Python ] + +``` +@jsii.implements(core.IAspect) +class BucketVersioningChecker: + + def visit(self, node): + # See that we're dealing with a CfnBucket + if isinstance(node, s3.CfnBucket): + + # Check for versioning property, exclude the case where the property + # can be a token (IResolvable). + if (!node.versioning_configuration or + !Tokenization.is_resolvable(node.versioning_configuration) + and node.versioning_configuration.status != "Enabled"): + + node.node.add_error('Bucket versioning is not enabled') + +# Apply to the stack +stack.node.apply_aspect(BucketVersioningChecker()) +``` + +------ +#### [ Java ] + +``` +public class BucketVersioningChecker implements IAspect +{ + @Override + public void visit(Construct node) + { + // See that we're dealing with a CfnBucket + if (node instanceof CfnBucket) + { + CfnBucket bucket = (CfnBucket)node; + Object versioningConfiguration = bucket.getVersioningConfiguration(); + if (versioningConfiguration == null || + !Tokenization.isResolvable(versioningConfiguration.toString()) && + !versioningConfiguration.toString().contains("Enabled") + bucket.getNode().addError("Bucket versioning is not enabled"); + } + } +} +``` + +------ +#### [ C\# ] + +``` +class BucketVersioningChecker : Amazon.Jsii.Runtime.DeputyBase, IAspect +{ + public void Visit(IConstruct node) + { + // See that we're dealing with a CfnBucket + if (node is CfnBucket) + { + var bucket = (CfnBucket)node; + if (bucket.VersioningConfiguration is null || + !Tokenization.IsResolvable(bucket.VersioningConfiguration) && + !bucket.VersioningConfiguration.ToString().Contains("Enabled") + bucket.Node.AddError("Bucket versioning is not enabled"); + } + } +} +``` + +------ \ No newline at end of file diff --git a/doc_source/assets.md b/doc_source/assets.md index 3db37ae7..9ac07872 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -2,7 +2,7 @@ Assets are local files, directories, or Docker images that can be bundled into AWS CDK libraries and apps; for example, a directory that contains the handler code for an AWS Lambda function\. Assets can represent any artifact that the app needs to operate\. -You typically reference assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html#code) property enables you to pass an [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function's code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-assetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. +You typically reference assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html#code) property lets you pass an [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function's code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-assetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. ## Assets in Detail @@ -36,6 +36,9 @@ You can define local files and directories as assets, and the AWS CDK packages a The following example defines a local directory asset and a file asset\. +------ +#### [ TypeScript ] + ``` import { Asset } from '@aws-cdk/aws-s3-assets'; @@ -50,13 +53,75 @@ const fileAsset = new Asset(this, 'SampleSingleFileAsset', { }); ``` +------ +#### [ Python ] + +``` +import os.path +dirname = os.path.dirname(__file__) + +from aws_cdk.aws_s3_assets import Asset + +# Archived and uploaded to Amazon S3 as a .zip file +directory_asset = Asset(self, "SampleZippedDirAsset", + path=os.path.join(dirname, "sample-asset-directory") +) + +# Uploaded to Amazon S3 as-is +file_asset = Asset(self, 'SampleSingleFileAsset', + path=os.path.join(dirname, 'file-asset.txt') +) +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.services.s3.assets.Asset; + +// Directory where app was started +File startDir = new File(System.getProperty("user.dir")); + +// Archived and uploaded to Amazon S3 as a .zip file +Asset directoryAsset = Asset.Builder.create(this, "SampleZippedDirAsset") + .path(new File(startDir, "sample-asset-directory").toString()).build(); + +// Uploaded to Amazon S3 as-is +Asset fileAsset = Asset.Builder.create(this, "SampleSingleFileAsset") + .path(new File(startDir, "file-asset.txt").toString()).build(); +``` + +------ +#### [ C\# ] + +``` +using System.IO; +using Amazon.CDK.AWS.S3.Assets; + +// Archived and uploaded to Amazon S3 as a .zip file +var directoryAsset = new Asset(this, "SampleZippedDirAsset", new AssetProps +{ + Path = Path.Combine(Directory.GetCurrentDirectory(), "sample-asset-directory") +}); + +// Uploaded to Amazon S3 as-is +var fileAsset = new Asset(this, "SampleSingleFileAsset", new AssetProps +{ + Path = Path.Combine(Directory.GetCurrentDirectory(), "file-asset.txt") +}); +``` + +------ + In most cases, you don't need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods that enable you to use assets\. For Lambda functions, the [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) property enables you to specify a directory or a \.zip file in the local file system\. #### Lambda Function Example A common use case is to create AWS Lambda functions with the handler code, which is the entry point for the function, as an Amazon S3 asset\. -The following example uses an Amazon S3 asset to define a handler in the local directory `handler` and creates a Lambda function with the local directory asset as the `code` property\. +The following example uses an Amazon S3 asset to define a Python handler in the local directory `handler` and creates a Lambda function with the local directory asset as the `code` property\. Below is the Python code for the handler\. ``` def lambda_handler(event, context): @@ -68,6 +133,9 @@ def lambda_handler(event, context): The code for the main AWS CDK app should look like the following\. +------ +#### [ TypeScript ] + ``` import cdk = require('@aws-cdk/core'); import lambda = require('@aws-cdk/aws-lambda'); @@ -78,7 +146,7 @@ export class HelloAssetStack extends cdk.Stack { super(scope, id, props); new lambda.Function(this, 'myLambdaFunction', { - code: lambda.Code.asset(path.join(__dirname, 'handler')), + code: lambda.Code.fromAsset(path.join(__dirname, 'handler')), runtime: lambda.Runtime.PYTHON_3_6, handler: 'index.lambda_handler' }); @@ -86,6 +154,80 @@ export class HelloAssetStack extends cdk.Stack { } ``` +------ +#### [ Python ] + +``` +from aws_cdk.core import Stack, Construct +from aws_cdk import aws_lambda as lambda_ + +import os.path +dirname = os.path.dirname(__file__) + +class HelloAssetStack(Stack): + def __init__(self, scope: Construct, id: str, **kwargs): + super().__init__(scope, id, **kwargs) + + lambda_.Function(self, 'myLambdaFunction', + code=lambda_.Code.from_asset(os.path.join(dirname, 'handler')), + runtime=lambda_.Runtime.PYTHON_3_6, + handler="index.lambda_handler") +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.lambda.Runtime; + +public class HelloAssetStack extends Stack { + + public HelloAssetStack(final App scope, final String id) { + this(scope, id, null); + } + + public HelloAssetStack(final App scope, final String id, final StackProps props) { + super(scope, id, props); + + File startDir = new File(System.getProperty("user.dir")); + + Function.Builder.create(this, "myLambdaFunction") + .code(Code.fromAsset(new File(startDir, "handler").toString())) + .runtime(Runtime.PYTHON_3_6) + .handler("index.lambda_handler").build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.Lambda; +using System.IO; + +public class HelloAssetStack : Stack +{ + public HelloAssetStack(Construct scope, string id, StackProps props) : base(scope, id, props) + { + new Function(this, "myLambdaFunction", new FunctionProps + { + Code = Code.FromAsset(Path.Combine(Directory.GetCurrentDirectory(), "handler")), + Runtime = Runtime.PYTHON_3_6, + Handler = "index.lambda_handler" + }); + } +} +``` + +------ + The `Function` method uses assets to bundle the contents of the directory and use it for the function's code\. #### Deploy\-Time Attributes Example @@ -94,7 +236,13 @@ Amazon S3 asset types also expose [deploy\-time attributes](resources.md#resourc The following example uses deploy\-time attributes to pass the location of an image asset into a Lambda function as environment variables\. +------ +#### [ TypeScript ] + ``` +import { Asset } from '@aws-cdk/aws-s3-assets'; +import path = require('path'); + const imageAsset = new Asset(this, "SampleAsset", { path: path.join(__dirname, "images/my-image.png") }); @@ -111,13 +259,108 @@ new lambda.Function(this, "myLambdaFunction", { }); ``` +------ +#### [ Python ] + +``` +import os.path + +from aws_cdk import aws_lambda as lambda_ +from aws_cdk.aws_s3_assets import Asset + +dirname = os.path.dirname(__file__) + +image_asset = Asset(self, "SampleAsset", + path=os.path.join(dirname, "images/my-image.png")) + +lambda_.Function(self, "myLambdaFunction", + code=lambda_.Code.asset(os.path.join(dirname, "handler")), + runtime=lambda_.Runtime.PYTHON_3_6, + handler="index.lambda_handler", + environment=dict( + S3_BUCKET_NAME=image_asset.s3_bucket_name, + S3_OBJECT_KEY=image_asset.s3_object_key, + S3_URL=image_asset.s3_url)) +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.lambda.Runtime; +import software.amazon.awscdk.services.s3.assets.Asset; + +public class FunctionStack extends Stack { + public FunctionStack(final App scope, final String id, final StackProps props) { + super(scope, id, props); + + File startDir = new File(System.getProperty("user.dir")); + + Asset imageAsset = Asset.Builder.create(this, "SampleAsset") + .path(new File(startDir, "images/my-image.png").toString()).build()) + + Function.Builder.create(this, "myLambdaFunction") + .code(Code.fromAsset(new File(startDir, "handler").toString())) + .runtime(Runtime.PYTHON_3_6) + .handler("index.lambda_handler") + .environment(new HashMap() {{ + put("S3_BUCKET_NAME", imageAsset.getS3BucketName()); + put("S3_OBJECT_KEY", imageAsset.getS3ObjectKey()); + put("S3_URL", imageAsset.getS3Url()); + }}).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.Lambda; +using Amazon.CDK.AWS.S3.Assets; +using System.IO; +using System.Collections.Generic; + +var imageAsset = new Asset(this, "SampleAsset", new AssetProps +{ + Path = Path.Combine(Directory.GetCurrentDirectory(), @"images\my-image.png") +}); + +new Function(this, "myLambdaFunction", new FunctionProps +{ + Code = Code.FromAsset(Path.Combine(Directory.GetCurrentDirectory(), "handler")), + Runtime = Runtime.PYTHON_3_6, + Handler = "index.lambda_handler", + Environment = new Dictionary + { + ["S3_BUCKET_NAME"] = imageAsset.S3BucketName, + ["S3_OBJECT_KEY"] = imageAsset.S3ObjectKey, + ["S3_URL"] = imageAsset.S3Url + } +}); +``` + +------ + #### Permissions If you use Amazon S3 assets directly through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-assets-readme.html) module, IAM roles, users, or groups, and need to read assets in runtime, grant those assets IAM permissions through the [asset\.grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3-assets.Asset.html#grant-readgrantee) method\. The following example grants an IAM group read permissions on a file asset\. +------ +#### [ TypeScript ] + ``` +import { Asset } from '@aws-cdk/aws-s3-assets'; +import path = require('path'); + const asset = new Asset(this, 'MyFile', { path: path.join(__dirname, 'my-image.png') }); @@ -126,12 +369,76 @@ const group = new iam.Group(this, 'MyUserGroup'); asset.grantRead(group); ``` +------ +#### [ Python ] + +``` +from aws_cdk.aws_s3_assets import Asset +from aws_cdk import aws_iam as iam + +import os.path +dirname = os.path.dirname(__file__) + + asset = Asset(self, "MyFile", + path=os.path.join(dirname, "my-image.png")) + + group = iam.Group(this, "MyUserGroup") + asset.grantRead(group) +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; +import software.amazon.awscdk.services.iam.Group; +import software.amazon.awscdk.services.s3.assets.Asset; + +public class GrantStack extends Stack { + public GrantStack(final App scope, final String id, final StackProps props) { + super(scope, id, props); + + File startDir = new File(System.getProperty("user.dir")); + + Asset asset = Asset.Builder.create(this, "SampleAsset") + .path(new File(startDir, "images/my-image.png").toString()).build(); + + Group group = new Group(this, "MyUserGroup"); + asset.grantRead(group); } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.IAM; +using Amazon.CDK.AWS.S3.Assets; +using System.IO; + +var asset = new Asset(this, "MyFile", new AssetProps { + Path = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), @"images\my-image.png")) +}); + +var group = new Group(this, "MyUserGroup"); +asset.GrantRead(group); +``` + +------ + ### Docker Image Assets The AWS CDK supports bundling local Docker images as assets through the [aws\-ecr\-assets](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecr-assets-readme.html) module\. The following example defines a docker image that is built locally and pushed to Amazon ECR\. Images are built from a local Docker context directory \(with a Dockerfile\) and uploaded to Amazon ECR by the AWS CDK CLI or your app's CI/CD pipeline, and can be naturally referenced in your AWS CDK app\. +------ +#### [ TypeScript ] + ``` import { DockerImageAsset } from '@aws-cdk/aws-ecr-assets'; @@ -140,12 +447,55 @@ const asset = new DockerImageAsset(this, 'MyBuildImage', { }); ``` +------ +#### [ Python ] + +``` +from aws_cdk.aws_ecr_assets import DockerImageAsset + +import os.path +dirname = os.path.dirname(__file__) + +asset = DockerImageAsset(self, 'MyBuildImage', + directory=os.path.join(dirname, 'my-image')) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.ecr.assets.DockerImageAsset; + +File startDir = new File(System.getProperty("user.dir")); + +DockerImageAsset asset = DockerImageAsset.Builder.create(this, "MyBuildImage") + .directory(new File(startDir, "my-image").toString()).build(); +``` + +------ +#### [ C\# ] + +``` +using System.IO; +using Amazon.CDK.AWS.Ecr.Assets; + +var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps +{ + Directory = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "my-image")) +}); +``` + +------ + The `my-image` directory must include a Dockerfile\. The AWS CDK CLI builds a Docker image from `my-image`, pushes it to an Amazon ECR repository, and specifies the name of the repository as an AWS CloudFormation parameter to your stack\. Docker image asset types expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. #### Amazon ECS Task Definition Example A common use case is to create an Amazon ECS [TaskDefinition](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.TaskDefinition.html) to run docker containers\. The following example specifies the location of a Docker image asset that the AWS CDK builds locally and pushes to Amazon ECR\. +------ +#### [ TypeScript ] + ``` import ecs = require('@aws-cdk/aws-ecs'); import path = require('path'); @@ -160,10 +510,73 @@ taskDefinition.addContainer("my-other-container", { }); ``` +------ +#### [ Python ] + +``` +import aws_cdk.aws_ecs as ecs + +import os.path +dirname = os.path.dirname(__file__) + +task_definition = ecs.FargateTaskDefinition(self, "TaskDef", + memory_limit_mib=1024, + cpu=512) + +task_definition.add_container("my-other-container", + image=ecs.ContainerImage.from_asset( + os.path.join(dirname, "..", "demo-image"))) +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.services.ecs.FargateTaskDefinition; +import software.amazon.awscdk.services.ecs.ContainerDefinitionOptions; +import software.amazon.awscdk.services.ecs.ContainerImage; + +File startDir = new File(System.getProperty("user.dir")); + +FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create( + this, "TaskDef").memoryLimitMiB(1024).cpu(512).build(); + +taskDefinition.addContainer("my-other-container", + ContainerDefinitionOptions.builder() + .image(ContainerImage.fromAsset(new File(startDir, + "demo-image").toString())).build()); +``` + +------ +#### [ C\# ] + +``` +using System.IO; +using Amazon.CDK.AWS.ECS; + +var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps +{ + MemoryLimitMiB = 1024, + Cpu = 512 +}); + +taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions +{ + Image = ContainerImage.FromAsset(Path.Combine(Directory.GetCurrentDirectory(), "demo-image"); +}); +``` + +------ + #### Deploy\-Time Attributes Example The following example shows how to use the deploy\-time attributes `repository` and `imageUri` to create an Amazon ECS task definition with the AWS Fargate launch type\. +------ +#### [ TypeScript ] + ``` import ecs = require('@aws-cdk/aws-ecs'); import path = require('path'); @@ -183,9 +596,84 @@ taskDefinition.addContainer("my-other-container", { }); ``` +------ +#### [ Python ] + +``` +import aws_cdk.aws_ecs as ecs +from aws_cdk.aws_ecr_assets import DockerImageAsset + +import os.path +dirname = os.path.dirname(__file__) + +asset = DockerImageAsset(self, 'my-image', + directory=os.path.join(dirname, "..", "demo-image")) + +task_definition = ecs.FargateTaskDefinition(self, "TaskDef", + memory_limit_mib=1024, cpu=512) + +task_definition.add_container("my-other-container", + image=ecs.ContainerImage.fromEcrRepository( + asset.repository, asset.image_uri)) +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.services.ecr.assets.DockerImageAsset; + +import software.amazon.awscdk.services.ecs.FargateTaskDefinition; +import software.amazon.awscdk.services.ecs.ContainerDefinitionOptions; +import software.amazon.awscdk.services.ecs.ContainerImage; + +File startDir = new File(System.getProperty("user.dir")); + +DockerImageAsset asset = DockerImageAsset.Builder.create(this, "my-image") + .directory(new File(startDir, "demo-image").toString()).build(); + +FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create( + this, "TaskDef").memoryLimitMiB(1024).cpu(512).build(); + +taskDefinition.addContainer("my-other-container", + ContainerDefinitionOptions.builder().image(ContainerImage.fromEcrRepository( + asset.getRepository(), asset.getImageUri())).build()); +``` + +------ +#### [ C\# ] + +``` +using System.IO; +using Amazon.CDK.AWS.ECS; +using Amazon.CDK.AWS.Ecr.Assets; + +var asset = new DockerImageAsset(this, "my-image", new DockerImageAssetProps { + Directory = Path.Combine(Directory.GetCurrentDirectory(), "demo-image") +}); + +var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps +{ + MemoryLimitMiB = 1024, + Cpu = 512 +}); + +taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions +{ + Image = ContainerImage.FromEcrRepository(asset.Repository, asset.ImageUri) +}); +``` + +------ + #### Build Arguments Example -You can provide customized build arguments for the Docker build step through the `buildArgs` property option when the AWS CDK CLI builds the image during deployment\. +You can provide customized build arguments for the Docker build step through the `buildArgs` \(Python: `build_args`\) property option when the AWS CDK CLI builds the image during deployment\. + +------ +#### [ TypeScript ] ``` const asset = new DockerImageAsset(this, 'MyBuildImage', { @@ -196,11 +684,46 @@ const asset = new DockerImageAsset(this, 'MyBuildImage', { }); ``` +------ +#### [ Python ] + +``` +asset = DockerImageAsset(self, "MyBulidImage", + directory=os.path.join(dirname, "my-image"), + build_args=dict(HTTP_PROXY="http://10.20.30.2:1234")) +``` + +------ +#### [ Java ] + +``` +DockerImageAsset asset = DockerImageAsset.Builder.create(this, "my-image"), + .directory(new File(startDir, "my-image").toString()) + .buildArgs(new HashMap() {{ + put("HTTP_PROXY", "http://10.20.30.2:1234"); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps { + Directory = Path.Combine(Directory.GetCurrentDirectory(), "my-image"), + BuildArgs = new Dictionary + { + ["HTTP_PROXY"] = "http://10.20.30.2:1234" + } +}); +``` + +------ + #### Permissions -If you use a module that supports Docker image assets, such as [aws\-ecs](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html), the AWS CDK manages permissions for you when you use assets directly or through [ContainerImage\.fromEcrRepository](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-ecr-repositoryrepository-tag)\. If you use Docker image assets directly, you need to ensure that the consuming principal has permissions to pull the image\. +If you use a module that supports Docker image assets, such as [aws\-ecs](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html), the AWS CDK manages permissions for you when you use assets directly or through [ContainerImage\.fromEcrRepository](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-ecr-repositoryrepository-tag) \(Python: `from_ecr_repository`\)\. If you use Docker image assets directly, you need to ensure that the consuming principal has permissions to pull the image\. -In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecr.Repository.html#grant-pullgrantee) method\. This modifies the IAM policy of the principal to enable it to pull images from this repository\. If the principal that is pulling the image is not in the same account or is an AWS service, such as AWS CodeBuild, that does not assume a role in your account, you must grant pull permissions on the resource policy and not on the principal's policy\. Use the [asset\.repository\.addToResourcePolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecr.Repository.html#add-to-resource-policystatement) method to grant the appropriate principal permissions\. +In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecr.Repository.html#grant-pullgrantee) method \(Python: `grant_pull`\. This modifies the IAM policy of the principal to enable it to pull images from this repository\. If the principal that is pulling the image is not in the same account or is an AWS service, such as AWS CodeBuild, that does not assume a role in your account, you must grant pull permissions on the resource policy and not on the principal's policy\. Use the [asset\.repository\.addToResourcePolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecr.Repository.html#add-to-resource-policystatement) method \(Python: `add_to_resource_policy`\) to grant the appropriate principal permissions\. ## AWS CloudFormation Resource Metadata @@ -213,4 +736,4 @@ To enable such use cases, external tools consult a set of metadata entries on AW Using these two metadata entries, tools can identify that assets are used by a certain resource, and enable advanced local experiences\. -To add these metadata entries to a resource, use the `asset.addResourceMetadata` method\. +To add these metadata entries to a resource, use the `asset.addResourceMetadata` \(Python: `add_resource_metadata`\) method\. \ No newline at end of file diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index e2994edd..7da5d7ea 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -13,6 +13,9 @@ If there are no Construct classes available for the service, you can fall back t For example, to instantiate a low\-level Amazon S3 bucket CFN Resource with analytics enabled, you would write something like the following\. +------ +#### [ TypeScript ] + ``` new s3.CfnBucket(this, 'MyBucket', { analyticsConfigurations: [ @@ -24,13 +27,55 @@ new s3.CfnBucket(this, 'MyBucket', { }); ``` -In the rare case where you want to define a resource that doesn't have a corresponding `CfnXxx` class, such as a new resource that wasn't published yet in the AWS CloudFormation resource specification, you can instantiate the `cdk.CfnResource` directly and specify the resource type and properties\. This is shown in the following example\. +------ +#### [ Python ] + +``` +s3.CfnBucket(self, "MyBucket", + analytics_configurations: [ + dict(id="Config", + # ... + ) + ] +) +``` + +------ +#### [ Java ] + +``` +CfnBucket.Builder.create(this, "MyBucket") + .analyticsConfigurations(Arrays.asList(new HashMap() {{ + put("id", "Config"); + // ... + }})).build(); +``` + +------ +#### [ C\# ] + +``` +new CfnBucket(this, 'MyBucket', new CfnBucketProps { + AnalyticsConfigurations = new Dictionary + { + ["id"] = "Config", + // ... + } +}); +``` + +------ + +In the rare case where you want to define a resource that doesn't have a corresponding `CfnXxx` class, such as a new resource type that hasn't yet been published in the AWS CloudFormation resource specification, you can instantiate the `cdk.CfnResource` directly and specify the resource type and properties\. This is shown in the following example\. + +------ +#### [ TypeScript ] ``` new cdk.CfnResource(this, 'MyBucket', { type: 'AWS::S3::Bucket', properties: { - // Note the PascalCase here! + // Note the PascalCase here! These are CloudFormation identifiers. AnalyticsConfigurations: [ { Id: 'Config', @@ -41,6 +86,61 @@ new cdk.CfnResource(this, 'MyBucket', { }); ``` +------ +#### [ Python ] + +``` +cdk.CfnResource(this, 'MyBucket', + type="AWS::S3::Bucket", + properties=dict( + # Note the PascalCase here! These are CloudFormation identifiers. + "AnalyticsConfigurations": [ + { + "Id": "Config", + # ... + } + ] + } +) +``` + +------ +#### [ Java ] + +``` +CfnResource.Builder.create(this, "MyBucket") + .type("AWS::S3::Bucket") + .properties(new HashMap() {{ + // Note the PascalCase here! These are CloudFormation identifiers + put("AnalyticsConfigurations", Arrays.asList( + new HashMap() {{ + put("Id", "Config"); + // ... + }})); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +new CfnResource(this, "MyBucket", new CfnResourceProps +{ + Type = "AWS::S3::Bucket", + Properties = new Dictionary + { // Note the PascalCase here! These are CloudFormation identifiers + ["AnalyticsConfigurations"] = new List> + { + new Dictionary { + ["Id"] = "Config" + } + } + } +}); +``` + +------ + For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. ## Modifying the AWS CloudFormation Resource behind AWS Constructs @@ -49,7 +149,10 @@ If an Construct is missing a feature or you are trying to work around an issue, All Constructs contain within them the corresponding CFN Resource\. For example, the high\-level `Bucket` construct wraps the low\-level `CfnBucket` construct\. Because the `CfnBucket` corresponds directly to the AWS CloudFormation resource, it exposes all features that are available through AWS CloudFormation\. -The basic approach to get access to the CFN Resource class is to use `construct.node.defaultChild`, cast it to the right type for the resource, and modify its properties\. Again, let's take the example of a `Bucket`\. +The basic approach to get access to the CFN Resource class is to use `construct.node.defaultChild` \(Python: `default_child`\), cast it to the right type \(if necessary\), and modify its properties\. Again, let's take the example of a `Bucket`\. + +------ +#### [ TypeScript ] ``` // Get the AWS CloudFormation resource @@ -64,19 +167,99 @@ cfnBucket.analyticsConfiguration = [ ]; ``` +------ +#### [ Python ] + +``` +# Get the AWS CloudFormation resources +cfn_bucket = bucket.node.default_child + +# Change its properties +cfn_bucket.analytics_configuration = [ + { + "id": "Config", + # ... + } +] +``` + +------ +#### [ Java ] + +``` +cfnBucket.setAnalyticsConfigurations( + Arrays.asList(new HashMap() {{ + put("Id", "Config"); + // ... + }})); +``` + +------ +#### [ C\# ] + +``` +var cfnBucket = (CfnBucket)bucket.Node.DefaultChild; + +cfnBucket.AnalyticsConfigurations = new List { + new Dictionary + { + ["Id"] = "Config", + // ... + } +}; +``` + +------ + You can also use this object to change AWS CloudFormation options such as `Metadata` and `UpdatePolicy`\. +------ +#### [ TypeScript ] + ``` cfnBucket.cfnOptions.metadata = { MetadataKey: 'MetadataValue' }; ``` +------ +#### [ Python ] + +``` +cfn_bucket.cfn_options.metadata = { + "MetadataKey": "MetadataValue" +} +``` + +------ +#### [ Java ] + +``` +cfnBucket.getCfnOptions().setMetadata(new HashMap() {{ + put("MetadataKey", "Metadatavalue"); +}}); +``` + +------ +#### [ C\# ] + +``` +cfnBucket.CfnOptions.Metadata = new Dictionary +{ + ["MetadataKey"] = "Metadatavalue" +}; +``` + +------ + ## Raw Overrides If there are properties that are missing from the CFN Resource, you can bypass all typing using raw overrides\. This also makes it possible to delete synthesized properties\. -Use one of the `addOverride` or `addDeletionOverride` methods, as shown in the following example\. +Use one of the `addOverride` methods \(Python: `add_override`\) methods, as shown in the following example\. + +------ +#### [ TypeScript ] ``` // Get the AWS CloudFormation resource @@ -92,6 +275,42 @@ cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); ``` +------ +#### [ Python ] + +``` +# Get the AWS CloudFormation resource +cfn_bucket = bucket.node.default_child + +# Use dot notation to address inside the resource template fragment +cfn_bucket.add_override("Properties.VersioningConfiguration.Status", "NewStatus") +cfn_bucket.add_deletion_override("Properties.VersioningConfiguration.Status") + +# add_property_override is a convenience function, which implies the +# path starts with "Properties." +cfn_bucket.add_property_override("VersioningConfiguration.Status", "NewStatus") +cfn_bucket.add_property_deletion_override("VersioningConfiguration.Status") +``` + +------ +#### [ C\# ] + +``` +// Get the AWS CloudFormation resource +var cfnBucket = (CfnBucket)bucket.node.defaultChild; + +// Use dot notation to address inside the resource template fragment +cfnBucket.AddOverride("Properties.VersioningConfiguration.Status", "NewStatus"); +cfnBucket.AddDeletionOverride("Properties.VersioningConfiguration.Status"); + +// addPropertyOverride is a convenience function, which implies the +// path starts with "Properties." +cfnBucket.AddPropertyOverride("VersioningConfiguration.Status", "NewStatus"); +cfnBucket.AddPropertyDeletionOverride("VersioningConfiguration.Status"); +``` + +------ + ## Custom Resources If the feature isn't available through AWS CloudFormation, but only through a direct API call, the only solution is to write an AWS CloudFormation Custom Resource to make the API call you need\. Don't worry, the AWS CDK makes it easier to write these, and wrap them up into a regular construct interface, so from another user's perspective the feature feels native\. diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index a73fbba5..7b17a644 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -4,23 +4,93 @@ This example creates a code pipeline using the AWS CDK\. The AWS CDK enables you to easily create applications running in the AWS Cloud\. But creating the application is just the start of the journey\. You also want to make changes to it, test those changes, and finally deploy them to your stack\. The AWS CDK enables this workflow by using the **Code\*** suite of AWS tools: AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline\. Together, they allow you to build what's called a [deployment pipeline](https://aws.amazon.com/getting-started/tutorials/continuous-deployment-pipeline/) for your application\. -The following example shows how to deploy an AWS Lambda function in a pipeline\. In this example, your AWS CDK code and your Lambda code are in the same repository\. The Lambda code is in the `Lambda` directory, while your CDK code is in the `bin` and `lib` directories that the `cdk init` command sets up for your CDK code\. +The following example shows how to deploy an AWS Lambda function in a pipeline\. In this example, your AWS CDK code and your Lambda code are in the same project\. The Lambda code is in the `Lambda` directory\. -**Note** -If you are setting up a new project using `cdk init` for the sake of trying this example, be sure to name your project folder `pipeline`\. For example: +To set up a project like this from scratch, follow these instructions\. + +------ +#### [ TypeScript ] + +``` +mkdir pipeline +cd pipeline +cdk init --language typescript +mkdir Lambda +npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild +npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 +``` + +------ +#### [ Python ] + +``` +mkdir pipeline +cd pipeline +cdk init --language python +source .env/bin/activate || "on Windows, use: .env\Scripts\activate.bat" +pip install -r requirements.txt +mkdir Lambda +pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild +pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_s3 +``` + +------ +#### [ Java ] + +``` +mkdir pipeline +cd pipeline +cdk init --language java +``` + +You can import the resulting Maven project into your Java IDE\. + +Using the Maven integration in your IDE \(for example, in Eclipse, right\-click the project and choose **Maven** > **Add Dependency**\), add the following packages in the group `software.amazon.awscdk`\. + +``` +lambda +codedeploy +codebuild +codecommit +codepipeline-actions +s3 +``` + +------ +#### [ C\# ] ``` mkdir pipeline cd pipeline -cdk init --language=typescript +cdk init --language csharp ``` -The `cdk init` command uses a template that creates classes and files based on your project name, and some of the instructions in this example rely on these names\. + +You can open the file `src/Pipeline.sln` in Visual Studio\. + +Choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio and add the following packages\. + +``` +Amazon.CDK.AWS.CodeDeploy +Amazon.CDK.AWS.Lambda +Amazon.CDK.AWS.CodeBuild +Amazon.CDK.AWS.CodeCommit +Amazon.CDK.AWS.CodePipeline.Actions +Amazon.CDK.AWS.S3 +``` + +**Tip** +If you don't see these packages in the **Browse** tab of the **Manage Packages for Solution** page, make sure the **Include prerelease** checkbox is ticked\. +For a better experience, also add the `Amazon.Jsii.Analyzers` package to provide compile\-time checks for missing required properties\. + +------ ## Lambda Stack -The first step is to create the file `lambda-stack.ts` in which we define the class `LambdaStack`\. This class defines the AWS CloudFormation stack for the Lambda function\. This is the stack that is deployed in our pipeline\. +The first step is to define the AWS CloudFormation stack that will create the Lambda function\. This is the stack that we'll deploy in our pipeline\. -This class includes the `lambdaCode` property, which is an instance of the `CfnParametersCode` class\. This property represents the code that is supplied later by the pipeline\. Because the pipeline needs access to the object, we expose it as a public, read\-only property on our class\. +We'll create a new file to hold this stack\. + +This class includes the `lambdaCode` \(Python: `lambda_code`\) property, which is an instance of the `CfnParametersCode` class\. This property represents the code that is supplied later by the pipeline\. Because the pipeline needs access to the object, we expose it as a public property of our class\. The example also uses the CodeDeploy support for blue\-green deployments to Lambda, and the deployment increases the traffic to the new version in 10\-percent increments every minute\. As blue\-green deployment can only operate on aliases, not on the function directly, we create an alias for our function, named `Prod`\. @@ -28,60 +98,205 @@ The alias uses a Lambda version, which is named after the date when the code exe If the Lambda function needs any other resources when executing, such as an Amazon S3 bucket, Amazon DynamoDB table, or Amazon API Gateway, declare those resources here\. +------ +#### [ TypeScript ] + +File: `lib/lambda-stack.ts` + ``` -// file: lib/lambda-stack.ts - - import codedeploy = require('@aws-cdk/aws-codedeploy'); - import lambda = require('@aws-cdk/aws-lambda'); - import { App, Stack, StackProps } from '@aws-cdk/core'; - - export class LambdaStack extends Stack { - public readonly lambdaCode: lambda.CfnParametersCode; +import codedeploy = require('@aws-cdk/aws-codedeploy'); +import lambda = require('@aws-cdk/aws-lambda'); +import { App, Stack, StackProps } from '@aws-cdk/core'; + +export class LambdaStack extends Stack { + public readonly lambdaCode: lambda.CfnParametersCode; + + constructor(app: App, id: string, props?: StackProps) { + super(app, id, props); + + this.lambdaCode = lambda.Code.cfnParameters(); + + const func = new lambda.Function(this, 'Lambda', { + code: this.lambdaCode, + handler: 'index.handler', + runtime: lambda.Runtime.NODEJS_10_X, + }); + + const version = func.addVersion(new Date().toISOString()); + const alias = new lambda.Alias(this, 'LambdaAlias', { + aliasName: 'Prod', + version, + }); + + new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', { + alias, + deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE, + }); + } +} +``` + +------ +#### [ Python ] + +File: `pipeline/lambda_stack.py` + +``` +from aws_cdk import core, aws_codedeploy as codedeploy, aws_lambda as lambda_ + +from datetime import datetime + +class LambdaStack(core.Stack): + def __init__(self, app: core.App, id: str, **kwargs): + super().__init__(app, id, **kwargs) + + self.lambda_code = lambda_.Code.cfn_parameters() + + func = lambda_.Function(self, "Lambda", + code=self.lambda_code, + handler="index.handler", + runtime=lambda_.Runtime.NODEJS_10_X, + ) + + version = func.add_version(datetime.now().isoformat()) + alias = lambda_.Alias(self, "LambdaAlias", + alias_name="Prod", version=version) + + codedeploy.LambdaDeploymentGroup(self, "DeploymentGroup", + alias=alias, + deployment_config= + codedeploy.LambdaDeploymentConfig.LINEAR_10_PERCENT_EVERY_1_MINUTE + ) +``` + +------ +#### [ Java ] + +File: src/main/java/com/myorg/LambdaStack\.java + +``` +package com.myorg; + +import java.time.Instant; + +import software.amazon.awscdk.core.App; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; + +import software.amazon.awscdk.services.codedeploy.LambdaDeploymentConfig; +import software.amazon.awscdk.services.codedeploy.LambdaDeploymentGroup; + +import software.amazon.awscdk.services.lambda.Alias; +import software.amazon.awscdk.services.lambda.CfnParametersCode; +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.lambda.Runtime; +import software.amazon.awscdk.services.lambda.Version; + +public class LambdaStack extends Stack { + + // private attribute to hold our Lambda's code, with public getters + private CfnParametersCode lambdaCode; - constructor(app: App, id: string, props?: StackProps) { - super(app, id, props); + public CfnParametersCode getLambdaCode() { + return lambdaCode; + } - this.lambdaCode = lambda.Code.cfnParameters(); + // Constructor without props argument + public LambdaStack(final App scope, final String id) { + this(scope, id, null); + } - const func = new lambda.Function(this, 'Lambda', { - code: this.lambdaCode, - handler: 'index.handler', - runtime: lambda.Runtime.NODEJS_8_10, - }); + public LambdaStack(final App scope, final String id, final StackProps props) { + super(scope, id, props); - const version = func.addVersion(new Date().toISOString()); - const alias = new lambda.Alias(this, 'LambdaAlias', { - aliasName: 'Prod', - version, - }); - - new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', { - alias, - deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE, - }); - } + lambdaCode = CfnParametersCode.fromCfnParameters(); + + Function func = Function.Builder.create(this, "Lambda") + .code(lambdaCode) + .handler("index.handler") + .runtime(Runtime.NODEJS_10_X).build(); + + Version version = func.addVersion(Instant.now().toString()); + Alias alias = Alias.Builder.create(this, "LambdaAlias") + .aliasName("LambdaAlias") + .version(version).build(); + + LambdaDeploymentGroup.Builder.create(this, "DeploymentGroup") + .alias(alias) + .deploymentConfig(LambdaDeploymentConfig.LINEAR_10_PERCENT_EVERY_1_MINUTE).build(); + } +} +``` + +------ +#### [ C\# ] + +File: `src/pipeline/LambdaStack.cs` + +``` +using System; +using Amazon.CDK; +using Amazon.CDK.AWS.CodeDeploy; +using Amazon.CDK.AWS.Lambda; + +namespace Pipeline +{ + public class LambdaStack : Stack + { + public readonly CfnParametersCode lambdaCode; + + public LambdaStack(App app, string id, StackProps props=null) : base(app, id, props) + { + lambdaCode = Code.FromCfnParameters(); + + var func = new Function(this, "Lambda", new FunctionProps + { + Code = lambdaCode, + Handler = "index.handler", + Runtime = Runtime.NODEJS_10_X + }); + + var version = func.AddVersion(DateTime.UtcNow.ToString("s")); + var alias = new Alias(this, "LambdaAlias", new AliasProps + { + AliasName = "Prod", + Version = version + }); + + new LambdaDeploymentGroup(this, "DeploymentGroup", new LambdaDeploymentGroupProps + { + Alias = alias, + DeploymentConfig = LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE + }); + } } +} ``` +------ + ## Pipeline Stack The second class, `PipelineStack`, is the stack that contains our pipeline\. -First it needs a reference to the Lambda code it's deploying\. For that, we define a new props interface for it, `PipelineStackProps`\. This extends the standard `StackProps`, and use it in its constructor signature\. This is how clients of this class pass the Lambda code that the class needs\. +First it needs a reference to the Lambda code it's deploying\. For that, we define a new props interface for it, `PipelineStackProps`\. \(This isn't necessary in Python, where properties are instead passed as keyword arguments\.\) This extends the standard `StackProps` and is how clients of this class \(including ourselves\) pass the Lambda code that the class needs\. -Then comes the Git repository used to store the source code\. In the example, it's hosted by CodeCommit\. The `Repository.fromRepositoryName` method is a standard AWS CDK idiom for referencing a resource, such as a CodeCommit repository, that lives outside the AWS CDK code\. Replace *NameOfYourCodeCommitRepository* with the name of your repository\. +Then comes the Git repository used to store the source code\. In the example, it's hosted by CodeCommit\. The `Repository.fromRepositoryName` method \(Python: `from_repository_name`\) is a standard AWS CDK idiom for referencing a resource, such as a CodeCommit repository, that lives outside the AWS CDK code\. Replace *NameOfYourCodeCommitRepository* with the name of your repository\. The example has two CodeBuild projects\. The first project obtains the AWS CloudFormation template from the AWS CDK code\. To do that, it calls the standard install and build targets for Node\.js, and then calls the cdk synth command\. This produces AWS CloudFormation templates in the target directory `dist`\. Finally, it uses the `dist/LambdaStack.template.json` file as its output\. The second project does a similar thing, except for the Lambda code\. Because of that, it starts by changing the current directory to `lambda`, which is where we said the Lambda code lives in the repository\. It then invokes the same install and build Node\.js targets as before\. The output is the contents of the node\_modules directory, plus the `index.js` file\. Because `index.handler` is the entry point to the Lambda code, `index.js` must exist, and must export a `handler` function\. This function is called by the Lambda runtime to handle requests\. If your Lambda code uses more files than just `index.js`, add them here\. -Finally, we create our pipeline\. It has a source Action targeting the CodeCommit repository, two build Actions using the previously defined projects, and finally a deploy Action that uses AWS CloudFormation\. It takes the template generated by the AWS CDK build Project \(stored in the `LambdaStack.template.json` file, same as the build specified\), and then uses the Lambda code that was passed in its props to reference the output of the build of our Lambda function\. The deployed Lambda function uses the output of that build as its code\. We have to make sure that the Lambda build output is an input to the AWS CloudFormation action though, and that's why we pass it in the `extraInputs` property\. +Finally, we create our pipeline\. It has a source Action targeting the CodeCommit repository, two build Actions using the previously defined projects, and finally a deploy Action that uses AWS CloudFormation\. It takes the template generated by the AWS CDK build Project \(stored in the `LambdaStack.template.json` file, same as the build specified\), and then uses the Lambda code that was passed in its props to reference the output of the build of our Lambda function\. The deployed Lambda function uses the output of that build as its code\. We have to make sure that the Lambda build output is an input to the AWS CloudFormation action though, and that's why we pass it in the `extraInputs` property \(Python: `extra_inputs`\)\. We also change the name of the stack that will be deployed, from `LambdaStack` to `LambdaDeploymentStack`\. The name change isn't required\. We could have left it the same\. -``` -// lib/pipeline-stack.ts +------ +#### [ TypeScript ] +File: `lib/pipeline-stack.ts` + +``` import codebuild = require('@aws-cdk/aws-codebuild'); import codecommit = require('@aws-cdk/aws-codecommit'); import codepipeline = require('@aws-cdk/aws-codepipeline'); @@ -123,7 +338,7 @@ export class PipelineStack extends Stack { }, }), environment: { - buildImage: codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_8_11_0, + buildImage: codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1, }, }); const lambdaBuild = new codebuild.PipelineProject(this, 'LambdaBuild', { @@ -149,7 +364,7 @@ export class PipelineStack extends Stack { }, }), environment: { - buildImage: codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_8_11_0, + buildImage: codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1, }, }); @@ -206,20 +421,416 @@ export class PipelineStack extends Stack { } ``` -## Main Program +------ +#### [ Python ] -Finally, we have our main AWS CDK entry point file, `pipeline.ts`, in the `bin` directory\. +File: `pipeline/pipeline_stack.py` -**Note** -This file may have a different name\. Check your `package.json` file if you're not sure which file is your main entry point\. +``` +from aws_cdk import (core, aws_codebuild as codebuild, + aws_codecommit as codecommit, + aws_codepipeline as codepipeline, + aws_codepipeline_actions as codepipeline_actions, + aws_lambda as lambda_, aws_s3 as s3) + +class PipelineStack(core.Stack): + + def __init__(self, scope: core.Construct, id: str, *, + lambda_code: lambda_.CfnParametersCode = None, **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + code = codecommit.Repository.from_repository_name(self, "ImportedRepo", + "NameOfYourCodeCommitRepository"); + + cdk_build = codebuild.PipelineProject(self, "CdkBuild", + build_spec=codebuild.BuildSpec.from_object(dict( + version="0.2", + phases=dict( + install=dict( + commands="npm install"), + build=dict(commands=[ + "npm run build", + "npm run cdk synth -- -o dist"])), + artifacts={ + "base-directory": "dist", + "files": [ + "LambdaStack.template.json"]}, + environment=dict(buildImage= + codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1)))) + + lambda_build = codebuild.PipelineProject(self, 'LambdaBuild', + build_spec=codebuild.BuildSpec.from_object(dict( + version="0.2", + phases=dict( + install=dict( + commands=[ + "cd lambda", + "npm install"]), + build=dict( + commands="npm run build")), + artifacts={ + "base-directory": "lambda", + "files": [ + "index.js", + "node_modules/**/*"]}, + environment=dict(buildImage= + codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1)))) + + source_output = codepipeline.Artifact() + cdk_build_output = codepipeline.Artifact("CdkBuildOutput") + lambda_build_output = codepipeline.Artifact("LambdaBuildOutput") + + lambda_location = lambda_build_output.s3_location + + codepipeline.Pipeline(self, "Pipeline", + stages=[ + codepipeline.StageProps(stage_name="Source", + actions=[ + codepipeline_actions.CodeCommitSourceAction( + action_name="CodeCommit_Source", + repository=code, + output=source_output)]), + codepipeline.StageProps(stage_name="Build", + actions=[ + codepipeline_actions.CodeBuildAction( + action_name="Lambda_Build", + project=lambda_build, + input=source_output, + outputs=[lambda_build_output]), + codepipeline_actions.CodeBuildAction( + action_name="CDK_Build", + project=cdk_build, + input=source_output, + outputs=[cdk_build_output])]), + codepipeline.StageProps(stage_name="Deploy", + actions=[ + codepipeline_actions.CloudFormationCreateUpdateStackAction( + action_name="Lambda_CFN_Deploy", + template_path=cdk_build_output.at_path( + "LambdaStack.template.json"), + stack_name="LambdaDeploymentStack", + admin_permissions=True, + parameter_overrides=dict( + lambda_code.assign( + bucket_name=lambda_location.bucket_name, + object_key=lambda_location.object_key, + object_version=lambda_location.object_version)), + extra_inputs=[lambda_build_output])]) + ] + ) +``` + +------ +#### [ Java ] + +File: src/main/java/com/myorg/PipelineStack\.java + +``` +package com.myorg; + +import java.util.Arrays; +import java.util.List; +import java.util.HashMap; + +import software.amazon.awscdk.core.App; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; + +import software.amazon.awscdk.services.codebuild.BuildEnvironment; +import software.amazon.awscdk.services.codebuild.BuildSpec; +import software.amazon.awscdk.services.codebuild.LinuxBuildImage; +import software.amazon.awscdk.services.codebuild.PipelineProject; + +import software.amazon.awscdk.services.codecommit.Repository; + +import software.amazon.awscdk.services.codepipeline.Artifact; +import software.amazon.awscdk.services.codepipeline.StageProps; +import software.amazon.awscdk.services.codepipeline.Pipeline; + +import software.amazon.awscdk.services.codepipeline.actions.CloudFormationCreateUpdateStackAction; +import software.amazon.awscdk.services.codepipeline.actions.CodeBuildAction; +import software.amazon.awscdk.services.codepipeline.actions.CodeCommitSourceAction; + +import software.amazon.awscdk.services.lambda.CfnParametersCode; + +public class PipelineStack extends Stack { + // alternate constructor for calls without props. lambdaCode is required. + public PipelineStack(final App scope, final String id, final CfnParametersCode lambdaCode) { + this(scope, id, null, lambdaCode); + } + + @SuppressWarnings("serial") + public PipelineStack(final App scope, final String id, final StackProps props, final CfnParametersCode lambdaCode) { + super(scope, id, props); + + Repository code = (Repository)Repository.fromRepositoryName(this, "ImportedRepo", + "NameOfYourCodeCommitRepository"); + + PipelineProject cdkBuild = PipelineProject.Builder.create(this, "CDKBuild") + .buildSpec(BuildSpec.fromObject(new HashMap() {{ + put("version", "0.2"); + put("phases", new HashMap() {{ + put("install", new HashMap() {{ + put("commands", "npm install"); + }}); + put("build", new HashMap() {{ + put("commands", Arrays.asList("npm run build", + "npm run cdk synth -- o dist")); + }}); + }}); + put("artifacts", new HashMap() {{ + put("base-directory", "dist"); + }}); + put("files", Arrays.asList("LambdaStack.template.json")); + }})) + .environment(BuildEnvironment.builder().buildImage( + LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1).build()) + .build(); + + PipelineProject lambdaBuild = PipelineProject.Builder.create(this, "LambdaBuild") + .buildSpec(BuildSpec.fromObject(new HashMap() {{ + put("version", "0.2"); + put("phases", new HashMap() {{ + put("install", new HashMap>() {{ + put("commands", Arrays.asList("cd lambda", "npm install")); + }}); + put("build", new HashMap>() {{ + put("commands", Arrays.asList("npm run build")); + }}); + }}); + put("artifacts", new HashMap() {{ + put("base-directory", "lambda"); + put("files", Arrays.asList("index.js", "node_modules/**/*")); + }}); + }})) + .environment(BuildEnvironment.builder().buildImage( + LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1).build()) + .build(); + + Artifact sourceOutput = new Artifact(); + Artifact cdkBuildOutput = new Artifact("CdkBuildOutput"); + Artifact lambdaBuildOutput = new Artifact("LambdaBuildOutput"); + + Pipeline.Builder.create(this, "Pipeline") + .stages(Arrays.asList( + StageProps.builder() + .stageName("Source") + .actions(Arrays.asList( + CodeCommitSourceAction.Builder.create() + .actionName("Source") + .repository(code) + .output(sourceOutput) + .build())) + .build(), + StageProps.builder() + .stageName("Build") + .actions(Arrays.asList( + CodeBuildAction.Builder.create() + .actionName("Lambda_Build") + .project(lambdaBuild) + .input(sourceOutput) + .outputs(Arrays.asList(lambdaBuildOutput)).build(), + CodeBuildAction.Buildercreate() + .actionName("Lambda_Build") + .project(cdkBuild) + .input(sourceOutput) + .outputs(Arrays.asList(cdkBuildOutput)) + .build())) + .build(), + StageProps.builder() + .stageName("Deploy") + .actions(Arrays.asList( + CloudFormationCreateUpdateStackAction.Builder.create() + .actionName("Lambda_CFN_Deploy") + .templatePath(cdkBuildOutput.atPath("LambdaStack.template.json")) + .adminPermissions(true) + .parameterOverrides(lambdaCode.assign(lambdaBuildOutput.getS3Location())) + .extraInputs(Arrays.asList(lambdaBuildOutput)) + .build()) + .build())) + .build(); + } +} +``` + +------ +#### [ C\# ] + +File: src/pipeline/PipelineStack\.cs + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.CodeBuild; +using Amazon.CDK.AWS.CodeCommit; +using Amazon.CDK.AWS.CodePipeline; +using Amazon.CDK.AWS.CodePipeline.Actions; +using Amazon.CDK.AWS.Lambda; +using System.Collections.Generic; + +namespace Pipeline +{ + public class PipelineStackProps : StackProps + { + public CfnParametersCode LambdaCode { get; set; } + } + + public class PipelineStack : Stack + { + public PipelineStack(App app, string id, PipelineStackProps props=null) + { + var code = Repository.FromRepositoryName(this, "ImportedRepo", + "NameOfYourCodeCommitRepository"); + + var cdkBuild = new PipelineProject(this, "CDKBuild", new PipelineProjectProps + { + BuildSpec = BuildSpec.FromObject(new Dictionary + { + ["version"] = "0.2", + ["phases"] = new Dictionary + { + ["install"] = new Dictionary + { + ["commands"] = "npm install" + }, + ["build"] = new Dictionary + { + ["commands"] = new List { + "npm run build", + "npm run cdk synth -- o dist" + } + } + }, + ["artifacts"] = new Dictionary + { + ["base-directory"] = "dist" + }, + ["files"] = new List + { + "LambdaStack.template.json" + } + }), + Environment = new BuildEnvironment + { + BuildImage = LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1 + } + }); + + var lambdaBuild = new PipelineProject(this, "LambdaBuild", new PipelineProjectProps + { + BuildSpec = BuildSpec.FromObject(new Dictionary + { + ["version"] = "0.2", + ["phases"] = new Dictionary + { + ["install"] = new Dictionary + { + ["commands"] = new List + { + "cd lambda", + "npm install" + } + }, + ["build"] = new Dictionary + { + ["commands"] = "npm run build" + } + }, + ["artifacts"] = new Dictionary + { + ["base-directory"] = "lambda", + ["files"] = new List + { + "index.js", + "node_modules/**/*" + } + } + }), + Environment = new BuildEnvironment + { + BuildImage = LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1 + } + }); + + var sourceOutput = new Artifact_(); + var cdkBuildOutput = new Artifact_("CdkBuildOutput"); + var lambdaBuildOutput = new Artifact_("LambdaBuildOutput"); + + new Amazon.CDK.AWS.CodePipeline.Pipeline(this, "Pipeline", new PipelineProps + { + Stages = new [] + { + new StageProps + { + StageName = "Source", + Actions = new [] + { + new CodeCommitSourceAction(new CodeCommitSourceActionProps + { + ActionName = "Source", + Repository = code, + Output = sourceOutput + }) + } + }, + new StageProps + { + StageName = "Build", + Actions = new [] + { + new CodeBuildAction(new CodeBuildActionProps + { + ActionName = "Lambda_Build", + Project = lambdaBuild, + Input = sourceOutput, + Outputs = new [] { lambdaBuildOutput } + }), + new CodeBuildAction(new CodeBuildActionProps + { + ActionName = "CDK_Build", + Project = cdkBuild, + Input = sourceOutput, + Outputs = new [] { cdkBuildOutput } + }) + } + }, + new StageProps + { + StageName = "Deploy", + Actions = new [] + { + new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps { + ActionName = "Lambda_CFN_Deploy", + TemplatePath = cdkBuildOutput.AtPath("LambdaStack.template.json"), + StackName = "LambdaDeploymentStack", + AdminPermissions = true, + ParameterOverrides = props.LambdaCode.Assign(lambdaBuildOutput.S3Location), + ExtraInputs = new [] { lambdaBuildOutput } + }) + } + } + } + }); + } + } +} +``` + +------ + +## Main Program + +Finally, we have our main AWS CDK entry point file, which contains our app\. This code is straightforward: it first instantiates the `LambdaStack` class as `LambdaStack`, which is what the AWS CDK build in the pipeline expects\. Then it instantiates the `PipelineStack` class, passing the required Lambda code from the `LambdaStack` object\. +------ +#### [ TypeScript ] + +File: `bin/pipeline.ts` + ``` #!/usr/bin/env node -// bin/pipeline.ts - import { App } from '@aws-cdk/core'; import { LambdaStack } from '../lib/lambda-stack'; import { PipelineStack } from '../lib/pipeline-stack'; @@ -234,24 +845,133 @@ new PipelineStack(app, 'PipelineDeployingLambdaStack', { app.synth(); ``` +------ +#### [ Python ] + +File: `app.py` + +``` +#!/usr/bin/env python3 + +from aws_cdk import core + +from pipeline.pipeline_stack import PipelineStack +from pipeline.lambda_stack import LambdaStack + +app = core.App() + +lambda_stack = LambdaStack(app, "LambdaStack") + +PipelineStack(app, "PipelineDeployingLambdaStack", + lambda_code=lambda_stack.lambda_code) + +app.synth() +``` + +------ +#### [ Java ] + +File: src/main/java/com/myorg/PipelineApp\.java + +``` +package com.myorg; + +import software.amazon.awscdk.core.App; + +public class PipelineApp { + public static void main(final String argv[]) { + App app = new App(); + + LambdaStack lambdaStack = new LambdaStack(app, "LambdaStack"); + new PipelineStack(app, "PipelineStack", lambdaStack.getLambdaCode()); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; + +namespace Pipeline +{ + class Program + { + static void Main(string[] args) + { + var app = new App(); + + var lambdaStack = new LambdaStack(app, "LambdaStack"); + new PipelineStack(app, "PipelineDeployingLambdaStack", new PipelineStackProps + { + LambdaCode = lambdaStack.lambdaCode + }); + + app.Synth(); + } + } +} +``` + +------ + ## Creating the Pipeline -The final steps are building the code and deploying the pipeline\. Use the following command to build the TypeScript code\. +The final steps are building the code and deploying the pipeline\. + +------ +#### [ TypeScript ] ``` npm run build ``` -Use the following command to deploy the pipeline stack\. +------ +#### [ Python ] + +No build step is necessary\. + +------ +#### [ Java ] + +``` +mvn compile +``` + +**Note** +Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. + +------ +#### [ C\# ] + +``` +dotnet build src +``` + +**Note** +Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. + +------ ``` cdk deploy PipelineDeployingLambdaStack ``` -The name, **PipelineDeployingLambdaStack**, is the name we used when we instantiated `PipelineStack` in `pipeline.ts`\. +The name, **PipelineDeployingLambdaStack**, is the name we used when we instantiated `PipelineStack`\. After the deployment finishes, you should have a three\-stage pipeline that looks something like the following\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/pipeline.jpg) -Try making a change, such as to your `LambdaStack` AWS CDK code or to your Lambda function code, and push it to the repository\. The pipeline should pick up your change, build it, and deploy it automatically, without any human intervention\. \ No newline at end of file +Try making a change, such as to your `LambdaStack` AWS CDK code or to your Lambda function code, and push it to the repository\. The pipeline should pick up your change, build it, and deploy it automatically, without any human intervention\. + +## Cleaning Up + +To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done with this exercise\. + +``` +cdk destroy +``` \ No newline at end of file diff --git a/doc_source/constructs.md b/doc_source/constructs.md index d84904ea..32d93c4d 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -12,7 +12,7 @@ This library includes constructs that represent all the resources available on A There are different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources*\. These constructs represent all of the AWS resources that are available in AWS CloudFormation\. CFN Resources are generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) on a regular basis\. They are named **Cfn***Xyz*, where *Xyz* represents the name of the resource\. For example, [s3\.CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) CFN Resource\. When you use CFN resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying resource model\. -The next level of constructs also represent AWS resources, but with a higher\-level, intent\-based API\. They provide the same functionality, but handle much of the details, boilerplate, and glue logic required by CFN constructs\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#aws_s3_Bucket) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#aws_s3_Bucket_addLifecycleRule), which adds a lifecycle rule to the bucket\. +The next level of constructs also represent AWS resources, but with a higher\-level, intent\-based API\. They provide the same functionality, but handle much of the details, boilerplate, and glue logic required by CFN constructs\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#add-wbr-lifecycle-wbr-rulerule), which adds a lifecycle rule to the bucket\. Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs-patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. @@ -20,7 +20,7 @@ For more information about how to navigate the library and discover constructs t ## Composition -The key pattern for defining higher\-level abstractions through constructs is called *composition*\. A high\-level construct can be composed from any number of lower\-level constructs, and in turn, those could be composed from even lower\-level constructs\. To enable this pattern, constructs are always defined within the scope of another construct\. This scoping pattern results in a hierarchy of constructs known as a *construct tree*\. In the AWS CDK, the root of the tree represents your entire **[AWS CDK app](https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#apps)**\. Within the app, you typically define one or more **[stacks](https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#stacks)**, which are the unit of deployment, analogous to AWS CloudFormation stacks\. Within stacks, you define resources, or other constructs that eventually contain resources\. +The key pattern for defining higher\-level abstractions through constructs is called *composition*\. A high\-level construct can be composed from any number of lower\-level constructs, and in turn, those could be composed from even lower\-level constructs\. To enable this pattern, constructs are always defined within the scope of another construct\. This scoping pattern results in a hierarchy of constructs known as a *construct tree*\. In the AWS CDK, the root of the tree represents your entire **[AWS CDK app](apps.md)**\. Within the app, you typically define one or more **[stacks](stacks.md)**, which are the unit of deployment, analogous to AWS CloudFormation stacks\. Within stacks, you define resources, or other constructs that eventually contain resources\. Composition of constructs means that you can define reusable components and share them like any other code\. For example, a central team can define a construct that implements the company's best practice for a DynamoDB table with backup, global replication, auto\-scaling, and monitoring, and share it with teams across a company or publicly\. Teams can now use this construct as they would any other library package in their favorite programming language to define their tables and comply with their team's best practices\. When the library is updated, developers can pick up the updates and enjoy any bug fixes and improvements through the workflows they already have for their other types of code\. @@ -31,11 +31,14 @@ Constructs are implemented in classes that extend the [https://docs.aws.amazon.c + **id** – An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's encapsulated within the scope's subtree and is used to allocate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. + **props** – A set of properties or keyword arguments, depending upon the supported language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. -Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/tag.html) or for specifying where the constructs will be deployed\. +Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html) or for specifying where the constructs will be deployed\. ## Apps and Stacks -We call your CDK application an *app*, which is represented by the AWS CDK class [App](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/app.html)\. The following example defines an app with a single stack that contains a single Amazon S3 bucket with versioning enabled: +We call your CDK application an *app*, which is represented by the AWS CDK class [App](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.App.html)\. The following example defines an app with a single stack that contains a single Amazon S3 bucket with versioning enabled: + +------ +#### [ TypeScript ] ``` import { App, Stack, StackProps } from '@aws-cdk/core'; @@ -55,10 +58,69 @@ const app = new App(); new HelloCdkStack(app, "HelloCdkStack"); ``` -As you can see, you need a scope within which to define your bucket\. Since resources eventually need to be deployed as part of a AWS CloudFormation stack into an *AWS *[https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#environments](https://docs.aws.amazon.com/cdk/latest/guide/apps_and_stacks.html#environments), which covers a specific AWS account and AWS region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html)\. +------ +#### [ Python ] + +``` +from aws_cdk.core import App, Stack +from aws_cdk import aws_s3 as s3 + +class HelloCdkStack(core.Stack): + + def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + s3.Bucket(self, "MyFirstBucket", versioned=True) + +app = core.App() +HelloCdkStack(app, "HelloCdkStack") +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.core.*; +import software.amazon.awscdk.services.s3.*; + +public class HelloCdkStack extends Stack { + public HelloCdkStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public HelloCdkStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + Bucket.Builder.create(this, "MyFirstBucket") + .versioned(true).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +public HelloCdkStack(Construct scope, string id, IStackProps props) : base(scope, id, props) +{ + new Bucket(this, "MyFirstBucket", new BucketProps { + Versioned = true + }); +} +``` + +------ + +As you can see, you need a scope within which to define your bucket\. Since resources eventually need to be deployed as part of a AWS CloudFormation stack into an *AWS [environment](environments.md)*, which covers a specific AWS account and AWS region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html)\. Stacks in AWS CDK apps extend the **Stack** base class, as shown in the previous example\. This is a common pattern when creating a stack within your AWS CDK app: extend the **Stack** class, define a constructor that accepts **scope**, **id**, and **props**, and invoke the base class constructor via `super` with the received **scope**, **id**, and **props**, as shown in the following example\. +------ +#### [ TypeScript ] + ``` class HelloCdkStack extends Stack { constructor(scope: App, id: string, props?: StackProps) { @@ -69,9 +131,56 @@ class HelloCdkStack extends Stack { } ``` +------ +#### [ Python ] + +``` +class HelloCdkStack(core.Stack): + + def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + # ... +``` + +------ +#### [ Java ] + +``` +public class HelloCdkStack extends Stack { + public HelloCdkStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public HelloCdkStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + // ... + } +} +``` + +------ +#### [ C\# ] + +``` +public class HelloCdkStack : Stack +{ + public HelloCdkStack(App scope, string id, StackProps props) : base(scope, id, props) + { + //... + } +} +``` + +------ + ## Using Constructs -Once you have defined a stack, you can populate it with resources\. The following example imports the [Amazon S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) module and uses it to define a new Amazon S3 bucket by creating an instance of the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class within the current scope \(`this`\) which, in our case is the `HelloCdkStack` instance\. +Once you have defined a stack, you can populate it with resources\. The following example imports the [Amazon S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) module and uses it to define a new Amazon S3 bucket by creating an instance of the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class within the current scope \(`this` or, in Python, `self`\) which, in our case is the `HelloCdkStack` instance\. + +------ +#### [ TypeScript ] ``` import s3 = require('@aws-cdk/aws-s3'); @@ -82,14 +191,62 @@ new s3.Bucket(this, 'MyFirstBucket', { }); ``` +------ +#### [ Python ] + +``` +from aws_cdk import aws_s3 as s3 + +# "self" is HelloCdkStack +s3.Bucket(self, "MyFirstBucket", versioned=True) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.s3.*; + +public class HelloCdkStack extends Stack { + public HelloCdkStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public HelloCdkStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + Bucket.Builder.create(this, "MyFirstBucket") + .versioned(true).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.S3; + +// "this" is HelloCdkStack +new Bucket(this, "MyFirstBucket", new BucketProps +{ + Versioned = true +}); +``` + +------ + The [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) includes constructs that represent many AWS resources\. **Note** -`MyFirstBucket` is not the name of the bucket that AWS CloudFormation creates\. It is a logical identifier given to the new construct\. See [Physical Names](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/resource.html#core_Resource_physicalName) for details\. +`MyFirstBucket` is not the name of the bucket that AWS CloudFormation creates\. It is a logical identifier given to the new construct\. See [Physical Names](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Resource.html#physicalname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) for details\. ## Configuration -Most constructs accept `props` as their third initialization argument\. This is a name/value collection that defines the construct's configuration\. The following example defines a bucket with AWS Key Management Service \(AWS KMS\) encryption and static website hosting enabled\. Since it does not explicitly specify an encryption key, the `Bucket` construct defines a new `kms.Key` and associates it with the bucket\. +Most constructs accept `props` as their third argument \(or in Python, keyword arguments\), a name/value collection that defines the construct's configuration\. The following example defines a bucket with AWS Key Management Service \(AWS KMS\) encryption and static website hosting enabled\. Since it does not explicitly specify an encryption key, the `Bucket` construct defines a new `kms.Key` and associates it with the bucket\. + +------ +#### [ TypeScript ] ``` new s3.Bucket(this, 'MyEncryptedBucket', { @@ -98,26 +255,91 @@ new s3.Bucket(this, 'MyEncryptedBucket', { }); ``` +------ +#### [ Python ] + +``` +s3.Bucket(self, "MyEncryptedBucket", encryption=s3.BucketEncryption.KMS, + website_index_document="index.html") +``` + +------ +#### [ Java ] + +``` +Bucket.Builder.create(this, "MyEncryptedBucket") + .encryption(BucketEncryption.KMS_MANAGED) + .websiteIndexDocument("index.html").build(); +``` + +------ +#### [ C\# ] + +``` +new Bucket(this, "MyEncryptedBucket", new BucketProps +{ + Encryption = BucketEncryption.KMS_MANAGED, + WebsiteIndexDocument = "index.html" +}); +``` + +------ + AWS constructs are designed around the concept of "sensible defaults\." Most constructs have a minimal required configuration, enabling you to quickly get started while also providing full control over the configuration when you need it\. ## Interacting with Constructs -Constructs are classes that extend the base [Construct](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/construct.html) class\. After you instantiate a construct, the construct object exposes a set of methods and properties that enable you to interact with the construct and pass it around as a reference to other parts of the system\. The AWS CDK framework doesn't put any restrictions on the APIs of constructs; authors can define any API they wish\. However, the AWS constructs that are included with the AWS Construct Library, such as `s3.Bucket`, follow guidelines and common patterns in order to provide a consistent experience across all AWS resources\. +Constructs are classes that extend the base [Construct](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html) class\. After you instantiate a construct, the construct object exposes a set of methods and properties that enable you to interact with the construct and pass it around as a reference to other parts of the system\. The AWS CDK framework doesn't put any restrictions on the APIs of constructs; authors can define any API they wish\. However, the AWS constructs that are included with the AWS Construct Library, such as `s3.Bucket`, follow guidelines and common patterns in order to provide a consistent experience across all AWS resources\. For example, almost all AWS constructs have a set of [grant](permissions.md#permissions_grants) methods that you can use to grant AWS Identity and Access Management \(IAM\) permissions on that construct to a principal\. The following example grants the IAM group `data-science` permission to read from the Amazon S3 bucket `raw-data`\. +------ +#### [ TypeScript ] + ``` const rawData = new s3.Bucket(this, 'raw-data'); const dataScience = new iam.Group(this, 'data-science'); rawData.grantRead(dataScience); ``` +------ +#### [ Python ] + +``` +raw_data = s3.Bucket(self, 'raw-data') +data_science = iam.Group(self, 'data-science') +raw_data.grant_read(data_science) +``` + +------ +#### [ Java ] + +``` +Bucket rawData = new Bucket(this, "raw-data"); +Group dataScience = new Group(this, "data-science"); +rawData.grantRead(dataScience); +``` + +------ +#### [ C\# ] + +``` +var rawData = new Bucket(this, "raw-data"); +var dataScience = new Group(this, "data-science"); +rawData.GrantRead(dataScience); +``` + +------ + Another common pattern is for AWS constructs to set one of the resource's attributes, such as its Amazon Resource Name \(ARN\), name, or URL from data supplied elsewhere\. For example, the following code defines an AWS Lambda function and associates it with an Amazon Simple Queue Service \(Amazon SQS\) queue through the queue's URL in an environment variable\. +------ +#### [ TypeScript ] + ``` const jobsQueue = new sqs.Queue(this, 'jobs'); const createJobLambda = new lambda.Function(this, 'create-job', { - runtime: lambda.Runtime.NODEJS_8_10, + runtime: lambda.Runtime.NODEJS_10_X, handler: 'index.handler', code: lambda.Code.fromAsset('./create-job-lambda-code'), environment: { @@ -126,16 +348,66 @@ const createJobLambda = new lambda.Function(this, 'create-job', { }); ``` +------ +#### [ Python ] + +``` +jobs_queue = sqs.Queue(self, "jobs") + create_job_lambda = lambda_.Function(self, "create-job", + runtime=lambda_.Runtime.NODEJS_10_X, + handler="index.handler", + code=lambda_.Code.from_asset("./create-job-lambda-code"), + environment=dict( + QUEUE_URL=jobs_queue.queue_url + ) + ) +``` + +------ +#### [ Java ] + +``` +final Queue jobsQueue = new Queue(this, "jobs"); +Function createJobLambda = Function.Builder.create(this, "create-job") + .handler("index.handler") + .code(Code.fromAsset("./create-job-lambda-code")) + .environment(new HashMap() {{ + put("QUEUE_URL", jobsQueue.getQueueUrl()); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +var jobsQueue = new Queue(this, "jobs"); +var createJobLambda = new Function(this, "create-job", new FunctionProps +{ + Runtime = Runtime.NODEJS_10_X, + Handler = "index.handler", + Code = Code.FromAsset(@".\create-job-lambda-code"), + Environment = new Dictionary + { + ["QUEUE_URL"] = jobsQueue.QueueUrl + } +}); +``` + +------ + For information about the most common API patterns in the AWS Construct Library, see [Resources](https://docs.aws.amazon.com/cdk/latest/guide/resources.html)\. ## Authoring Constructs In addition to using existing constructs like `s3.Bucket`, you can also author your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct imported from a third\-party library that someone published on npm or Maven or PyPI—or to your company's internal package repository\. -To declare a new construct, create a class that extends the [Construct](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/construct.html) base class, then follow the pattern for initializer arguments\. +To declare a new construct, create a class that extends the [Construct](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html) base class, then follow the pattern for initializer arguments\. For example, you could declare a construct that represents an Amazon S3 bucket which sends an Amazon Simple Notification Service \(Amazon SNS\) notification every time someone uploads a file into it: +------ +#### [ TypeScript ] + ``` export interface NotifyingBucketProps { prefix?: string; @@ -151,19 +423,146 @@ export class NotifyingBucket extends Construct { } ``` -The `NotifyingBucket` constructor has the same signature as the base `Construct` class: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. This means that you could define an instance of this construct in your app without `props`, for example: +------ +#### [ Python ] + +``` +class NotifyingBucket(core.Construct): + + def __init__(self, scope: core.Construct, id: str, *, prefix=None, **kwargs): + super().__init__(scope, id, **kwargs) + bucket = s3.Bucket(self, "bucket") + topic = sns.Topic(self, "topic") + bucket.add_object_created_notification(topic, + s3.NotificationKeyFilter(prefix=prefix)) +``` + +------ +#### [ Java ] + +``` +public class NotifyingBucket extends Bucket { + + public NotifyingBucket(final Construct scope, final String id) { + this(scope, id, null, null); + } + + public NotifyingBucket(final Construct scope, final String id, final BucketProps props) { + this(scope, id, props, null); + } + + public NotifyingBucket(final Construct scope, final String id, final String prefix) { + this(scope, id, null, prefix); + } + + public NotifyingBucket(final Construct scope, final String id, final BucketProps props, final String prefix) { + super(scope, id, props); + + Bucket bucket = new Bucket(this, "bucket"); + Topic topic = new Topic(this, "topic"); + if (prefix != null) + bucket.addObjectCreatedNotification(new SnsDestination(topic), + NotificationKeyFilter.builder().prefix(prefix).build()); + } +} +``` + +------ +#### [ C\# ] + +``` +public class NotifyingBucketProps : BucketProps +{ + public string Prefix = null; +} + +public class NotifyingBucket : Construct +{ + public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id, props) + { + var bucket = new Bucket(this, "bucket"); + var topic = new Topic(this, "topic"); + bucket.AddObjectCreatedNotification(new SnsDestination(topic), new NotificationKeyFilter + { + Prefix = props?.Prefix + }); + } +} +``` + +------ + +The `NotifyingBucket` constructors have signature compatible with the base `Construct` class: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. This means that you could define an instance of this construct in your app without `props`, for example: + +------ +#### [ TypeScript ] ``` new NotifyingBucket(this, 'MyNotifyingBucket'); ``` -Or you could use `props` to specify the path prefix to filter on, for example: +------ +#### [ Python ] + +``` +NotifyingBucket(this, "MyNotifyingBucket") +``` + +------ +#### [ Java ] + +``` +new NotifyingBucket(this, "MyNotifyingBucket"); +``` + +------ +#### [ C\# ] + +``` +new NotifyingBucket(this, "MyNotifyingBucket"); +``` + +------ + +Or you could use `props` \(in Java, an additional parameter\) to specify the path prefix to filter on, for example: + +------ +#### [ TypeScript ] ``` new NotifyingBucket(this, 'MyNotifyingBucket', { prefix: 'images/' }); ``` -Typically, you would also want to expose some properties or methods from your constructs\. For example, it's not very useful to have a topic hidden behind your construct, because it wouldn't be possible to subscribe to it\. Adding a `topic` property allows consumers to access the inner topic, as shown in the following example: +------ +#### [ Python ] + +``` +NotifyingBucket(self, "MyNotifyingBucket", prefix="images/") +``` + +------ +#### [ Java ] + +``` +new NotifyingBucket(this, "MyNotifyingBucket", "/images"); +``` + +------ +#### [ C\# ] + +``` +new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketProps +{ + Prefix = "/images" +}); +``` + +------ + +Typically, you would also want to expose some properties or methods on your constructs\. For example, it's not very useful to have a topic hidden behind your construct, because it wouldn't be possible for users of your construct to subscribe to it\. Adding a `topic` property allows consumers to access the inner topic, as shown in the following example: + +------ +#### [ TypeScript ] ``` export class NotifyingBucket extends Construct { @@ -178,10 +577,112 @@ export class NotifyingBucket extends Construct { } ``` +------ +#### [ Python ] + +``` +class NotifyingBucket(core.Construct): + + def __init__(self, scope: core.Construct, id: str, *, prefix=None, **kwargs): + super().__init__(scope, id, **kwargs) + bucket = s3.Bucket(self, "bucket") + self.topic = sns.Topic(self, "topic") + bucket.add_object_created_notification(self.topic, + s3.NotificationKeyFilter(prefix=prefix)) +``` + +------ +#### [ Java ] + +``` +public class NotifyingBucket extends Bucket { + + public Topic topic = null; + + public NotifyingBucket(final Construct scope, final String id) { + this(scope, id, null, null); + } + + public NotifyingBucket(final Construct scope, final String id, final BucketProps props) { + this(scope, id, props, null); + } + + public NotifyingBucket(final Construct scope, final String id, final String prefix) { + this(scope, id, null, prefix); + } + + public NotifyingBucket(final Construct scope, final String id, final BucketProps props, final String prefix) { + super(scope, id, props); + + Bucket bucket = new Bucket(this, "bucket"); + topic = new Topic(this, "topic"); + if (prefix != null) + bucket.addObjectCreatedNotification(new SnsDestination(topic), + NotificationKeyFilter.builder().prefix(prefix).build()); + } +} +``` + +------ +#### [ C\# ] + +``` +public class NotifyingBucket : Construct +{ + public readonly Topic topic; + + public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id) + { + var bucket = new Bucket(this, "bucket"); + topic = new Topic(this, "topic"); + bucket.AddObjectCreatedNotification(new SnsDestination(topic), new NotificationKeyFilter + { + Prefix = props?.Prefix + }); + } +} +``` + +------ + Now, consumers can subscribe to the topic, for example: +------ +#### [ TypeScript ] + ``` const queue = new sqs.Queue(this, 'NewImagesQueue'); const images = new NotifyingBucket(this, 'Images'); -images.topic.addSubscription(new sns_sub.QueueSubscription(queue)); -``` \ No newline at end of file +images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); +``` + +------ +#### [ Python ] + +``` +queue = qs.Queue(this, "NewImagesQueue") +images = NotifyingBucket(this, prefix="Images") +images.topic.add_subscription(sns_sub.SqsSubscription(queue)) +``` + +------ +#### [ Java ] + +``` +NotifyingBucket images = new NotifyingBucket(this, "MyNotifyingBucket", "/images"); +images.topic.addSubscription(new SqsSubscription(queue)); +``` + +------ +#### [ C\# ] + +``` +var queue = new Queue(this, "NewImagesQueue"); +var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketProps +{ + Prefix = "/images" +}); +images.topic.AddSubscription(new SqsSubscription(queue)); +``` + +------ \ No newline at end of file diff --git a/doc_source/context.md b/doc_source/context.md index 726a1f1e..42992841 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -30,10 +30,13 @@ Gets the hosted zones in your account\. Gets the supported Availability Zones\. [StringParameter\.valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) -Gets a value from the current Region's AWS Systems Manager Parameter Store\. +Gets a value from the current Region's Amazon EC2 Systems Manager Parameter Store\. [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options) -Gets the existing VPCs in your accounts\. +Gets the existing Amazon Virtual Private Clouds in your accounts\. + +[LookupMachineImage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.LookupMachineImage.html) +Looks up a machine image for use with a NAT instance in an Amazon Virtual Private Cloud\. If a given context information isn't available, the AWS CDK app notifies the AWS CDK CLI that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. @@ -89,10 +92,14 @@ $ cdk context --clear Below is an example of importing an existing Amazon VPC using AWS CDK context\. +------ +#### [ TypeScript ] + ``` import cdk = require('@aws-cdk/core'); import ec2 = require('@aws-cdk/aws-ec2'); -export class ExistsvpcStack extends cdk.Stack { + +export class ExistsVpcStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { @@ -112,6 +119,92 @@ export class ExistsvpcStack extends cdk.Stack { } ``` +------ +#### [ Python ] + +``` +import aws_cdk.core as cdk +import aws_cdk.aws_ec2 as ec2 + +class ExistsVpcStack(cdk.Stack): + + def __init__(scope: cdk.Construct, id: str, **kwargs): + + super().__init__(scope, id, **kwargs) + + vpcid = self.node.try_get_context("vpcid"); + vpc = ec2.Vpc.from_lookup(this, "VPC", vpc_id=vpcid) + + pubsubnets = vpc.select_subnets(subnetType=ec2.SubnetType.PUBLIC); + + cdk.CfnOutput(this, "publicsubnets", + value=pubsubnets.subnet_ids.to_string()) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.core.CfnOutput; + +import software.amazon.awscdk.services.ec2.Vpc; +import software.amazon.awscdk.services.ec2.VpcLookupOptions; +import software.amazon.awscdk.services.ec2.SelectedSubnets; +import software.amazon.awscdk.services.ec2.SubnetSelection; +import software.amazon.awscdk.services.ec2.SubnetType; + +public class ExistsVpcStack extends Stack { + public ExistsVpcStack(App context, String id) { + this(context, id, null); + } + + public ExistsVpcStack(App context, String id, StackProps props) { + super(context, id, props); + + String vpcId = (String)this.getNode().tryGetContext("vpcid"); + Vpc vpc = (Vpc)Vpc.fromLookup(this, "VPC", VpcLookupOptions.builder() + .vpcId(vpcId).build()); + + SelectedSubnets pubSubNets = vpc.selectSubnets(SubnetSelection.builder() + .subnetType(SubnetType.PUBLIC).build()); + + CfnOutput.Builder.create(this, "publicsubnets") + .value(pubSubNets.getSubnetIds().toString()).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.EC2; + +class ExistsVpcStack : Stack +{ + public ExistsVpcStack(App scope, string id, StackProps props) : base(scope, id, props) + { + var vpcId = (string)this.Node.TryGetContext("vpcid"); + var vpc = Vpc.FromLookup(this, "VPC", new VpcLookupOptions + { + VpcId = vpcId + }); + + SelectedSubnets pubSubNets = vpc.SelectSubnets([new SubnetSelection + { + SubnetType = SubnetType.PUBLIC + }]); + + new CfnOutput(this, "publicsubnets", new CfnOutputProps { + Value = pubSubNets.SubnetIds.ToString() + }); + } +} +``` + +------ + You can use cdk diff to see the effects of passing in a context value on the command line: ``` diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 75082b26..2d692464 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -1,8 +1,8 @@ # Document History for the AWS CDK Developer Guide This document is based on the following release of the AWS Cloud Development Kit \(AWS CDK\)\. -+ **API version: 1\.8\.0** -+ **Latest documentation update:** September 17, 2019 ++ **API version: 1\.18\.0** ++ **Latest documentation update:** November 25, 2019 See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the AWS CDK releases\. @@ -11,6 +11,9 @@ The table below represents significant milestones\. We fix errors and improve co | Change | Description | Date | | --- |--- |--- | +| [Version 1\.18\.0](#doc-history) | Add Java code snippets throughout\. Designate Java and C\# bindings stable\. | November 25, 2019 | +| [Version 1\.17\.0](#doc-history) | Add C\# code snippets throughout\. | November 19, 2019 | +| [Version 1\.16\.0](#doc-history) | Add Python code snippets throughout\. Add Troubleshooting and Testing topics\. | November 14, 2019 | | [Version 1\.8\.0](#doc-history) | Updates to reflect improvements to ECS Patterns module\. | September 17, 2019 | | [Version 1\.3\.0](#doc-history) | Update tagging topic to use new API\. | August 13, 2019 | | [Version 1\.0\.0](#doc-history) | The AWS CDK Developer Guide is released\. | July 11, 2019 | \ No newline at end of file diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 88150586..ba27fb21 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -31,19 +31,91 @@ See [ECS](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html) f Let's start by creating a directory to hold the AWS CDK code, and then creating a AWS CDK app in that directory\. +------ +#### [ TypeScript ] + ``` mkdir MyEcsConstruct cd MyEcsConstruct cdk init --language typescript ``` -Build the app and confirm that it creates an empty stack\. +------ +#### [ Python ] + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language python +source .env/bin/activate || "on Windows, use: .env\Scripts\activate.bat" +pip install -r requirements.txt +``` + +------ +#### [ Java ] + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language java +``` + +You may now import the Maven project into your IDE\. + +------ +#### [ C\# ] + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language csharp +``` + +You may now open `src/MyEcsConstruct.sln` in Visual Studio\./ + +------ + +Build and run the app and confirm that it creates an empty stack\. + +------ +#### [ TypeScript ] ``` npm run build cdk synth ``` +------ +#### [ Python ] + +``` +cdk synth +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk synth +``` + +**Note** +Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. + +------ +#### [ C\# ] + +``` +dotnet build src +cdk synth +``` + +**Note** +Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. + +------ + You should see a stack like the following, where *CDK\-VERSION* is the version of the CDK and *NODE\-VERSION* is the version of Node\.js\. \(Your output may differ slightly from what's shown here\.\) ``` @@ -56,21 +128,64 @@ Resources: ## Add the Amazon EC2 and Amazon ECS Packages -Install support for Amazon EC2 and Amazon ECS\. +Install the AWS construct library modules for Amazon EC2 and Amazon ECS\. + +------ +#### [ TypeScript ] ``` npm install @aws-cdk/aws-ec2 @aws-cdk/aws-ecs @aws-cdk/aws-ecs-patterns ``` +------ +#### [ Python ] + +``` +pip install aws_cdk.aws_ec2 aws_cdk.aws_ecs aws_cdk.aws_ecs_patterns +``` + +------ +#### [ Java ] + +Using your IDE's Maven integration \(e\.g\., in Eclipse, right\-click your project and choose **Maven** > **Add Dependency**\), install the following artifacts from the group `software.amazon.awscdk`: + +``` +ec2 +ecs +ecs-patterns +``` + +------ +#### [ C\# ] + +Choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio and add the following packages\. + +``` +Amazon.CDK.AWS.EC2 +Amazon.CDK.AWS.ECS +AMazon.CDK.AWS.ECS.Patterns +``` + +**Tip** +If you don't see these packages in the **Browse** tab of the **Manage Packages for Solution** page, make sure the **Include prerelease** checkbox is ticked\. +For a better experience, also add the `Amazon.Jsii.Analyzers` package to provide compile\-time checks for missing required properties\. + +------ + ## Create a Fargate Service There are two different ways to run your container tasks with Amazon ECS: + Use the `Fargate` launch type, where Amazon ECS manages the physical machines that your containers are running on for you\. + Use the `EC2` launch type, where you do the managing, such as specifying automatic scaling\. -The following tutorial creates a Fargate service running on an ECS cluster fronted by an internet\-facing Application load Balancer\. +For this example, we'll create a Fargate service running on an ECS cluster fronted by an internet\-facing Application Load Balancer\. -Add the following `import` statements to `lib/my_ecs_construct-stack.ts`\. +Add the following AWS Construct Library module imports to the indicated file\. + +------ +#### [ TypeScript ] + +File: `lib/my_ecs_construct-stack.ts` ``` import ec2 = require("@aws-cdk/aws-ec2"); @@ -78,8 +193,45 @@ import ecs = require("@aws-cdk/aws-ecs"); import ecs_patterns = require("@aws-cdk/aws-ecs-patterns"); ``` +------ +#### [ Python ] + +File: `my_ecs_construct/my_ecs_construct_stack.py` + +``` +from aws_cdk import (core, aws_ec2 as ec2, aws_ecs as ecs, + aws_ecs_patterns as ecs_patterns) +``` + +------ +#### [ Java ] + +File: `src/main/java/com/myorg/MyEcsConstructStack.java` + +``` +import software.amazon.awscdk.services.ec2.*; +import software.amazon.awscdk.services.ecs.*; +import software.amazon.awscdk.services.ecs.patterns.*; +``` + +------ +#### [ C\# ] + +File: `src/MyEcsConstruct/MyEcsConstructStack.cs` + +``` +using Amazon.CDK.AWS.EC2; +using Amazon.CDK.AWS.ECS; +using Amazon.CDK.AWS.ECS.Patterns; +``` + +------ + Replace the comment at the end of the constructor with the following code\. +------ +#### [ TypeScript ] + ``` const vpc = new ec2.Vpc(this, "MyVpc", { maxAzs: 3 // Default is all AZs in region @@ -94,18 +246,127 @@ Replace the comment at the end of the constructor with the following code\. cluster: cluster, // Required cpu: 512, // Default is 256 desiredCount: 6, // Default is 1 - image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"), // Required + taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, memoryLimitMiB: 2048, // Default is 512 publicLoadBalancer: true // Default is false }); ``` +------ +#### [ Python ] + +``` + vpc = ec2.Vpc(self, "MyVpc", max_azs=3) # default is all AZs in region + + cluster = ecs.Cluster(self, "MyCluster", vpc=vpc) + + ecs_patterns.ApplicationLoadBalancedFargateService(self, "MyFargateService", + cluster=cluster, # Required + cpu=512, # Default is 256 + desired_count=6, # Default is 1 + task_image_options=ecs_patterns.ApplicationLoadBalancedTaskImageOptions( + image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")), + memory_limit_mib=2048, # Default is 512 + public_load_balancer=True) # Default is False +``` + +------ +#### [ Java ] + +``` + Vpc vpc = Vpc.Builder.create(this, "MyVpc") + .maxAzs(3) // Default is all AZs in region + .build(); + + Cluster cluster = Cluster.Builder.create(this, "MyCluster") + .vpc(vpc).build(); + + // Create a load-balanced Fargate service and make it public + ApplicationLoadBalancedFargateService.Builder.create(this, "MyFargateService") + .cluster(cluster) // Required + .cpu(512) // Default is 256 + .desiredCount(6) // Default is 1 + .taskImageOptions( + ApplicationLoadBalancedTaskImageOptions.builder() + .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample")) + .build()) + .memoryLimitMiB(2048) // Default is 512 + .publicLoadBalancer(true) // Default is false + .build(); +``` + +------ +#### [ C\# ] + +``` + var vpc = new Vpc(this, "MyVpc", new VpcProps + { + MaxAzs = 3 // Default is all AZs in region + }); + + var cluster = new Cluster(this, "MyCluster", new ClusterProps + { + Vpc = vpc + }); + + // Create a load-balanced Fargate service and make it public + new ApplicationLoadBalancedFargateService(this, "MyFargateService", + new ApplicationLoadBalancedFargateServiceProps + { + Cluster = cluster, // Required + DesiredCount = 6, // Default is 1 + TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions + { + Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample") + }, + MemoryLimitMiB = 2048, // Default is 256 + PublicLoadBalancer = true // Default is false + } + ); +``` + +------ + Save it and make sure it builds and creates a stack\. +------ +#### [ TypeScript ] + ``` npm run build -cdk synth +cdk deploy +``` + +------ +#### [ Python ] + +``` +cdk deploy +``` + +------ +#### [ Java ] + ``` +mvn compile +cdk deploy +``` + +**Note** +Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. + +------ +#### [ C\# ] + +``` +dotnet build src +cdk deploy +``` + +**Note** +Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. + +------ The stack is hundreds of lines, so we don't show it here\. The stack should contain one default instance, a private subnet and a public subnet for the three Availability Zones, and a security group\. @@ -117,4 +378,12 @@ cdk deploy AWS CloudFormation displays information about the dozens of steps that it takes as it deploys your app\. -That's how easy it is to create a Fargate service to run a Docker image\. \ No newline at end of file +That's how easy it is to create a Fargate service to run a Docker image\. + +## Clean Up + +To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done with this exercise\. + +``` +cdk destroy +``` \ No newline at end of file diff --git a/doc_source/environments.md b/doc_source/environments.md index c023de57..0350878d 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -1,31 +1,338 @@ # Environments -Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and AWS Region into which this stack needs to be deployed\. +Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and AWS Region into which the stack is intended to be deployed\. -By default, if you don't specify an environment when you define a stack, the stack is said to be environment agnostic\. This means that AWS CloudFormation templates which are synthesized from this stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availablityZones`\. When using cdk deploy to deploy environment\-agnostic stacks, the CLI uses the default CLI environment configuration to determine where to deploy this stack\. The AWS CDK CLI follows a protocol similar to the AWS CLI for determining which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Command Line Interface \(cdk\)](tools.md#cli) for details\. +If you don't specify an environment when you define a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availablityZones` \(Python: `availability_zones`\)\. -For production systems, we recommend that you explicitly specify the environment for each stack in your app using the `env` property\. The following example specifies two environments used in two different stacks\. +**Note** +In an environment\-agnostic stack, any constructs that use availability zones will see two of them\. This allows the stack to be deployed to almost any region, since nearly all regions have at least two availability zones\. The only exception is Osaka \(`ap-northeast-3`\), which has one\. + +When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Command Line Interface \(cdk\)](tools.md#cli) for details\. + +For production stacks, we recommend that you explicitly specify the environment for each stack in your app using the `env` property\. The following example specifies different environments for its two different stacks\. + +------ +#### [ TypeScript ] ``` const envEU = { account: '2383838383', region: 'eu-west-1' }; const envUSA = { account: '8373873873', region: 'us-west-2' }; -new MyFirstStack(this, 'first-stack-us', { env: envUSA, encryption: false }); -new MyFirstStack(this, 'first-stack-eu', { env: envEU, encryption: true }); +new MyFirstStack(app, 'first-stack-us', { env: envUSA, encryption: false }); +new MyFirstStack(app, 'first-stack-eu', { env: envEU, encryption: true }); +``` + +------ +#### [ Python ] + ``` +env_EU = core.Environment(account="8373873873", region="eu-west-1") +env_USA = core.Environment(account="2383838383", region="us-west-2") + +MyFirstStack(app, "first-stack-us", env=env_USA, encryption=False) +MyFirstStack(app, "first-stack-eu", env=env_EU, encryption=True) +``` + +------ +#### [ Java ] + +``` +public class MyApp { + + // Helper method to build an environment + static Environment makeEnv(String account, String region) { + return Environment.builder() + .account(account) + .region(region) + .build(); + } + + public static void main(final String argv[]) { + App app = new App(); + + Environment envEU = makeEnv("8373873873", "eu-west-1"); + Environment envUSA = makeEnv("2383838383", "us-west-2"); + + new MyFirstStack(app, "first-stack-us", StackProps.builder() + .env(envUSA).build()); + new MyFirstStack(app, "first-stack-eu", StackProps.builder() + .env(envEU).build()); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +``` +Amazon.CDK.Environment makeEnv(string account, string region) +{ + return new Amazon.CDK.Environment + { + Account = account, + Region = region + }; +} + +var envEU = makeEnv(account: "8373873873", region: "eu-west-1"); +var envUSA = makeEnv(account: "2383838383", region: "us-west-2"); + +new MyFirstStack(app, "first-stack-us", new StackProps { Env=envUSA }); +new MyFirstStack(app, "first-stack-eu", new StackProps { Env=envEU }); +``` + +------ + +When you hard\-code the target account and region as above, the stack will always be deployed to that specific account and region\. To make the stack deployable to a different target, but to determine the target at synthesis time, your stack can use two environment variables provided by the AWS CDK CLI: `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. These variables are set based on the AWS profile specified using the \-\-profile option, or the default AWS profile if you don't specify one\. + +The following code fragment shows how to access the account and region passed from the AWS CDK CLI in your stack\. + +------ +#### [ TypeScript ] + +Access environment variables via the `process` object\. -By explicitly specifying the target account and Region, the AWS CDK CLI ensures that you only deploy this stack to the desired target and deployment if the configured credentials are not aligned\. To deploy stacks to multiple accounts or different Regions, you must set the correct credentials or Region each time you run a cdk deploy *STACK* command\. +**Note** +TypeScript users must install the DefinitelyTyped NodeJS module with NPM to be able to use `process`\. `cdk init` now installs this module for you, but if you are working with a project created before it was added, or didn't set up your project using `cdk init`, install it manually\. -You can use the `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION` environment variables to explicitly associate a stack with the default CLI environment, as shown in the following example\. This is a common practice for development stacks that you want to include in your app, and have each developer use their own account\. +``` +npm install @types/node +``` ``` -new MyDevStack(this, 'dev', { +new MyDevStack(app, 'dev', { env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION - } -}); +}}); ``` -**Note** -There is a distinction between not specifying the `env` property at all and specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. This means that constructs that are defined in such a stack cannot make assumptions about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-ec2/vpc.html#aws_ec2_Vpc_fromLookup), which need to query your AWS account\. When specifying `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, you tell the stack that it will be deployed in the account and Region as configured in the CLI at the time of synthesis\. This means that the synthesized template could be different on different machines, users, or sessions\. This might be acceptable for use cases like development stacks, but would be an anti\-pattern for production stacks\. \ No newline at end of file +------ +#### [ Python ] + +Use the `os` module's `environ` dictonary to access environment variables\. + +``` +import os +MyDevStack(app, "dev", env=core.Environment( + account=os.environ["CDK_DEFAULT_ACCOUNT"], + region=os.environ["CDK_DEFAULT_REGION"])) +``` + +------ +#### [ Java ] + +Use `System.getenv()` to get the value of an environment variable\. + +``` +public class MyApp { + + // Helper method to build an environment + static Environment makeEnv(String account, String region) { + account = (account == null) ? System.getenv("CDK_DEFAULT_ACCOUNT") : account; + region = (region == null) ? System.getenv("CDK_DEFAULT_REGION") : region; + + return Environment.builder() + .account(account) + .region(region) + .build(); + } + + public static void main(final String argv[]) { + App app = new App(); + + Environment envEU = makeEnv(null, null); + Environment envUSA = makeEnv(null, null); + + new MyDevStack(app, "first-stack-us", StackProps.builder() + .env(envUSA).build()); + new MyDevStack(app, "first-stack-eu", StackProps.builder() + .env(envEU).build()); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +Use `System.Environment.GetEnvironmentVariable()` to get the value of an environment variable\. + +``` +Amazon.CDK.Environment makeEnv(string account=null, string region=null) +{ + return new Amazon.CDK.Environment + { + Account = account ?? System.Environment.GetEnvironmentVariable("CDK_DEFAULT_ACCOUNT"), + Region = region ?? System.Environment.GetEnvironmentVariable("CDK_DEFAULT_REGION") + }; +} + +new MyDevStack(app, "dev", new StackProps { Env = makeEnv() }); +``` + +------ + +The AWS CDK distinguishes between not specifying the `env` property at all and specifying it using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. Constructs that are defined in such a stack cannot use any information about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options) \(Python: `from_lookup`\), which need to query your AWS account\. + +When you pass in your environment using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, the stack will be deployed in the account and Region determined by the AWS CDK CLI at the time of synthesis\. This allows environment\-dependent code to work, but it also means that the synthesized template could be different based on the machine, user, or session under which it is synthesized\. This behavior is often acceptable or even desirable during development, but it would probably be an anti\-pattern for production use\. + +You can set `env` however you like, using any valid expression\. For example, you might write your stack to support two additional environment variables to let you override the account and region at synthesis time\. We'll call these `CDK_DEPLOY_ACCOUNT` and `CDK_DEPLOY_REGION` here, but you could name them anything you like, as they are not set by the AWS CDK\. In the following stack's environment, we use our alternative environment variables if they're set, falling back to the default environment provided by the AWS CDK if they are not\. + +------ +#### [ TypeScript ] + +``` +new MyDevStack(app, 'dev', { + env: { + account: process.env.CDK_DEPLOY_ACCOUNT || process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEPLOY_REGION || process.env.CDK_DEFAULT_REGION +}}); +``` + +------ +#### [ Python ] + +``` +MyDevStack(app, "dev", env=core.Environment( + account=os.environ.get("CDK_DEPLOY_ACCOUNT", os.environ["CDK_DEFAULT_ACCOUNT"]) + region=os.environ.get("CDK_DEPLOY_REGION", os.environ["CDK_DEFAULT_REGION"]) +``` + +------ +#### [ Java ] + +``` +public class MyApp { + + // Helper method to build an environment + static Environment makeEnv(String account, String region) { + account = (account == null) ? System.getenv("CDK_DEPLOY_ACCOUNT") : account; + region = (region == null) ? System.getenv("CDK_DEPLOY_REGION") : region; + account = (account == null) ? System.getenv("CDK_DEFAULT_ACCOUNT") : account; + region = (region == null) ? System.getenv("CDK_DEFAULT_REGION") : region; + + return Environment.builder() + .account(account) + .region(region) + .build(); + } + + public static void main(final String argv[]) { + App app = new App(); + + Environment envEU = makeEnv(null, null); + Environment envUSA = makeEnv(null, null); + + new MyDevStack(app, "first-stack-us", StackProps.builder() + .env(envUSA).build()); + new MyDevStack(app, "first-stack-eu", StackProps.builder() + .env(envEU).build()); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +``` +Amazon.CDK.Environment makeEnv(string account=null, string region=null) +{ + return new Amazon.CDK.Environment + { + Account = account ?? + System.Environment.GetEnvironmentVariable("CDK_DEPLOY_ACCOUNT") ?? + System.Environment.GetEnvironmentVariable("CDK_DEFAULT_ACCOUNT"), + Region = region ?? + System.Environment.GetEnvironmentVariable("CDK_DEPLOY_REGION") ?? + System.Environment.GetEnvironmentVariable("CDK_DEFAULT_REGION") + }; +} + +new MyDevStack(app, "dev", new StackProps { Env = makeEnv() }); +``` + +------ + +With your stack's environment declared this way, you can now write a short script or batch file like the following to set the variables from command line arguments, then call `cdk deploy`\. + +------ +#### [ Linux/Mac OS X ] + +``` +#!bash +# cdk-deploy-to.sh +CDK_DEPLOY_ACCOUNT=$1 +shift +CDK_DEPLOY_REGION=$1 +shift +cdk deploy "$@" +``` + +------ +#### [ Windows ] + +``` +@echo off +rem cdk-deploy-to.bat +set CDK_DEPLOY_ACCOUNT=%1 +shift +set CDK_DEPLOY_REGION=%1 +shift +cdk deploy %* +``` + +------ + +Then you can write additional scripts that call that script to deploy to specific environments \(even multiple environments per script\): + +------ +#### [ Linux/Mac OS X ] + +``` +#!bash +# cdk-deploy-to-test.sh +bash cdk-deploy-to.sh 123457689 us-east-1 "$@" +``` + +------ +#### [ Windows ] + +``` +@echo off +rem cdk-deploy-to-test.bat +cdk-deploy-to 135792469 us-east-1 %* +``` + +------ + +When deploying to multiple environments, consider whether you want to continue deploying to other anvironments after a deployment fails\. The following example avoids deploying to the second production environment if the first doesn't succeed\. + +------ +#### [ Linux/Mac OS X ] + +``` +#!bash +# cdk-deploy-to-prod.sh +bash cdk-deploy-to.sh 135792468 us-west-1 "$@" || exit +bash cdk-deploy-to.sh 246813579 eu-west-1 "$@" +``` + +------ +#### [ Windows ] + +``` +@echo off +rem cdk-deploy-to-prod.bat +cdk-deploy-to 135792469 us-west-1 %* || goto :eof +cdk-deploy-to 245813579 eu-west-1 %* +``` + +------ + +Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. \ No newline at end of file diff --git a/doc_source/get_cfn_param.md b/doc_source/get_cfn_param.md index fa2731f6..1123db81 100644 --- a/doc_source/get_cfn_param.md +++ b/doc_source/get_cfn_param.md @@ -2,4 +2,4 @@ See [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for information about using the optional *Parameters* section to customize your AWS CloudFormation templates\. -You can also get a reference to a resource in an existing AWS CloudFormation template, as described in the next section\. \ No newline at end of file +You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [Use an Existing AWS CloudFormation Template](use_cfn_template.md)\. \ No newline at end of file diff --git a/doc_source/get_context_var.md b/doc_source/get_context_var.md index 727a3337..5c7d3317 100644 --- a/doc_source/get_context_var.md +++ b/doc_source/get_context_var.md @@ -18,8 +18,72 @@ To specify the same context variable and value in the `cdk.json` file, use the f } ``` -To get the value of a context variable in your app, use code like the following, which gets the value of the context variable **bucket\_name**\. +To get the value of a context variable in your app, use code like the following in the context of a construct \(that is, when `this`, or `self` in Python, is an instance of some construct\)\. The example gets the value of the context variable **bucket\_name**\. +------ +#### [ TypeScript ] + +``` +const bucket_name = this.node.tryGetContext('bucket_name'); +``` + +------ +#### [ Python ] + +``` +bucket_name = this.node.try_get_context("bucket_name") +``` + +------ +#### [ Java ] + +``` +String bucketName = (String)this.getNode().tryGetContext("bucket_name"); +``` + +------ +#### [ C\# ] + +``` +var bucketName = this.Node.TryGetContext("bucket_name"); +``` + +------ + +Outside the context of a construct, you can access the context variable from the app object, like this\. + +------ +#### [ TypeScript ] + +``` +const app = new cdk.App(); +const bucket_name = app.node.tryGetContext('bucket_name') ``` -const bucket_name = this.node.tryGetContext("bucket_name"); -``` \ No newline at end of file + +------ +#### [ Python ] + +``` +app = cdk.App() +bucket_name = app.node.try_get_context("bucket_name") +``` + +------ +#### [ Java ] + +``` +App app = App(); +String bucketName = (String)app.getNode().tryGetContext("bucket_name"); +``` + +------ +#### [ C\# ] + +``` +app = App(); +var bucketName = app.Node.TryGetContext("bucket_name"); +``` + +------ + +For more details on working with context variables, see [Runtime Context](context.md)\. \ No newline at end of file diff --git a/doc_source/get_env_var.md b/doc_source/get_env_var.md index d2458a25..91fa2357 100644 --- a/doc_source/get_env_var.md +++ b/doc_source/get_env_var.md @@ -2,6 +2,56 @@ To get the value of an environment variable, use code like the following\. This code gets the value of the environment variable `MYBUCKET`\. +------ +#### [ TypeScript ] + ``` +// Sets bucket_name to undefined if environment variable not set const bucket_name = process.env.MYBUCKET; -``` \ No newline at end of file + +// Sets bucket_name to a default if env var doesn't exist +const bucket_name = process.env.MYBUCKET || "DefaultName"; +``` + +------ +#### [ Python ] + +``` +import os + +# Throws error if environment variable doesn't exist +bucket_name = os.env["MYBUCKET"] + +# Sets bucket_name to None if environment variable doesn't exist +bucket_name = os.env.get("MYBUCKET") + +# Sets bucket_name to a default if env var doesn't exist +bucket_name = os.env.get("MYBUCKET", "DefaultName") +``` + +------ +#### [ Java ] + +``` +// Sets bucketName to null if environment variable doesn't exist +String bucketName = System.getenv("MYBUCKET"); + +// Sets bucketName to a defalut if env var doesn't exist +String bucketName = System.getenv("MYBUCKET"); +if (bucketName == null) bucketName = "DefaultName"; +``` + +------ +#### [ C\# ] + +``` +using System; + +// Sets bucket name to null if environment variable doesn't exist +string bucketName = Environment.GetEnvironmentVariable("MYBUCKET"); + +// Sets bucket_name to a default if env var doesn't exist +string bucketName = Environment.GetEnvironmentVariable("MYBUCKET") ?? "DefaultName"; +``` + +------ \ No newline at end of file diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index 577d20d5..45d0a6c2 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -2,6 +2,9 @@ To use values from AWS Secrets Manager in your CDK app, use the [fromSecretAttributes](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-secretsmanager/secret.html#aws_secretsmanager_Secret_fromSecretAttributes) method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. +------ +#### [ TypeScript ] + ``` import sm = require("@aws-cdk/aws-secretsmanager"); @@ -13,10 +16,71 @@ export class SecretsManagerStack extends core.Stack { secretArn: "arn:aws:secretsmanager:::secret:-" // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: - // Key, + // encryptionKey: ... }); ``` +------ +#### [ Python ] + +``` +import aws_cdk.aws_secretsmanager as sm + +class SecretsManagerStack(core.Stack): + def __init__(self, scope: core.App, id: str, **kwargs): + super().__init__(scope, name, **kwargs) + + secret = sm.Secret.from_secret_attributes(this, "ImportedSecret", + secret_arn="arn:aws:secretsmanager:::secret:-", + # If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: + # encryption_key=.... + ) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.secretsmanager.Secret; +import software.amazon.awscdk.services.secretsmanager.SecretAttributes; + +public class SecretsManagerStack extends Stack { + public SecretsManagerStack(App scope, String id) { + this(scope, id, null); + } + + public SecretsManagerStack(App scope, String id, StackProps props) { + super(scope, id, props); + + Secret secret = (Secret)Secret.fromSecretAttributes(this, "ImportedSecret", SecretAttributes.builder() + .secretArn("arn:aws:secretsmanager:::secret:-") + // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: + // .encryptionKey(...) + .build()); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.SecretsManager; + +public class SecretsManagerStack : Stack +{ + public SecretsManagerStack(App scope, string id, StackProps props) : base(scope, id, props) { + + var secret = Secret.FromSecretAttributes(this, "ImportedSecret", new SecretAttributes { + SecretArn = "arn:aws:secretsmanager:::secret:-" + // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: + // encryptionKey = ..., + }); + } +``` + +------ + Use the [create\-secret](https://docs.aws.amazon.com/cli/latest/reference/secretsmanager/create-secret.html) CLI command to create a secret from the command\-line, such as when testing: ``` diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 01378b62..8eecf6e3 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -11,6 +11,9 @@ The AWS CDK supports retrieving both plain and secure values\. You may request a To read values from the Systems Manager Parameter Store, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-string-parameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-secure-string-parameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md), not the actual value\. The value is resolved by AWS CloudFormation during deployment\. +------ +#### [ TypeScript ] + ``` import ssm = require('@aws-cdk/aws-ssm'); @@ -25,20 +28,103 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` +------ +#### [ Python ] + +``` +import aws_cdk.aws_ssm as ssm + +# Get latest version or specified version of plain string attribute +latest_string_token = ssm.StringParameter.value_for_string_parameter( + self, "my-plain-parameter-name") +latest_string_token = ssm.StringParameter.value_for_string_parameter( + self, "my-plain-parameter-name", 1) + +# Get specified version of secure string attribute +secure_string_token = ssm.StringParameter.value_for_secure_string_parameter( + self, "my-secure-parameter-name", 1) # must specify version +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.ssm.StringParameter; + +//Get latest version or specified version of plain string attribute +String latestStringToken = StringParameter.valueForStringParameter( + this, "my-plain-parameter-name"); // latest version +String versionOfStringToken = StringParameter.valueForStringParameter( + this, "my-plain-parameter-name", 1); // version 1 + +//Get specified version of secure string attribute +String secureStringToken = StringParameter.valueForSecureStringParameter( + this, "my-secure-parameter-name", 1); // must specify version +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.SSM; + +// Get latest version or specified version of plain string attribute +var latestStringToken = StringParameter.ValueForStringParameter( + this, 'my-plain-parameter-name'); // latest version +var versionOfStringToken = StringParameter.ValueForStringParameter( + this, 'my-plain-parameter-name', 1); // version 1 + +// Get specified version of secure string attribute +var secureStringToken = StringParameter.ValueForSecureStringParameter( + this, 'my-secure-parameter-name', 1); // must specify version +``` + +------ + ## Reading Systems Manager Values at Synthesis Time It is sometimes useful to "bake in" a parameter at synthesis time, so that the resulting AWS CloudFormation template always uses the same value, rather than resolving the value during deployment\. -To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method\. This method returns the actual value of the parameter as a [Runtime Context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. +To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime Context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. + +------ +#### [ TypeScript ] ``` import ssm = require('@aws-cdk/aws-ssm'); -// ... later ... const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` -**Note** +------ +#### [ Python ] + +``` +import aws_cdk.aws_ssm as ssm + +string_value = ssm.StringParameter.value_from_lookup(self, "my-plain-parameter-name") +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.ssm.StringParameter; + +String stringValue = StringParameter.valueFromLookup(this, "my-plain-parameter-name"); +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.SSM; + +var stringValue = StringParameter.ValueFromLookup(this, "my-plain-parameter-name"); +``` + +------ + Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. ## Writing Values to Systems Manager @@ -50,5 +136,9 @@ aws ssm put-parameter --name "parameter-name" --type "String" --value "parameter aws ssm put-parameter --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" ``` -**Note** -When updating an SSM value that already exists, also include the `--overwrite` option\. \ No newline at end of file +When updating an SSM value that already exists, also include the `--overwrite` option\. + +``` +aws ssm put-parameter --overwrite --name "parameter-name" --type "String" --value "parameter-value" +aws ssm put-parameter --overwrite --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" +``` \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 589b4bcd..3e046ca8 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -5,42 +5,42 @@ This topic describes how to install and configure the AWS CDK and create your fi **Note** Want to dig deeper? Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour of a real\-world project\. +**Tip** +The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the AWS Toolkit](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. + ## Prerequisites -**AWS CDK command line tools** -+ [Node\.js \(>= 10\.3\.0\)](https://nodejs.org/en/download) -+ You must specify both your credentials and an AWS Region to use the AWS CDK CLI, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. +All CDK developers need to install [Node\.js](https://nodejs.org/en/download) \(>= 10\.3\.0\), even those working in languages other than TypeScript or JavaScript\. The AWS CDK Toolkit \(`cdk` command\-line tool\) and the AWS Construct Library are developed in TypeScript and run on Node\.js\. The bindings for other supported languages use this backend and toolset\. -**Note** -Why do you need Node\.js when you're a Python, C\#, or Java developer? The AWS CDK is developed in TypeScript and transpiled to JavaScript\. Bindings for the other supported languages make use of the AWS CDK engine running on Node\.js, as does the `cdk` command\-line tool\. +You must provide your credentials and an AWS Region to use the AWS CDK CLI, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. + +Other prerequisites depend on your development language, as follows\. ------ #### [ TypeScript ] TypeScript >= 2\.7 ------- -#### [ JavaScript ] - -none - ------ #### [ Python ] + Python >= 3\.6 ------ #### [ Java ] -+ Maven 3\.5\.4 and Java 8 ++ Maven 3\.5\.4 or later and Java 8 ++ A Java IDE is preferred \(the examples in this guide may refer to Eclipse\)\. `cdk init` creates a Maven project; most IDEs can import this style of project\. Some IDEs may need to be configured to use Java 8 \(also known as 1\.8\)\. + Set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine ------ #### [ C\# ] -\.NET standard 2\.0 compatible implementation: -+ \.NET Core >= 2\.0 -+ \.NET Framework >= 4\.6\.1 +\.NET standard 2\.1 compatible implementation: ++ \.NET Core >= 3\.0 \(3\.1 upon its release\) ++ \.NET Framework >= 4\.6\.1, or + Mono >= 5\.4 +Visual Studio 2019 \(any edition\) recommended\. + ------ ## Installing the AWS CDK @@ -51,7 +51,7 @@ Install the AWS CDK using the following command\. npm install -g aws-cdk ``` -Run the following command to see the version number of the AWS CDK\. +Run the following command to verify correct installation and print the version number of the AWS CDK\. ``` cdk --version @@ -68,13 +68,6 @@ If you get an error message that your language framework is out of date, use one npx npm-check-updates -u ``` ------- -#### [ JavaScript ] - -``` -npx npm-check-updates -u -``` - ------ #### [ Python ] @@ -98,12 +91,17 @@ mvn versions:use-latest-versions nuget update ``` +Or **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio + ------ ## Using the env Property to Specify Account and Region You can use the `env` property on a stack to specify the account and region used when deploying a stack, as shown in the following example, where *REGION* is the region and *ACCOUNT* is the account ID\. +------ +#### [ TypeScript ] + ``` new MyStack(app, 'MyStack', { env: { @@ -113,20 +111,131 @@ new MyStack(app, 'MyStack', { }); ``` +------ +#### [ Python ] + +``` +MyStack(app, "MyStack", env=core.Environment(region="REGION",account="ACCOUNT") +``` + +------ +#### [ Java ] + +``` +new MyStack(app, "MyStack", StackProps.builder().env( + Environment.builder() + .account("ACCOUNT") + .region("REGION") + .build()).build()); +``` + +------ +#### [ C\# ] + +``` +new MyStack(app, "MyStack", new StackProps +{ + Env = new Amazon.CDK.Environment + { + Account = "ACCOUNT", + Region = "REGION" + } +}); +``` + +------ + **Note** The AWS CDK team recommends that you explicitly set your account and region using the `env` property on a stack when you deploy stacks to production\. Since you can create any number of stacks in any of your accounts in any region that supports all of the stack's resources, the AWS CDK team recommends that you create your production stacks in one AWS CDK app, and deploy them as necessary\. For example, if you own three accounts, with account IDs *ONE*, *TWO*, and *THREE* and want to be able to deploy each one in **us\-west\-2** and **us\-east\-1**, you might declare them as: +------ +#### [ TypeScript ] + ``` new MyStack(app, 'Stack-One-W', { env: { account: 'ONE', region: 'us-west-2' }}); -new MyStack(app, 'Stack-One-E', { env: { account: 'ONE', region: 'us-east-1' }}); -new MyStack(app, 'Stack-Two-W', { env: { account: 'TWO', region: 'us-west-2' }}); -new MyStack(app, 'Stack-Two-E', { env: { account: 'TWO', region: 'us-east-1' }}); +new MyStack(app, 'Stack-One-E', { env: { account: 'ONE', region: 'us-east-1' }}); +new MyStack(app, 'Stack-Two-W', { env: { account: 'TWO', region: 'us-west-2' }}); +new MyStack(app, 'Stack-Two-E', { env: { account: 'TWO', region: 'us-east-1' }}); new MyStack(app, 'Stack-Three-W', { env: { account: 'THREE', region: 'us-west-2' }}); new MyStack(app, 'Stack-Three-E', { env: { account: 'THREE', region: 'us-east-1' }}); ``` +------ +#### [ Python ] + +``` +MyStack(app, "Stack-One-W", env=core.Environment{account="ONE", region="us-west-2")) +MyStack(app, "Stack-One-E", env=core.Environment(account="ONE", region="us-east-1")) +MyStack(app, "Stack-Two-W", env=core.Environment(account="TWO", region="us-west-2")) +MyStack(app, "Stack-Two-E", env=core.Environment(account="TWO", region="us-east-1")) +MyStack(app, "Stack-Three-W", env=core.Environment(account="THREE", region="us-west-2")) +MyStack(app, "Stack-Three-E", env=core.Environment(account="THREE", region="us-east-1")) +``` + +------ +#### [ Java ] + +``` +public class MyApp { + + private static App app; + + // Helper method to declare MyStacks in specific accounts/regions + private static MyStack makeMyStack(final String name, final String account, + final String region) { + + return new MyStack(app, name, StackProps.builder() + .env(Environment.builder() + .account(account) + .region(region) + .build()) + .build()); + } + + public static void main(final String argv[]) { + app = new App(); + + makeMyStack("Stack-One-W", "ONE", "us-west-2"); + makeMyStack("Stack-One-E", "ONE", "us-east-1"); + makeMyStack("Stack-Two-W", "TWO", "us-west-2"); + makeMyStack("Stack-Two-E", "TWO", "us-east-1"); + makeMyStack("Stack-Three-W", "THREE", "us-west-2"); + makeMyStack("Stack-Three-E", "THREE", "us-east-1"); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +``` +// Helper func to declare MyStacks in specific accounts/regions +Stack makeMyStack(string name, string account, string region) +{ + return new MyStack(app, name, new StackProps + { + Env = new Amazon.CDK.Environment + { + Account = account, + Region = region + } + }); +} + +makeMyStack("Stack-One-W", account: "ONE", region: "us-west-2"); +makeMyStack("Stack-One-E", account: "ONE", region: "us-east-1"); +makeMyStack("Stack-Two-W", account: "TWO", region: "us-west-2"); +makeMyStack("Stack-Two-E", account: "TWO", region: "us-east-1"); +makeMyStack("Stack-Three-W", account: "THREE", region: "us-west-2"); +makeMyStack("Stack-Three-E", account: "THREE", region: "us-east-1"); +``` + +------ + And deploy the stack for account *TWO* in **us\-east\-1** with: ``` @@ -240,7 +349,10 @@ Where: The following table describes the templates available with the supported languages\. -[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) +| | | +| --- |--- | +| app \(default\) | Creates an empty AWS CDK app\. | +| sample\-app | Creates an AWS CDK app with a stack containing an Amazon SQS queue, an Amazon SNS topic, and an IAM policy document that allows the topic to send messages to the queue\. | For Hello World, you can just use the default template\. @@ -251,13 +363,6 @@ For Hello World, you can just use the default template\. cdk init --language typescript ``` ------- -#### [ JavaScript ] - -``` -cdk init --language javascript -``` - ------ #### [ Python ] @@ -270,7 +375,6 @@ Once the init command finishes, your prompt should show **\(\.env\)**, indicatin On Linux/MacOS: ``` -python3 -m venv .env source .env/bin/activate ``` @@ -299,14 +403,6 @@ HelloCdkStack(app, "HelloCdkStack") cdk init --language java ``` -Once the init command finishes, we need to modify the template's output\. -+ Open `src/main/java/com/myorg/HelloApp.java`\. -+ Change the two stacks to one: - - ``` - new HelloStack(app, "HelloCdkStack"); - ``` - ------ #### [ C\# ] @@ -314,21 +410,6 @@ Once the init command finishes, we need to modify the template's output\. cdk init --language csharp ``` -Once the init command finishes, we need to modify the template's output\. -+ Open `src/HelloCdk/Program.cs`\. -+ Change the two stacks to one: - - ``` - new HelloStack(app, "HelloCdkStack", new StackProps()); - ``` -+ Open `src/HelloCdk/HelloStack.cs`\. -+ Delete all of the using statements except the first\. - - ``` - using Amazon.CDK; - ``` -+ Delete everything from the constructor\. - ------ ### Compiling the App @@ -342,11 +423,6 @@ Compile your program, as follows\. npm run build ``` ------- -#### [ JavaScript ] - -Nothing to compile\. - ------ #### [ Python ] @@ -359,21 +435,21 @@ Nothing to compile\. mvn compile ``` +or press Control\-B in Eclipse + +**Tip** +You can suppress the **\[INFO\]** messages in the build log by adding the **\-q** option to your `mvn` commands\. \(Don"t forget the one in `cdk.json`\.\) + ------ -#### [ C♯ ] +#### [ C\# ] ``` dotnet build src ``` ------- +or press F6 in Visual Studio -**Note** -If you are using Java and get annoyed by the **\[INFO\]** log messages, you can suppress them by including the **\-q** option to your **mvn** commands\. This includes changing `cdk.json to:` - -``` -"app": "mvn -q exec:java" -``` +------ ### Listing the Stacks in the App @@ -402,13 +478,6 @@ Install the `@aws-cdk/aws-s3` package\. npm install @aws-cdk/aws-s3 ``` ------- -#### [ JavaScript ] - -``` -npm install @aws-cdk/aws-s3 -``` - ------ #### [ Python ] @@ -440,6 +509,8 @@ Run the following command in the `src/HelloCdk` directory\. dotnet add package Amazon.CDK.AWS.S3 ``` +Or **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio, then locate and install the `Amazon.CDK.AWS.S3` package + ------ Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represented by the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) class\. @@ -464,28 +535,6 @@ export class HelloCdkStack extends core.Stack { } ``` ------- -#### [ JavaScript ] - -In `lib/hello-cdk-stack.js`: - -``` -const cdk = require('@aws-cdk/core'); -const s3 = require('@aws-cdk/aws-s3'); - -class HelloCdkStack extends cdk.Stack { - constructor(scope, id, props) { - super(scope, id, props); - - new s3.Bucket(this, 'MyFirstBucket', { - versioned: true - }); - } -} - -module.exports = { HelloCdkStack } -``` - ------ #### [ Python ] @@ -514,23 +563,21 @@ In `src/main/java/com/myorg/HelloStack.java`: ``` package com.myorg; -import software.amazon.awscdk.Construct; -import software.amazon.awscdk.Stack; -import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.core.Construct; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; import software.amazon.awscdk.services.s3.Bucket; -import software.amazon.awscdk.services.s3.BucketProps; public class HelloStack extends Stack { - public HelloStack(final Construct parent, final String id) { - this(parent, id, null); + public HelloStack(final Construct scope, final String id) { + this(scope, id, null); } - public HelloStack(final Construct parent, final String id, final StackProps props) { - super(parent, id, props); + public HelloStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); - new Bucket(this, "MyFirstBucket", BucketProps.builder() - .versioned(true) - .build()); + Bucket.Builder.create(this, "MyFirstBucket") + .versioned(true).build(); } } ``` @@ -548,7 +595,7 @@ namespace HelloCdk { public class HelloStack : Stack { - public HelloStack(Construct parent, string id, IStackProps props) : base(parent, id, props) + public HelloStack(Construct scope, string id, IStackProps props) : base(scope, id, props) { new Bucket(this, "MyFirstBucket", new BucketProps { @@ -575,11 +622,6 @@ Compile your program, as follows\. npm run build ``` ------- -#### [ JavaScript ] - -Nothing to compile\. - ------ #### [ Python ] @@ -592,18 +634,25 @@ Nothing to compile\. mvn compile ``` +or press Control\-B in Eclipse + +**Tip** +You can suppress the **\[INFO\]** messages in the build log by adding the **\-q** option to your `mvn` commands\. \(Don"t forget the one in `cdk.json`\.\) + ------ -#### [ C♯ ] +#### [ C\# ] ``` dotnet build src ``` +or press F6 in Visual Studio + ------ ### Synthesizing an AWS CloudFormation Template -Synthesize an AWS CloudFormation template for the app, as follows\. If you get an error like "\-\-app is required\.\.\.", it's because you are running the command from within the `hello_cdk` sub\-directory\. Navigate to the parent directory and try again\. +Synthesize an AWS CloudFormation template for the app, as follows\. If you get an error like "\-\-app is required\.\.\.", it's because you are running the command from a subirectory of your project directory\. Navigate to the project directory and try again\. ``` cdk synth @@ -660,18 +709,6 @@ new s3.Bucket(this, 'MyFirstBucket', { }); ``` ------- -#### [ JavaScript ] - -Update `lib/hello-cdk-stack.js`\. - -``` -new s3.Bucket(this, 'MyFirstBucket', { - versioned: true, - encryption: s3.BucketEncryption.KMS_MANAGED -}); -``` - ------ #### [ Python ] @@ -692,10 +729,10 @@ import software.amazon.awscdk.services.s3.BucketEncryption; ``` ``` -new Bucket(this, "MyFirstBucket", BucketProps.builder() - .versioned(true) - .encrypted(BucketEncryption.KMS_MANAGED) - .build()); +Bucket.Builder.create(this, "MyFirstBucket") + .versioned(true) + .encryption(BucketEncryption.KMS_MANAGED) + .build(); ``` ------ @@ -722,11 +759,6 @@ Compile your program, as follows\. npm run build ``` ------- -#### [ JavaScript ] - -Nothing to compile\. - ------ #### [ Python ] @@ -739,13 +771,20 @@ Nothing to compile\. mvn compile ``` +or press Control\-B in Eclipse + +**Tip** +You can suppress the **\[INFO\]** messages in the build log by adding the **\-q** option to your `mvn` commands\. \(Don"t forget the one in `cdk.json`\.\) + ------ -#### [ C♯ ] +#### [ C\# ] ``` dotnet build src ``` +or press F6 in Visual Studio + ------ ### Preparing for Deployment diff --git a/doc_source/home.md b/doc_source/home.md index 940caed0..c33bbc60 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -8,7 +8,7 @@ AWS CloudFormation enables you to: + Build highly reliable, highly scalable, cost\-effective applications in the cloud without worrying about creating and configuring the underlying AWS infrastructure\. + Use a template file to create and delete a collection of resources together as a single unit \(a stack\)\. -Use the AWS CDK to define your cloud resources in a familiar programming language\. The AWS CDK supports TypeScript, JavaScript, and Python\. The AWS CDK also provides Developer Preview support for C\#/\.NET, and Java\. +Use the AWS CDK to define your cloud resources in a familiar programming language\. The AWS CDK supports TypeScript, JavaScript, Python, Java, and C\#/\.Net\. Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. @@ -16,7 +16,10 @@ Developers can use one of the supported programming languages to define reusable ## Why Use the AWS CDK? -Let's look at the power of the AWS CDK\. Here is some TypeScript code in an AWS CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md)\)\. +Let's look at the power of the AWS CDK\. Here is some code in an AWS CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md)\)\. + +------ +#### [ TypeScript ] ``` export class MyEcsConstructStack extends core.Stack { @@ -36,7 +39,7 @@ export class MyEcsConstructStack extends core.Stack { cluster: cluster, // Required cpu: 512, // Default is 256 desiredCount: 6, // Default is 1 - image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"), // Required + taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, memoryLimitMiB: 2048, // Default is 512 publicLoadBalancer: true // Default is false }); @@ -44,7 +47,100 @@ export class MyEcsConstructStack extends core.Stack { } ``` -This produces an AWS CloudFormation [template of more than 500 lines](https://github.com/awsdocs/aws-cdk-guide/blob/master/doc_source/my_ecs_construct-stack.yaml); deploying the AWS CDK app produces more than 50 resources of the following types\. +------ +#### [ Python ] + +``` +class MyEcsConstructStack(core.Stack): + + def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + vpc = ec2.Vpc(self, "MyVpc", max_azs=3) # default is all AZs in region + + cluster = ecs.Cluster(self, "MyCluster", vpc=vpc) + + ecs_patterns.ApplicationLoadBalancedFargateService(self, "MyFargateService", + cluster=cluster, # Required + cpu=512, # Default is 256 + desired_count=6, # Default is 1 + task_image_options=ecs_patterns.ApplicationLoadBalancedTaskImageOptions( + image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")), + memory_limit_mib=2048, # Default is 512 + public_load_balancer=True) # Default is False +``` + +------ +#### [ Java ] + +``` +public class MyEcsConstructStack extends Stack { + + public MyEcsConstructStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyEcsConstructStack(final Construct scope, final String id, + StackProps props) { + super(scope, id, props); + + Vpc vpc = Vpc.Builder.create(this, "MyVpc").maxAzs(3).build(); + + Cluster cluster = Cluster.Builder.create(this, "MyCluster") + .vpc(vpc).build(); + + ApplicationLoadBalancedFargateService.Builder.create(this, "MyFargateService") + .cluster(cluster) + .cpu(512) + .desiredCount(6) + .taskImageOptions( + ApplicationLoadBalancedTaskImageOptions.builder() + .image(ContainerImage + .fromRegistry("amazon/amazon-ecs-sample")) + .build()).memoryLimitMiB(2048) + .publicLoadBalancer(true).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +public class MyEcsConstructStack : Stack +{ + public MyEcsConstructStack(Construct scope, string id, IStackProps props) : base(scope, id, props) + { + var vpc = new Vpc(this, "MyVpc", new VpcProps + { + MaxAzs = 3 + }); + + var cluster = new Cluster(this, "MyCluster", new ClusterProps + { + Vpc = vpc + }); + + new ApplicationLoadBalancedFargateService(this, "MyFargateService", + new ApplicationLoadBalancedFargateServiceProps + { + Cluster = cluster, + Cpu = 512, + DesiredCount = 6, + TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions + { + Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample") + }, + MemoryLimitMiB = 2048, + PublicLoadBalancer = true, + }); + } +} +``` + +------ + +This class produces an AWS CloudFormation [template of more than 500 lines](https://github.com/awsdocs/aws-cdk-guide/blob/master/doc_source/my_ecs_construct-stack.yaml); deploying the AWS CDK app produces more than 50 resources of the following types\. + [AWS::EC2::EIP](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html) + [AWS::EC2::InternetGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html) + [AWS::EC2::NatGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html) diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index 7b61874b..7906d050 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -2,17 +2,63 @@ The **aws\-cloudwatch** package supports setting CloudWatch alarms on CloudWatch metrics\. The syntax is as follows, where *METRIC* is a CloudWatch metric you have created, and the alarm is raised there are more than 100 of the measured metrics in two of the last three seconds: +------ +#### [ TypeScript ] + ``` -new cloudwatch.Alarm(this, 'Alarm', { - metric: METRIC, +const alarm = new cloudwatch.Alarm(this, 'Alarm', { + metric: metric, // see below threshold: 100, evaluationPeriods: 3, datapointsToAlarm: 2, }); ``` +------ +#### [ Python ] + +``` +alarm = cloudwatch.Alarm(self, "Alarm", + metric=metric, # see below + threshold=100, + evaluation_periods=3, + datapoints_to_alarm=2 +) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.cloudwatch.Alarm; + +Alarm alarm = Alarm.Builder.create(this, "Alarm") + .metric(metric) // see below + .threshold(100) + .evaluationPeriods(3) + .datapointsToAlarm(2).build(); +``` + +------ +#### [ C\# ] + +``` +var alarm = new Alarm(this, "Alarm", new AlarmProps +{ + Metric = metric, // see below + Threshold = 100, + EvaluationPeriods = 3, + DatapointsToAlarm = 2 +}); +``` + +------ + The syntax for creating a metric is as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. +------ +#### [ TypeScript ] + ``` const metric = new cloudwatch.Metric({ namespace: 'MyNamespace', @@ -21,8 +67,51 @@ const metric = new cloudwatch.Metric({ }); ``` +------ +#### [ Python ] + +``` +metric = cloudwatch.Metric( + namespace="MyNamespace", + metric_name="MyMetric", + dimensions=dict(MyDimension="MyDimensionValue") +) +``` + +------ +#### [ Java ] + +``` +Metric metric = Metric.Builder.create() + .namespace("MyNamespace") + .metricName("MyMetric") + .dimensions(new HashMap() {{ + put("MyDimension", "MyDimensionValue"); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +var metric = new Metric(this, "Metric", new MetricProps +{ + Namespace = "MyNamespace", + MetricName = "MyMetric", + Dimensions = new Dictionary + { + ["MyDimension"]: "MyDimensionValue" + } +}); +``` + +------ + Many AWS CDK packages contain functionality to enable setting an alarm based on an existing metric\. For example, you can create an Amazon SQS alarm for the **ApproximateNumberOfMessagesVisible** metric that raises an alarm if the queue has more than 100 messages available for retrieval in two of the last three seconds\. +------ +#### [ TypeScript ] + ``` const qMetric = queue.metric("ApproximateNumberOfMessagesVisible"); @@ -32,4 +121,45 @@ Many AWS CDK packages contain functionality to enable setting an alarm based on evaluationPeriods: 3, datapointsToAlarm: 2 }); -``` \ No newline at end of file +``` + +------ +#### [ Python ] + +``` +q_metric = queue.metric("ApproximateNumberOfMessagesVisible") + +cloudwatch.Alarm(self, "Alarm", + metric=q_metric, + threshold=100, + evaluation_periods=3, + datapoints_to_alarm=2 +) +``` + +------ +#### [ Java ] + +``` +Alarm.Builder.create(this, "Alarm") + .metric(qMetric) + .threshold(100) + .evaluationPeriods(3) + .datapointsToAlarm(2).build(); +``` + +------ +#### [ C\# ] + +``` +var qMetric = queue.Metric("ApproximateNumberOfMessagesVisible"); + +new Alarm(this, "Alarm", new AlarmProps { + Metric = qMetric, + Threshold = 100, + EvaluationPeriods = 3, + DatapointsToAlarm = 2 +}); +``` + +------ \ No newline at end of file diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index e91d05b3..792f388a 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -12,8 +12,11 @@ The most common identifier, `id`, is the identifier passed as the second argumen Lets look at an example where we have two constructs with the identifier `MyBucket` in our app\. However, since they are defined in different scopes, the first in the scope of the stack with the identifier `Stack1`, and the second in the scope of a stack with the identifier `Stack2`, that doesn't cause any sort of conflict, and they can co\-exist in the same app without any issues\. +------ +#### [ TypeScript ] + ``` -import { App, Construct, Stack, StackProps } from '@aws-cdk/cdk'; +import { App, Construct, Stack, StackProps } from '@aws-cdk/core'; import s3 = require('@aws-cdk/aws-s3'); class MyStack extends Stack { @@ -29,28 +32,164 @@ new MyStack(app, 'Stack1'); new MyStack(app, 'Stack2'); ``` +------ +#### [ Python ] + +``` +from aws_cdk.core import App, Construct, Stack, StackProps +from aws_cdk import aws_s3 as s3 + +class MyStack(Stack): + + def __init__(self, scope: Construct, id: str, **kwargs): + + super().__init__(scope, id, **kwargs) + s3.Bucket(self, "MyBucket"); + +app = App() +MyStack(app, 'Stack1') +MyStack(app, 'Stack2') +``` + +------ +#### [ Java ] + +``` +// MyStack.java +package com.myorg; + +import software.amazon.awscdk.core.App; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; +import software.amazon.awscdk.services.s3.Bucket; + +public class MyStack extends Stack { + public MyStack(final App scope, final String id) { + this(scope, id, null); + } + + public MyStack(final App scope, final String id, final StackProps props) { + super(scope, id, props); + new Bucket(this, "MyBucket"); + } +} + +// Main.java +package com.myorg; + +import software.amazon.awscdk.core.App; + +public class Main { + public static void main(String[] args) { + App app = new App(); + new MyStack(app, "Stack1"); + new MyStack(app, "Stack2"); + } +} +``` + +------ +#### [ C\# ] + +``` +using core = Amazon.CDK; +using s3 = Amazon.CDK.AWS.S3; + +public class MyStack : core.Stack +{ + public MyStack(core.App scope, string id, core.IStackProps props) : base(scope, id, props) + { + new s3.Bucket(this, "MyBucket"); + } +} + +class Program +{ + static void Main(string[] args) + { + var app = new core.App(); + new MyStack(app, "Stack1"); + new MyStack(app, "Stack2"); + } +} +``` + +------ + ## Paths -As the constructs in an AWS CDK application form a hierarchy, we refer to the collection of ids from a given construct, then of its parent construct, then grandparent construct, and so on up to the root of the construct tree, which is an instance of the `App` class as a *path*\. +As the constructs in an AWS CDK application form a hierarchy, we refer to the collection of IDs from a given construct, then of its parent construct, then grandparent construct, and so on up to the root of the construct tree, which is an instance of the `App` class, as a *path*\. + +The AWS CDK typically displays paths in your templates as a string, with the IDs from the levels separated by slashes, starting at the node just below the root `App` instance, which is usually a stack\. For example, the paths of the two Amazon S3 bucket resources in the previous code example are `Stack1/MyBucket` and `Stack2/MyBucket`\. -The AWS CDK typically displays paths in your templates as a string, with the ids from the levels separated by slashes, starting at the node just below the root `App` instance, which is usually a stack\. For example, the paths of the two Amazon S3 bucket resources in the previous code example are `Stack1/MyBucket` and `Stack2/MyBucket`\. +You can access the path of any construct programmatically, as shown in the following example, which gets the path of `myConstruct` \(or `my_construct`, as Python developers would write it\)\. Since IDs must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. -You can access the path of any construct programmatically, as shown in the following example, which gets the path of `myConstruct`\. Since ids must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. +------ +#### [ TypeScript ] ``` const path: string = myConstruct.node.path; ``` +------ +#### [ Python ] + +``` +path = my_construct.node.path +``` + +------ +#### [ Java ] + +``` +String path = myConstruct.getNode().getPath(); +``` + +------ +#### [ C\# ] + +``` +string path = myConstruct.Node.Path; +``` + +------ + ## Unique IDs Since AWS CloudFormation requires that all logical IDs in a template are unique, the AWS CDK must be able to generate unique identifier for each construct in an application\. Since the AWS CDK already has paths that are globally unique, the AWS CDK generates these unique identifiers by concatenating the elements of the path, and adds an 8\-digit hash\. The hash is necessary, as otherwise two distinct paths, such as `A/B/C` and `A/BC` would result in the same identifier\. The AWS CDK calls this concatenated path elements and hash the *unique ID* of the construct\. -You can access the unique ID of any construct programmatically, as shown in the following example, which gets the unique ID of `myConstruct`\. Since ids must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. +You can access the unique ID of any construct programmatically, as shown in the following example, which gets the unique ID of `myConstruct` \(or `my_costruct` in Python conventions\)\. Since ids must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. + +------ +#### [ TypeScript ] ``` const uid: string = myConstruct.node.uniqueId; ``` +------ +#### [ Python ] + +``` +uid = my_construct.node.unique_id +``` + +------ +#### [ Java ] + +``` +String uid = myConstruct.getNode().getUniqueId(); +``` + +------ +#### [ C\# ] + +``` +string uid = myConstruct.Node.UniqueId; +``` + +------ + ## Logical IDs Unique IDs serve as the *logical identifiers*, which are sometimes called *logical names*, of resources in the generated AWS CloudFormation templates for those constructs that represent AWS resources\. diff --git a/doc_source/index.md b/doc_source/index.md index 65bf4247..138b5a77 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -47,6 +47,7 @@ Amazon's trademarks and trade dress may not be used in + [Set a CloudWatch Alarm](how_to_set_cw_alarm.md) + [Get a Value from a Context Variable](get_context_var.md) + [AWS CDK Tools](tools.md) -+ [Troubleshooting the AWS CDK](troubleshooting.md) ++ [Troubleshooting Common AWS CDK Issues](troubleshooting.md) ++ [Testing Constructs](testing.md) + [OpenPGP Keys for the AWS CDK and JSII](pgp-keys.md) + [Document History for the AWS CDK Developer Guide](doc-history.md) \ No newline at end of file diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 4b91492f..c3f86535 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -1,6 +1,6 @@ # AWS CDK in Other Languages -In some cases the example code in the AWS CDK documentation is available only in TypeScript\. This topic describes how to read TypeScript code and translate it into Python\. This is currently the only other [stable](reference.md#aws_construct_lib_versioning_binding) programming language that the AWS CDK supports \(the AWS CDK supports a developer preview version of Java and C\#/\.NET\)\. See [Hello World Tutorial](getting_started.md#hello_world_tutorial) for an example of creating an AWS CDK app in a supported language\. +In some cases the example code in the AWS CDK documentation is available only in TypeScript\. This topic describes how to read TypeScript code and translate it into other languages\. See [Hello World Tutorial](getting_started.md#hello_world_tutorial) for an example of creating an AWS CDK app in a supported language\. ## Importing a Module @@ -27,7 +27,7 @@ The following table shows how you can translate TypeScript class instantiations ## Methods -Methods names and argument names in TypeScript are `camelCased`, whereas in Python they are `snake_cased`\. Props objects at the end of an argument list in TypeScript are translated into keyword\-only arguments in Python, and their names become `snake_case`\. +Methods and argument names in TypeScript are `camelCased`, whereas in Python they are `snake_cased`\. Props objects at the end of an argument list in TypeScript are translated into keyword\-only arguments in Python, and their names become `snake_case`\. The following table shows how you can translate TypeScript methods to Python methods\. diff --git a/doc_source/permissions.md b/doc_source/permissions.md index 18f0baa2..b2f52504 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -4,18 +4,21 @@ The AWS Construct Library uses a few common, widely\-implemented idioms to manag ## Grants -Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. +Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` \(Python: `grant_read`, `grant_write`\) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)`\. Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other enttites that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. -Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly \(`bucket.grantRead(lambda)`\) instead of granting access to their role \(`bucket.grantRead(lambda.role)`\)\. +Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly \(`bucket.grantRead(lambda)`, or `grant_read` in Python\) instead of granting access to their role\. ## Roles The IAM package contains a `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)` construct that represents IAM roles\. The following code creates a new role, trusting the Amazon EC2 Service Principal\. +------ +#### [ TypeScript ] + ``` import iam = require('@aws-cdk/aws-iam'); @@ -24,9 +27,47 @@ const role = new iam.Role(this, 'Role', { }); ``` -You can add permissions to a role by calling the role's `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.htm#add-to-policystatement)` method, passing in a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. +------ +#### [ Python ] + +``` +import aws_cdk.aws_iam as iam + +role = iam.Role(self, 'Role', + assumed_by=iam.ServicePrincipal('ec2.amazonaws.com')) # required +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.iam.Role; +import software.amazon.awscdk.services.iam.ServicePrincipal; + +Role role = Role.Builder.create(this, "Role") + .assumedBy(new ServicePrincipal("ec2.amazonaws.com")).build(); +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.IAM; + +var role = new Role(this, "Role", new RoleProps +{ + AssumedBy = new ServicePrincipal("ec2.amazonaws.com"), // required +}); +``` + +------ + +You can add permissions to a role by calling the role's `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.htm#add-to-policystatement)` method \(Python: `add_to_policy`\), passing in a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. - The following example adds a `Deny` policy statement to the role for the actions `ec2:SomeAction` and `s3:AnotherAction` on the resources `bucket` and `otherRole`, under the condition that the authorized service is AWS CodeBuild\. + The following example adds a `Deny` policy statement to the role for the actions `ec2:SomeAction` and `s3:AnotherAction` on the resources `bucket` and `otherRole` \(Python: `other_role`\), under the condition that the authorized service is AWS CodeBuild\. + +------ +#### [ TypeScript ] ``` role.addToPolicy(new iam.PolicyStatement({ @@ -38,11 +79,62 @@ role.addToPolicy(new iam.PolicyStatement({ }}})); ``` -**Note** - In our example above, we've created a new `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` inline with the `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. +------ +#### [ Python ] + +``` +role.add_to_policy(iam.PolicyStatement( + effect=iam.Effect.DENY, + resources=[bucket.bucket_arn, other_role.role_arn], + actions=["ec2:SomeAction", "s3:AnotherAction"], + conditions={"StringEquals": { + "ec2:AuthorizedService": "codebuild.amazonaws.com"}} +)) +``` + +------ +#### [ Java ] + +``` +role.addToPolicy(PolicyStatement.Builder.create() + .effect(Effect.DENY) + .resources(Arrays.asList(bucket.getBucketArn(), otherRole.getRoleArn())) + .actions(Arrays.asList("ec2:SomeAction", "s3:AnotherAction")) + .conditions(new HashMap() {{ + put("StringEquals", new HashMap() {{ + put("ec2:AuthorizedService", "codebuild.amazonaws.com"); + }}); + }}).build()); +``` + +------ +#### [ C\# ] + +``` +role.AddToPolicy(new PolicyStatement(new PolicyStatementProps +{ + Effect = Effect.DENY, + Resources = [bucket.BucketArn, otherRole.RoleArn], + Actions = ["ec2:SomeAction", "s3:Anotheraction"], + Conditions = new Dictionary + { + ["StringEquals"] = new Dictionary + { + ["ec2:AuthorizedService"] = "codebuild.amazonaws.com" + } + } +})); +``` + +------ + + In our example above, we've created a new `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` inline with the `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` \(Python: `add_to_policy`\) call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. If you're using a construct that requires a role to function correctly, you can either pass in an existing role when instantiating the construct object, or let the construct create a new role for you, trusting the appropriate service principal\. The following example uses such a construct: a CodeBuild project\. +------ +#### [ TypeScript ] + ``` import codebuild = require('@aws-cdk/aws-codebuild'); @@ -57,7 +149,63 @@ const project = new codebuild.Project(this, 'Project', { }); ``` -Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. This property is not available on imported resources, however, so the constructs have an `addToRolePolicy` method that does nothing if the construct is an imported resource, and calls the `addToPolicy` method of the `role` property otherwise, saving you the trouble of handling the undefined case explicitly\. The following example demonstrates: +------ +#### [ Python ] + +``` +import aws_cdk.aws_codebuild as codebuild + +# imagine role_or_none is a function that might return a Role object +# under some conditions, and None under other conditions +some_role = role_or_none(); + +project = codebuild.Project(self, "Project", +# if role is None, the Project creates a new default role, +# trusting the codebuild.amazonaws.com service principal +role=some_role) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.iam.Role; +import software.amazon.awscdk.services.codebuild.Project; + +// imagine roleOrNull is a function that might return a Role object +// under some conditions, and null under other conditions +Role someRole = roleOrNull(); + +// if someRole is null, the Project creates a new default role, +// trusting the codebuild.amazonaws.com service principal +Project project = Project.Builder.create(this, "Project") + .role(someRole).build(); +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.CodeBuild; + +// imagine roleOrNull is a function that might return a Role object +// under some conditions, and null under other conditions +var someRole = roleOrNull(); + +// if someRole is null, the Project creates a new default role, +// trusting the codebuild.amazonaws.com service principal +var project = new Project(this, "Project", new ProjectProps +{ + Role = someRole +}); +``` + +------ + +Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. This property is not available on imported resources, however, so the constructs have an `addToRolePolicy` \(Python: `add_to_role_policy`\) method that does nothing if the construct is an imported resource, and calls the `addToPolicy` \(Python: `add_to_policy`\) method of the `role` property otherwise, saving you the trouble of handling the undefined case explicitly\. The following example demonstrates: + +------ +#### [ TypeScript ] ``` // project is imported into the CDK application @@ -69,12 +217,57 @@ project.addToRolePolicy(new iam.PolicyStatement({ })); ``` +------ +#### [ Python ] + +``` +# project is imported into the CDK application +project = codebuild.Project.from_project_name(this, 'Project', 'ProjectName') + +# project is imported, so project.role is undefined, and this call has no effect +project.add_to_role_policy(new iam.PolicyStatement( + effect=iam.Effect.ALLOW, # ... and so on defining the policy +) +``` + +------ +#### [ Java ] + +``` +// project is imported into the CDK application +Project project = Project.fromProjectName(this, "Project", "ProjectName"); + +// project is imported, so project.getRole() is null, and this call has no effect +project.addToRolePolicy(PolicyStatement.Builder.create() + .effect(Effect.ALLOW) // .. and so on defining the policy + .build(); +``` + +------ +#### [ C\# ] + +``` +// project is imported into the CDK application +var project = Project.FromProjectName(this, "Project", "ProjectName"); + +// project is imported, so project.role is null, and this call has no effect +project.AddToRolePolicy(new PolicyStatement(new PolicyStatementProps +{ + Effect = Effect.ALLOW, // ... and so on defining the policy +})); +``` + +------ + ## Resource Policies -A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. These constructs have an `addToResourcePolicy` method, which takes a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` as its argument\. Every policy statement added to a resource policy must specify at least one principal\. +A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. These constructs have an `addToResourcePolicy` method \(Python: `add_to_resource_policy`\), which takes a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` as its argument\. Every policy statement added to a resource policy must specify at least one principal\. In the following example, the [Amazon S3 bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) `bucket` grants a role with the `s3:SomeAction` permission to itself\. +------ +#### [ TypeScript ] + ``` bucket.addToResourcePolicy(new iam.PolicyStatement({ effect: iam.Effect.ALLOW, @@ -84,6 +277,44 @@ bucket.addToResourcePolicy(new iam.PolicyStatement({ })); ``` +------ +#### [ Python ] + +``` +bucket.add_to_resource_policy(iam.PolicyStatement( + effect=iam.Effect.ALLOW, + actions=["s3:SomeAction"], + resources=[bucket.bucket_arn], + principals=role)) +``` + +------ +#### [ Java ] + +``` +bucket.addToResourcePolicy(PolicyStatement.Builder.create() + .effect(Effect.ALLOW) + .actions(Arrays.asList("s3:SomeAction")) + .resources(Arrays.asList(bucket.getBucketArn())) + .principals(Arrays.asList(role)) + .build()); +``` + +------ +#### [ C\# ] + +``` +bucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps +{ + Effect = Effect.ALLOW, + Actions = ["s3:SomeAction"], + Resources = [bucket.BucketArn], + Principals = [role] +})); +``` + +------ + ## Principals The AWS CDK Construct Library supports many types of principals, including: diff --git a/doc_source/reference.md b/doc_source/reference.md index 4ca9626c..f2ae5008 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -43,7 +43,7 @@ The module level gives an indication of the stability of the majority of the API ### Language Binding Stability -In addition to modules of the AWS CDK Construct Library, language support is also subject to a stability indication\. Although the API described in all the languages is the same, the specific programming model and naming of language bindings is considered experimental and can change as it stabilizes\. +In addition to modules of the AWS CDK Construct Library, language support is also subject to a stability indication\. Although the API described in all the languages is the same, the way that API is expressed varies by language and may change as the language support evolves\. For this reason, language bindings are deemed experimental for a time until they are considered ready for production use\. | Language | Stability | @@ -51,5 +51,5 @@ In addition to modules of the AWS CDK Construct Library, language support is als | TypeScript | Stable | | JavaScript | Stable | | Python | Stable | -| Java | Experimental | -| C\#/\.NET | Experimental | \ No newline at end of file +| Java | Stable | +| C\#/\.NET | Stable | \ No newline at end of file diff --git a/doc_source/resources.md b/doc_source/resources.md index 127decc2..f19b9e76 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -4,28 +4,94 @@ As described in [Constructs](constructs.md), the AWS CDK provides a rich class l Defining AWS resources in your CDK app is exactly like defining any other construct\. You create an instance of the construct class, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here's how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. +------ +#### [ TypeScript ] + ``` import sqs = require('@aws-cdk/aws-sqs'); new sqs.Queue(this, 'MyQueue', { - encryption: sqs.QueueEncryption.KmsManaged + encryption: sqs.QueueEncryption.KMS_MANAGED }); ``` +------ +#### [ Python ] + +``` +import aws_cdk.aws_sqs as sqs + +sqs_Queue(self, "MyQueue", encryption=sqs.QueueEncryption.KMS_MANAGED) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.sqs.*; + +Queue.Builder.create(this, "MyQueue").encryption( + QueueEncryption.KMS_MANAGED).build(); +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.SQS; + +new Queue(this, "MyQueue", new QueueProps +{ + Encryption = QueueEncryption.KMS_MANAGED +}); +``` + +------ + Some configuration props are optional, and in many cases have default values\. In some cases, all props are optional, and the last argument can be omitted entirely\. ## Resource Attributes -Most resources in the AWS Construct Library expose attributes, which are resolved at deployment time by AWS CloudFormation\. Attributes are exposed in the form of properties on the resource classes with the type name as a prefix\. The following example shows how to get the URL of an Amazon SQS queue using the `queueUrl` property\. +Most resources in the AWS Construct Library expose attributes, which are resolved at deployment time by AWS CloudFormation\. Attributes are exposed in the form of properties on the resource classes with the type name as a prefix\. The following example shows how to get the URL of an Amazon SQS queue using the `queueUrl` \(Python: `queue_url`\) property\. + +------ +#### [ TypeScript ] ``` import sqs = require('@aws-cdk/aws-sqs'); - + const queue = new sqs.Queue(this, 'MyQueue'); +const url = queue.queueUrl; // => A string representing a deploy-time value +``` + +------ +#### [ Python ] + +``` +from aws_cdk.aws_sqs as sqs + +queue = sqs.Queue(self, "MyQueue") +url = queue.queue_url # => A string representing a deploy-time value +``` + +------ +#### [ Java ] + +``` +Queue queue = new Queue(this, "MyQueue"); +String url = queue.getQueueUrl(); // => A string representing a deploy-time value +``` + +------ +#### [ C\# ] -queue.queueUrl; // => A string representing a deploy-time value +``` +var queue = new Queue(this, "MyQueue"); +var url = queue.QueueUrl; // => A string representing a deploy-time value ``` +------ + See [Tokens](tokens.md) for information about how the AWS CDK encodes deploy\-time attributes as strings\. ## Referencing Resources @@ -36,23 +102,54 @@ Many AWS CDK classes require properties that are AWS CDK resource objects \(reso For example, an Amazon ECS service requires a reference to the cluster on which it runs; an Amazon CloudFront distribution requires a reference to the bucket containing source code\. -If a construct property represents another AWS construct, its type is that of the interface type of that construct\. For example, the Amazon ECS service takes a property `cluster` of type `ecs.ICluster`; the CloudFront distribution takes a property `sourceBucket` of type `s3.IBucket`\. +If a construct property represents another AWS construct, its type is that of the interface type of that construct\. For example, the Amazon ECS service takes a property `cluster` of type `ecs.ICluster`; the CloudFront distribution takes a property `sourceBucket` \(Python: `source_bucket`\) of type `s3.IBucket`\. Because every resource implements its corresponding interface, you can directly pass any resource object you're defining in the same AWS CDK app\. The following example defines an Amazon ECS cluster and then uses it to define an Amazon ECS service\. +------ +#### [ TypeScript ] + ``` const cluster = new ecs.Cluster(this, 'Cluster', { /* ... */ }); -const service = new ecs.Service(this, 'Service', { - cluster: cluster, - /* ... */ -}); +const service = new ecs.Ec2Service(this, 'Service', { cluster: cluster }); +``` + +------ +#### [ Python ] + ``` +cluster = ecs.Cluster(self, "Cluster") + +service = ecs.Ec2Service(self, "Service", cluster=cluster) +``` + +------ +#### [ Java ] + +``` +Cluster cluster = new Cluster(this, "Cluster"); +Ec2Service service = new Ec2Service(this, "Service", + new Ec2ServiceProps.Builder().cluster(cluster).build()); +``` + +------ +#### [ C\# ] + +``` +var cluster = new Cluster(this, "Cluster"); +var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cluster }); +``` + +------ ## Accessing Resources in a Different Stack You can access resources in a different stack, as long as they are in the same account and AWS Region\. The following example defines the stack `stack1`, which defines an Amazon S3 bucket\. Then it defines a second stack, `stack2`, which takes the bucket from `stack1` as a constructor property\. +------ +#### [ TypeScript ] + ``` const prod = { account: '123456789012', region: 'us-east-1' }; @@ -65,6 +162,60 @@ const stack2 = new StackThatExpectsABucket(app, 'Stack2', { }); ``` +------ +#### [ Python ] + +``` +prod = core.Environment(account="123456789012", region="us-east-1") + +stack1 = StackThatProvidesABucket(app, "Stack1", env=prod) + +# stack2 will take a property "bucket" +stack2 = StackThatExpectsABucket(app, "Stack2", bucket=stack1.bucket, env=prod) +``` + +------ +#### [ Java ] + +``` +// Helper method to build an environment +static Environment makeEnv(String account, String region) { + return Environment.builder().account(account).region(region) + .build(); +} + +App app = new App(); + +Environment prod = makeEnv("123456789012", "us-east-1"); + +StackThatProvidesABucket stack1 = new StackThatProvidesABucket(app, "Stack1", + StackProps.builder().env(prod).build()); + +// stack2 will take an argument "bucket" +StackThatExpectsABucket stack2 = new StackThatExpectsABucket(app, "Stack,", + StackProps.builder().env(prod).build(), stack1.getBucket()); +``` + +------ +#### [ C\# ] + +``` +Amazon.CDK.Environment makeEnv(string account, string region) +{ + return new Amazon.CDK.Environment { Account = account, Region = region }; +} + +var prod = makeEnv(account: "123456789012", region: "us-east-1"); + +var stack1 = new StackThatProvidesABucket(app, "Stack1", new StackProps { Env = prod }); + +// stack2 will take an argument "bucket" +var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = prod }, + bucket: stack1.Bucket); +``` + +------ + If the AWS CDK determines that the resource is in the same account and Region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. ## Physical Names @@ -75,36 +226,129 @@ For example, AWS CloudFormation might create the Amazon S3 bucket with the logic You can specify a physical name when creating constructs that represent resources by using the property Name\. The following example creates an Amazon S3 bucket with the physical name **my\-bucket\-name**\. +------ +#### [ TypeScript ] + ``` const bucket = new s3.Bucket(this, 'MyBucket', { bucketName: 'my-bucket-name', }); ``` +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket-name") +``` + +------ +#### [ Java ] + +``` +Bucket bucket = Bucket.Builder.create(this, "MyBucket") + .bucketName("my-bucket-name").build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-bucket-name" }); +``` + +------ + Assigning physical names to resources has some disadvantages in AWS CloudFormation\. Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource's properties that are immutable after creation, will fail if a resource has a physical name assigned\. If you end up in a state like that, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again\. See the [AWS CloudFormation documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) for details\. In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value `PhysicalName.GENERATE_IF_NEEDED,`, as follows\. +------ +#### [ TypeScript ] + ``` const bucket = new s3.Bucket(this, 'MyBucket', { - bucketName: PhysicalName.GENERATE_IF_NEEDED, + bucketName: core.PhysicalName.GENERATE_IF_NEEDED, }); ``` +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, "MyBucket", + bucket_name=core.PhysicalName.GENERATE_IF_NEEDED) +``` + +------ +#### [ Java ] + +``` +Bucket bucket = Bucket.Builder.create(this, "MyBucket") + .bucketName(PhysicalName.GENERATE_IF_NEEDED).build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new Bucket(this, "MyBucket", new BucketProps + { BucketName = PhysicalName.GENERATE_IF_NEEDED }); +``` + +------ + ## Passing Unique Identifiers Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. For example, when you are using the low\-level AWS CloudFormation resources, or need to expose resources to the runtime components of an AWS CDK application, such as when referring to Λ functions through environment variables\. These identifiers are available as attributes on the resources, such as the following\. +------ +#### [ TypeScript ] + ``` bucket.bucketName -lambda.functionArn -securityGroup.securityGroupId +lambdaFunc.functionArn +securityGroup.groupArn +``` + +------ +#### [ Python ] + +``` +bucket.bucket_name +lambda_func.function_arn +security_group_arn ``` +------ +#### [ Java ] + +The Java AWS CDK binding uses getter methods for attributes\. + +``` +bucket.getBucketName() +lambdaFunc.getFunctionArn() +securityGroup.getGroupArn() +``` + +------ +#### [ C\# ] + +``` +bucket.BucketName +lambdaFunc.FunctionArn +securityGroup.GroupArn +``` + +------ + The following example shows how to pass a generated bucket name to an AWS Lambda function\. +------ +#### [ TypeScript ] + ``` const bucket = new s3.Bucket(this, 'Bucket'); @@ -116,29 +360,121 @@ new lambda.Function(this, 'MyLambda', { }); ``` +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, "Bucket") + +lambda.Function(self, "MyLambda", environment=dict(BUCKET_NAME=bucket.bucket_name)) +``` + +------ +#### [ Java ] + +``` +final Bucket bucket = new Bucket(this, "Bucket"); + +Function.Builder.create(this, "MyLambda") + .environment(new HashMap() {{ + put("BUCKET_NAME", bucket.getBucketName()); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new Bucket(this, "Bucket"); + +new Function(this, "MyLambda", new FunctionProps +{ + Environment = new Dictionary + { + ["BUCKET_NAME"] = bucket.BucketName + } +}); +``` + +------ + ## Importing Existing External Resources Sometimes you already have a resource in your AWS account and want to use it in your AWS CDK app, for example, a resource that was defined through the console, the AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into an AWS CDK object in the current stack by calling a static factory method on the resource's class\. The following example shows how to define a bucket based on the existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a VPC based on the existing VPC with the resource name `booh`\. +------ +#### [ TypeScript ] + ``` // Construct a resource (bucket) just by its name (must be same account) -Bucket.fromName(this, 'Bucket', 'my-bucket-name'); +s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); // Construct a resource (bucket) by its full ARN (can be cross account) -Bucket.fromArn(this, 'Bucket', 'arn:aws:s3:::my-bucket-name'); +s3.Bucket.fromArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); -// Construct a resource by giving more than one attribute (complex resources) -Resource.fromAttributes(this, 'MyResource', { - resourceName: 'booh', - vpc: vpc +// Construct a resource by giving attribute(s) (complex resources) +ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { + vpcId: 'vpc-1234567890abcde', }); ``` -Because the `ec2.Vpc` construct is composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables\), the complexity makes it difficult to import those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future usage in `cdk.context.json`\. +------ +#### [ Python ] + +``` +# Construct a resource (bucket) just by its name (must be same account) +s3.Bucket.from__bucket_name(self, "MyBucket", "my-bucket-name") + +# Construct a resource (bucket) by its full ARN (can be cross account) +s3.Bucket.from_arn(self, "MyBucket", "arn:aws:s3:::my-bucket-name") + +# Construct a resource by giving attribute(s) (complex resources) +ec2.Vpc.from_vpc_attributes(self, "MyVpc", vpc_id="vpc-1234567890abcdef") +``` + +------ +#### [ Java ] -The following example shows how to get the default VPC of a stack's environment\. +``` +// Construct a resource (bucket) just by its name (must be same account) +Bucket.fromBucketName(this, "MyBucket", "my-bucket-name"); + +// Construct a resource (bucket) by its full ARN (can be cross account) +Bucket.fromBucketArn(this, "MyBucket", + "arn:aws:s3:::my-bucket-name"); + +// Construct a resource by giving attribute(s) (complex resources) +Vpc.fromVpcAttributes(this, "MyVpc", VpcAttributes.builder() + .vpcId("vpc-1234567890abcdef").build()); +``` + +------ +#### [ C\# ] + +``` +// Construct a resource (bucket) just by its name (must be same account) +Bucket.FromBucketName(this, "MyBucket", "my-bucket-name"); + +// Construct a resource (bucket) by its full ARN (can be cross account) +Bucket.FromBucketArn(this, "MyBucket", "arn:aws:s3:::my-bucket-name"); + +// Construct a resource by giving attribute(s) (complex resources) +Vpc.FromVpcAttributes(this, "MyVpc", new VpcAttributes +{ + VpcId = "vpc-1234567890abcdef" +}); +``` + +------ + +Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables\), it can be difficult to import those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. + +You must provide attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want to import the VPC marked as the default is sufficient\. + +------ +#### [ TypeScript ] ``` ec2.Vpc.fromLookup(this, 'DefaultVpc', { @@ -146,9 +482,74 @@ ec2.Vpc.fromLookup(this, 'DefaultVpc', { }); ``` -Note that this approach works only for stacks that are defined with an explicit **account** and **region** in their `env` property\. If this is called from an [environment\-agnostic stack](stacks.md#stack_api), the CLI does not know which environment to query for the VPC\. +------ +#### [ Python ] -Although you can use an imported resource anywhere, you cannot modify the imported resource\. For example, calling `addToResourcePolicy` on an imported `s3.IBucket` does nothing\. +``` +ec2.Vpc.from_lookup(self, "DefaultVpc", is_default=True) +``` + +------ +#### [ Java ] + +``` +Vpc.fromLookup(this, "DefaultVpc", VpcLookupOptions.builder() + .isDefault(true).build()); +``` + +------ +#### [ C\# ] + +``` +Vpc.FromLookup(this, id = "DefaultVpc", new VpcLookupOptions { IsDefault = true }); +``` + +------ + +You can use the `tags` property to query by tag\. Tags may be added to the VPC at the time of its creation using AWS CloudFormation or the AWS CDK, and they may be edited at any time after creation using the AWS Management Console, the AWS CLI, or an AWS SDK\. In addition to any tags you have added yourself, the AWS CDK automatically adds the following tags to all VPCs it creates\. ++ *Name* – The name of the VPC\. ++ *aws\-cdk:subnet\-name* – The name of the subnet\. ++ *aws\-cdk:subnet\-type* – The type of the subnet: Public, Private, or Isolated\. + +------ +#### [ TypeScript ] + +``` +ec2.Vpc.fromLookup(this, 'PublicVpc', + {tags: {'aws-cdk:subnet-type': "Public"}}); +}); +``` + +------ +#### [ Python ] + +``` +ec2.Vpc.from_lookup(self, "PublicVpc", + tags={"aws-cdk:subnet-type": "Public"}) +``` + +------ +#### [ Java ] + +``` +Vpc.fromLookup(this, "PublicVpc", VpcLookupOptions.builder() + .tags(new HashMap {{ put("aws-cdk:subnet-type", "Public"); }}) + .build()); +``` + +------ +#### [ C\# ] + +``` +Vpc.FromLookup(this, id = "PublicVpc", new VpcLookupOptions + { Tags = new Dictionary { ["aws-cdk:subnet-type"] = "Public" }); +``` + +------ + +Note that `Vpc.fromLookup()` works only in stacks that are defined with an explicit **account** and **region** in their `env` property\. If the AWS CDK attempts to look up an Amazon VPC from an [environment\-agnostic stack](stacks.md#stack_api), the CLI does not know which environment to query to find the VPC\. + +Although you can use an imported resource anywhere, you cannot modify the imported resource\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an imported `s3.IBucket` does nothing\. ## Permission Grants @@ -156,23 +557,83 @@ AWS constructs make least\-privilege permissions easy to achieve by offering sim The following example creates the permissions to allow a Lambda function's execution role to read and write objects to a particular Amazon S3 bucket\. If the Amazon S3 bucket is encrypted using an AWS KMS key, this method also grants the Lambda function's execution role permissions to decrypt using this key\. +------ +#### [ TypeScript ] + +``` +if (bucket.grantReadWrite(func).success) { + // ... +} +``` + +------ +#### [ Python ] + +``` +if bucket.grant_read_write(func).success: + # ... +``` + +------ +#### [ Java ] + +``` +if (bucket.grantReadWrite(func).getSuccess()) { + // ... +} +``` + +------ +#### [ C\# ] + ``` -bucket.grantReadWrite(lambda); +if (bucket.GrantReadWrite(func).Success) +{ + // ... +} ``` -The grant methods return an `iam.Grant` object\. Use the success attribute of the `Grant` object to determine whether the grant was effectively applied \(for example, it may not have been applied on [imported resources](#resources_referencing)\)\. You can also use the `assertSuccess` method of the `Grant` object to enforce that the grant was successfully applied\. +------ + +The grant methods return an `iam.Grant` object\. Use the `success` attribute of the `Grant` object to determine whether the grant was effectively applied \(for example, it may not have been applied on [imported resources](#resources_referencing)\)\. You can also use the `assertSuccess` \(Python: `assert_success`\) method of the `Grant` object to enforce that the grant was successfully applied\. If a specific grant method isn't available for the particular use case, you can use a generic grant method to define a new grant with a specified list of actions\. The following example shows how to grant a Lambda function access to the Amazon DynamoDB `CreateBackup` action\. +------ +#### [ TypeScript ] + +``` +table.grant(func, 'dynamodb:CreateBackup'); +``` + +------ +#### [ Python ] + +``` +table.grant(func, "dynamodb:CreateBackup") +``` + +------ +#### [ Java ] + ``` -table.grant(lambda, 'dynamodb:CreateBackup'); +table.grant(func, "dynamodb:CreateBackup"); ``` +------ +#### [ C\# ] + +``` +table.Grant(func, "dynamodb:CreateBackup"); +``` + +------ + Many resources, such as Lambda functions, require a role to be assumed when executing code\. A configuration property enables you to specify an `iam.IRole`\. If no role is specified, the function automatically creates a role specifically for this use\. You can then use grant methods on the resources to add statements to the role\. -The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-iam-readme.html) objects\. Add statements directly to roles \(or a construct's attached role\) using the `addToRolePolicy` method, or to a resource's policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` method\. +The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-iam-readme.html) objects\. Add statements directly to roles \(or a construct's attached role\) using the `addToRolePolicy` method \(Python: `add_to_role_policy`\), or to a resource's policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` \(Python: `add_to_role_policy`\) method\. ## Metrics and Alarms @@ -180,6 +641,9 @@ Many resources emit CloudWatch metrics that can be used to set up monitoring das The following example shows how to define an alarm when the `ApproximateNumberOfMessagesNotVisible` of an Amazon SQS queue exceeds 100\. +------ +#### [ TypeScript ] + ``` import cw = require('@aws-cdk/aws-cloudwatch'); import sqs = require('@aws-cdk/aws-sqs'); @@ -193,12 +657,83 @@ const metric = queue.metricApproximateNumberOfMessagesNotVisible({ // ... }); metric.createAlarm(this, 'TooManyMessagesAlarm', { - comparisonOperator: cw.ComparisonOperator.GreaterThan, + comparisonOperator: cw.ComparisonOperator.GREATER_THAN_THRESHOLD, threshold: 100, // ... }); ``` +------ +#### [ Python ] + +``` +import aws_cdk.aws_cloudwatch as cw +import aws_cdk.aws_sqs as sqs +from aws_cdk.core import Duration + +queue = sqs.Queue(self, "MyQueue") +metric = queue.metric_approximate_number_of_messages_not_visible( + label="Messages Visible (Approx)", + period=Duration.minutes(5), + # ... +) +metric.create_alarm(self, "TooManyMessagesAlarm", + comparison_operator(cw.ComparisonOperator.GREATER_THAN_THRESHOLD + threshold=100, + # ... +) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.core.Duration; +import software.amazon.awscdk.services.sqs.Queue; +import software.amazon.awscdk.services.cloudwatch.Metric; +import software.amazon.awscdk.services.cloudwatch.MetricOptions; +import software.amazon.awscdk.services.cloudwatch.CreateAlarmOptions; +import software.amazon.awscdk.services.cloudwatch.ComparisonOperator; + +Queue queue = new Queue(this, "MyQueue"); + +Metric metric = queue + .metricApproximateNumberOfMessagesNotVisible(MetricOptions.builder() + .label("Messages Visible (Approx)") + .period(Duration.minutes(5)).build()); + +metric.createAlarm(this, "TooManyMessagesAlarm", CreateAlarmOptions.builder() + .comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD) + .threshold(100) + // ... + .build()); +``` + +------ +#### [ C\# ] + +``` +using cdk = Amazon.CDK; +using cw = Amazon.CDK.AWS.CloudWatch; +using sqs = Amazon.CDK.AWS.SQS; + +var queue = new sqs.Queue(this, "MyQueue"); +var metric = queue.MetricApproximateNumberOfMessagesNotVisible(new cw.MetricOptions +{ + Label = "Messages Visible (Approx)", + Period = cdk.Duration.Minutes(5), + // ... +}); +metric.CreateAlarm(this, "TooManyMessagesAlarm", new cw.CreateAlarmOptions +{ + ComparisonOperator = cw.ComparisonOperator.GREATER_THAN_THRESHOLD, + Threshold = 100, + // .. +}); +``` + +------ + If there is no method for a particular metric, you can use the general metric method to specify the metric name manually\. Metrics can also be added to CloudWatch dashboards\. See [CloudWatch](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudwatch-readme.html)\. @@ -211,38 +746,172 @@ In many cases, you must enable permissions on a network for an application to wo You enable data to flow on a given network path by using `allow` methods\. The following example enables HTTPS connections to the web and incoming connections from the Amazon EC2 Auto Scaling group `fleet2`\. +------ +#### [ TypeScript ] + ``` import asg = require('@aws-cdk/aws-autoscaling'); import ec2 = require('@aws-cdk/aws-ec2'); -const fleet: asg.AutoScalingGroup = /*…*/ +const fleet: asg.AutoScalingGroup = /* ... */ // Allow surfing the (secure) web -fleet.connections.allowTo(new ec2.AnyIpv4(), new ec2.Port(443)); +fleet.connections.allowTo(new ec2.Peer.anyIpv4(), new ec2.Port({ fromPort: 443, toPort: 443 })); + +const fleet2: asg.AutoScalingGroup = /* ... */; +fleet.connections.allowFrom(fleet, ec2.Port.AllTraffic()); +``` + +------ +#### [ Python ] -const fleet2: asg.AutoScalingGroup = this.newASG(); -fleet.connections.allowFrom(fleet2); ``` +import aws_cdk.aws_autoscaling as asg +import aws_cdk.aws_ec2 as ec2 + +fleet = asg.AutoScalingGroup( ... ) + +# Allow surfing the (secure) web +fleet.connections.allow_to(ec2.Peer.any_ipv4(), + ec2.Port(PortProps(from_port=443, to_port=443))) + +fleet2 = asg.AutoScalingGroup( ... ) +fleet.connections.allow_from(fleet, ec2.Port.all_traffic()) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.autoscaling.AutoScalingGroup; +import software.amazon.awscdk.services.ec2.Peer; +import software.amazon.awscdk.services.ec2.Port; + +AutoScalingGroup fleet = AutoScalingGroup.Builder.create(this, "MyFleet") + /* ... */.build(); + +// Allow surfing the (secure) Web +fleet.getConnections().allowTo(Peer.anyIpv4(), + Port.Builder.create().fromPort(443).toPort(443).build()); + +AutoScalingGroup fleet2 = AutoScalingGroup.Builder.create(this, "MyFleet2") + /* ... */.build(); +fleet2.getConnections().allowFrom(fleet, Port.allTraffic()); +``` + +------ +#### [ C\# ] + +``` +using cdk = Amazon.CDK; +using asg = Amazon.CDK.AWS.AutoScaling; +using ec2 = Amazon.CDK.AWS.EC2; + +// Allow surfing the (secure) Web +var fleet = new asg.AutoScalingGroup(this, "MyFleet", new asg.AutoScalingGroupProps { ... }); +fleet.Connections.AllowTo(ec2.Peer.AnyIpv4(), new ec2.Port(new ec2.PortProps + { FromPort = 443, ToPort = 443 }); + +var fleet2 = new asg.AutoScalingGroup(this, "MyFleet2", new asg.AutoScalingGroupProps { ... }); +fleet2.Connections.AllowFrom(fleet, ec2.Port.AllTraffic()); +``` + +------ -Certain resources have default ports associated with them, for example, the listener of a load balancer on the public port, and the ports on which the database engine accepts connections for instances of an Amazon RDS database\. In such cases, you can enforce tight network control without having to manually specify the port by using the `allowDefaultPortFrom` and `allowToDefaultPort` methods\. +Certain resources have default ports associated with them, for example, the listener of a load balancer on the public port, and the ports on which the database engine accepts connections for instances of an Amazon RDS database\. In such cases, you can enforce tight network control without having to manually specify the port by using the `allowDefaultPortFrom` and `allowToDefaultPort` methods \(Python: `allow_default_port_from`, `allow_to_default_port`\)\. The following example shows how to enable connections from any IPV4 address, and a connection from an Auto Scaling group to access a database\. +------ +#### [ TypeScript ] + ``` listener.connections.allowDefaultPortFromAnyIpv4('Allow public access'); fleet.connections.allowToDefaultPort(rdsDatabase, 'Fleet can access database'); ``` +------ +#### [ Python ] + +``` +listener.connections.allow_default_port_from_any_ipv4("Allow public access") + +fleet.connections.allow_to_default_port(rds_database, "Fleet can acceess database") +``` + +------ +#### [ Java ] + +``` +listener.getConnections().allowDefaultPortFromAnyIpv4("Allow public access"); + +fleet.getConnections().AllowToDefaultPort(rdsDatabase, "Fleet can access database"); +``` + +------ +#### [ C\# ] + +``` +listener.Connections.AllowDefaultPortFromAnyIpv4("Allow public access"); + +fleet.Connections.AllowToDefaultPort(rdsDatabase, "Fleet can access database"); +``` + +------ + ## Amazon CloudWatch Events -Some resources can act as event sources\. Use the `addEventNotification` method to register an event target to a particular event type emitted by the resource\. In addition to this, `addXxxNotification` methods offer a simplified way to register a handler for a common event type\. +Some resources can act as event sources\. Use the `addEventNotification` method \(Python: `add_event_notification`\) to register an event target to a particular event type emitted by the resource\. In addition to this, `addXxxNotification` methods offer a simplified way to register a handler for a common event type\. The following example shows how to trigger a Lambda function when an object is added to an Amazon S3 bucket\. +------ +#### [ TypeScript ] + ``` -Import targets = require('@aws-cdk/aws-events-targets'); +import s3nots = require('@aws-cdk/aws-s3-notifications'); + const handler = new lambda.Function(this, 'Handler', { /*…*/ }); const bucket = new s3.Bucket(this, 'Bucket'); -bucket.addObjectCreatedNotification(new targets.LambdaFunction(handler)); -``` \ No newline at end of file +bucket.addObjectCreatedNotification(new s3nots.LambdaDestination(handler)); +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_s3_notifications as s3_nots + +handler = lambda_.Function(self, "Handler", ...) +bucket = s3.Bucket(self, "Bucket") +bucket.add_object_created_notification(s3_not.LambdaDestination(handler)) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.s3.Bucket; +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.s3.notifications.LambdaDestination; + +Function handler = Function.Builder.create(this, "Handler")/* ... */.build(); +Bucket bucket = new Bucket(this, "Bucket"); +bucket.addObjectCreatedNotification(new LambdaDestination(handler)); +``` + +------ +#### [ C\# ] + +``` +using lambda = Amazon.CDK.AWS.Lambda; +using s3 = Amazon.CDK.AWS.S3; +using s3_not = Amazon.CDK.AWS.S3.Notifications; + +var handler = new lambda.Function(this, "Handler", new lambda.FunctionProps { .. }); +var bucket = new s3.Bucket(this, "Bucket"); +bucket.AddObjectCreatedNotification(new s3_not.LambdaDestination(handler)); +``` + +------ \ No newline at end of file diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index f8184748..f150ff8f 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -1,6 +1,6 @@ # Creating a Serverless Application Using the AWS CDK -This example walks you through how to create the resources for a simple widget dispensing service\. It includes: +This example walks you through how to create the resources for a simple widget dispensing service\. \(For the purpose of this example, a widget is just an name or identifier that can be added to, retrieved from, and deleted from a collection\.\) The example includes: + An AWS Lambda function\. + An Amazon API Gateway API to call the Lambda function\. + An Amazon S3 bucket that contains the Lambda function code\. @@ -9,7 +9,7 @@ This tutorial contains the following steps\. 1. Creates a AWS CDK app -1. Creates a Lambda function that gets a list of widgets with: GET / +1. Creates a Lambda function that gets a list of widgets with HTTP GET / 1. Creates the service that calls the Lambda function @@ -17,14 +17,17 @@ This tutorial contains the following steps\. 1. Tests the app -1. Add Lambda functions to do the following: +1. Adds Lambda functions to do the following: + Create a widget with POST /\{name\} + Get a widget by name with GET /\{name\} + Delete a widget by name with DELETE /\{name\} ## Create a AWS CDK App -Create the TypeScript app **MyWidgetService** in the current folder\. +Create the app **MyWidgetService** in the current folder\. + +------ +#### [ TypeScript ] ``` mkdir MyWidgetService @@ -32,16 +35,107 @@ cd MyWidgetService cdk init --language typescript ``` -This creates `my_widget_service.ts` in the `bin` directory, and `my_widget_service-stack.ts` in the `lib` directory\. +------ +#### [ Python ] + +``` +mkdir MyWidgetService +cd MyWidgetService +cdk init --language python +source .env/bin/activate || "on Windows, use: .env\Scripts\activate.bat" +pip install -r requirements.txt +``` + +------ +#### [ Java ] + +``` +mkdir MyWidgetService +cd MyWidgetService +cdk init --language java +``` + +You may now import the Maven project into your IDE\. -Build the app and notice that it creates an empty stack\. +------ +#### [ C\# ] + +``` +mkdir MyWidgetService +cd MyWidgetService +cdk init --language csharp +``` + +You may now open `src/MyWidgetService.sln` in Visual Studio\. + +------ + +The important files in the blank project are as follows\. \(We will also be adding a couple of new files\.\) + +------ +#### [ TypeScript ] ++ `bin/my_widget_service.ts` – Main entry point for the application ++ `lib/my_widget_service-stack.ts` – Defines the widget service stack + +------ +#### [ Python ] ++ `app.py` – Main entry point for the application ++ `my_widget_service/my_widget_service_stack.py` – Defines the widget service stack + +------ +#### [ Java ] ++ `src/main/java/com/myorg/MyWidgetServiceApp.java` – Main entry point for the application ++ `src/main/java/com/myorg/MyWidgetServiceStack.java` – Defines the widget service stack + +------ +#### [ C\# ] ++ `src/MyWidgetService/Program.cs` – Main entry point for the application ++ `src/MyWidgetService/MyWidgetServiceStack.cs` – Defines the widget service stack + +------ + +Build the app and note that it synthesizes an empty stack\. + +------ +#### [ TypeScript ] ``` npm run build cdk synth ``` -You should see a stack like the following, where *CDK\-VERSION* is the version of the AWS CDK\. +------ +#### [ Python ] + +``` +cdk synth +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk synth +``` + +**Note** +Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. + +------ +#### [ C\# ] + +``` +dotnet build src +cdk synth +``` + +**Note** +Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. + +------ + +You should see output like the following, where *CDK\-VERSION* is the version of the AWS CDK\. ``` Resources: @@ -53,9 +147,9 @@ Resources: ## Create a Lambda Function to List All Widgets -The next step is to create a Lambda function to list all of the widgets in our Amazon S3 bucket\. +The next step is to create a Lambda function to list all of the widgets in our Amazon S3 bucket\. We will provide the Lambda function's code in JavaScript\. -Create the `resources` directory at the same level as the `bin` directory\. +Create the `resources` directory in the project's main directory\. ``` mkdir resources @@ -104,22 +198,99 @@ exports.main = async function(event, context) { } ``` -Save it and be sure it builds and creates an empty stack\. Because we haven't wired the function to the app, the Lambda file doesn't appear in the output\. +Save it and be sure the project still results in an empty stack\. We haven't yet wired the Lambda function to the AWS CDK app, so the Lambda asset doesn't appear in the output\. + +------ +#### [ TypeScript ] ``` npm run build cdk synth ``` +------ +#### [ Python ] + +``` +cdk synth +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk synth +``` + +**Note** +Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. + +------ +#### [ C\# ] + +``` +dotnet build src +cdk synth +``` + +**Note** +Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. + +------ + ## Creating a Widget Service Add the API Gateway, Lambda, and Amazon S3 packages to the app\. +------ +#### [ TypeScript ] + ``` npm install @aws-cdk/aws-apigateway @aws-cdk/aws-lambda @aws-cdk/aws-s3 ``` -Create the TypeScript file `widget_service.ts` in the `lib` directory\. +------ +#### [ Python ] + +``` +pip install aws_cdk.aws_apigateway aws_cdk.aws_lambda aws_cdk.aws_s3 +``` + +------ +#### [ Java ] + +Using your IDE's Maven integration \(e\.g\., in Eclipse, right\-click your project and choose **Maven** > **Add Dependency**\), install the following artifacts from the group `software.amazon.awscdk`: + +``` +apigateway +lambda +s3 +``` + +------ +#### [ C\# ] + +Choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio and add the following packages\. + +``` +Amazon.CDK.AWS.ApiGateway +Amazon.CDK.AWS.Lambda +Amazon.CDK.AWS.S3 +``` + +**Tip** +If you don't see these packages in the **Browse** tab of the **Manage Packages for Solution** page, make sure the **Include prerelease** checkbox is ticked\. +For a better experience, also add the `Amazon.Jsii.Analyzers` package to provide compile\-time checks for missing required properties\. + +------ + +Create a new source file to define the widget service with the source code shown below\. + +------ +#### [ TypeScript ] + +File: `lib/widget_service.ts` ``` import core = require("@aws-cdk/core"); @@ -158,16 +329,202 @@ export class WidgetService extends core.Construct { } ``` -Save the app and be sure it builds and creates a \(still empty\) stack\. +------ +#### [ Python ] + +File: `my_widget_service/widget_service.py` + +``` +from aws_cdk import (core, + aws_apigateway as apigateway, + aws_s3 as s3, + aws_lambda as lambda_) + +class WidgetService(core.Construct): + def __init__(self, scope: core.Construct, id: str): + super().__init__(scope, id) + + bucket = s3.Bucket(self, "WidgetStore") + + handler = lambda_.Function(self, "WidgetHandler", + runtime=lambda_.Runtime.NODEJS_10_X, + code=lambda_.Code.asset("resources"), + handler="widgets.main", + environment=dict( + BUCKET=bucket.bucket_name) + ) + + bucket.grant_read_write(handler) + + api = apigateway.RestApi(self, "widgets-api", + rest_api_name="Widget Service", + description="This service serves widgets.") + + get_widgets_integration = apigateway.LambdaIntegration(handler, + request_templates={"application/json": '{ "statusCode": "200" }'}) + + api.root.add_method("GET", get_widgets_integration) # GET / +``` + +------ +#### [ Java ] + +File: `src/src/main/java/com/myorg/WidgetService.java` + +``` +package com.myorg; + +import java.util.HashMap; + +import software.amazon.awscdk.core.Construct; +import software.amazon.awscdk.services.apigateway.LambdaIntegration; +import software.amazon.awscdk.services.apigateway.Resource; +import software.amazon.awscdk.services.apigateway.RestApi; +import software.amazon.awscdk.services.lambda.Code; +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.lambda.Runtime; +import software.amazon.awscdk.services.s3.Bucket; + +public class WidgetService extends Construct { + + @SuppressWarnings("serial") + public WidgetService(Construct scope, String id) { + super(scope, id); + + Bucket bucket = new Bucket(this, "WidgetStore"); + + Function handler = Function.Builder.create(this, "WidgetHandler") + .runtime(Runtime.NODEJS_10_X) + .code(Code.fromAsset("resources")) + .handler("widgets.main") + .environment(new HashMap() {{ + put("BUCKET", bucket.getBucketName()); + }}).build(); + + bucket.grantReadWrite(handler); + + RestApi api = RestApi.Builder.create(this, "Widgets-API") + .restApiName("Widget Service").description("This service services widgets.") + .build(); + + LambdaIntegration getWidgetsIntegration = LambdaIntegration.Builder.create(handler) + .requestTemplates(new HashMap() {{ + put("application/json", "{ \"statusCode\": \"200\" }"); + }}).build(); + + api.getRoot().addMethod("GET", getWidgetsIntegration); + } +} +``` + +------ +#### [ C\# ] + +File: `src/MyWidgetService/WidgetService.cs` + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.APIGateway; +using Amazon.CDK.AWS.Lambda; +using Amazon.CDK.AWS.S3; +using System.Collections.Generic; + +namespace MyWidgetService +{ + + public class WidgetService : Construct + { + public WidgetService(Construct scope, string id) : base(scope, id) + { + var bucket = new Bucket(this, "WidgetStore"); + + var handler = new Function(this, "WidgetHandler", new FunctionProps + { + Runtime = Runtime.NODEJS_10_X, + Code = Code.FromAsset("resources"), + Handler = "widgets.main", + Environment = new Dictionary + { + ["BUCKET"] = bucket.BucketName + } + }); + + bucket.GrantReadWrite(handler); + + var api = new RestApi(this, "Widgets-API", new RestApiProps + { + RestApiName = "Widget Service", + Description = "This service services widgets." + }); + + var getWidgetsIntegration = new LambdaIntegration(handler, new LambdaIntegrationOptions + { + RequestTemplates = new Dictionary + { + ["application/json"] = "{ \"statusCode\": \"200\" }" + } + }); + + api.Root.AddMethod("GET", getWidgetsIntegration); + + } + } +} +``` + +------ + +Save the app and make sure it still synthesizes an empty stack\. + +------ +#### [ TypeScript ] ``` npm run build cdk synth ``` +------ +#### [ Python ] + +``` +cdk synth +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk synth +``` + +**Note** +Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. + +------ +#### [ C\# ] + +``` +dotnet build src +cdk synth +``` + +**Note** +Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. + +------ + ## Add the Service to the App -To add the service to the app, first modify `my_widget_service-stack.ts` in the `lib` directory\. Add the following line of code after the existing `import` statement\. +To add the widget service to our AWS CDK app, we'll need to modify the source file that defines the stack to instantiate the service construct\. + +------ +#### [ TypeScript ] + +File: `lib/my_widget_service-stack.ts` + +Add the following line of code after the existing `import` statement\. ``` import widget_service = require('../lib/widget_service'); @@ -179,22 +536,97 @@ Replace the comment in the constructor with the following line of code\. new widget_service.WidgetService(this, 'Widgets'); ``` -Be sure the app builds and creates a stack \(we don't show the stack because it's over 250 lines\)\. +------ +#### [ Python ] + +File: `lib/my_widget_service-stack.ts` + +Add the following line of code after the existing `import` statement\. + +``` +from . import widget_service +``` + +Replace the comment in the constructor with the following line of code\. + +``` + widget_service.WidgetService(self, "Widgets") +``` + +------ +#### [ Java ] + +File: `src/src/main/java/com/myorg/MyWidgetServiceStack.java` + +Replace the comment in the constructor with the following line of code\. + +``` +new WidgetService(this, "Widgets"); +``` + +------ +#### [ C\# ] + +File: `src/MyWidgetService/MyWidgetServiceStack.cs` + +Replace the comment in the constructor with the following line of code\. + +``` +new WidgetService(this, "Widgets"); +``` + +------ + +Be sure the app builds and synthesizes a stack \(we won't show the stack here: it's over 250 lines\)\. + +------ +#### [ TypeScript ] ``` npm run build cdk synth ``` +------ +#### [ Python ] + +``` +cdk synth +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk synth +``` + +**Note** +Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. + +------ +#### [ C\# ] + +``` +dotnet build src +cdk synth +``` + +**Note** +Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. + +------ + ## Deploy and Test the App -Before you can deploy your first AWS CDK app, you must bootstrap your deployment\. This creates some AWS infrastructure that the AWS CDK needs\. For details, see the **bootstrap** section of the [AWS CDK Tools](tools.md) \(if you've already bootstrapped a AWS CDK app, you'll get a warning and nothing will change\)\. +Before you can deploy your first AWS CDK app containing a lambda function, you must bootstrap your AWS environment\. This creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see the **bootstrap** section of the [AWS CDK Tools](tools.md) \(if you've already bootstrapped, you'll get a warning and nothing will change\)\. ``` cdk bootstrap ``` -Deploy your app, as follows\. +Now we're ready to deploy the app as follows\. ``` cdk deploy @@ -338,7 +770,12 @@ exports.main = async function(event, context) { } ``` -Wire up these functions to your API Gateway code in `widget_service.ts` by adding the following code at the end of the constructor\. +Wire up these functions to your API Gateway code at the end of the `WidgetService` constructor\. + +------ +#### [ TypeScript ] + +File: `lib/widget_service.ts` ``` const widget = api.root.addResource("{id}"); @@ -357,13 +794,113 @@ Wire up these functions to your API Gateway code in `widget_service.ts` by addin widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} ``` +------ +#### [ Python ] + +File: `my_widget_service/widget_service.py` + +``` + widget = api.root.add_resource("{id}") + + # Add new widget to bucket with: POST /{id} + post_widget_integration = apigateway.LambdaIntegration(handler) + + # Get a specific widget from bucket with: GET /{id} + get_widget_integration = apigateway.LambdaIntegration(handler) + + # Remove a specific widget from the bucket with: DELETE /{id} + delete_widget_integration = apigateway.LambdaIntegration(handler) + + widget.add_method("POST", post_widget_integration); # POST /{id} + widget.add_method("GET", get_widget_integration); # GET /{id} + widget.add_method("DELETE", delete_widget_integration); # DELETE /{id} +``` + +------ +#### [ Java ] + +File: `src/src/main/java/com/myorg/WidgetService.java` + +``` + // Add new widget to bucket with: POST /{id} + LambdaIntegration postWidgetIntegration = new LambdaIntegration(handler); + + // Get a specific widget from bucket with: GET /{id} + LambdaIntegration getWidgetIntegration = new LambdaIntegration(handler); + + // Remove a specific widget from the bucket with: DELETE /{id} + LambdaIntegration deleteWidgetIntegration = new LambdaIntegration(handler); + + widget.addMethod("POST", postWidgetIntegration); // POST /{id} + widget.addMethod("GET", getWidgetIntegration); // GET /{id} + widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} +``` + +------ +#### [ C\# ] + +File: `src/MyWidgetService/WidgetService.cs` + +``` + var widget = api.Root.AddResource("{id}"); + + // Add new widget to bucket with: POST /{id} + var postWidgetIntegration = new LambdaIntegration(handler); + + // Get a specific widget from bucket with: GET /{id} + var getWidgetIntegration = new LambdaIntegration(handler); + + // Remove a specific widget from the bucket with: DELETE /{id} + var deleteWidgetIntegration = new LambdaIntegration(handler); + + widget.AddMethod("POST", postWidgetIntegration); // POST /{id} + widget.AddMethod("GET", getWidgetIntegration); // GET /{id} + widget.AdMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} +``` + +------ + Save, build, and deploy the app\. +------ +#### [ TypeScript ] + ``` npm run build cdk deploy ``` +------ +#### [ Python ] + +``` +cdk deploy +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk deploy +``` + +**Note** +Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. + +------ +#### [ C\# ] + +``` +dotnet build src +cdk deploy +``` + +**Note** +Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. + +------ + We can now store, show, or delete an individual widget\. Use the following commands to list the widgets, create the widget **example**, list all of the widgets, show the contents of **example** \(it should show today's date\), delete **example**, and then show the list of widgets again\. ``` @@ -375,4 +912,12 @@ curl -X DELETE 'https://GUID.execute-api-REGION.amazonaws.com/prod/example' curl -X GET 'https://GUID.execute-api-REGION.amazonaws.com/prod' ``` -You can also use the API Gateway console to test these functions\. You have to set the **name** value to the name of a widget, such as **example**\. \ No newline at end of file +You can also use the API Gateway console to test these functions\. Set the **name** value to the name of a widget, such as **example**\. + +## Clean Up + +To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done with this exercise\. + +``` +cdk destroy +``` \ No newline at end of file diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index 512c2edd..2753be38 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -2,55 +2,224 @@ Most of the other code examples in the *AWS CDK Developer Guide* involve only a single stack\. However, you can create apps containing any number of stacks\. Each stack results in its own AWS CloudFormation template\. Stacks are the *unit of deployment:* each stack in an app can be synthesized and deployed individually using the `cdk deploy` command\. -This topic shows how to create a simple stack that contains an Amazon S3 bucket\. The stack uses a Boolean property, named `encryptBucket`, to indicate whether the bucket should be encrypted\. If so, the stack enables encryption, using a key managed by AWS Key Management Service \(AWS KMS\)\. The app creates two instances of this stack, one with encryption and one without\. +This topic illustrates how to extend the `Stack` class to accept new properties or arguments, how to use these properties affect what resources the stack contains and their configuration, and how to instantiate multiple stacks from this class\. The example uses a Boolean property, named `encryptBucket` \(Python: `encrypt_bucket`\), to indicate whether an Amazon S3 bucket should be encrypted\. If so, the stack enables encryption using a key managed by AWS Key Management Service \(AWS KMS\)\. The app creates two instances of this stack, one with encryption and one without\. -## Prerequisites +## Before You Begin -To complete this example, first do the following: -+ Install Node\.js and the AWS CDK command line tools, if you haven't already\. See [Getting Started With the AWS CDK](getting_started.md) for details\. -+ Create a TypeScript AWS CDK project by entering the following commands at the command line\. +First, install Node\.js and the AWS CDK command line tools, if you haven't already\. See [Getting Started With the AWS CDK](getting_started.md) for details\. - ``` - mkdir multistack && cd multistack - cdk init --language=typescript - ``` -+ Install the `core` and `s3` AWS Construct Library modules\. We use these modules in our app\. +Next, create an AWS CDK project by entering the following commands at the command line\. - ``` - npm install @aws-cdk/core - npm install @aws-cdk/aws-s3 - ``` +------ +#### [ TypeScript ] -## Extend `StackProps` +``` +mkdir multistack +cd multistack +cdk init --language=typescript +``` + +------ +#### [ Python ] + +``` +mkdir multistack +cd multistack +cdk init --language=python +source ./env/bin/activate +pip install -r requirements.txt +``` + +------ +#### [ Java ] + +``` +mkdir multistack +cd multistack +cdk init --language=java +``` + +You can import the resulting Maven project into your Java IDE\. + +------ +#### [ C\# ] + +``` +mkdir multistack +cd multistack +cdk init --language=csharp +``` + +You can open the file `src/Pipeline.sln` in Visual Studio\. + +------ + +Finally, install the `core` and `s3` AWS Construct Library modules\. We use these modules in our app\. + +------ +#### [ TypeScript ] + +``` +npm install @aws-cdk/core @aws-cdk/aws-s3 +``` + +------ +#### [ Python ] + +``` +pip install aws_cdk.core aws_cdk.aws_s3 +``` + +------ +#### [ Java ] + +Using the Maven integration in your IDE \(for example, in Eclipse, right\-click the project and choose **Maven** > **Add Dependency**\), add the following packages in the group `software.amazon.awscdk`\. + +``` +core +s3 +``` + +------ +#### [ C\# ] + +``` +nuget install Amazon.CDK +nuget install Amazon.CDK.AWS.S3 +``` + +Or **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio + +**Tip** +If you don't see these packages in the **Browse** tab of the **Manage Packages for Solution** page, make sure the **Include prerelease** checkbox is ticked\. +For a better experience, also add the `Amazon.Jsii.Analyzers` package to provide compile\-time checks for missing required properties\. + +------ + +## Add Optional Parameter + +The `props` argument of the `Stack` constructor fulfills the interface `StackProps`\. Because we want our stack to accept an additional property to tell us whether to encrypt the Amazon S3 bucket, we should create an interface or class that includes that property\. This allows the compiler to make sure the property has a Boolean value and enables autocompletion for it in your IDE\. + +So open the indicated source file in your IDE or editor and add the new interface, class, or argument\. The code should look like this after the changes\. The lines we added are shown in boldface\. + +------ +#### [ TypeScript ] + +File: `lib/multistack-stack.ts` + +``` +import cdk = require('@aws-cdk/core'); +import s3 = require('@aws-cdk/aws-s3'); + +interface MultiStackProps extends cdk.StackProps { + encryptBucket?: boolean; +} + +export class MultistackStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: MultiStackProps) { + super(scope, id, props); + + // The code that defines your stack goes here + } +} +``` + +------ +#### [ Python ] + +File: `multistack/multistack_stack.py` + +Python does not have an interface feature, so we'll extend our stack to accept the new property by adding a keyword argument\. + +``` +from aws_cdk import aws_s3 as s3 + +class MultistackStack(core.Stack): + + # The Stack class doesn't know about our encrypt_bucket parameter, + # so accept it separately and pass along any other keyword arguments. + def __init__(self, scope: core.Construct, id: str, *, encrypt_bucket=False, + **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + # The code that defines your stack goes here +``` + +------ +#### [ Java ] + +File: `src/main/java/com/myorg/MultistackStack.java` + +It's more complicated than we really want to get into to extend a props type in Java, so we'll simply write our stack's constructor to accept an optional Boolean parameter\. Since `props` is an optional argument, we'll write an additional constructor that allows you to skip it\. It will default to `false`\. + +``` +package com.myorg; + +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; +import software.amazon.awscdk.core.Construct; + +import software.amazon.awscdk.services.s3.Bucket; + +public class MultistackStack extends Stack { + // additional constructors to allow props and/or encryptBucket to be omitted + public MultistackStack(final Construct scope, final String id, boolean encryptBucket) { + this(scope, id, null, encryptBucket); + } + + public MultistackStack(final Construct scope, final String id) { + this(scope, id, null, false); + } + + public MultistackStack(final Construct scope, final String id, final StackProps props, + final boolean encryptBucket) { + super(scope, id, props); + + // The code that defines your stack goes here + } +} +``` + +------ +#### [ C\# ] + +File: `src/Multistack/MultistackStack.cs` + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; +namespace Multistack +{ + + + public class MultiStackProps : StackProps + { + public bool? EncryptBucket { get; set; } + } -The `props` argument of the `Stack` constructor fulfills the interface `StackProps`\. Because we want our stack to accept an additional property to tell us whether to encrypt the Amazon S3 bucket, we should create an interface that includes that property\. This allows TypeScript to make sure the property has a Boolean value and enables autocompletion for it in your IDE\. -1. Open `lib/multistack-stack.ts` in your IDE or editor\. + public class MultistackStack : Stack + { + public MultistackStack(Construct scope, string id, MultiStackProps props) : base(scope, id, props) + { + // The code that defines your stack goes here + } + } +} +``` -1. Add the new interface definition\. The code in `multistack-stack.ts` should now look like this\. The lines we added are shown in boldface\. +------ - ``` - import cdk = require('@aws-cdk/core'); - import s3 = require('@aws-cdk/aws-s3'); - - interface MyStackProps extends cdk.StackProps { - encryptBucket?: boolean; - } - - export class MultistackStack extends cdk.Stack { - constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { - super(scope, id, props); - - // The code that defines your stack goes here - } - } - ``` +The new property is optional\. If `encryptBucket` \(Python: `encrypt_bucket`\) is not present, its value is `undefined`, or the local equivalent\. The bucket will be unencrypted by default\. -We've declared the new property as optional\. If `encryptBucket` is not present, its value is `undefined`, which is false in a Boolean context\. In other words, the bucket will be unencrypted by default\. +## Define the Stack Class -## Define the Stack Class + Now let's define our stack class, using our new property\. Make the code look like the following\. The code you need to add or change is shown in boldface\. - Now let's define our stack class, using our new property\. Still working in `multistack-stack.ts`, make the code look like the following\. The code that you need to add or change is shown in boldface\. +------ +#### [ TypeScript ] + +File: `lib/multistack-stack.ts` ``` import cdk = require('@aws-cdk/core'); @@ -64,25 +233,152 @@ export class MultistackStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: MultistackProps) { super(scope, id, props); - // Add a Boolean property "encryptBucket" to the StackProps constructor. + // Add a Boolean property "encryptBucket" to the stack constructor. // If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. // Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). if (props && props.encryptBucket) { new s3.Bucket(this, "MyGroovyBucket", { encryption: s3.BucketEncryption.KMS_MANAGED, - removalPolicy: RemovalPolicy.DESTROY + removalPolicy: cdk.RemovalPolicy.DESTROY }); } else { new s3.Bucket(this, "MyGroovyBucket", { - removalPolicy: RemovalPolicy.DESTROY}); + removalPolicy: cdk.RemovalPolicy.DESTROY}); } } } ``` -## Create Two Stack Instances +------ +#### [ Python ] + +File: `multistack/multistack_stack.py` + +``` +from aws_cdk import core +from aws_cdk import aws_s3 as s3 + +class MultistackStack(core.Stack): + + # The Stack class doesn't know about our encrypt_bucket parameter, + # so accept it separately and pass along any other keyword arguments. + def __init__(self, scope: core.Construct, id: str, *, encrypt_bucket=False, + **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + # Add a Boolean property "encryptBucket" to the stack constructor. + # If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. + # Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). + if encrypt_bucket: + s3.Bucket(this, "MyGroovyBucket", + encryption=s3BucketEncryption.KMS_MANAGED, + removal_policy=core.RemovalPolicy.DESTROY) + else: + s3.Bucket(this, "MyGroovyBucket", + removal_policy=core.RemovalPolicy.DESTROY) +``` + +------ +#### [ Java ] + +File: `src/main/java/com/myorg/MultistackStack.java` + +``` +package com.myorg; + +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; +import software.amazon.awscdk.core.Construct; +import software.amazon.awscdk.core.RemovalPolicy; -Open the file `bin/multistack.ts` and add the code to instantiate two stacks\. As before, the lines of code shown in boldface are the ones you need to add\. Delete the existing `new MultistackStack` definition\. +import software.amazon.awscdk.services.s3.Bucket; +import software.amazon.awscdk.services.s3.BucketEncryption; + +public class MultistackStack extends Stack { + // additional constructors to allow props and/or encryptBucket to be omitted + public MultistackStack(final Construct scope, final String id, + boolean encryptBucket) { + this(scope, id, null, encryptBucket); + } + + public MultistackStack(final Construct scope, final String id) { + this(scope, id, null, false); + } + + // main constructor + public MultistackStack(final Construct scope, final String id, + final StackProps props, final boolean encryptBucket) { + super(scope, id, props); + + // Add a Boolean property "encryptBucket" to the stack constructor. + // If true, creates an encrypted bucket. Otherwise, the bucket is + // unencrypted. Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). + if (encryptBucket) { + Bucket.Builder.create(this, "MyGroovyBucket") + .encryption(BucketEncryption.KMS_MANAGED) + .removalPolicy(RemovalPolicy.DESTROY).build(); + } else { + Bucket.Builder.create(this, "MyGroovyBucket") + .removalPolicy(RemovalPolicy.DESTROY).build(); + } + } +} +``` + +------ +#### [ C\# ] + +File: `src/Multistack/MultistackStack.cs` + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +namespace Multistack +{ + + public class MultiStackProps : StackProps + { + public bool? EncryptBucket { get; set; } + } + + public class MultistackStack : Stack + { + public MultistackStack(Construct scope, string id, IMultiStackProps props = null) : base(scope, id, props) + { + // Add a Boolean property "EncryptBucket" to the stack constructor. + // If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. + // Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). + if (props?.EncryptBucket ?? false) + { + new Bucket(this, "MyGroovyBucket", new BucketProps + { + Encryption = BucketEncryption.KMS_MANAGED, + RemovalPolicy = RemovalPolicy.DESTROY + }); + } + else + { + new Bucket(this, "MyGroovyBucket", new BucketProps + { + RemovalPolicy = RemovalPolicy.DESTROY + }); + } + } + } +} +``` + +------ + +## Create Two Stack Instances + +Now we'll add the code to instantiate two separate stacks\. As before, the lines of code shown in boldface are the ones you need to add\. Delete the existing `MultistackStack` definition\. + +------ +#### [ TypeScript ] + +File: `bin/multistack.ts` ``` #!/usr/bin/env node @@ -93,7 +389,7 @@ import { MultistackStack } from '../lib/multistack-stack'; const app = new cdk.App(); new MultistackStack(app, "MyWestCdkStack", { - env: {region: "us-west-2"}, + env: {region: "us-west-1"}, encryptBucket: false }); @@ -103,19 +399,140 @@ new MultistackStack(app, "MyEastCdkStack", { }); ``` - This code uses the new `encryptBucket` property on the `MultistackStack` class to create the following: +------ +#### [ Python ] + +File: `./app.py` + +``` +#!/usr/bin/env python3 + +from aws_cdk import core + +from multistack.multistack_stack import MultistackStack + +app = core.App() +MultistackStack(app, "MyWestCdkStack", + env=core.Environment(region="us-west-1"), + encrypt_bucket=False) + +MultistackStack(app, "MyEastCdkStack", + env=core.Environment(region="us-east-1"), + encrypt_bucket=False) +``` + +------ +#### [ Java ] + +File: `src/main/java/com/myorg/MultistackApp.java` + +``` +package com.myorg; + +import software.amazon.awscdk.core.App; +import software.amazon.awscdk.core.Environment; +import software.amazon.awscdk.core.StackProps; + +public class MultistackApp { + public static void main(final String argv[]) { + App app = new App(); + + new MultistackStack(app, "MyWestCdkStack", StackProps.builder() + .env(Environment.builder() + .region("us-west-1") + .build()) + .build(), false); + + new MultistackStack(app, "MyEastCdkStack", StackProps.builder() + .env(Environment.builder() + .region("us-east-1") + .build()) + .build(), true); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +File: src/Multistack/Program\.cs + +``` +using Amazon.CDK; + +namespace Multistack +{ + class Program + { + static void Main(string[] args) + { + var app = new App(); + + new MultistackStack(app, "MyWestCdkStack", new MultiStackProps + { + Env = new Environment { Region = "us-west-1" }, + EncryptBucket = false + }); + + new MultistackStack(app, "MyEastCdkStack", new MultiStackProps + { + Env = new Environment { Region = "us-east-1" }, + EncryptBucket = true + }); + + app.Synth(); + } + } +} +``` + +------ + + This code uses the new `encryptBucket` \(Python: `encrypt_bucket`\) property on the `MultistackStack` class to instantiate the following: + One stack with an encrypted Amazon S3 bucket in the `us-east-1` AWS Region\. + One stack with an unencrypted Amazon S3 bucket in the `us-west-1` AWS Region\. -## Define the Stack Class +## Synthesize and Deploy the Stack + +Now you can deploy stacks from the app\. First, build the project, if necessary\. -Now you can build the app\. The TypeScript compiler converts your code to JavaScript\. +------ +#### [ TypeScript ] ``` npm run build ``` -Next, synthesize an AWS CloudFormation template for `MyEastCdkStack`—, the stack in `us-east-1`\. This is the stack with the encrypted S3 bucket\. +------ +#### [ Python ] + +No build step is necessary\. + +------ +#### [ Java ] + +``` +mvn compile +``` + +**Note** +Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. + +------ +#### [ C\# ] + +``` +dotnet build src +``` + +**Note** +Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. + +------ + +Next, synthesize a AWS CloudFormation template for `MyEastCdkStack`—the stack in `us-east-1`\. This is the stack with the encrypted S3 bucket\. ``` $ cdk synth MyEastCdkStack @@ -142,13 +559,17 @@ Resources: Modules: aws-cdk=1.10.0,@aws-cdk/aws-events=1.10.0,@aws-cdk/aws-iam=1.10.0,@aws-cdk/aws-kms=1.10.0,@aws-cdk/aws-s3=1.10.0,@aws-cdk/core=1.10.0,@aws-cdk/cx-api=1.10.0,@aws-cdk/region-info=1.10.0,jsii-runtime=node.js/v10.16.2 ``` -To deploy this stack to your AWS account, issue the following command\. For *PROFILE\_NAME*, substitute the name of an AWS CLI profile that contains appropriate credentials for deploying to the `us-east-1` AWS Region\. +To deploy this stack to your AWS account, issue one of the following commands\. The first command uses your default AWS profile to obtain the credentials to deploy the stack\. The second uses a profile you specify: for *PROFILE\_NAME*, substitute the name of an AWS CLI profile that contains appropriate credentials for deploying to the `us-east-1` AWS Region\. + +``` +cdk deploy MyEastCdkStack +``` ``` cdk deploy MyEastCdkStack --profile=PROFILE_NAME ``` -## Clean Up +## Clean Up To avoid charges for resources that you deployed, destroy the stack using the following command\. @@ -156,4 +577,4 @@ To avoid charges for resources that you deployed, destroy the stack using the fo cdk destroy MyEastCdkStack ``` -The destroy operation fails if there is anything stored in the bucket\. There shouldn't be anything stored if you've only followed the instructions in this topic\. But if you put something in the bucket yourself, you must delete it using the AWS Management Console or the AWS CLI before destroying the stack\. \ No newline at end of file +The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket's contents, but not the bucket itself, using the AWS Management Console or the AWS CLI before destroying the stack\. \ No newline at end of file diff --git a/doc_source/stacks.md b/doc_source/stacks.md index c0ab4afd..81d9fd2d 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -8,6 +8,9 @@ You can define any number of stacks in your AWS CDK app\. Any instance of the `S For example, the following code defines an AWS CDK app with two stacks\. +------ +#### [ TypeScript ] + ``` const app = new App(); @@ -17,6 +20,44 @@ new MySecondStack(app, 'stack2'); app.synth(); ``` +------ +#### [ Python ] + +``` +app = App() + +MyFirstStack(app, 'stack1') +MySecondStack(app, 'stack2') + +app.synth() +``` + +------ +#### [ Java ] + +``` +App app = new App(); + +new MyFirstStack(app, "stack1"); +new MySecondStack(app, "stack2"); + +app.synth(); +``` + +------ +#### [ C\# ] + +``` +var app = new App(); + +new MyFirstStack(app, "stack1"); +new MySecondStack(app, "stack2"); + +app.Synth(); +``` + +------ + To list all the stacks in an AWS CDK app, run the cdk ls command, which for the previous AWS CDK app would have the following output\. ``` @@ -37,38 +78,174 @@ This approach is conceptually different from how AWS CloudFormation templates ar **Note** The AWS CDK provides as much resolution as possible during synthesis time to enable idiomatic and natural usage of your programming language\. -Like any other construct, stacks can be composed together into groups\. The following pseudocode shows an example of a service that consists of three stacks: a control plane, a data plane, and monitoring stacks\. The service construct is defined twice: once for the beta environment and once for the production environment\. +Like any other construct, stacks can be composed together into groups\. The following code shows an example of a service that consists of three stacks: a control plane, a data plane, and monitoring stacks\. The service construct is defined twice: once for the beta environment and once for the production environment\. + +------ +#### [ TypeScript ] ``` -import cdk = require("@aws-cdk/core"); -import { Construct, Stack } from "@aws-cdk/core"; +import { App, Construct, Stack } from "@aws-cdk/core"; interface EnvProps { prod: boolean; } +// imagine these stacks declare a bunch of related resources class ControlPlane extends Stack {} -class Dataplane extends Stack {} +class DataPlane extends Stack {} class Monitoring extends Stack {} -class MyService extends cdk.Construct { +class MyService extends Construct { constructor(scope: Construct, id: string, props?: EnvProps) { super(scope, id); - new ControlPlane(this, "cp", {}); - new Dataplane(this, "data", {}); - new Monitoring(this, "mon", {}); } + // we might use the prod argument to change how the service is configured + new ControlPlane(this, "cp"); + new DataPlane(this, "data"); + new Monitoring(this, "mon"); } } -const app = new cdk.App(); +const app = new App(); new MyService(app, "beta"); new MyService(app, "prod", { prod: true }); app.synth(); ``` +------ +#### [ Python ] + +``` +from aws_cdk.core import App, Construct, Stack + +# imagine these stacks declare a bunch of related resources +class ControlPlane(Stack): pass +class DataPlane(Stack): pass +class Monitoring(Stack): pass + +class MyService(Construct): + + def __init__(self, scope: Construct, id: str, *, prod=False): + + super().__init__(scope, id) + + # we might use the prod argument to change how the service is configured + ControlPlane(self, "cp") + DataPlane(self, "data") + Monitoring(self, "mon") + +app = App(); +MyService(app, "beta"); +MyService(app, "prod", prod=True) + +app.synth() +``` + +------ +#### [ Java ] + +``` +package com.myorg; + +import software.amazon.awscdk.core.App; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.Construct; + +public class MyApp { + + // imagine these stacks declare a bunch of related resources + static class ControlPlane extends Stack { + ControlPlane(Construct scope, String id) { + super(scope, id); + } + } + + static class DataPlane extends Stack { + DataPlane(Construct scope, String id) { + super(scope, id); + } + } + + static class Monitoring extends Stack { + Monitoring(Construct scope, String id) { + super(scope, id); + } + } + + static class MyService extends Construct { + MyService(Construct scope, String id) { + this(scope, id, false); + } + + MyService(Construct scope, String id, boolean prod) { + super(scope, id); + + // we might use the prod argument to change how the service is configured + new ControlPlane(this, "data"); + new DataPlane(this, "data"); + new Monitoring(this, "mon"); + } + } + + public static void main(final String argv[]) { + App app = new App(); + + new MyService(app, "beta"); + new MyService(app, "prod", true); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; + +// imagine these stacks declare a bunch of related resources +public class ControlPlane : Stack { + public ControlPlane(Construct scope, string id=null) : base(scope, id) { } +} + +public class DataPlane : Stack { + public DataPlane(Construct scope, string id=null) : base(scope, id) { } +} + +public class Monitoring : Stack +{ + public Monitoring(Construct scope, string id=null) : base(scope, id) { } +} + +public class MyService : Construct +{ + public MyService(Construct scope, string id, Boolean prod=false) : base(scope, id) + { + // we might use the prod argument to change how the service is configured + new ControlPlane(this, "data"); + new DataPlane(this, "data"); + new Monitoring(this, "mon"); + } +} + +class Program +{ + static void Main(string[] args) + { + + var app = new App(); + new MyService(app, "beta"); + new MyService(app, "prod", prod: true); + app.Synth(); + } +} +``` + +------ + This AWS CDK app eventually consists of six stacks, three for each environment: ``` @@ -82,23 +259,52 @@ proddataF7378CE5 prodmon631A1083 ``` -The physical names of the AWS CloudFormation stacks are automatically determined by the AWS CDK based on the stack's construct path in the tree\. By default, a stack's name is derived from the construct ID of the `Stack` object, but you can specify an explicit name using the `stackName` prop, as follows\. +The physical names of the AWS CloudFormation stacks are automatically determined by the AWS CDK based on the stack's construct path in the tree\. By default, a stack's name is derived from the construct ID of the `Stack` object, but you can specify an explicit name using the `stackName` prop \(in Python, `stack_name`\), as follows\. + +------ +#### [ TypeScript ] ``` new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name' }); ``` +------ +#### [ Python ] + +``` +MyStack(self, "not:a:stack:name", stack_name="this-is-stack-name") +``` + +------ +#### [ Java ] + +``` +new MyStack(this, "not:a:stack:name", StackProps.builder() + .StackName("this-is-stack-name").build()); +``` + +------ +#### [ C\# ] + +``` +new MyStack(this, "not:a:stack:name", new StackProps +{ + StackName = "this-is-stack-name" +}); +``` + +------ + ## Stack API The [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html) object provides a rich API, including the following: + `Stack.of(construct)` – A static method that returns the **Stack** in which a construct is defined\. This is useful if you need to interact with a stack from within a reusable construct\. The call fails if a stack cannot be found in scope\. -+ `stack.stackName` – Returns the physical name of the stack\. As mentioned previously, all AWS CDK stacks have a physical name that the AWS CDK can resolve during synthesis\. ++ `stack.stackName` \(Python: `stack_name`\) – Returns the physical name of the stack\. As mentioned previously, all AWS CDK stacks have a physical name that the AWS CDK can resolve during synthesis\. + `stack.region` and `stack.account` – Return the AWS Region and account, respectively, into which this stack will be deployed\. These properties return either the account or Region explicitly specified when the stack was defined, or a string\-encoded token that resolves to the AWS CloudFormation pseudo\-parameters for account and Region to indicate that this stack is environment agnostic\. See [Environments](environments.md) for information about how environments are determined for stacks\. -+ `stack.account` – Returns the AWS account into which this stack will be deployed\. Similarly to Region, this property returns either an explicit account ID or a token that resolves to \{ Ref: AWS::AccountId \}\. Use `Token.isUnresolved` method to determine whether the value is a token before reading the value returned from this property\. -+ `stack.addDependency(stack)` – Can be used to explicitly define dependency order between two stacks\. This order is respected by the cdk deploy command when deploying multiple stacks at once\. -+ `stack.tags` – Returns a [TagManager](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/tagmanager.html#core_TagManager) that you can use to add or remove stack\-level tags\. This tag manager tags all resources within the stack, and also tags the stack itself when it's created through AWS CloudFormation\. -+ `stack.partition`, `stack.urlSuffix`, `stack.stackId`, and `stack.notificationArn` – Return tokens that resolve to the respective AWS CloudFormation pseudo\-parameters, such as \{ "Ref": "AWS::Partition" \}\. These tokens are associated with this specific stack object, so the framework can identify cross\-stack references\. -+ `stack.availabilityZones` – Returns the set of Availability Zones available in the environment in which this stack is deployed\. For environment\-agnostic stacks, this always returns an array with two Availability Zones, but for environment\-specific stacks, the AWS CDK queries the environment and returns the exact set of Availability Zones that are available\. -+ `stack.parseArn(arn)` and `stack.formatArn(comps)` – Can be used to work with Amazon Resource Names \(ARNs\)\. -+ `stack.toJsonString(obj)` – Can be used to format an arbitrary object as a JSON string that can be embedded in an AWS CloudFormation template\. The object can include tokens, attributes, and references, which are only resolved during deployment\. -+ `stack.templateOptions` – Enables you to specify AWS CloudFormation template options, such as Transform, Description, and Metadata, for your stack\. \ No newline at end of file ++ `stack.addDependency(stack)` \(Python: `stack.add_dependency(stack)` – Can be used to explicitly define dependency order between two stacks\. This order is respected by the cdk deploy command when deploying multiple stacks at once\. ++ `stack.tags` – Returns a [TagManager](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.TagManager.html) that you can use to add or remove stack\-level tags\. This tag manager tags all resources within the stack, and also tags the stack itself when it's created through AWS CloudFormation\. ++ `stack.partition`, `stack.urlSuffix` \(Python: `url_suffix`\), `stack.stackId` \(Python: `stack_id`\), and `stack.notificationArn` \(Python: `notification_arn`\) – Return tokens that resolve to the respective AWS CloudFormation pseudo\-parameters, such as `{ "Ref": "AWS::Partition" }`\. These tokens are associated with the specific stack object so that the AWS CDK framework can identify cross\-stack references\. ++ `stack.availabilityZones` \(Python: `availability_zones`\) – Returns the set of Availability Zones available in the environment in which this stack is deployed\. For environment\-agnostic stacks, this always returns an array with two Availability Zones, but for environment\-specific stacks, the AWS CDK queries the environment and returns the exact set of Availability Zones available in the region you specified\. ++ `stack.parseArn(arn)` and `stack.formatArn(comps)` \(Python: `parse_arn`, `format_arn`\) – Can be used to work with Amazon Resource Names \(ARNs\)\. ++ `stack.toJsonString(obj)` \(Python: `to_json_string`\) – Can be used to format an arbitrary object as a JSON string that can be embedded in an AWS CloudFormation template\. The object can include tokens, attributes, and references, which are only resolved during deployment\. ++ `stack.templateOptions` \(Python: `template_options`\) – Enables you to specify AWS CloudFormation template options, such as Transform, Description, and Metadata, for your stack\. \ No newline at end of file diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 66834bfe..94369392 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -7,21 +7,76 @@ The `Tag` class includes two methods that you can use to create and delete tags: **Note** Tagging is implemented using [Aspects](aspects.md)\. Aspects are a way to apply an operation \(such as tagging\) to all constructs in a given scope\. -Let's look at a couple of examples\. The following example applies the tag **key** with the value **value** to `myConstruct`\. +Let's look at a couple of examples\. The following example applies the tag **key** with the value **value** to a construct\. + +------ +#### [ TypeScript ] ``` Tag.add(myConstruct, 'key', 'value'); ``` -The following example deletes the tag **key** from `myConstruct`\. +------ +#### [ Python ] + +``` +Tag.add(my_construct, "key", "value") +``` + +------ +#### [ Java ] + +``` +Tag.add(myConstruct, "key", "value"); +``` + +------ +#### [ C\# ] + +``` +Tag.Add(myConstruct, "key", "value"); +``` + +------ + +The following example deletes the tag **key** from a construct\. + +------ +#### [ TypeScript ] + +``` +Tag.remove(my_construct, 'key'); +``` + +------ +#### [ Python ] + +``` +Tag.remove(my_construct, "key") +``` + +------ +#### [ Java ] ``` -tag.remove(myConstruct, 'key'); +Tag.remove(myConstruct, "key"); ``` +------ +#### [ C\# ] + +``` +Tag.Remove(myConstruct, "key"); +``` + +------ + The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. If the priorities are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 and removing a tag has a priority of 200\. To change the priority of applying a tag, pass a `priority` property to `Tag.add()` or `Tag.remove()`\. -The following applies a tag with a priority of 300 to `myConstruct`\. +The following applies a tag with a priority of 300 to a construct\. + +------ +#### [ TypeScript ] ``` Tag.add(myConstruct, 'key', 'value', { @@ -29,11 +84,38 @@ Tag.add(myConstruct, 'key', 'value', { }); ``` +------ +#### [ Python ] + +``` +Tag.add(my_construct, "key", "value", priority=300) +``` + +------ +#### [ Java ] + +``` +Tag.add(myConstruct, "key", "value", TagProps.builder() + .priority(300).build()); +``` + +------ +#### [ C\# ] + +``` +Tag.Add(myConstruct, "key", "value", new TagProps { Priority = 300 }); +``` + +------ + ## Tag\.add\(\) `Tag.add()` supports properties that fine\-tune how tags are applied to resources\. All properties are optional\. -The following example applies the tag **tagname** with the value **value** and priority **100** to resources of type **AWS::Xxx::Yzz** in `myConstruct`, but not to instances launched in an Amazon EC2 Auto Scaling group or to resources of type **AWS::Xxx::Zss**\. +The following example applies the tag **tagname** with the value **value** and priority **100** to resources of type **AWS::Xxx::Yzz** in the construct, but not to instances launched in an Amazon EC2 Auto Scaling group or to resources of type **AWS::Xxx::Zss**\. + +------ +#### [ TypeScript ] ``` Tag.add(myConstruct, 'tagname', 'value', { @@ -44,13 +126,50 @@ Tag.add(myConstruct, 'tagname', 'value', { }); ``` +------ +#### [ Python ] + +``` +Tag.add(my_construct, "tagname", "value", + apply_to_launched_instances=False, + include_resource_types=["AWS::Xxx::Yyy"], + exclude_resource_types=["AWS::Xxx::Zzz"], + priority=100,) +``` + +------ +#### [ Java ] + +``` +Tag.add(myConstruct, "key", "value", TagProps.builder() + .applyToLaunchedInstances(false) + .includeResourceTypes(Arrays.asList("AWS::Xxx::Yyy")) + .excludeResourceTypes(Arrays.asList("AWS::Xxx::Zzz")) + .priority(100).build()); +``` + +------ +#### [ C\# ] + +``` +Tag.Add(myConstruct, "tagname", "value", new TagProps +{ + ApplyToLaunchedInstances = false, + IncludeResourceTypes = ["AWS::Xxx::Yyy"], + ExcludeResourceTypes = ["AWS::Xxx::Zzz"], + Priority = 100 +}); +``` + +------ + These properties have the following meanings\. -applyToLaunchedInstances +applyToLaunchedInstances \(Python: apply\_to\_launched\_instances\) By default, tags are applied to instances launched in an Auto Scaling group\. Set this property to **false** to not apply tags to instances launched in an Auto Scaling group\. -includeResourceTypes/excludeResourceTypes -Use these to apply tags only to a subset of resources, based on AWS CloudFormation resource types\. By default, the tag is applied to all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. +includeResourceTypes/excludeResourceTypes \(Python: include\_resource\_types, exclude\_resource\_types\) + Use these to apply tags only to a subset of resources, based on AWS CloudFormation resource types\. By default, the tag is applied to all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. priority Use this to set the priority of this operation with respect to other `Tag.add()` and `Tag.remove()` operations\. Higher values take precedence over lower values\. The default is 100\. @@ -59,7 +178,10 @@ Use this to set the priority of this operation with respect to other `Tag.add()` `Tag.remove()` supports properties to fine\-tune how tags are removed from resources\. All properties are optional\. -The following example removes the tag **tagname** with priority **200** from resources of type **AWS::Xxx::Yzz** in `myConstruct`, but not from resources of type **AWS::Xxx::Zzz**\. +The following example removes the tag **tagname** with priority **200** from resources of type **AWS::Xxx::Yzz** in the construct, but not from resources of type **AWS::Xxx::Zzz**\. + +------ +#### [ TypeScript ] ``` Tag.remove(myConstruct, 'tagname', { @@ -69,10 +191,44 @@ Tag.remove(myConstruct, 'tagname', { }); ``` +------ +#### [ Python ] + +``` +Tag.remove(my_construct, "tagname", + include_resource_types=["AWS::Xxx::Yyy"], + exclude_resource_types=["AWS::Xxx::Zzz"], + priority=200,) +``` + +------ +#### [ Java ] + +``` +Tag.remove(myConstruct, "tagname", TagProps.builder() + .includeResourceTypes(Arrays.asList("AWS::Xxx::Yyy")) + .excludeResourceTypes(Arrays.asList("AWS::Xxx::Zzz")) + .priority(100).build()); +``` + +------ +#### [ C\# ] + +``` +Tag.Remove(myConstruct, "tagname", "value", new TagProps +{ + IncludeResourceTypes = ["AWS::Xxx::Yyy"], + ExcludeResourceTypes = ["AWS::Xxx::Zzz"], + Priority = 100 +}); +``` + +------ + These properties have the following meanings\. includeResourceTypes/excludeResourceTypes -Use these properties to remove tags only from subset of resources based on AWS CloudFormation resource types\. By default, the tag is removed from all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. +\(Python: include\_resource\_types/exclude\_resource\_types\) Use these properties to remove tags only from subset of resources based on AWS CloudFormation resource types\. By default, the tag is removed from all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. priority Use this property to specify the priority of this operation with respect to other `Tag.add()` and `Tag.remove()` operations\. Higher values take precedence over lower values\. The default is 200\. @@ -81,6 +237,9 @@ Use this property to specify the priority of this operation with respect to othe The following example adds the tag key **StackType** with value **TheBest** to any resource created within the Stack named `MarketingSystem`\. Then it removes it again from all resources except Amazon EC2 VPC subnets\. The result is that only the subnets have the tag applied\. +------ +#### [ TypeScript ] + ``` import { App, Stack, Tag } from require('@aws-cdk/core'); @@ -96,9 +255,94 @@ Tag.remove(theBestStack, 'StackType', { }); ``` -**Note** -The following code achieves the same result\. Consider which approach \(inclusion or exclusion\) makes your intent clearer\. +------ +#### [ Python ] + +``` +from aws_cdk.core import App, Stack, Tag + +app = App(); +the_best_stack = Stack(app, 'MarketingSystem') + +# Add a tag to all constructs in the stack +Tag.add(the_best_stack, "StackType", "TheBest") + +# Remove the tag from all resources except subnet resources +Tag.remove(the_best_stack, "StackType", + exclude_resource_types=["AWS::EC2::Subnet"]) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.core.App; +import software.amazon.awscdk.core.Tag; + +// Add a tag to all constructs in the stack +Tag.add(theBestStack, "StackType", "TheBest"); + +// Remove the tag from all resources except subnet resources +Tag.remove(theBestStack, "StackType", TagProps.builder() + .excludeResourceTypes(Arrays.asList("AWS::EC2::Subnet")) + .build()); +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +var app = new App(); +var theBestStack = new Stack(app, 'MarketingSystem'); + +// Add a tag to all constructs in the stack +Tag.Add(theBestStack, "StackType", "TheBest"); + +// Remove the tag from all resources except subnet resources +Tag.Remove(theBestStack, "StackType", new TagProps +{ + ExcludeResourceTypes = ["AWS::EC2::Subnet"] +}); +``` + +------ + +The following code achieves the same result\. Consider which approach \(inclusion or exclusion\) makes your intent clearer\. + +------ +#### [ TypeScript ] + +``` +Tag.add(theBestStack, 'StackType', 'TheBest', + { includeResourceTypes: ['AWS::EC2::Subnet']}); ``` - Tag.add(theBestStack, 'StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet']}); -``` \ No newline at end of file + +------ +#### [ Python ] + +``` +Tag.add(the_best_stack, "StackType", "TheBest", + include_resource_types=["AWS::EC2::Subnet"]) +``` + +------ +#### [ Java ] + +``` +Tag.add(theBestStack, "StackType", "TheBest", TagProps.builder() + .includeResourceTypes(Arrays.asList("AWS::EC2::Subnet")) + .build()); +``` + +------ +#### [ C\# ] + +``` +Tag.Add(theBestStack, "StackType", "TheBest", new TagProps { + IncludeResourceTypes = ["AWS::EC2::Subnet"] +}); +``` + +------ \ No newline at end of file diff --git a/doc_source/testing.md b/doc_source/testing.md new file mode 100644 index 00000000..23ec8e16 --- /dev/null +++ b/doc_source/testing.md @@ -0,0 +1,354 @@ +# Testing Constructs + +With the AWS CDK, your infrastructure can be as testable as any other code you write\. This article illustrates one approach to testing AWS CDK apps written in TypeScript using the [Jest](https://jestjs.io/) test framework\. Currently, TypeScript is the only supported language for testing AWS CDK infrastructure, though we intend to eventually make this capability available in all languages supported by the AWS CDK\. + +There are three categories of tests you can write for AWS CDK apps\. ++ **Snapshot tests** test the synthesized AWS CloudFormation template against a previously\-stored "golden master" template\. This way, when you're refactoring your app, you can be sure that the refactored code works exactly the same way as the original\. If the changes were intentional, you can accept a new master for future tests\. ++ **Fine\-grained assertions** test specific aspects of the generated AWS CloudFormation template, such as "this resource has this property with this value\." These tests help when you're developing new features, since any code you add will cause your snapshot test to fail even if existing features still work\. When this happens, your fine\-grained tests will reassure you that the existing functionality is unaffected\. ++ **Validation tests** help you "fail fast" by making sure your AWS CDK constructs raise errors when you pass them invalid data\. The ability to do this type of testing is a big advantage of developing your infrastructure in a general\-purpose programming language\. + +## Getting Started + +As an example, we'll create a [dead letter queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) construct\. A dead letter queue holds messages from another queue that have failed delivery for some time\. This usually indicates failure of the message processor, which we want to know about, so our dead letter queue has an alarm that fires when a message arrives\. The user of the construct can hook up actions such as notifying an Amazon SNS topic to this alarm\. + +### Creating the Construct + + Start by creating an empty construct library project using the AWS CDK Toolkit and installing the construct libraries we'll need: + +``` +mkdir dead-letter-queue && cd dead-letter-queue +cdk init --language=typescript lib +npm install @aws-cdk/aws-sqs @aws-cdk/aws-cloudwatch +``` + + Place the following code in `lib/dead-letter-queue.ts`: + +``` +import cloudwatch = require('@aws-cdk/aws-cloudwatch'); +import sqs = require('@aws-cdk/aws-sqs'); +import { Construct, Duration } from '@aws-cdk/core'; + +export class DeadLetterQueue extends sqs.Queue { + public readonly messagesInQueueAlarm: cloudwatch.IAlarm; + + constructor(scope: Construct, id: string) { + super(scope, id); + + // Add the alarm + this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { + alarmDescription: 'There are messages in the Dead Letter Queue', + evaluationPeriods: 1, + threshold: 1, + metric: this.metricApproximateNumberOfMessagesVisible(), + }); + } +} +``` + +### Installing the Testing Framework + +Since we're using the Jest framework, our next setup step is to install Jest\. We'll also need the AWS CDK assertion module\. + +``` +npm install --save-dev jest @types/jest @aws-cdk/assert +``` + +### Updating `project.json` + +Finally, edit the project's `project.json` to tell NPM how to run Jest, and to tell Jest what kinds of files to collect\. The necessary changes are as follows\. ++ Add a new `test` key to the `scripts` section ++ Add Jest and its types to the `devDependencies` section ++ Add a new `jest` top\-level key with a `moduleFileExtensions` declaration + +These changes are shown in outline below\. Place the new text where indicated in `project.json`\. The "\.\.\." placeholders indicate existing parts of the file that should not be changed\. + +``` +{ + ... + "scripts": { + ... + "test": "jest" + }, + "devDependencies": { + ... + "@types/jest": "^24.0.18", + "jest": "^24.9.0", + }, + "jest": { + "moduleFileExtensions": ["js"] + } +} +``` + +## Snapshot Tests + +Add a snapshot test by placing the following code in `test/dead-letter-queue.test.ts`\. + +``` +import { SynthUtils } from '@aws-cdk/assert'; +import { Stack } from '@aws-cdk/core'; + +import dlq = require('../lib/dead-letter-queue'); + +test('dlq creates an alarm', () => { + const stack = new Stack(); + new dlq.DeadLetterQueue(stack, 'DLQ'); + expect(SynthUtils.toCloudFormation(stack)).toMatchSnapshot(); +}); +``` + +To build the project and run the test, issue these commands\. + +``` +npm run build +npm test +``` + +The output from Jest indicates that it has run the test and recorded a snapshot\. + +``` +PASS test/dead-letter-queue.test.js + ✓ dlq creates an alarm (55ms) + › 1 snapshot written. +Snapshot Summary +› 1 snapshot written +``` + +Jest stores the snapshots in a directory named `__snapshots__` inside the project\. In this directory is a copy of the AWS CloudFormation template generated by the dead letter queue construct\. The beginning looks something like this\. + +``` +exports[`dlq creates an alarm 1`] = ` +Object { + "Resources": Object { + "DLQ581697C4": Object { + "Type": "AWS::SQS::Queue", + }, + "DLQAlarm008FBE3A": Object { + "Properties": Object { + "AlarmDescription": "There are messages in the Dead Letter Queue", + "ComparisonOperator": "GreaterThanOrEqualToThreshold", +... +``` + +### Testing the Test + +To make sure the test works, change the construct so that it generates different AWS CloudFormation output, then build and test again\. For example, add a `period` property of 1 minute to override the default of 5 minutes\. The boldface line below shows the code that needs to be added to `dead-letter-queue.ts`\. + +``` +this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { + this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { + alarmDescription: 'There are messages in the Dead Letter Queue', + evaluationPeriods: 1, + threshold: 1, + metric: this.metricApproximateNumberOfMessagesVisible(), + period: Duration.minutes(1), +}); +``` + +Build the project and run the tests again\. + +``` +npm run build && npm test +``` + +``` +FAIL test/dead-letter-queue.test.js +✕ dlq creates an alarm (58ms) + +● dlq creates an alarm + +expect(received).toMatchSnapshot() + +Snapshot name: `dlq creates an alarm 1` + +- Snapshot ++ Received + +@@ -19,11 +19,11 @@ + }, + ], + "EvaluationPeriods": 1, + "MetricName": "ApproximateNumberOfMessagesVisible", + "Namespace": "AWS/SQS", + - "Period": 300, + + "Period": 60, + "Statistic": "Maximum", + "Threshold": 1, + }, + "Type": "AWS::CloudWatch::Alarm", + }, + + › 1 snapshot failed. +Snapshot Summary + › 1 snapshot failed from 1 test suite. Inspect your code changes or run `npm test -- -u` to update them. +``` + +### Accepting the New Snapshot + +Jest has told us that the `Period` attribute of the synthesized AWS CloudFormation template has changed from 300 to 60\. To accept the new snapshot, issue: + +``` +npm test -- -u +``` + +Now we can run the test again and see that it passes\. + +### Limitations + +Snapshot tests are easy to create and are a powerful backstop when refactoring\. They can serve as an early warning sign that more testing is needed\. Snapshot tests can even be useful for test\-driven development: modify the snapshot to reflect the result you're aiming for, and adjust the code until the test passes\. + +The chief limitation of snapshot tests is that they test the *entire* template\. Consider that our dead letter queue uses the default retention period\. To give ourselves as much time as possible to recover the undelivered messages, for example, we might set the queue's retention time to the maximum—14 days—by changing the code as follows\. + +``` +export class DeadLetterQueue extends sqs.Queue { + public readonly messagesInQueueAlarm: cloudwatch.IAlarm; + + constructor(scope: Construct, id: string) { + super(scope, id, { + // Maximum retention period + retentionPeriod: Duration.days(14) + }); +``` + +When we run the test again, it breaks\. The name we've given the test hints that we are interested mainly in testing whether the alarm is created, but the snapshot test also tests whether the queue is created with default options—along with literally everything else about the synthesized template\. This problem is magnified when a project contains many constructs, each with a snapshot test\. + +## Fine\-Grained Assertions + +To avoid needing to review every snapshot whenever you make a change, use the custom assertions in the `@aws-cdk/assert/jest` module to write fine\-grained tests that verify only part of the construct's behavior\. For example, the test we called "dlq creates an alarm" in our example really should assert only that an alarm is created with the appropriate metric\. + +The [AWS::CloudWatch::Alarm](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html) resource specification reveals that we're interested in the properties Namespace, MetricName and Dimensions\. We'll use the `expect(stack).toHaveResource(...)` assertion, which is in the `@aws-cdk/assert/jest` module, to make sure these properties have the appropriate values\. + +Replace the code in `test/dead-letter-queue.test.ts` with the following\. + +``` +import { Stack } from '@aws-cdk/core'; +import '@aws-cdk/assert/jest'; + +import dlq = require('../lib/dead-letter-queue'); + +test('dlq creates an alarm', () => { + const stack = new Stack(); + + new dlq.DeadLetterQueue(stack, 'DLQ'); + + expect(stack).toHaveResource('AWS::CloudWatch::Alarm', { + MetricName: "ApproximateNumberOfMessagesVisible", + Namespace: "AWS/SQS", + Dimensions: [ + { + Name: "QueueName", + Value: { "Fn::GetAtt": [ "DLQ581697C4", "QueueName" ] } + } + ], + }); +}); + +test('dlq has maximum retention period', () => { + const stack = new Stack(); + + new dlq.DeadLetterQueue(stack, 'DLQ'); + + expect(stack).toHaveResource('AWS::SQS::Queue', { + MessageRetentionPeriod: 1209600 + }); +}); +``` + +There are now two tests\. The first checks that the dead letter queue creates an alarm on its `ApproximateNumberOfMessagesVisible` metric\. The second verifies the message retention period\. + +Again, build the project and run the tests\. + +``` +npm run build && npm test +``` + +**Note** +Since we've replaced the snapshot test, the first time we run the new tests, Jest reminds us that we have a snapshot that is not used by any test\. Issue `npm test -- -u` to tell Jest to clean it up\. + +## Validation Tests + +Suppose we want to make the dead letter queue's retention period configurable\. Of course, we also want to make sure that the value provided by the user of the construct is within an allowable range\. We can write a test to make sure that the validation logic works: pass in invalid values and see what happens\. + +First, create a `propes` interface for the construct\. + +``` +export interface DeadLetterQueueProps { + /** + * The amount of days messages will live in the dead letter queue + * + * Cannot exceed 14 days. + * + * @default 14 + */ + retentionDays?: number; +} + +export class DeadLetterQueue extends sqs.Queue { + public readonly messagesInQueueAlarm: cloudwatch.IAlarm; + + constructor(scope: Construct, id: string, props: DeadLetterQueueProps = {}) { + if (props.retentionDays !== undefined && props.retentionDays > 14) { + throw new Error('retentionDays may not exceed 14 days'); + } + + super(scope, id, { + // Given retention period or maximum + retentionPeriod: Duration.days(props.retentionDays || 14) + }); + // ... + } +} +``` + +To test that the new feature actually does what we expect, we write two tests: ++ One that makes sure the configured value ends up in the template ++ One that supplies an incorrect value to the construct and checks it raises the expected error + +Add the following to `test/dead-letter-queue.test.ts`\. + +``` +test('retention period can be configured', () => { + const stack = new Stack(); + + new dlq.DeadLetterQueue(stack, 'DLQ', { + retentionDays: 7 + }); + + expect(stack).toHaveResource('AWS::SQS::Queue', { + MessageRetentionPeriod: 604800 + }); +}); + +test('configurable retention period cannot exceed 14 days', () => { + const stack = new Stack(); + + expect(() => { + new dlq.DeadLetterQueue(stack, 'DLQ', { + retentionDays: 15 + }); + }).toThrowError(/retentionDays may not exceed 14 days/); +}); +``` + +Run the tests to confirm the construct behaves as expected\. + +``` +npm run build && npm test +``` + +``` +PASS test/dead-letter-queue.test.js + ✓ dlq creates an alarm (62ms) + ✓ dlq has maximum retention period (14ms) + ✓ retention period can be configured (18ms) + ✓ configurable retention period cannot exceed 14 days (1ms) + +Test Suites: 1 passed, 1 total +Tests: 4 passed, 4 total +``` + +## Tips for Tests + +Remember, your tests will live just as long as the code they test, and be read and modified just as often, so it pays to take a moment to consider how best to write them\. Don't copy and paste setup lines or common assertions, for example; refactor this logic into helper functions\. Use good names that reflect what each test actually tests\. + +Don't assert too much in one test\. Preferably, a test should test one and only one behavior\. If you accidentally break that behavior, exactly one test should fail, and the name of the test should tell you exactly what failed\. This is more an ideal to be striven for, however; sometimes you will unavoidably \(or inadvertently\) write tests that test more than one behavior\. Snapshot tests are, for reasons we've already described, especially prone to this problem, so use them sparingly\. \ No newline at end of file diff --git a/doc_source/tokens.md b/doc_source/tokens.md index 90001381..6407cd74 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -10,6 +10,9 @@ This is how the AWS CDK encodes a token whose value is not yet known at construc You can pass this string around as if it was the name of the bucket, such as in the following example, where the bucket name is specified as an environment variable to an AWS Lambda function\. +------ +#### [ TypeScript ] + ``` const bucket = new s3.Bucket(this, 'MyBucket'); @@ -21,6 +24,44 @@ const fn = new lambda.Function(stack, 'MyLambda', { }); ``` +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, "MyBucket") + +fn = lambda_.Function(stack, "MyLambda", + environment=dict(BUCKET_NAME=bucket.bucket_name)) +``` + +------ +#### [ Java ] + +``` +final Bucket bucket = new Bucket(this, "MyBucket"); + +Function fn = Function.Builder.create(this, "MyLambda") + .environment(new HashMap() {{ + put("BUCKET_NAME", bucket.getBucketName()); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new s3.Bucket(this, "MyBucket"); + +var fn = new Function(this, "MyLambda", new FunctionProps { + Environment = new Dictionary + { + ["BUCKET_NAME"] = bucket.BucketName + } +}); +``` + +------ + When the AWS CloudFormation template is finally synthesized, the token is rendered as the AWS CloudFormation intrinsic `{ "Ref": "MyBucket" }`\. At deployment time, AWS CloudFormation replaces this intrinsic with the actual name of the bucket that was created\. ## Tokens and Token Encodings @@ -31,18 +72,21 @@ Tokens are objects that implement the [IResolvable](https://docs.aws.amazon.com/ You'll hardly ever work directly with the `IResolvable` interface\. You will most likely only see string\-encoded versions of tokens\. Other functions typically only accept arguments of basic types, such as `string` or `number`\. To use tokens in these cases, you can encode them into one of three types using static methods on the [core\.Token](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html) class\. -+ Strings using [Token\.asString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) -+ List of strings using [Token\.asList](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) -+ Number \(float\) using [Token\.asNumber](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) ++ Strings using [Token\.asString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) \(Python: `as_string`\) ++ List of strings using [Token\.asList](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) \(Python: `as_list`\) ++ Number \(float\) using [Token\.asNumber](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) \(Python: `as_number`\) These take an arbitrary value, which can also be an `IResolvable` interface, and encode them into a primitive value of the appropriate type\. **Important** Because any one of the previous types can potentially be an encoded token, be careful when you parse or try to read their contents\. For example, if you attempt to parse a string to extract a value from it, and the string is an encoded token, your parsing will fail\. Similarly, if you attempt to query the length of an array, or perform math operations with a number, you must first verify that they are not encoded tokens\. -To check whether a value has an unresolved token in it, call the `Token.isUnresolved` method\. +To check whether a value has an unresolved token in it, call the `Token.isUnresolved` \(Python: `is_unresolved`\) method\. -The following example validates that the length of a value, which could be a token, is no more than 10 characters\. +The following example validates that a string value, which could be a token, is no more than 10 characters long\. + +------ +#### [ TypeScript ] ``` if (!Token.isUnresolved(name) && name.length > 10) { @@ -50,7 +94,33 @@ if (!Token.isUnresolved(name) && name.length > 10) { } ``` -If **name** is a token, validation is not be performed, and the error could occur in a later stage in the lifecycle, such as during deployment\. +------ +#### [ Python ] + +``` +if not Token.is_unresolved(name) and len(name) > 10: + raise ValueError("Maximum length for name is 10 characters") +``` + +------ +#### [ Java ] + +``` +if (!Token.isUnresolved(name) && name.length() > 10) + throw new IllegalArgumentException("Maximum length for name is 10 characters"); +``` + +------ +#### [ C\# ] + +``` +if (!Token.IsUnresolved(name) && name.Length > 10) + throw new ArgumentException("Maximum length for name is 10 characters"); +``` + +------ + +If **name** is a token, validation isn't performed, and the error could occur in a later stage in the lifecycle, such as during deployment\. **Note** You can use token encodings to escape the type system\. For example, you could string\-encode a token that produces a number value at synthesis time\. If you use these functions, it's your responsibility to ensure that your template resolves to a usable state after synthesis\. @@ -65,17 +135,69 @@ ${TOKEN[Bucket.Name.1234]} They can be passed around like regular strings, and can be concatenated, as shown in the following example\. +------ +#### [ TypeScript ] + ``` const functionName = bucket.bucketName + 'Function'; ``` -In languages that support it, you can also use string interpolation, as shown in the following example\. +------ +#### [ Python ] + +``` +function_name = bucket.bucket_name + "Function" +``` + +------ +#### [ Java ] + +``` +String functionName = bucket.getBucketName().concat("Function"); +``` + +------ +#### [ C\# ] + +``` +string functionName = bucket.BucketName + "Function"; +``` + +------ + +You can also use string interpolation, if your language supports it, as shown in the following example\. + +------ +#### [ TypeScript ] ``` const functionName = `${bucket.bucketName}Function`; ``` -Concatenation is safe, but avoid manipulating the string in other ways\. For example, taking a substring of a string is likely to break the string token\. +------ +#### [ Python ] + +``` +function_name = f"{bucket.bucket_name}Function" +``` + +------ +#### [ Java ] + +``` +String functionName = String.format("%sFunction". bucket.getBucketName()); +``` + +------ +#### [ C\# ] + +``` +string functionName = $"${bucket.bucketName}Function"; +``` + +------ + +Avoid manipulating the string in other ways\. For example, taking a substring of a string is likely to break the string token\. ## List\-Encoded Tokens @@ -89,7 +211,7 @@ The only safe thing to do with these lists is pass them directly to other constr ## Number\-Encoded Tokens -Number\-encoded tokens are a set of very tiny negative floating\-point numbers that look like the following\. +Number\-encoded tokens are a set of tiny negative floating\-point numbers that look like the following\. ``` -1.8881545897087626e+289 @@ -101,14 +223,19 @@ As with list tokens, you cannot modify the number value, as doing so is likely t In addition to representing deploy\-time values, such as AWS CloudFormation attributes\), Tokens are also commonly used to represent synthesis\-time lazy values\. These are values for which the final value will be determined before synthesis has completed, just not at the point where the value is constructed\. Use tokens to pass a literal string or number value to another construct, while the actual value at synthesis time may depend on some calculation that has yet to occur\. -You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.stringValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-string-valueproducer-options) and [Lazy\.numberValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-number-valueproducer)\. For following example creates an Auto Scaling group whose capacity is determined after its creation\. +You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.stringValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-string-valueproducer-options) \(Python: `Lazy.string_value`\) and [Lazy\.numberValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-number-valueproducer) \(Python: `Lazy.number_value`\. These methods accept an object whose `producer` property is a function that accepts a context argument and returns the final value when called\. + +The following example creates an Auto Scaling group whose capacity is determined after its creation\. + +------ +#### [ TypeScript ] ``` let actualValue: number; new AutoScalingGroup(this, 'Group', { desiredCapacity: Lazy.numberValue({ - produce() { + produce(context) { return actualValue; } }) @@ -118,13 +245,118 @@ new AutoScalingGroup(this, 'Group', { actualValue = 10; ``` +------ +#### [ Python ] + +``` +class Producer: + def __init__(self, func): + self.produce = func + +actual_value = None + +AutoScalingGroup(self, "Group", + desired_capacity=Lazy.number_value(Producer(lambda context: actual_value)) +) + +# At some later point +actual_value = 10 +``` + +------ +#### [ Java ] + +``` +double actualValue = 0; + +class ProduceActualValue implements INumberProducer { + + @Override + public Number produce(IResolveContext context) { + return actualValue; + } +} + +AutoScalingGroup.Builder.create(this, "Group") + .desiredCapacity(Lazy.numberValue(new ProduceActualValue())).build(); + +// At some later point +actualValue = 10; +``` + +------ +#### [ C\# ] + +``` +public class NumberProducer : INumberProducer +{ + Func function; + + public NumberProducer(Func function) + { + this.function = function; + } + + public Double Produce(IResolveContext context) + { + return function(); + } +} + +double actualValue = 0; + +new AutoScalingGroup(this, "Group", new AutoScalingGroupProps +{ + DesiredCapacity = Lazy.NumberValue(new NumberProducer(() => actualValue)) +}); + +// At some later point +actualValue = 10; +``` + +------ + ## Converting to JSON -Sometimes you have to produce a JSON string of arbitrary data, and you may not know whether the data contains tokens\. To properly JSON\-encode any data structure, regardless of whether it contains tokens, use the [stack\.toJsonString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#to-json-stringobj-space), as shown in the following example\. +Sometimes you want to produce a JSON string of arbitrary data, and you may not know whether the data contains tokens\. To properly JSON\-encode any data structure, regardless of whether it contains tokens, use the method [stack\.toJsonString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#to-json-stringobj-space), as shown in the following example\. + +------ +#### [ TypeScript ] ``` const stack = Stack.of(this); const str = stack.toJsonString({ value: bucket.bucketName }); -``` \ No newline at end of file +``` + +------ +#### [ Python ] + +``` +stack = Stack.of(self) +string = stack.to_json_string(dict(value=bucket.bucket_name)) +``` + +------ +#### [ Java ] + +``` +Stack stack = Stack.of(this); +String stringVal = stack.toJsonString(new HashMap() {{ + put("value", bucket.getBucketName()); +}}); +``` + +------ +#### [ C\# ] + +``` +var stack = Stack.Of(this); +var stringVal = stack.ToJsonString(new Dictionary +{ + ["value"] = bucket.BucketName +}); +``` + +------ \ No newline at end of file diff --git a/doc_source/tools.md b/doc_source/tools.md index f1790efd..956d27e7 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -2,6 +2,10 @@ This section contains information about AWS CDK tools\. +## AWS Toolkit for Visual Studio Code + +The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the AWS Toolkit](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. + ## AWS CDK Command Line Interface \(cdk\) The AWS CDK CLI, cdk, is the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 04c0cd39..e750785c 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -1,29 +1,259 @@ -# Troubleshooting the AWS CDK +# Troubleshooting Common AWS CDK Issues -This section describes how to troubleshoot problems with your AWS CDK app\. +This topic describes how to troubleshoot the following issues with the AWS CDK\. ++ [After updating the AWS CDK, code that used to work fine now results in errors](#troubleshooting_modules) ++ [After updating the AWS CDK, the AWS CDK Toolkit \(CLI\) reports a mismatch with the AWS Construct Library](#troubleshooting_toolkit) ++ [When deploying my AWS CDK stack, I receive a `NoSuchBucket` error](#troubleshooting_nobucket) ++ [When deploying my AWS CDK stack, I receive a `forbidden: null` message](#troubleshooting_forbidden_null) ++ [When synthesizing an AWS CDK stack, I get the message `--app is required either in command-line, in cdk.json or in ~/.cdk.json`](#troubleshooting_app_required) ++ [When deploying an AWS CDK stack, I receive an error because the AWS CloudFormation template contains too many resources](#troubleshooting_resource_count) ++ [I specified three \(or more\) Availability Zones for my EC2 Auto\-Scaling Group or Virtual Private Cloud, but it was only deployed in two](#troubleshooting_availability_zones) ++ [My S3 bucket, DynamoDB table, or other resource is not deleted when I issue `cdk destroy`](#troubleshooting_resource_not_deleted) -## Inconsistent Module Versions +**After updating the AWS CDK, code that used to work fine now results in errors** +Errors in code that used to work is typically a symptom of having mismatched versions of AWS Construct Library modules\. Make sure all library modules are the same version and up\-to\-date\. -If you have inconsistent module versions in your `package.json` file or `node_modules` directory, you might see error messages such as the following: +The modules that make up the AWS Construct Library are a matched set\. They are released together and are intended to be used together\. Interfaces between modules are considered private; we may change them when necessary to implement new features in the library\. +We also update the libraries that are used by the AWS Construct Library from time to time, and different versions of the library modules may have incompatible dependencies\. Synchronizing the versions of the library modules will also address this issue\. + +Below, you'll find details on managing the versions of your installed AWS Construct Library modules TypeScript, JavaScript, and Python + +------ +#### [ TypeScript/JavaScript ] + +Install your project's AWS Construct Library modules locally \(the default\)\. Use `npm` to install the modules and keep them up to date\. + +To see what needs to be updated: + +``` +npm outdated +``` + +To actually update the modules to the latest version: + +``` +npm update +``` + +If you are working with a specific older version of the AWS Construct Library, rather than the latest, first uninstall all of your project's `@aws-cdk` modules, then reinstall the specific version you want to use\. For example, to install version 1\.9\.0 of the Amazon S3 module, use: + +``` +npm uninstall @aws-cdk/aws-s3 +npm install @aws-cdk/aws-s3@1.9.0 ``` -lib/my_ecs_construct-stack.ts:56:49 - error TS2345: Argument of type 'this' is not assignable to parameter of type 'Construct'. - Type 'MyEcsConstructStack' is not assignable to type 'Construct'. - Types of property 'node' are incompatible. - Property 'root' is missing in type 'ConstructNode' but required in type 'ConstructNode'. - -56 new ecs_patterns.LoadBalancedFargateService(this, "MyNewFargateService", { - ~~~~ - - node_modules/@aws-cdk/aws-ecs-patterns/node_modules/@aws-cdk/cdk/lib/construct.d.ts:187:14 - 187 readonly root: IConstruct; - ~~~~ - 'root' is declared here. + +Repeat these commands for each module your project uses\. + +You can edit your `package.json` file to lock the AWS Construct Library modules to a specific version, so `npm update` won't update them\. You can also specify a version using `~` or `^` to allow modules to be updated to versions that are API\-compatible with the current version, such as `^1.0.0` to accept any update API\-compatible with version 1\.x\. Use the same version specification for all AWS Construct Library modules within a project\. + +------ +#### [ Python ] + +Use a virtual environment to manage your project's AWS Construct Library modules\. For your convenience, `cdk init` creates a virtual environment for new Python projects in the project's `.env` directory\. + +Add the AWS Construct Library modules your project uses to its `requirements.txt` file\. Use the `=` syntax to specify an exact version, or the `~=` syntax to constrain updates to versions without breaking API changes\. For example, the following specifies the latest version of the listed modules that are API\-compatible with version 1\.x: + +``` +aws-cdk.core~=1.0 +aws-cdk.aws-s3~=1.0 ``` -The solution is to delete the `node_modules` directory and re\-install your AWS CDK modules: +If you wanted to accept only bug\-fix updates to, for example, version 1\.9\.0, you could instead specify `~=1.9.0`\. Use the same version specification for all AWS Construct Library modules within a single project\. + +Use `pip` to install and update the modules\. + +To see what needs to be updated: + +``` +pip list --local --outdated +``` + +To actually update the modules to the latest compatible version: + +``` +pip install --upgrade -r requirements.txt +``` + +If your project requires a specific older version of the AWS Construct Library, rather than the latest, first uninstall all of your project's `aws-cdk` modules\. Edit `requirements.txt` to specify the exact versions of the modules you want to use using `=`, then install from `requirements.txt`\. + +``` +pip install -r requirements.txt +``` + +------ + +\([back to list](#troubleshooting_top)\) + +**After updating the AWS CDK, the AWS CDK Toolkit \(CLI\) reports a mismatch with the AWS Construct Library** +The version of the AWS CDK Toolkit \(which provides the `cdk` command\) must be at least equal to the version of the AWS Construct Library\. The Toolkit is intended to be backward compatible within the same major version; the latest 1\.x version of the toolkit can be used with any 1\.x release of the library\. For this reason, we recommend you install this component globally and keep it up\-to\-date\. + +``` +npm update -g aws-cdk +``` + +If, for some reason, you need to work with multiple versions of the AWS CDK Toolkit, you can install a specific version of the toolkit locally in your project folder\. + +If you are using a language other than TypeScript or JavaScript, first create a `node_modules` folder in your project directory\. Then, regardless of language, use `npm` to install the AWS CDK Toolkit, omitting the `-g` flag and specifying the desired version\. For example: + +``` +npm install aws-cdk@1.9.0 +``` + +To run a locally\-installed AWS CDK Toolkit, use the command `npx cdk` rather than just `cdk`\. For example: + +``` +npx cdk deploy MyStack +``` + +`npx cdk` runs the local version of the AWS CDK Toolkit if one exists, and falls back to the global version when a project doesn't have a local installation\. You may find it convenient to set up a shell alias or batch file to make sure `cdk` is always invoked this way\. For example, Linux users might add the following statement to their `.bash_profile` file\. + +``` +alias cdk=npx cdk +``` + +\([back to list](#troubleshooting_top)\) + +**When deploying my AWS CDK stack, I receive a `NoSuchBucket` error** +Your AWS environment does not have a staging bucket, which the AWS CDK uses to hold resources during deployment\. Stacks require staging if they contain [Assets](assets.md) or synthesize to AWS CloudFormation templates larger than 50 kilobytes\. You can create the staging bucket with the following command: ``` -rm -rf node_modules -npm install @aws-cdk/... -``` \ No newline at end of file +cdk bootstrap +``` + +To avoid generating unexpected AWS charges, the AWS CDK does not automatically create a staging bucket\. You must bootstrap your environment explicitly\. + +By default, the staging bucket is created in the region specified by the default AWS profile \(set by `aws configure`\), using that profile's account\. You can specify a different account and region on the command line as follows\. + +``` +cdk bootstrap aws://123456789/us-east-1 +``` + +You must bootstrap in every region where you will deploy stacks that require a staging bucket\. + +To avoid undesired AWS charges, you can delete the contents of the staging bucket after deploying\. You can find the bucket in the Amazon S3 management console; it has a name starting with `cdktoolkit-stagingbucket` \(It is possible to specify a different name when bootstrapping, but generally you should use the default name\.\) + +You should not need to delete the bucket itself, but if you do, it is best to delete the entire `CDKToolkit` stack through the AWS CloudFormation management console\. If you delete the staging bucket entirely, you must re\-bootstrap before deploying a stack that requires staging\. + +\([back to list](#troubleshooting_top)\) + +**When deploying my AWS CDK stack, I receive a `forbidden: null` message** +You are deploying a stack that requires the use of a staging bucket, but are using an IAM role or account that lacks permission to write to it\. \(The staging bucket is used when deploying stacks that contain assets or that synthesize an AWS CloudFormation template larger than 50K\.\) Use an account or role that has permission to perform the action `s3:*` against the resource `arn:aws:s3:::cdktoolkit-stagingbucket-*`\. + +\([back to list](#troubleshooting_top)\) + +**When synthesizing an AWS CDK stack, I get the message `--app is required either in command-line, in cdk.json or in ~/.cdk.json`** + This message usually means that you aren't in the main directory of your AWS CDK project when you issue `cdk synth`\. The file `cdk.json` in this directory, created by the `cdk init` command, contains the command line needed to run \(and thereby synthesize\) your AWS CDK app\. For a TypeScript app, for example, the default `cdk.json` looks something like this: + +``` +{ + "app": "npx ts-node bin/my-cdk-app.ts" +} +``` + + We recommend issuing `cdk` commands only in your project's main directory, so the AWS CDK toolkit can find `cdk.json` there and successfully run your app\. + + If this isn't practical for some reason, the AWS CDK Toolkit looks for the app's command line in two other locations: ++ in `cdk.json` in your home directory ++ on the `cdk synth` command itself using the `-a` option + +For example, you might synthesize a stack from a TypeScript app as follows\. + +``` +cdk synth --app "npx ts-node my-cdk-app.ts" MyStack +``` + +\([back to list](#troubleshooting_top)\) + +**When deploying an AWS CDK stack, I receive an error because the AWS CloudFormation template contains too many resources** +The AWS CDK generates and deploys AWS CloudFormation templates\. AWS CloudFormation has a hard limit of 200 resources per stack\. With the AWS CDK, you can run up against this limit more quickly than you might expect, especially if you haven't already worked with AWS CloudFormation enough to know what resources are being generated by the AWS CloudFormation Construct Library constructs you're using\. + +The AWS Construct Library's higher\-level, intent\-based constructs automatically provision any auxiliary resources that are needed for logging, key management, authorization, and other purposes\. For example, granting one resource access to another generates any IAM objects needed for the relevant services to communicate\. + +In our experience, real\-world use of intent\-based constructs results in 1–5 AWS CloudFormation resources per construct, though this can vary\. For serverless applications, 5–8 AWS resources per API endpoint is typical\. + +Patterns, which represent a higher level of abstraction, let you define even more AWS resources with even less code\. The AWS CDK code in [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md), for example, generates more than fifty AWS CloudFormation resources while defining only three constructs\! + +Synthesize regularly and keep an eye on how many resources your stack contains\. You'll quickly get a feel for how many resources will be generated by the constructs you use most frequently\. + +**Tip** +You can count the resources in your synthesized output using the following short script\. \(Since every CDK user has Node\.js installed, it is written in JavaScript\.\) + +``` +// rescount.js - count the resources defined in a stack +// invoke with: node rescount.js +// e.g. node rescount.js cdk.out/MyStack.template.json + +const fs = require('fs'); +const path = process.argv[2]; + +if (path) fs.readFile(path, 'utf8', function(err, contents) { + console.log(err ? `${err}` : + `${Object.keys(JSON.parse(contents).Resources).length} resources defined in ${path}`); +}); else console.log("Please specify the path to the stack's output .json file"); +``` + +As your stack's resource count approaches 200, consider re\-architecting to reduce the number of resources your stack contains, for example by combining some Lambda functions, or to break it up into multiple stacks\. The CDK supports [references between stacks](https://docs.aws.amazon.com/cdk/latest/guide/resources.html#resource_stack), so it is straightforward to separate your app's functionality into different stacks in whatever way makes the most sense to you\. + +**Note** +AWS CloudFormation experts often suggest the use of nested stacks as a solution to the 200 resource limit\. The AWS CDK supports this approach via the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudformation.NestedStack.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudformation.NestedStack.html) construct\. + +\([back to list](#troubleshooting_top)\) + +**I specified three \(or more\) Availability Zones for my EC2 Auto\-Scaling Group or Virtual Private Cloud, but it was only deployed in two** +To get the number of Availability Zones you requested, specify the account and region in the stack's `env` property\. If you do not specify both, the AWS CDK, by default, synthesizes the stack as environment\-agnostic, such that it can be deployed to any region\. You can then deploy the stack to a specific region using AWS CloudFormation\. Because some regions have only two availability zones, an environment\-agnostic template never uses more than two\. + +**Note** +At this writing, there is one AWS region that has only one availability zone: ap\-northeast\-3 \(Osaka, Japan\)\. Environment\-agnostic AWS CDK stacks cannot be deployed to this region\. + +You can change this behavior by overriding your stack's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) \(Python: `availability_zones`\) property to explicitly specify the zones you want to use\. + +For more information on how to specify a stack's account and region at synthesis time, while retaining the flexibility to deploy to any region, see [Environments](environments.md)\. + +\([back to list](#troubleshooting_top)\) + +**My S3 bucket, DynamoDB table, or other resource is not deleted when I issue `cdk destroy`** +By default, resources that can contain user data have a `removalPolicy` \(Python: `removal_policy`\) property of `RETAIN`, and the resource is not deleted when the stack is destroyed\. Instead, the resource is orphaned from the stack\. You must then delete the resource manually after the stack is destroyed\. Until you do, redeploying the stack fails, because the name of the new resource being created during deployment conflicts with the name of the orphaned resource\. + +If you set a resource's removal policy to `DESTROY`, that resource will be deleted when the stack is destroyed\. + +------ +#### [ TypeScript ] + +``` +import cdk = require('@aws-cdk/core'); +import s3 = require('@aws-cdk/aws-s3') + +export class CdkTestStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const bucket = new s3.Bucket(this, 'Bucket', { + removalPolicy: cdk.RemovalPolicy.DESTROY, + }); + } +} +``` + +------ +#### [ Python ] + +``` +import aws_cdk.core as cdk +import aws_cdk.aws_s3 as s3 + +class CdkTestStack(cdk.stack): + def __init__(self, scope: cdk.Construct, id: str, **kwargs): + super().__init__(scope, id, **kwargs) + + bucket = s3.Bucket(this, "Bucket", + removal_policy=cdk.RemovalPolicy.DESTROY) +``` + +------ + +**Note** +AWS CloudFormation cannot delete a non\-empty Amazon S3 bucket\. If you set an Amazon S3 bucket's removal policy to `DESTROY`, and it contains data, attempting to destroy the stack will fail because the bucket cannot be deleted\. +It is possible to handle the destruction of an Amazon S3 bucket using an AWS CloudFormation [custom resource](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) that deletes the bucket's contents before attempting to delete the bucket itself\. The third\-party construct [https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda](https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda), for example, uses such a custom resource\. + +\([back to list](#troubleshooting_top)\) \ No newline at end of file diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 8f9386be..64054c19 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -13,7 +13,10 @@ The AWS CDK provides a mechanism that you can use to incorporate resources from } ``` -You can include this bucket in your AWS CDK app, as shown in the following example: +You can include this bucket in your AWS CDK app, as shown in the following example\. + +------ +#### [ TypeScript ] ``` import cdk = require("@aws-cdk/core"); @@ -24,8 +27,76 @@ new cdk.CfnInclude(this, "ExistingInfrastructure", { }); ``` +------ +#### [ Python ] + +``` +import json + +cdk.CfnInclude(self, "ExistingInfrastructure", + template=json.load(open("my-template.json")) +``` + +------ +#### [ Java ] + +``` +import java.util.*; +import java.io.File; + +import software.amazon.awscdk.core.CfnInclude; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +CfnInclude.Builder.create(this, "ExistingInfrastructure") + .template((ObjectNode)new ObjectMapper().readTree(new File("my-template.json"))) + .build(); +``` + +------ +#### [ C\# ] + +``` +using Newtonsoft.Json.Linq; + +new CfnInclude(this, "ExistingInfrastructure", new CfnIncludeProps +{ + Template = JObject.Parse(File.ReadAllText("my-template.json")) +}); +``` + +------ + Then to access an attribute of the resource, such as the bucket's ARN: +------ +#### [ TypeScript ] + ``` const bucketArn = cdk.Fn.getAtt("S3Bucket", "Arn"); -``` \ No newline at end of file +``` + +------ +#### [ Python ] + +``` +bucket_arn = cdk.Fn.get_att("S3Bucket", "Arn") +``` + +------ +#### [ Java ] + +``` +IResolvable bucketArn = Fn.getAtt("S3Bucket", "Arn"); +``` + +------ +#### [ C\# ] + +``` +var bucketArn = Fn.GetAtt("S3Bucket", "Arn"); +``` + +------ \ No newline at end of file From 0e759c6b47d16b804522cef6f26635a36e193e3b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 11 Dec 2019 21:31:17 +0000 Subject: [PATCH 074/655] post re:Invent update with some typos and code issues fixed --- doc_source/assets.md | 2 +- doc_source/cfn_layer.md | 2 +- doc_source/constructs.md | 6 +++--- doc_source/context.md | 4 ++-- doc_source/doc-history.md | 2 +- doc_source/get_context_var.md | 2 +- doc_source/get_secrets_manager_value.md | 2 +- doc_source/home.md | 7 ++++++- doc_source/permissions.md | 10 +++++----- doc_source/serverless_example.md | 4 ++-- doc_source/stack_how_to_create_multiple_stacks.md | 4 ++-- doc_source/troubleshooting.md | 2 +- 12 files changed, 26 insertions(+), 21 deletions(-) diff --git a/doc_source/assets.md b/doc_source/assets.md index 9ac07872..ecdbe7d2 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -382,7 +382,7 @@ dirname = os.path.dirname(__file__) asset = Asset(self, "MyFile", path=os.path.join(dirname, "my-image.png")) - group = iam.Group(this, "MyUserGroup") + group = iam.Group(self, "MyUserGroup") asset.grantRead(group) ``` diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 7da5d7ea..57c5c5c6 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -90,7 +90,7 @@ new cdk.CfnResource(this, 'MyBucket', { #### [ Python ] ``` -cdk.CfnResource(this, 'MyBucket', +cdk.CfnResource(self, 'MyBucket', type="AWS::S3::Bucket", properties=dict( # Note the PascalCase here! These are CloudFormation identifiers. diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 32d93c4d..075cdcdd 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -505,7 +505,7 @@ new NotifyingBucket(this, 'MyNotifyingBucket'); #### [ Python ] ``` -NotifyingBucket(this, "MyNotifyingBucket") +NotifyingBucket(self, "MyNotifyingBucket") ``` ------ @@ -660,8 +660,8 @@ images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); #### [ Python ] ``` -queue = qs.Queue(this, "NewImagesQueue") -images = NotifyingBucket(this, prefix="Images") +queue = qs.Queue(self, "NewImagesQueue") +images = NotifyingBucket(self, prefix="Images") images.topic.add_subscription(sns_sub.SqsSubscription(queue)) ``` diff --git a/doc_source/context.md b/doc_source/context.md index 42992841..ca6248a4 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -133,11 +133,11 @@ class ExistsVpcStack(cdk.Stack): super().__init__(scope, id, **kwargs) vpcid = self.node.try_get_context("vpcid"); - vpc = ec2.Vpc.from_lookup(this, "VPC", vpc_id=vpcid) + vpc = ec2.Vpc.from_lookup(self, "VPC", vpc_id=vpcid) pubsubnets = vpc.select_subnets(subnetType=ec2.SubnetType.PUBLIC); - cdk.CfnOutput(this, "publicsubnets", + cdk.CfnOutput(self, "publicsubnets", value=pubsubnets.subnet_ids.to_string()) ``` diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 2d692464..93ae654e 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -1,6 +1,6 @@ # Document History for the AWS CDK Developer Guide -This document is based on the following release of the AWS Cloud Development Kit \(AWS CDK\)\. +This document reflects the following release of the AWS Cloud Development Kit \(AWS CDK\)\. + **API version: 1\.18\.0** + **Latest documentation update:** November 25, 2019 diff --git a/doc_source/get_context_var.md b/doc_source/get_context_var.md index 5c7d3317..eb0f9e30 100644 --- a/doc_source/get_context_var.md +++ b/doc_source/get_context_var.md @@ -31,7 +31,7 @@ const bucket_name = this.node.tryGetContext('bucket_name'); #### [ Python ] ``` -bucket_name = this.node.try_get_context("bucket_name") +bucket_name = self.node.try_get_context("bucket_name") ``` ------ diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index 45d0a6c2..ee7578bf 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -30,7 +30,7 @@ class SecretsManagerStack(core.Stack): def __init__(self, scope: core.App, id: str, **kwargs): super().__init__(scope, name, **kwargs) - secret = sm.Secret.from_secret_attributes(this, "ImportedSecret", + secret = sm.Secret.from_secret_attributes(self, "ImportedSecret", secret_arn="arn:aws:secretsmanager:::secret:-", # If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: # encryption_key=.... diff --git a/doc_source/home.md b/doc_source/home.md index c33bbc60..e380c74f 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -107,9 +107,14 @@ public class MyEcsConstructStack extends Stack { #### [ C\# ] ``` +using Amazon.CDK; +using Amazon.CDK.AWS.EC2; +using Amazon.CDK.AWS.ECS; +using Amazon.CDK.AWS.ECS.Patterns; + public class MyEcsConstructStack : Stack { - public MyEcsConstructStack(Construct scope, string id, IStackProps props) : base(scope, id, props) + public MyEcsConstructStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) { var vpc = new Vpc(this, "MyVpc", new VpcProps { diff --git a/doc_source/permissions.md b/doc_source/permissions.md index b2f52504..de91e45a 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -33,8 +33,8 @@ const role = new iam.Role(this, 'Role', { ``` import aws_cdk.aws_iam as iam -role = iam.Role(self, 'Role', - assumed_by=iam.ServicePrincipal('ec2.amazonaws.com')) # required +role = iam.Role(self, "Role", + assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")) # required ``` ------ @@ -62,7 +62,7 @@ var role = new Role(this, "Role", new RoleProps ------ -You can add permissions to a role by calling the role's `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.htm#add-to-policystatement)` method \(Python: `add_to_policy`\), passing in a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. +You can add permissions to a role by calling the role's `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` method \(Python: `add_to_policy`\), passing in a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. The following example adds a `Deny` policy statement to the role for the actions `ec2:SomeAction` and `s3:AnotherAction` on the resources `bucket` and `otherRole` \(Python: `other_role`\), under the condition that the authorized service is AWS CodeBuild\. @@ -202,7 +202,7 @@ var project = new Project(this, "Project", new ProjectProps ------ -Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. This property is not available on imported resources, however, so the constructs have an `addToRolePolicy` \(Python: `add_to_role_policy`\) method that does nothing if the construct is an imported resource, and calls the `addToPolicy` \(Python: `add_to_policy`\) method of the `role` property otherwise, saving you the trouble of handling the undefined case explicitly\. The following example demonstrates: +Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. This property is not available on imported resources, however, so such constructs have an `addToRolePolicy` \(Python: `add_to_role_policy`\) method that does nothing if the construct is an imported resource, and calls the `addToPolicy` \(Python: `add_to_policy`\) method of the `role` property otherwise, saving you the trouble of handling the undefined case explicitly\. The following example demonstrates: ------ #### [ TypeScript ] @@ -222,7 +222,7 @@ project.addToRolePolicy(new iam.PolicyStatement({ ``` # project is imported into the CDK application -project = codebuild.Project.from_project_name(this, 'Project', 'ProjectName') +project = codebuild.Project.from_project_name(self, 'Project', 'ProjectName') # project is imported, so project.role is undefined, and this call has no effect project.add_to_role_policy(new iam.PolicyStatement( diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index f150ff8f..2ee2cfff 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -1,6 +1,6 @@ # Creating a Serverless Application Using the AWS CDK -This example walks you through how to create the resources for a simple widget dispensing service\. \(For the purpose of this example, a widget is just an name or identifier that can be added to, retrieved from, and deleted from a collection\.\) The example includes: +This example walks you through how to create the resources for a simple widget dispensing service\. \(For the purpose of this example, a widget is just a name or identifier that can be added to, retrieved from, and deleted from a collection\.\) The example includes: + An AWS Lambda function\. + An Amazon API Gateway API to call the Lambda function\. + An Amazon S3 bucket that contains the Lambda function code\. @@ -539,7 +539,7 @@ Replace the comment in the constructor with the following line of code\. ------ #### [ Python ] -File: `lib/my_widget_service-stack.ts` +File: `my_widget_service/my_widget_service_stack.py` Add the following line of code after the existing `import` statement\. diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index 2753be38..e1bda105 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -270,11 +270,11 @@ class MultistackStack(core.Stack): # If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. # Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). if encrypt_bucket: - s3.Bucket(this, "MyGroovyBucket", + s3.Bucket(self, "MyGroovyBucket", encryption=s3BucketEncryption.KMS_MANAGED, removal_policy=core.RemovalPolicy.DESTROY) else: - s3.Bucket(this, "MyGroovyBucket", + s3.Bucket(self, "MyGroovyBucket", removal_policy=core.RemovalPolicy.DESTROY) ``` diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index e750785c..8d15cd3a 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -246,7 +246,7 @@ class CdkTestStack(cdk.stack): def __init__(self, scope: cdk.Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) - bucket = s3.Bucket(this, "Bucket", + bucket = s3.Bucket(self, "Bucket", removal_policy=cdk.RemovalPolicy.DESTROY) ``` From ea37a96501d1bd0a26d7a38889c47e39000d55fd Mon Sep 17 00:00:00 2001 From: Alan Williams Date: Thu, 12 Dec 2019 13:30:27 -0800 Subject: [PATCH 075/655] Fixed typo in boolean logic --- doc_source/stack_how_to_create_multiple_stacks.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index e1bda105..d7ed8643 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -418,7 +418,7 @@ MultistackStack(app, "MyWestCdkStack", MultistackStack(app, "MyEastCdkStack", env=core.Environment(region="us-east-1"), - encrypt_bucket=False) + encrypt_bucket=True) ``` ------ @@ -577,4 +577,4 @@ To avoid charges for resources that you deployed, destroy the stack using the fo cdk destroy MyEastCdkStack ``` -The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket's contents, but not the bucket itself, using the AWS Management Console or the AWS CLI before destroying the stack\. \ No newline at end of file +The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket's contents, but not the bucket itself, using the AWS Management Console or the AWS CLI before destroying the stack\. From 51a1eeecce32a4a35f3bbea4aada8cbe3acc720a Mon Sep 17 00:00:00 2001 From: Hyeonsoo David Lee Date: Fri, 13 Dec 2019 14:30:30 +0900 Subject: [PATCH 076/655] Update apps.md construccts => constructs --- doc_source/apps.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index bf2a38b9..e3f5c57b 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -105,7 +105,7 @@ app.Synth(); The `App` construct doesn't require any initialization arguments, because it's the only construct that can be used as a root for the construct tree\. You can now use the `App` instance as a scope for defining a single instance of your stack\. -You can also define construccts within an App\-derived class as follows\. +You can also define constructs within an App\-derived class as follows\. ------ #### [ TypeScript ] @@ -272,4 +272,4 @@ The CLI can also interact directly with an already synthesized cloud assembly\. ``` cdk --app ./my-cloud-assembly ls -``` \ No newline at end of file +``` From 5185b2805e84e1b75cefe777605490913d93265d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 16 Dec 2019 19:46:42 +0000 Subject: [PATCH 077/655] add help for CLI subcommands, fix minor issues, small tweaks --- doc_source/apps.md | 2 +- doc_source/environments.md | 2 +- .../stack_how_to_create_multiple_stacks.md | 2 +- doc_source/tools.md | 186 +++++++++++------- doc_source/troubleshooting.md | 2 +- 5 files changed, 119 insertions(+), 75 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index e3f5c57b..f58418f3 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -272,4 +272,4 @@ The CLI can also interact directly with an already synthesized cloud assembly\. ``` cdk --app ./my-cloud-assembly ls -``` +``` \ No newline at end of file diff --git a/doc_source/environments.md b/doc_source/environments.md index 0350878d..bbb60adc 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -7,7 +7,7 @@ If you don't specify an environment when you define a stack, the stack is said t **Note** In an environment\-agnostic stack, any constructs that use availability zones will see two of them\. This allows the stack to be deployed to almost any region, since nearly all regions have at least two availability zones\. The only exception is Osaka \(`ap-northeast-3`\), which has one\. -When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Command Line Interface \(cdk\)](tools.md#cli) for details\. +When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Toolkit \(`cdk`\)](tools.md#cli) for details\. For production stacks, we recommend that you explicitly specify the environment for each stack in your app using the `env` property\. The following example specifies different environments for its two different stacks\. diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index d7ed8643..923f0fc1 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -577,4 +577,4 @@ To avoid charges for resources that you deployed, destroy the stack using the fo cdk destroy MyEastCdkStack ``` -The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket's contents, but not the bucket itself, using the AWS Management Console or the AWS CLI before destroying the stack\. +The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket's contents, but not the bucket itself, using the AWS Management Console or the AWS CLI before destroying the stack\. \ No newline at end of file diff --git a/doc_source/tools.md b/doc_source/tools.md index 1e6b7dc3..1e215a32 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -6,9 +6,9 @@ This section contains information about AWS CDK tools\. The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the AWS Toolkit](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. -## AWS CDK Command Line Interface \(cdk\) +## AWS CDK Toolkit \(`cdk`\) -The AWS CDK CLI, cdk, is the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. +The AWS CDK Toolkit, the CLI cdk, is the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. There are two ways to tell cdk what command to use to run your AWS CDK app\. The first way is to include an explicit \-\-app option whenever you use a cdk command\. @@ -24,7 +24,7 @@ The second way is to add the following entry to the `cdk.json` file \(if you use } ``` -You can also use the npx cdk instead of just cdk\. +You can also use npx cdk instead of just cdk\. npx cdk looks for a locally\-installed copy of the AWS CDK CLI in the current project before falling back to a global installation\. Here are the actions you can take on your AWS CDK app \(this is the output of the cdk \-\-help command\)\. @@ -97,89 +97,135 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` +If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. + +### AWS CDK Toolkit Commands + +The AWS CDK CLI supports several distinct commands\. Help for each \(including only the command\-line options specific to the particular command\) follows\. Commands with no command\-specific options are not listed\. All commands additionally accept the options listed above\. + +#### `cdk list` \(`ls`\) + +``` +cdk list [STACKS..] + +Lists all stacks in the app + +Options: + --long, -l Display environment information for each stack + [boolean] [default: false] +``` + +#### `cdk synthesize` \(`synth`\) + +``` +cdk synthesize [STACKS..] + +Synthesizes and prints the CloudFormation template for this stack + +Options: + --exclusively, -e Only synthesize requested stacks, don't include + dependencies [boolean] +``` + If your app has a single stack, you don't have to specify the stack name\. -If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. +#### `cdk bootstrap` -Commands and individual options as follows. +``` +cdk bootstrap [ENVIRONMENTS..] -**cdk list | ls** +Deploys the CDK toolkit stack into an AWS environment -- --long, -l (boolean) - Display environment information for each stack - default: false +Options: + --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket + --toolkit-bucket-name [string] + --bootstrap-kms-key-id AWS KMS master key ID used for the + SSE-KMS encryption [string] + --tags, -t Tags to add for the stack + (KEY=VALUE) [array] [default: []] + --execute Whether to execute ChangeSet + (--no-execute will NOT execute the + ChangeSet) [boolean] [default: true] +``` -**cdk synthesize | synth** +#### `cdk deploy` -- --exclusively, -e (boolean) - Only deploy requested stacks, don\'t include dependencies +``` +cdk deploy [STACKS..] -**cdk bootstrap** +Deploys the stack(s) named STACKS into your AWS account -- --bootstrap-bucket-name, -b (string) - The name of the CDK toolkit bucket - default: undefined -- --bootstrap-kms-key-id (string) - AWS KMS master key ID used for the SSE-KMS encryption - default: undefined -- --tags, -t (array) - Tags to add for the stack (KEY=VALUE) - default: [] +Options: + --build-exclude, -E Do not rebuild asset with the given ID. Can be specified + multiple times. [array] [default: []] + --exclusively, -e Only deploy requested stacks, don't include dependencies + [boolean] + --require-approval What security-sensitive changes need manual approval + [string] [choices: "never", "any-change", "broadening"] + --ci Force CI detection. Use --no-ci to disable CI + autodetection. [boolean] [default: false] + --notification-arns ARNs of SNS topics that CloudFormation will notify with + stack related events [array] + --tags, -t Tags to add to the stack (KEY=VALUE) [array] + --execute Whether to execute ChangeSet (--no-execute will NOT + execute the ChangeSet) [boolean] [default: true] +``` + +If your app has a single stack, you don't have to specify the stack name\. -**cdk deploy** +#### `cdk destroy` -- --build-exclude, -E (array) - Do not rebuild asset with the given ID. Can be specified multiple times. - default: [] -- --exclusively, -e (boolean) - Only deploy requested stacks, don\'t include dependencies -- --require-approval (string) - What security-sensitive changes need manual approval - [Never,AnyChange,Broadening] -- --ci (boolean) - Force CI detection. Use --no-ci to disable CI autodetection. - default: process.env.CI !== undefined -- --notification-arns (array) - ARNs of SNS topics that CloudFormation will notify with stack related events -- --tags, -t (array) - Tags to add to the stack (KEY=VALUE) +``` +cdk destroy [STACKS..] -**cdk destroy** +Destroy the stack(s) named STACKS -- --exclusively, -e (boolean) - Only deploy requested stacks, don\'t include dependencies -- --force, -f (boolean) - Do not ask for confirmation before destroying the stacks +Options: + --exclusively, -e Only destroy requested stacks, don't include dependees + [boolean] + --force, -f Do not ask for confirmation before destroying the stacks + [boolean] +``` -**cdk diff** +If your app has a single stack, you don't have to specify the stack name\. -- --exclusively, -e (boolean) - Only deploy requested stacks, don\'t include dependencies -- --context-lines (number) - Number of context lines to include in arbitrary JSON diff rendering - default: 3 -- --template (string) - The path to the CloudFormation template to compare with -- --strict (boolean) - Do not filter out AWS::CDK::Metadata resources - default: false +#### `cdk init` -**cdk metadata** +``` +cdk init [TEMPLATE] -no option +Create a new, empty CDK project from a template. Invoked without TEMPLATE, the +app template will be used. -**cdk init** +Options: + --language, -l The language to be used for the new project (default can + be configured in ~/.cdk.json) + [string] [choices: "csharp", "fsharp", "java", "javascript", "python", + "typescript"] + --list List the available templates [boolean] + --generate-only If true, only generates project files, without executing + additional operations such as setting up a git repo, + installing dependencies or compiling the project + [boolean] [default: false] +``` -- --language, -l (string) - The language to be used for the new project (default can be configured in ~/.cdk.json) -- --list (boolean) - List the available templates +#### `cdk context` + +``` +cdk context + +Manage cached context values + +Options: + --reset, -e The context key (or its index) to reset [string] + --clear Clear all context [boolean] +``` ### Bootstrapping your AWS Environment Before you can use the AWS CDK you must bootstrap your AWS environment to create the infrastructure that the AWS CDK CLI needs to deploy your AWS CDK app\. Currently the bootstrap command creates only an Amazon S3 bucket\. -You incur any charges for what the AWS CDK stores in the bucket\. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your account\. +You incur any charges for what the AWS CDK stores in the bucket\. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your AWS account\. ### Security\-Related Changes @@ -191,7 +237,7 @@ You change the level of changes that requires approval by specifying: cdk deploy --require-approval LEVEL ``` -Where _LEVEL_ can be one of the following: +Where *LEVEL* can be one of the following: never Approval is never required\. @@ -229,14 +275,12 @@ CDKMetadata: ### Opting Out from Version Reporting To opt out of version reporting, use one of the following methods: - -- Use the cdk command with the \-\-no\-version\-reporting argument\. ++ Use the cdk command with the \-\-no\-version\-reporting argument\. ``` cdk --no-version-reporting synth ``` - -- Set versionReporting to **false** in `./cdk.json` or `~/cdk.json`\. ++ Set versionReporting to **false** in `./cdk.json` or `~/cdk.json`\. ``` { @@ -294,7 +338,7 @@ This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda fu cdk synth --no-staging > template.yaml ``` -1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`_12345678_, where _12345678_ represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: +1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: ``` Type: AWS::Lambda::Function @@ -311,12 +355,12 @@ This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda fu ``` 2019-04-01 12:22:41 Found credentials in shared credentials file: ~/.aws/credentials 2019-04-01 12:22:41 Invoking app.lambda_handler (python3.7) - + Fetching lambci/lambda:python3.7 Docker container image...... 2019-04-01 12:22:43 Mounting D:\cdk-sam-example\.cdk.staging\a57f59883918e662ab3c46b964d2faa5 as /var/task:ro,delegated inside runtime container START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB - + "This is a Lambda Function defined through CDK" - ``` + ``` \ No newline at end of file diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 8d15cd3a..e3eaad00 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -166,7 +166,7 @@ cdk synth --app "npx ts-node my-cdk-app.ts" MyStack \([back to list](#troubleshooting_top)\) **When deploying an AWS CDK stack, I receive an error because the AWS CloudFormation template contains too many resources** -The AWS CDK generates and deploys AWS CloudFormation templates\. AWS CloudFormation has a hard limit of 200 resources per stack\. With the AWS CDK, you can run up against this limit more quickly than you might expect, especially if you haven't already worked with AWS CloudFormation enough to know what resources are being generated by the AWS CloudFormation Construct Library constructs you're using\. +The AWS CDK generates and deploys AWS CloudFormation templates\. AWS CloudFormation has a hard limit of 200 resources per stack\. With the AWS CDK, you can run up against this limit more quickly than you might expect, especially if you haven't already worked with AWS CloudFormation enough to know what resources are being generated by the AWS Construct Library constructs you're using\. The AWS Construct Library's higher\-level, intent\-based constructs automatically provision any auxiliary resources that are needed for logging, key management, authorization, and other purposes\. For example, granting one resource access to another generates any IAM objects needed for the relevant services to communicate\. From 22179f16c876633cbe547247bfa5a0a5101f5704 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 16 Dec 2019 21:18:19 +0000 Subject: [PATCH 078/655] change 'project.json' to the correct 'package.json' --- doc_source/testing.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/testing.md b/doc_source/testing.md index 23ec8e16..e2dc310e 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -53,14 +53,14 @@ Since we're using the Jest framework, our next setup step is to install Jest\. W npm install --save-dev jest @types/jest @aws-cdk/assert ``` -### Updating `project.json` +### Updating `package.json` -Finally, edit the project's `project.json` to tell NPM how to run Jest, and to tell Jest what kinds of files to collect\. The necessary changes are as follows\. +Finally, edit the project's `package.json` to tell NPM how to run Jest, and to tell Jest what kinds of files to collect\. The necessary changes are as follows\. + Add a new `test` key to the `scripts` section + Add Jest and its types to the `devDependencies` section + Add a new `jest` top\-level key with a `moduleFileExtensions` declaration -These changes are shown in outline below\. Place the new text where indicated in `project.json`\. The "\.\.\." placeholders indicate existing parts of the file that should not be changed\. +These changes are shown in outline below\. Place the new text where indicated in `package.json`\. The "\.\.\." placeholders indicate existing parts of the file that should not be changed\. ``` { From 05a7f7da0e15e28270718d97c7b02b3c568a021b Mon Sep 17 00:00:00 2001 From: "Julian F. Wintermayr" Date: Wed, 18 Dec 2019 23:04:21 +0100 Subject: [PATCH 079/655] fix typo --- doc_source/getting_started.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 3e046ca8..7d655c3e 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -166,7 +166,7 @@ new MyStack(app, 'Stack-Three-E', { env: { account: 'THREE', region: 'us-east-1' #### [ Python ] ``` -MyStack(app, "Stack-One-W", env=core.Environment{account="ONE", region="us-west-2")) +MyStack(app, "Stack-One-W", env=core.Environment(account="ONE", region="us-west-2")) MyStack(app, "Stack-One-E", env=core.Environment(account="ONE", region="us-east-1")) MyStack(app, "Stack-Two-W", env=core.Environment(account="TWO", region="us-west-2")) MyStack(app, "Stack-Two-E", env=core.Environment(account="TWO", region="us-east-1")) From d9d64cc0d5543487e8bf43e027c53231860ef213 Mon Sep 17 00:00:00 2001 From: "Julian F. Wintermayr" Date: Wed, 18 Dec 2019 23:05:38 +0100 Subject: [PATCH 080/655] align whitespaces --- doc_source/getting_started.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 7d655c3e..76c08596 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -166,7 +166,7 @@ new MyStack(app, 'Stack-Three-E', { env: { account: 'THREE', region: 'us-east-1' #### [ Python ] ``` -MyStack(app, "Stack-One-W", env=core.Environment(account="ONE", region="us-west-2")) +MyStack(app, "Stack-One-W", env=core.Environment(account="ONE", region="us-west-2")) MyStack(app, "Stack-One-E", env=core.Environment(account="ONE", region="us-east-1")) MyStack(app, "Stack-Two-W", env=core.Environment(account="TWO", region="us-west-2")) MyStack(app, "Stack-Two-E", env=core.Environment(account="TWO", region="us-east-1")) From bbf0299522986ef5ea01dd66d6c98736b9d8917e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 18 Dec 2019 22:50:13 +0000 Subject: [PATCH 081/655] align code --- doc_source/getting_started.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 76c08596..55aa3616 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -154,7 +154,7 @@ Since you can create any number of stacks in any of your accounts in any region #### [ TypeScript ] ``` -new MyStack(app, 'Stack-One-W', { env: { account: 'ONE', region: 'us-west-2' }}); +new MyStack(app, 'Stack-One-W', { env: { account: 'ONE', region: 'us-west-2' }}); new MyStack(app, 'Stack-One-E', { env: { account: 'ONE', region: 'us-east-1' }}); new MyStack(app, 'Stack-Two-W', { env: { account: 'TWO', region: 'us-west-2' }}); new MyStack(app, 'Stack-Two-E', { env: { account: 'TWO', region: 'us-east-1' }}); @@ -197,10 +197,10 @@ public class MyApp { public static void main(final String argv[]) { app = new App(); - makeMyStack("Stack-One-W", "ONE", "us-west-2"); - makeMyStack("Stack-One-E", "ONE", "us-east-1"); - makeMyStack("Stack-Two-W", "TWO", "us-west-2"); - makeMyStack("Stack-Two-E", "TWO", "us-east-1"); + makeMyStack("Stack-One-W", "ONE", "us-west-2"); + makeMyStack("Stack-One-E", "ONE", "us-east-1"); + makeMyStack("Stack-Two-W", "TWO", "us-west-2"); + makeMyStack("Stack-Two-E", "TWO", "us-east-1"); makeMyStack("Stack-Three-W", "THREE", "us-west-2"); makeMyStack("Stack-Three-E", "THREE", "us-east-1"); From 27be7bdd95dcf8bc93027751f9010744847b6f2c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 23 Dec 2019 18:15:03 +0000 Subject: [PATCH 082/655] add security topics; remove reference to IAM policy document in sample-app template --- doc_source/compliance-validation.md | 16 ++++++++++++++++ doc_source/disaster-recovery-resiliency.md | 11 +++++++++++ doc_source/getting_started.md | 2 +- doc_source/index.md | 7 ++++++- doc_source/infrastructure-security.md | 3 +++ doc_source/security-iam.md | 11 +++++++++++ doc_source/security.md | 15 +++++++++++++++ 7 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 doc_source/compliance-validation.md create mode 100644 doc_source/disaster-recovery-resiliency.md create mode 100644 doc_source/infrastructure-security.md create mode 100644 doc_source/security-iam.md create mode 100644 doc_source/security.md diff --git a/doc_source/compliance-validation.md b/doc_source/compliance-validation.md new file mode 100644 index 00000000..faf24183 --- /dev/null +++ b/doc_source/compliance-validation.md @@ -0,0 +1,16 @@ +# Compliance Validation for the AWS Cloud Development Kit \(AWS CDK\) + +The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. + +The security and compliance of AWS services is assessed by third\-party auditors as part of multiple AWS compliance programs\. These include SOC, PCI, FedRAMP, HIPAA, and others\. AWS provides a frequently updated list of AWS services in scope of specific compliance programs at [AWS Services in Scope by Compliance Program](https://aws.amazon.com/compliance/services-in-scope/)\. + +Third\-party audit reports are available for you to download using AWS Artifact\. For more information, see [Downloading Reports in AWS Artifact](https://docs.aws.amazon.com/artifact/latest/ug/downloading-documents.html)\. + +For more information about AWS compliance programs, see [AWS Compliance Programs](https://aws.amazon.com/compliance/programs/)\. + +Your compliance responsibility when using the AWS CDK to access an AWS service is determined by the sensitivity of your data, your organization's compliance objectives, and applicable laws and regulations\. If your use of an AWS service is subject to compliance with standards such as HIPAA, PCI, or FedRAMP, AWS provides resources to help: ++ [Security and Compliance Quick Start Guides](https://aws.amazon.com/quickstart/?quickstart-all.sort-by=item.additionalFields.updateDate&quickstart-all.sort-order=desc&awsf.quickstart-homepage-filter=categories%23security-identity-compliance) – Deployment guides that discuss architectural considerations and provide steps for deploying security\-focused 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) – A whitepaper that describes how companies can use AWS to create HIPAA\-compliant applications\. ++ [AWS Compliance Resources](https://aws.amazon.com/compliance/resources/) – A collection of workbooks and guides that might apply to your industry and location\. ++ [AWS Config](https://aws.amazon.com/config/) – A service that assesses how well your resource configurations comply with internal practices, industry guidelines, and regulations\. ++ [AWS Security Hub](https://aws.amazon.com/security-hub/) – 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/disaster-recovery-resiliency.md b/doc_source/disaster-recovery-resiliency.md new file mode 100644 index 00000000..c99d21f9 --- /dev/null +++ b/doc_source/disaster-recovery-resiliency.md @@ -0,0 +1,11 @@ +# Resilience for the AWS Cloud Development Kit \(AWS CDK\) + +The Amazon Web Services \(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](https://aws.amazon.com/about-aws/global-infrastructure/)\. + +The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 55aa3616..76154a4c 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -352,7 +352,7 @@ The following table describes the templates available with the supported languag | | | | --- |--- | | app \(default\) | Creates an empty AWS CDK app\. | -| sample\-app | Creates an AWS CDK app with a stack containing an Amazon SQS queue, an Amazon SNS topic, and an IAM policy document that allows the topic to send messages to the queue\. | +| sample\-app | Creates an AWS CDK app with a stack containing an Amazon SQS queue and an Amazon SNS topic\. | For Hello World, you can just use the default template\. diff --git a/doc_source/index.md b/doc_source/index.md index 138b5a77..6096b970 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -47,7 +47,12 @@ Amazon's trademarks and trade dress may not be used in + [Set a CloudWatch Alarm](how_to_set_cw_alarm.md) + [Get a Value from a Context Variable](get_context_var.md) + [AWS CDK Tools](tools.md) -+ [Troubleshooting Common AWS CDK Issues](troubleshooting.md) + [Testing Constructs](testing.md) ++ [Security for the AWS Cloud Development Kit (AWS CDK)](security.md) + + [Identity and Access Management for the AWS Cloud Development Kit (AWS CDK)](security-iam.md) + + [Compliance Validation for the AWS Cloud Development Kit (AWS CDK)](compliance-validation.md) + + [Resilience for the AWS Cloud Development Kit (AWS CDK)](disaster-recovery-resiliency.md) + + [Infrastructure Security for the AWS Cloud Development Kit (AWS CDK)](infrastructure-security.md) ++ [Troubleshooting Common AWS CDK Issues](troubleshooting.md) + [OpenPGP Keys for the AWS CDK and JSII](pgp-keys.md) + [Document History for the AWS CDK Developer Guide](doc-history.md) \ No newline at end of file diff --git a/doc_source/infrastructure-security.md b/doc_source/infrastructure-security.md new file mode 100644 index 00000000..f3a2bb42 --- /dev/null +++ b/doc_source/infrastructure-security.md @@ -0,0 +1,3 @@ +# Infrastructure Security for the AWS Cloud Development Kit \(AWS CDK\) + +The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. \ No newline at end of file diff --git a/doc_source/security-iam.md b/doc_source/security-iam.md new file mode 100644 index 00000000..1a57c193 --- /dev/null +++ b/doc_source/security-iam.md @@ -0,0 +1,11 @@ +# Identity and Access Management for the AWS Cloud Development Kit \(AWS CDK\) + +AWS Identity and Access Management \(IAM\) is an Amazon Web Services \(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 resources in AWS services\. IAM is an AWS service that you can use with no additional charge\. + +To use the AWS CDK to access AWS, you need an AWS account and AWS credentials\. To increase the security of your AWS account, we recommend that you use an *IAM user* to provide access credentials instead of using your AWS account credentials\. + +For details about working with IAM, see [AWS Identity and Access Management](https://aws.amazon.com/iam/)\. + +For an overview of IAM users and why they are important for the security of your account, see [AWS Security Credentials](https://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html) in the [Amazon Web Services General Reference](https://docs.aws.amazon.com/general/latest/gr/)\. + +The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. \ No newline at end of file diff --git a/doc_source/security.md b/doc_source/security.md new file mode 100644 index 00000000..b25615eb --- /dev/null +++ b/doc_source/security.md @@ -0,0 +1,15 @@ +# Security for the AWS Cloud Development Kit \(AWS CDK\) + +Cloud security at Amazon Web Services \(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](https://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 all of the services offered in the AWS Cloud and providing you with services that you can use securely\. Our security responsibility is the highest priority at AWS, and the effectiveness of our security is regularly tested and verified by third\-party auditors as part of the [AWS Compliance Programs](https://aws.amazon.com/compliance/programs/)\. + +**Security in the Cloud** – Your responsibility is determined by the AWS service you are using, and other factors including the sensitivity of your data, your organization's requirements, and applicable laws and regulations\. + +The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. + +**Topics** ++ [Identity and Access Management](security-iam.md) ++ [Compliance Validation](compliance-validation.md) ++ [Resilience](disaster-recovery-resiliency.md) ++ [Infrastructure Security](infrastructure-security.md) \ No newline at end of file From 7e3c004abb1c3c1fa6649dfe4ee3102dafaafb5f Mon Sep 17 00:00:00 2001 From: Chris McKnight Date: Mon, 30 Dec 2019 16:39:29 -0600 Subject: [PATCH 083/655] fix(environments): Fix environments bash shebang line for bash --- doc_source/environments.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index bbb60adc..3d4705e1 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -265,7 +265,7 @@ With your stack's environment declared this way, you can now write a short scrip #### [ Linux/Mac OS X ] ``` -#!bash +#!/bin/bash # cdk-deploy-to.sh CDK_DEPLOY_ACCOUNT=$1 shift @@ -295,7 +295,7 @@ Then you can write additional scripts that call that script to deploy to specifi #### [ Linux/Mac OS X ] ``` -#!bash +#!/bin/bash # cdk-deploy-to-test.sh bash cdk-deploy-to.sh 123457689 us-east-1 "$@" ``` @@ -317,7 +317,7 @@ When deploying to multiple environments, consider whether you want to continue d #### [ Linux/Mac OS X ] ``` -#!bash +#!/bin/bash # cdk-deploy-to-prod.sh bash cdk-deploy-to.sh 135792468 us-west-1 "$@" || exit bash cdk-deploy-to.sh 246813579 eu-west-1 "$@" From b92900a63c3d38ad1b7e34a69e900361427e9bf4 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 2 Jan 2020 17:17:12 +0000 Subject: [PATCH 084/655] remove unneeded word --- doc_source/getting_started.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 76154a4c..3ed6b588 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -313,7 +313,7 @@ The typical workflow for creating a new app is: 1. Compile the app, if necessary\. -1. To deploy the resources defined in the app\. +1. Deploy the resources defined in the app\. 1. Test the app\. From 4c6266119cd9b5d090e8e7639d8dd1fbf1ecc6b8 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 3 Jan 2020 18:44:07 +0000 Subject: [PATCH 085/655] add missing . to ~/.cdk.json path --- doc_source/tools.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/tools.md b/doc_source/tools.md index 1e215a32..8246d0f6 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -280,7 +280,7 @@ To opt out of version reporting, use one of the following methods: ``` cdk --no-version-reporting synth ``` -+ Set versionReporting to **false** in `./cdk.json` or `~/cdk.json`\. ++ Set versionReporting to **false** in `./cdk.json` or `~/.cdk.json`\. ``` { From 82f2f9ced9f24833d8bad8c174682056ec4729bf Mon Sep 17 00:00:00 2001 From: Judson Neer Date: Fri, 3 Jan 2020 21:43:36 -0800 Subject: [PATCH 086/655] Add an example Federated principal to example list --- doc_source/permissions.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/doc_source/permissions.md b/doc_source/permissions.md index de91e45a..6905d446 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -323,6 +323,8 @@ The AWS CDK Construct Library supports many types of principals, including: 1. Service principals \(`new iam.[ServicePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ServicePrincipal.html)('service.amazonaws.com')`\) +1. Federated principals \(`new iam.[FederatedPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.FederatedPrincipal.html)('cognito-identity.amazonaws.com')`\) + 1. Account principals \(`new iam.[AccountPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.AccountPrincipal.html)('0123456789012'))` 1. Canonical user principals \(`new iam.[CanonicalUserPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CanonicalUserPrincipal.html)('79a59d[...]7ef2be')`\) @@ -331,4 +333,4 @@ The AWS CDK Construct Library supports many types of principals, including: 1. Arbitrary ARN principals \(`new iam.[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ArnPrincipal.html)(res.arn)`\) -1. An `iam.[CompositePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CompositePrincipal.html)(principal1, principal2, ...)` to trust multiple principals \ No newline at end of file +1. An `iam.[CompositePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CompositePrincipal.html)(principal1, principal2, ...)` to trust multiple principals From 41a4bac26bfeb446150268a00dd5c695504ee561 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 7 Jan 2020 21:14:48 +0000 Subject: [PATCH 087/655] fix typo --- doc_source/testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/testing.md b/doc_source/testing.md index e2dc310e..625ede22 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -269,7 +269,7 @@ Since we've replaced the snapshot test, the first time we run the new tests, Jes Suppose we want to make the dead letter queue's retention period configurable\. Of course, we also want to make sure that the value provided by the user of the construct is within an allowable range\. We can write a test to make sure that the validation logic works: pass in invalid values and see what happens\. -First, create a `propes` interface for the construct\. +First, create a `props` interface for the construct\. ``` export interface DeadLetterQueueProps { From 7d4a026a4719ff153f4b380645139537480cad51 Mon Sep 17 00:00:00 2001 From: Chris McKnight Date: Wed, 8 Jan 2020 16:10:36 -0600 Subject: [PATCH 088/655] fix(environments): Add missing exports --- doc_source/environments.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index bbb60adc..6a74d6a9 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -267,9 +267,9 @@ With your stack's environment declared this way, you can now write a short scrip ``` #!bash # cdk-deploy-to.sh -CDK_DEPLOY_ACCOUNT=$1 +export CDK_DEPLOY_ACCOUNT=$1 shift -CDK_DEPLOY_REGION=$1 +export CDK_DEPLOY_REGION=$1 shift cdk deploy "$@" ``` @@ -335,4 +335,4 @@ cdk-deploy-to 245813579 eu-west-1 %* ------ -Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. \ No newline at end of file +Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. From bcfb73069e237604a4b28edb236df29947c4a9c6 Mon Sep 17 00:00:00 2001 From: Yann Duval Date: Sat, 11 Jan 2020 14:45:54 +0100 Subject: [PATCH 089/655] Update nodejs runtime to NODEJS_10_X Fixing awsdocs/aws-cdk-guide#168 --- doc_source/serverless_example.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 2ee2cfff..4ffe7c6b 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -305,7 +305,7 @@ export class WidgetService extends core.Construct { const bucket = new s3.Bucket(this, "WidgetStore"); const handler = new lambda.Function(this, "WidgetHandler", { - runtime: lambda.Runtime.NODEJS_8_10, // So we can use async in widget.js + runtime: lambda.Runtime.NODEJS_10_X, // So we can use async in widget.js code: lambda.Code.asset("resources"), handler: "widgets.main", environment: { @@ -920,4 +920,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` \ No newline at end of file +``` From 3379049763fed6fb69a8dc54feeaa4d1205abaf0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 14 Jan 2020 17:23:05 +0000 Subject: [PATCH 090/655] add export keyword to shell scripts so the variables are passed through --- doc_source/environments.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index bbb60adc..1ba6e78f 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -267,9 +267,9 @@ With your stack's environment declared this way, you can now write a short scrip ``` #!bash # cdk-deploy-to.sh -CDK_DEPLOY_ACCOUNT=$1 +export CDK_DEPLOY_ACCOUNT=$1 shift -CDK_DEPLOY_REGION=$1 +export CDK_DEPLOY_REGION=$1 shift cdk deploy "$@" ``` From 5a5c858b2475b2f7c003bea962387cfba1527c81 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 14 Jan 2020 23:29:01 +0000 Subject: [PATCH 091/655] fix "with with" --- doc_source/permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/permissions.md b/doc_source/permissions.md index de91e45a..2aade332 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -4,7 +4,7 @@ The AWS Construct Library uses a few common, widely\-implemented idioms to manag ## Grants -Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` \(Python: `grant_read`, `grant_write`\) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. +Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` \(Python: `grant_read`, `grant_write`\) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)`\. From f5412566c290f63d4f33a6381667b1e0e6c4cce9 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 15 Jan 2020 00:07:16 +0000 Subject: [PATCH 092/655] clarify what changes deploying checks for --- doc_source/getting_started.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 3ed6b588..21a6eeb3 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -685,13 +685,13 @@ The AWS CDK CLI automatically adds the **AWS::CDK::Metadata** resource to your t ### Deploying the Stack -Deploy the app, as follows\. +Deploy the stack, as follows\. ``` cdk deploy ``` -The deploy command synthesizes an AWS CloudFormation template from the app, and then invokes the AWS CloudFormation create/update API to deploy it into your AWS account\. If your code includes changes to your existing infrastructure, the command displays information about those changes and requires you to confirm them before it deploys the changes\. The command displays information as it completes various steps in the process\. There is no mechanism to detect or react to any specific step in the process\. +The deploy command synthesizes an AWS CloudFormation template from the app's stack, and then invokes AWS CloudFormation to deploy it in your AWS account\. If your code would change your infrastructure's security posture, the command displays information about those changes and requires you to confirm them before your stack is deployed\. The command displays information as it completes various steps in the process\. ### Modifying the App From f3fae6127489c0eb54ff940430ae8099dfcc1c22 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 17 Jan 2020 20:29:17 +0000 Subject: [PATCH 093/655] update Node.js version --- doc_source/index.md | 2 +- doc_source/serverless_example.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/index.md b/doc_source/index.md index 6096b970..cb48e60b 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -1,7 +1,7 @@ # AWS Cloud Development Kit (AWS CDK) Developer Guide ----- -*****Copyright © 2019 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** +*****Copyright © 2020 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** ----- Amazon's trademarks and trade dress may not be used in diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 4ffe7c6b..d1624492 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -920,4 +920,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` +``` \ No newline at end of file From c339fc374bb034e91ad0d1f44e95fcdc592762b0 Mon Sep 17 00:00:00 2001 From: Yann Duval Date: Tue, 21 Jan 2020 21:33:43 +0100 Subject: [PATCH 094/655] Updating TS imports to modern style With the switch to a mordern style of imports it is a bit harder to understand where certain classes (e.g. App, Construct, Queue) come from. To make it a bit easier to follow the code the imports where added all code snippets. --- doc_source/constructs.md | 64 +++++++++++++++++++++++------------ doc_source/getting_started.md | 18 +++++----- 2 files changed, 52 insertions(+), 30 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 075cdcdd..341dd36b 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -42,13 +42,13 @@ We call your CDK application an *app*, which is represented by the AWS CDK class ``` import { App, Stack, StackProps } from '@aws-cdk/core'; -import s3 = require('@aws-cdk/aws-s3'); +import { Bucket } from '@aws-cdk/aws-s3'; class HelloCdkStack extends Stack { constructor(scope: App, id: string, props?: StackProps) { super(scope, id, props); - new s3.Bucket(this, 'MyFirstBucket', { + new Bucket(this, 'MyFirstBucket', { versioned: true }); } @@ -183,10 +183,10 @@ Once you have defined a stack, you can populate it with resources\. The followin #### [ TypeScript ] ``` -import s3 = require('@aws-cdk/aws-s3'); +import { Bucket } from '@aws-cdk/aws-s3'; // "this" is HelloCdkStack -new s3.Bucket(this, 'MyFirstBucket', { +new Bucket(this, 'MyFirstBucket', { versioned: true }); ``` @@ -249,8 +249,10 @@ Most constructs accept `props` as their third argument \(or in Python, keyword a #### [ TypeScript ] ``` -new s3.Bucket(this, 'MyEncryptedBucket', { - encryption: s3.BucketEncryption.KMS, +import { Bucket, BucketEncryption } from '@aws-cdk/aws-s3'; + +new Bucket(this, 'MyEncryptedBucket', { + encryption: BucketEncryption.KMS, websiteIndexDocument: 'index.html' }); ``` @@ -297,8 +299,11 @@ For example, almost all AWS constructs have a set of [grant](permissions.md#perm #### [ TypeScript ] ``` -const rawData = new s3.Bucket(this, 'raw-data'); -const dataScience = new iam.Group(this, 'data-science'); +import { Group } from '@aws-cdk/aws-iam'; +import { Bucket } from '@aws-cdk/aws-s3'; + +const rawData = new Bucket(this, 'raw-data'); +const dataScience = new Group(this, 'data-science'); rawData.grantRead(dataScience); ``` @@ -337,11 +342,14 @@ Another common pattern is for AWS constructs to set one of the resource's attrib #### [ TypeScript ] ``` -const jobsQueue = new sqs.Queue(this, 'jobs'); -const createJobLambda = new lambda.Function(this, 'create-job', { - runtime: lambda.Runtime.NODEJS_10_X, +import { Function, Runtime, Code } from '@aws-cdk/aws-lambda'; +import { Queue } from '@aws-cdk/aws-sqs'; + +const jobsQueue = new Queue(this, 'jobs'); +const createJobLambda = new Function(this, 'create-job', { + runtime: Runtime.NODEJS_10_X, handler: 'index.handler', - code: lambda.Code.fromAsset('./create-job-lambda-code'), + code: Code.fromAsset('./create-job-lambda-code'), environment: { QUEUE_URL: jobsQueue.queueUrl } @@ -409,6 +417,11 @@ For example, you could declare a construct that represents an Amazon S3 bucket w #### [ TypeScript ] ``` +import { Construct } from '@aws-cdk/core'; +import { Bucket } from '@aws-cdk/aws-s3'; +import { SnsDestination } from '@aws-cdk/aws-s3-notifications'; +import { Topic } from '@aws-cdk/aws-sns'; + export interface NotifyingBucketProps { prefix?: string; } @@ -416,9 +429,11 @@ export interface NotifyingBucketProps { export class NotifyingBucket extends Construct { constructor(scope: Construct, id: string, props: NotifyingBucketProps = {}) { super(scope, id); - const bucket = new s3.Bucket(this, 'bucket'); - const topic = new sns.Topic(this, 'topic'); - bucket.addObjectCreatedNotification(topic, { prefix: props.prefix }); + const bucket = new Bucket(this, 'bucket'); + + const topic = new Topic(this, 'topic'); + const snsDestination = new SnsDestination(topic); + bucket.addObjectCreatedNotification(snsDestination, { prefix: props.prefix }); } } ``` @@ -566,13 +581,15 @@ Typically, you would also want to expose some properties or methods on your cons ``` export class NotifyingBucket extends Construct { - public readonly topic: sns.Topic; + public readonly topic: Topic; constructor(scope: Construct, id: string, props: NotifyingBucketProps) { super(scope, id); - const bucket = new s3.Bucket(this, 'bucket'); - this.topic = new sns.Topic(this, 'topic'); - bucket.addObjectCreatedNotification(this.topic, { prefix: props.prefix }); + + const bucket = new Bucket(this, 'bucket'); + this.topic = new Topic(this, 'topic'); + const snsDestination = new SnsDestination(snsTopic); + bucket.addObjectCreatedNotification(snsDestination, { prefix: props.prefix }); } } ``` @@ -651,9 +668,12 @@ Now, consumers can subscribe to the topic, for example: #### [ TypeScript ] ``` -const queue = new sqs.Queue(this, 'NewImagesQueue'); +import { Queue } from '@aws-cdk/aws-sqs'; +import { SqsSubscription } from '@aws-cdk/aws-sns-subscriptions'; + +const queue = new Queue(this, 'NewImagesQueue'); const images = new NotifyingBucket(this, 'Images'); -images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); +images.topic.addSubscription(new SqsSubscription(queue)); ``` ------ @@ -685,4 +705,4 @@ var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketP images.topic.AddSubscription(new SqsSubscription(queue)); ``` ------- \ No newline at end of file +------ diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 21a6eeb3..4138372b 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -521,14 +521,14 @@ Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represente In `lib/hello-cdk-stack.ts`: ``` -import core = require('@aws-cdk/core'); -import s3 = require('@aws-cdk/aws-s3'); +import { App, Stack, StackProps, Construct } from '@aws-cdk/core'; +import { Bucket } from '@aws-cdk/aws-s3'; -export class HelloCdkStack extends core.Stack { - constructor(scope: core.App, id: string, props?: core.StackProps) { +export class HelloCdkStack extends Stack { + constructor(scope: App, id: string, props?: StackProps) { super(scope, id, props); - new s3.Bucket(this, 'MyFirstBucket', { + new Bucket(this, 'MyFirstBucket', { versioned: true }); } @@ -703,9 +703,11 @@ Configure the bucket to use AWS Key Management Service \(AWS KMS\) managed encry Update `lib/hello-cdk-stack.ts` ``` -new s3.Bucket(this, 'MyFirstBucket', { +import { Bucket, BucketEncryption } from "@aws-cdk/aws-s3"; + +new Bucket(this, 'MyFirstBucket', { versioned: true, - encryption: s3.BucketEncryption.KMS_MANAGED + encryption: BucketEncryption.KMS_MANAGED }); ``` @@ -837,4 +839,4 @@ Destroy the app's resources to avoid incurring any costs from the resources crea cdk destroy ``` -Enter y to approve the changes and delete any stack resources\. In some cases this command fails, such as when a resource isn't empty and must be empty before it can be destroyed\. See [Delete Stack Fails](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#troubleshooting-errors-delete-stack-fails) in the *AWS CloudFormation User Guide* for details\. \ No newline at end of file +Enter y to approve the changes and delete any stack resources\. In some cases this command fails, such as when a resource isn't empty and must be empty before it can be destroyed\. See [Delete Stack Fails](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#troubleshooting-errors-delete-stack-fails) in the *AWS CloudFormation User Guide* for details\. From 678b2463147d094db9bffda3b041a67430b4bae8 Mon Sep 17 00:00:00 2001 From: Bo-Xuan Fan Date: Sun, 25 Aug 2019 15:41:03 +0800 Subject: [PATCH 095/655] Add Java examples --- doc_source/multiple_languages.md | 66 ++++++++++++++++---------------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index c3f86535..7d9e3231 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -2,80 +2,80 @@ In some cases the example code in the AWS CDK documentation is available only in TypeScript\. This topic describes how to read TypeScript code and translate it into other languages\. See [Hello World Tutorial](getting_started.md#hello_world_tutorial) for an example of creating an AWS CDK app in a supported language\. -## Importing a Module +## Importing a Module (Package) -Both TypeScript and Python support namespaced module imports and selective imports\. Module names in Python look like **aws\_cdk\.***xxx*, where *xxx* represents an AWS service name, such as **s3** for Amazon S3 \(we'll use Amazon S3 for our examples\)\. Replace the dashes in the TypeScript module name with underscores to get the Python module name\. +All TypeScript, Python and Java support namespaced module (or package) imports and selective imports\. Module names in Python look like **aws\_cdk\.***xxx*, where *xxx* represents an AWS service name, such as **s3** for Amazon S3 \(we'll use Amazon S3 for our examples\)\. Replace the dashes in the TypeScript module name with underscores to get the Python module name\. Replace the `@aws-cdk` in the TypeScript module name with `software.amazon.awscdk` to get the Java package name. The following is how you import the entire Amazon S3 module or just a `Stack` class in both languages\. -| TypeScript | Python | -| --- |--- | -|
// Import entire module
import s3 = require('@aws-cdk/aws-s3')

// Selective import
import { Stack } from '@aws-cdk/core';
|
# Import entire module
import aws_cdk.aws_s3 as s3

# Selective import
from aws_cdk.core import Stack
| +| TypeScript | Python | Java | +| --- |--- | --- | +|
// Import entire module
import s3 = require('@aws-cdk/aws-s3')

// Selective import
import { Stack } from '@aws-cdk/core';
|
# Import entire module
import aws_cdk.aws_s3 as s3

# Selective import
from aws_cdk.core import Stack
|
// Import entire package
import software.amazon.awscdk.services.s3.*;

// Selective import
import software.amazon.awscdk.core.Stack;
| ## Instantiating a Class -Classes have the same name in TypeScript and in Python\. TypeScript uses **new** to instantiate classes, whereas in Python you call the class object directly, like a function\. Props objects at the end of an argument list become keyword\-only arguments in Python, and their names become `snake_case`\. The keyword **this** in TypeScript translates to **self** in Python\. +Classes have the same name in TypeScript, in Python and in Java\. TypeScript and Java uses **new** to instantiate classes, whereas in Python you call the class object directly, like a function\. Props objects at the end of an argument list become keyword\-only arguments in Python, and their names become `snake_case`\. The keyword **this** in TypeScript translates to **self** in Python\. -The following table shows how you can translate TypeScript class instantiations to Python class instantiations\. +The following table shows how you can translate TypeScript class instantiations to Python or Java class instantiations\. -| TypeScript | Python | -| --- |--- | -|
// Instantiate Bucket class
const bucket = new s3.Bucket(this, 'Bucket');
|
# Instantiate Bucket class
bucket = s3.Bucket(self, 'Bucket')
| -|
// Instantiate Bucket with props
const bucket = new s3.Bucket(this, 'Bucket', {
bucketName: 'my-bucket',
versioned: true,
});
|
# Instantiate Bucket with props
bucket = s3.Bucket(self, 'Bucket',
bucket_name='my-bucket',
versioned=True)
| +| TypeScript | Python | Java | +| --- |--- | --- | +|
// Instantiate Bucket class
const bucket = new s3.Bucket(this, 'Bucket');
|
# Instantiate Bucket class
bucket = s3.Bucket(self, 'Bucket')
|
// Instantiate Bucket class
Bucket bucket = new Bucket(this, "Bucket");
| +|
// Instantiate Bucket with props
const bucket = new s3.Bucket(this, 'Bucket', {
bucketName: 'my-bucket',
versioned: true,
});
|
# Instantiate Bucket with props
bucket = s3.Bucket(self, 'Bucket',
bucket_name='my-bucket',
versioned=True)
|
// Instantiate Bucket with props
Bucket bucket = new Bucket(this, "Bucket", BucketProps.builder()
.bucketName("my-bucket")
.versioned(true)
.build());
| ## Methods -Methods and argument names in TypeScript are `camelCased`, whereas in Python they are `snake_cased`\. Props objects at the end of an argument list in TypeScript are translated into keyword\-only arguments in Python, and their names become `snake_case`\. +Methods and argument names in TypeScript or Java are `camelCased`, whereas in Python they are `snake_cased`\. Props objects at the end of an argument list in TypeScript are translated into keyword\-only arguments in Python, and their names become `snake_case`\. Java used [Builder pattern](https://en.wikipedia.org/wiki/Builder_pattern) to generate props object. -The following table shows how you can translate TypeScript methods to Python methods\. +The following table shows how you can translate TypeScript methods to Python methods or Java methods\. -| TypeScript | Python | -| --- |--- | -|
// Call method
bucket.addCorsRule({
allowedOrigins: ['*'],
allowedMethods: [],
});
|
# Call method
bucket.add_cors_rule(
allowed_origins=['*'],
allowed_methods=[]
)
| +| TypeScript | Python | Java | +| --- |--- | --- | +|
// Call method
bucket.addCorsRule({
allowedOrigins: ['*'],
allowedMethods: [],
});
|
# Call method
bucket.add_cors_rule(
allowed_origins=['*'],
allowed_methods=[]
)
|
// Call method
bucket.addCorsRule(CorsRule.builder()
.allowedOrigins(List.of("*"))
.allowedMethods(List.of())
.build());
| ## Enum Constants -Enum constants are scoped to a class, and have uppercase names with underscores in both languages \(sometimes referred to as `SCREAMING_SNAKE_CASE`\)\. TypeScript enum constants and Python enum constants are identical\. +Enum constants are scoped to a class, and have uppercase names with underscores in all languages \(sometimes referred to as `SCREAMING_SNAKE_CASE`\)\. TypeScript enum constants, Python enum constants and Java enum constants are identical\. -| TypeScript | Python | -| --- |--- | -|
s3.BucketEncryption.KMS_MANAGED
|
s3.BucketEncryption.KMS_MANAGED
| +| TypeScript | Python | Java | +| --- |--- | --- | +|
s3.BucketEncryption.KMS_MANAGED
|
s3.BucketEncryption.KMS_MANAGED
|
BucketEncryption.KMS_MANAGED
| ## Defining Constructs -In TypeScript, a construct's props are defined with a shape\-based interface, whereas Python takes keyword \(or keyword\-only, see [PEP3102](https://www.python.org/dev/peps/pep-3102/)\) arguments\. +In TypeScript, a construct's props are defined with a shape\-based interface, whereas Python takes keyword \(or keyword\-only, see [PEP3102](https://www.python.org/dev/peps/pep-3102/)\) arguments\. Java's props object should be a POJO and provided [Builder pattern](https://en.wikipedia.org/wiki/Builder_pattern) to define props object\. (Using [Lombok](https://projectlombok.org/) will be most convenient for you.) -The following table shows how TypeScript construct definitions translate to Python construct definitions\. +The following table shows how TypeScript construct definitions translate to Python construct definitions or Java construct definitions\. -| TypeScript | Python | -| --- |--- | -|
interface MyConstructProps {
prop1: number;
prop2?: number;
}

class MyConstruct extends Construct {
constructor(scope: Construct, id: string, props: MyConstructProps) {
super(scope, id);
const prop2 = props.prop2 !== undefined ? props.prop2 : 10;

// Construct contents here

}
}
|
class MyConstruct(Construct):

def __init__(scope, id, *, prop1, prop2=10):
super().__init__(scope, id)

# Construct contents here
| +| TypeScript | Python | Java | +| --- |--- | --- | +|
interface MyConstructProps {
prop1: number;
prop2?: number;
}

class MyConstruct extends Construct {
constructor(scope: Construct, id: string, props: MyConstructProps) {
super(scope, id);
const prop2 = props.prop2 !== undefined ? props.prop2 : 10;

// Construct contents here

}
}
|
class MyConstruct(Construct):

def __init__(scope, id, *, prop1, prop2=10):
super().__init__(scope, id)

# Construct contents here
|
@lombok.Getter
@lombok.Builder
public class MyConstructProps {
private int prop1;
@lombok.Builder.Default
private int prop2 = 10;
}

public class MyConstruct extends Construct {
public MyConstruct(Construct scope, String id, MyConstructProps props) {
super(scope, id);

// Construct contents here
}
}
| ## Structs \(Interfaces\) Structs are TypeScript interfaces that represent a set of values\. You can recognize them because their name doesn't start with an `I`, and all of their fields are **read\-only**\. -In TypeScript, structs are passed as object literals\. In Python, if the struct is the last argument to a method, its fields are lifted into the method call itself\. If the argument list contains nested structs, wrap them in a class named after the struct\. +In TypeScript, structs are passed as object literals\. In Python, if the struct is the last argument to a method, its fields are lifted into the method call itself\. If the argument list contains nested structs, wrap them in a class named after the struct\. In Java, structs are passed as object directly\. The following table shows how to call a method with two levels of structs\. -| TypeScript | Python | -| --- |--- | -|
bucket.addLifecycleRule({
transitions: [
{
storageClass: StorageClass.GLACIER,
transitionAfter: Duration.days(10)
}
]
});
|
bucket.add_lifecycle_rule(
transitions=[
Transition(
storage_class=StorageClass.GLACIER,
transition_after=Duration.days(10)
)
]
)
| +| TypeScript | Python | Java | +| --- |--- | --- | +|
bucket.addLifecycleRule({
transitions: [
{
storageClass: StorageClass.GLACIER,
transitionAfter: Duration.days(10)
}
]
});
|
bucket.add_lifecycle_rule(
transitions=[
Transition(
storage_class=StorageClass.GLACIER,
transition_after=Duration.days(10)
)
]
)
|
bucket.addLifecycleRule(LifecycleRule.builder()
.transitions(List.of(Transition.builder()
.storageClass(StorageClass.GLACIER)
.transitionAfter(Duration.days(10))
.build()))
.build());
| ## Object Interfaces -The AWS CDK uses TypeScript object interfaces to indicate that a class implements an expected set of methods and properties\. You can recognize an object interface because its name starts with `I`\. +The AWS CDK uses TypeScript and Java object interfaces to indicate that a class implements an expected set of methods and properties\. You can recognize an object interface because its name starts with `I`\. Typically, Python users don't explicitly indicate that a class implements an interface\. However, for the AWS CDK you can do this by decorating your class with `@jsii.implements(interface)`\. -| TypeScript | Python | -| --- |--- | -|
import {IAspect, IConstruct } from '@aws-cdk/core';

class MyAspect implements IAspect {
public visit(node: IConstruct) {
console.log('Visited', node.node.path);
}
}
|
from aws_cdk.core import IAspect, IConstruct

@jsii.implements(IAspect)
class MyAspect():
def visit(self, node: IConstruct) -> None:
print("Visited", node.node.path)
| \ No newline at end of file +| TypeScript | Python | Java | +| --- |--- | --- | +|
import {IAspect, IConstruct } from '@aws-cdk/core';

class MyAspect implements IAspect {
public visit(node: IConstruct) {
console.log('Visited', node.node.path);
}
}
|
from aws_cdk.core import IAspect, IConstruct

@jsii.implements(IAspect)
class MyAspect():
def visit(self, node: IConstruct) -> None:
print("Visited", node.node.path)
|
import software.amazon.awscdk.core.IAspect;
import software.amazon.awscdk.core.IConstruct;

public class MyAspect implements IAspect {
@Override
public void visit(IConstruct node) {
System.out.println("Visited " + node.getNode().getPath());
}
}
| From 48ed01a016d851e0eeca8fe73dfc90844d703ff5 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 4 Feb 2020 20:55:52 +0000 Subject: [PATCH 096/655] Add new "working with" topics, "feature flags" topic; fix bugs and add FederatedPrincipal to permissions examples --- doc_source/environments.md | 6 +- doc_source/featureflags.md | 18 +++ doc_source/index.md | 7 ++ doc_source/permissions.md | 2 +- doc_source/work-with-cdk-csharp.md | 162 +++++++++++++++++++++++++ doc_source/work-with-cdk-java.md | 125 +++++++++++++++++++ doc_source/work-with-cdk-javascript.md | 149 +++++++++++++++++++++++ doc_source/work-with-cdk-python.md | 147 ++++++++++++++++++++++ doc_source/work-with-cdk-typescript.md | 95 +++++++++++++++ doc_source/work-with.md | 34 ++++++ 10 files changed, 741 insertions(+), 4 deletions(-) create mode 100644 doc_source/featureflags.md create mode 100644 doc_source/work-with-cdk-csharp.md create mode 100644 doc_source/work-with-cdk-java.md create mode 100644 doc_source/work-with-cdk-javascript.md create mode 100644 doc_source/work-with-cdk-python.md create mode 100644 doc_source/work-with-cdk-typescript.md create mode 100644 doc_source/work-with.md diff --git a/doc_source/environments.md b/doc_source/environments.md index 1a5fae70..b6fad768 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -265,7 +265,7 @@ With your stack's environment declared this way, you can now write a short scrip #### [ Linux/Mac OS X ] ``` -#!/bin/bash +#/bin/!bash # cdk-deploy-to.sh export CDK_DEPLOY_ACCOUNT=$1 shift @@ -317,7 +317,7 @@ When deploying to multiple environments, consider whether you want to continue d #### [ Linux/Mac OS X ] ``` -#!/bin/bash +#/bin/!bash # cdk-deploy-to-prod.sh bash cdk-deploy-to.sh 135792468 us-west-1 "$@" || exit bash cdk-deploy-to.sh 246813579 eu-west-1 "$@" @@ -335,4 +335,4 @@ cdk-deploy-to 245813579 eu-west-1 %* ------ -Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. +Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. \ No newline at end of file diff --git a/doc_source/featureflags.md b/doc_source/featureflags.md new file mode 100644 index 00000000..96618e53 --- /dev/null +++ b/doc_source/featureflags.md @@ -0,0 +1,18 @@ +# Feature Flags + +The AWS CDK uses *feature flags* to enable potentially breaking behaviors in a release\. Flags are stored as [Runtime Context](context.md) values in `cdk.json` \(or `~/.cdk.json`\) as shown here\. + +``` +{ + "app": "npx ts-node bin/tscdk.ts", + "context": { + "@aws-cdk/core:enableStackNameDuplicates": "true" + } +} +``` + +The names of all feature flags begin with the NPM name of the package affected by the particular flag\. In the example above, this is `@aws-cdk/core`, the AWS CDK framework itself, since the flag affects stack naming rules, a core AWS CDK function\. AWS Construct Library modules can also use feature flags\. + +Feature flags are disabled by default, so existing projects that do not specify the flag will continue to work with later AWS CDK releases\. New projects created using `cdk init` include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the old behavior, or to add flags to enable new behaviors after upgrading the AWS CDK\. + +See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. The AWS CDK source file [https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts) provides a complete list of all current feature flags \(look for values beginning with `@aws-cdk`\)\. \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index cb48e60b..1b5d2765 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -16,6 +16,12 @@ Amazon's trademarks and trade dress may not be used in ## Contents + [What Is the AWS CDK?](home.md) + [Getting Started With the AWS CDK](getting_started.md) ++ [Working with the AWS CDK](work-with.md) + + [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) + + [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) + + [Working with the AWS CDK in Python](work-with-cdk-python.md) + + [Working with the AWS CDK in C#](work-with-cdk-csharp.md) + + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Concepts](core_concepts.md) + [Constructs](constructs.md) + [Apps](apps.md) @@ -28,6 +34,7 @@ Amazon's trademarks and trade dress may not be used in + [Assets](assets.md) + [Permissions](permissions.md) + [Runtime Context](context.md) + + [Feature Flags](featureflags.md) + [Aspects](aspects.md) + [Escape Hatches](cfn_layer.md) + [API Reference](reference.md) diff --git a/doc_source/permissions.md b/doc_source/permissions.md index 5cb0e091..e7584589 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -333,4 +333,4 @@ The AWS CDK Construct Library supports many types of principals, including: 1. Arbitrary ARN principals \(`new iam.[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ArnPrincipal.html)(res.arn)`\) -1. An `iam.[CompositePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CompositePrincipal.html)(principal1, principal2, ...)` to trust multiple principals +1. An `iam.[CompositePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CompositePrincipal.html)(principal1, principal2, ...)` to trust multiple principals \ No newline at end of file diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md new file mode 100644 index 00000000..8621711f --- /dev/null +++ b/doc_source/work-with-cdk-csharp.md @@ -0,0 +1,162 @@ +# Working with the AWS CDK in C\# + +\.NET is a fully\-supported client platform for the AWS CDK and is considered stable\. Our \.NET code examples are in C\#\. It is possible to write AWS CDK applications in other \.NET languages, such as Visual Basic or F\#, but we are unable to provide support for these languages\. + +You can develop AWS CDK applications in C\# using familiar tools including Visual Studio, the `dotnet` command, and the NuGet package manager\. The modules comprising the AWS Construct Library are distributed via [nuget\.org](https://www.nuget.org/packages?q=amazon.cdk.aws)\. + +We suggest using [Visual Studio 2019](https://visualstudio.microsoft.com/downloads/) \(any edition\) and the Microsoft \.NET Framework on Windows to develop AWS CDK apps in C\#\. You may use other tools \(for example, Mono on Linux or Mac OS X\), but our ability to provide instruction and support for these environments may be limited\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +C\# AWS CDK applications require a \.NET Standard 2\.1 compatible implementation\. Suitable implementations include: ++ \.NET Core v3\.0 or later \(v3\.1 or later preferred\) ++ \.NET Framework v4\.6\.1 or later ++ Mono v5\.4 or later on Linux or Mac OS X; [download here](https://www.mono-project.com/download/stable/) + +If you have an up\-to\-date Windows 10 installation, you already have a suitable installation of \.NET Framework\. + +The \.NET Standard toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if you are using Visual Studio, this command is useful for batch operations and for installing AWS Construct Library packages\. + +## Creating a Project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language csharp +``` + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +The resulting project includes a reference to the `Amazon.CDK` NuGet package\. It and its dependencies are installed automatically by NuGet\. + +## Managing AWS Construct Library Modules + +The \.NET ecosystem uses the NuGet package manager\. AWS Construct Library modules are named like `Amazon.CDK.AWS.SERVICE-NAME`\. For example, the NuGet package name for the Amazon S3 module is `Amazon.CDK.AWS.S3`\. + +**Note** +All AWS Construct Library modules used in your project must be the same version\. + +NuGet has four standard, mostly\-equivalent interfaces; you can use the one that suits your needs and working style\. You can also use compatible tools, such as [Paket](https://fsprojects.github.io/Paket/) or [MyGet](https://fsprojects.github.io/Paket/)\. + +### The Visual Studio NuGet GUI + +Visual Studio's NuGet tools are accessible from **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution**\. Use the **Browse** tab to find the AWS Construct Library packages you want to install\. You can choose the desired version, including pre\-release versions \(mark the **Include prerelease** checkbox\) and add them to any of the open projects\. + +**Note** +All AWS Construct Library modules deemed "experimental" \(see [Versioning and Stability Model](reference.md#versioning)\) are flagged as pre\-release in NuGet\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/visual-studio-nuget.png) + +Look in the **Updates** panel to install new versions of your packages\. + +### The NuGet Console + +The NuGet console is a PowerShell\-based interface to NuGet that works in the context of a Visual Studio project\. You can open it in Visual Studio by choosing **Tools** > **NuGet Package Manager** > **Package Manager Console**\. For more information on using this tool, see [Install and Manage Packages with the Package Manager Console in Visual Studio](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-powershell)\. + +### The `dotnet` Command + +The `dotnet` command is the primary command\-line tool for working with Visual Studio C\# projects\. You can invoke it from any Windows command prompt\. Among its many capabilities, `dotnet` can add NuGet dependencies to a Visual Studio project\. + +Assuming you're in the same directory as the Visual Studio project \(`.csproj`\) file, issue a command like the following to install a package\. + +``` +dotnet add package Amazon.CDK.AWS.S3 +``` + +You may issue the command from another directory by including the path to the project file, or to the directory that contains it, after the `add` keyword\. The following example assumes that you are in your AWS CDK project's main directory\. + +``` +dotnet add src/PROJECT-DIR package Amazon.CDK.AWS.S3 +``` + +To install a specific version of a package, include the `-v` flag and the desired version\. AWS Construct Library modules that are deemed "experimental" \(see [Versioning and Stability Model](reference.md#versioning)\) are flagged as pre\-release in NuGet, and must be installed using an explicit version number\. + +``` +dotnet add package Amazon.CDK.AWS.S3 -v VERSION-NUMBER +``` + +To update a package, issue the same `dotnet add` command you used to install it\. If you do not specify a version number, the latest version is installed\. For experimental modules, again, you must specify an explicit version number\. + +For more information on managing packages using the `dotnet` command, see [Install and Manage Packages Using the dotnet CLI](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli)\. + +### The `nuget` Command + +The `nuget` command line tool can install and update NuGet packages\. However, it requires your Visual Studio project to be set up differently from the way `cdk init` sets up projects\. \(Technical details: `nuget` works with `Packages.config` projects, while `cdk init` creates a newer\-style `PackageReference` project\.\) + +We do not recommend the use of the `nuget` tool with AWS CDK projects created by `cdk init`\. If you are using another type of project, and want to use `nuget`, see the [NuGet CLI Reference](https://docs.microsoft.com/en-us/nuget/reference/nuget-exe-cli-reference)\. + +## AWS CDK Idioms in C\# + +### Props + +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. + +In C\#, props are expressed using a props type\. In idiomatic C\# fashion, we can use an object initializer to set the various properties\. Here we're creating an Amazon S3 bucket using the `Bucket` construct; its corresponding props type is `BucketProps`\. + +``` +var bucket = new Bucket(this, "MyBucket", new BucketProps { + Versioned = true +}); +``` + +**Tip** +Add the package `Amazon.JSII.Analyzers` to your project to get required\-values checking in your props definitions inside Visual Studio\. + +When extending a class or overriding a method, you may want to accept additional props for your own purposes that are not understood by the parent class\. To do this, subclass the appropriate props type and add the new attributes\. + +``` +// extend BucketProps for use with MimeBucket +class MimeBucketProps : BucketProps { + public string MimeType { get; set; } +} + +// hypothetical bucket that enforces MIME type of objects inside it +class MimeBucket : Bucket { + public MimeBucket(final Construct scope, final string id, final MimeBucketProps props=null) : base(scope, id, props) { + // ... + } +} + +// instantiate our MyBucket class +var bucket = new MyBucket(this, "MyBucket", new MimeBucketProps { + Versioned = true, + MimeType = "image/jpeg" +}); +``` + +When calling the parent class's initializer or overridden method, you can generally pass the props you received\. The new type is compatible with its parent, and extra props you added are ignored\. + +Keep in mind that future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues using your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion for your construct's users\. You can avoid this potential problem by naming your properties so they clearly belong to your construct \(e\.g\. `BobEncryption` rather than just `encryption`, assuming you're Bob\)\. If there are many new properties, bundle them into an appropriately\-named class \(`BobBucketPoperties`?\) and pass them as a single property\. + +### Missing Values + +In C\#, missing values in AWS CDK objects such as props are represented by `null`\. The null\-conditional member access operator `?.` and the null coalescing operator `??` are convenient for working with these values\. + +``` +// mimeType is null if props is null or if props.MimeType is null +string mimeType = props?.MimeType; + +// mimeType defaults to text/plain. either props or props.MimeType can be null +string MimeType = props?.MimeType ?? "text/plain"; +``` + +## Building, Synthesizing, and Deploying + +Before running, build \(compile\) the app by pressing F6 in Visual Studio or by issuing `dotnet build src` from the command line, where `src` is the directory in your project directory that contains the Visual Studio Solution \(`.sln`\) file\. + +The build step reports any syntax or type errors in your code\. Once you can build your application without errors, you're ready to synthesize or deploy\. + +The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md new file mode 100644 index 00000000..c046b665 --- /dev/null +++ b/doc_source/work-with-cdk-java.md @@ -0,0 +1,125 @@ +# Working with the AWS CDK in Java + +Java is a fully\-supported client platform for the AWS CDK and is considered stable\. You can develop AWS CDK applications in Java using familiar tools, including the JDK \(Oracle's, or an OpenJDK distribution such as Amazon Corretto\) and Apache Maven\. The modules comprising the AWS Construct Library are distributed via the [Maven Central Repository](https://search.maven.org/search?q=software.amazon.awscdk)\. + +You can use any text editor, or a Java IDE that can read Maven projects, to work on your AWS CDK apps\. We provide [Eclipse](https://www.eclipse.org/downloads/) hints in this Guide, but IntelliJ IDEA, NetBeans, and other IDEs can import Maven projects and will work fine for developing AWS CDK applications in Java\. + +It is possible to write AWS CDK applications in JVM\-hosted languages other than Java \(for example, Kotlin, Groovy, Clojure, or Scala\), but we are unable to provide support for these languages\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +Java AWS CDK applications require Java 8 \(v1\.8\) or later\. We recommend [Amazon Corretto](https://aws.amazon.com/corretto/), but you can use any OpenJDK distribution or [Oracle's JDK](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)\. You will also need [Apache Maven](https://maven.apache.org/download.cgi) 3\.5\.4 or later\. You can also use tools such as Gradle, but the application skeletons generated by the AWS CDK Toolkit are Maven projects\. + +## Creating a Project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language java +``` + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +The resulting project includes a reference to the `software.amazon.awscdk.core` Maven package\. It and its dependencies are automatically installed by Maven\. + +If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set ta use Java 8 \(1\.8\)\. + +## Managing AWS Construct Library Modules + +Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk` and named for their service\. For example, the Maven artifact ID for Amazon S3 is `s3`\. Its Java package name, for use in import statements, is `software.amazon.awscdk.services.s3`\. + +**Note** +All AWS Construct Library modules used in your project must be the same version\. + +### Using a Java IDE + +If you're using an IDE, its Maven integration is probably the simplest way to install AWS Construct Library packages\. For example, in Eclipse: + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/eclipse-maven.png) + +1. Open your project's `pom.xml` file in the Eclipse editor\. + +1. Switch to the editor's **Dependencies** page\. + +1. Click the **Add** button next to the **Dependencies** list\. + +1. Enter the AWS CDK Maven group ID, `software.amazon.awscdk`, in the search field\. + +1. In the search results, find the desired package \(e\.g\. `s3`\) and double\-click it\. \(You may also expand the package and choose a specific version, if you don't want the latest\.\) + +1. Repeat step 5 for each additional AWS Construct Library package you want to install\. + +You can periodically issue the following command to update your dependencies to the latest version\. Maven updates the version specification in `pom.xml` with the latest version of each specified package available in the Maven Central Repository\. + +``` +mvn versions:use-latest-versions +``` + +### Setting Dependencies Manually + +If you are not using an IDE, or just want full control over the versions of your dependencies, you can specify the modules that your application depends on by editing `pom.xml` and adding a new `` element in the `` container\. For example, the following `` element specifies the Amazon S3 construct library module: + +``` + + software.amazon.awscdk + s3 + [1.0,2.0) + +``` + +The version specifier `[1.0,2.0)` in this example indicates that the latest version between 1\.0 \(inclusive\) and 2\.0 \(exclusive\) will be installed\. Since the AWS CDK uses semantic versioning for stable AWS Construct Library modules, \(see [Versioning and Stability Model](reference.md#versioning)\), this ensures that only newer versions without breaking API changes will be installed\. + +Maven automatically downloads a version of your dependencies that will match the requirements in `pom.xml`, if necessary, the next time you build your project\. + +## AWS CDK Idioms in Java + +### Props + +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. + +In Java, props are expressed using the [Builder pattern](https://en.wikipedia.org/wiki/Builder_pattern)\. Each construct type has a corresponding props type; for example, the `Bucket` construct \(which represents an Amazon S3 bucket\) takes as its props an instance of `BucketProps`\. + +The `BucketProps` class \(like every AWS Construct Library props class\) has an inner class called `Builder`\. The `BucketProps.Builder` type offers methods to set the various properties of a `BucketProps` instance\. Each method returns the `Builder` instance, so the method calls can be chained to set multiple properties\. At the end of the chain, you call `build()` to actually produce the `BucketProps` object\. + +``` +Bucket bucket = new Bucket(this, "MyBucket", new BucketProps.Builder() + .versioned(true) + .encryption(BucketEncryption.KMS_MANAGED) + .build()); +``` + +Constructs, and other classes that take a props\-like object as their final argument, offer a shortcut\. The class has a `Builder` of its own that instantiates it and its props object in one step\. This way, you don't need to explicitly instantiate \(for example\) both `BucketProps` and a `Bucket`—and you don't need an import for the props type\. + +``` +Bucket bucket = Bucket.Builder.create(this, "MyBucket") + .versioned(true) + .encryption(BucketEncryption.KMS_MANAGED) + .build(); +``` + +When deriving your own construct from an existing construct, you may want to accept additional properties\. We recommend that you follow these builder patterns\. However, this isn't as simple as subclassing a construct class\. You must provide the moving parts of the two new `Builder` classes yourself\. Given this fact, you may prefer to simply have your construct accept additional arguments\. In this case, provide additional constructors when an argument is optional\. + +### Missing Values + +In Java, missing values in AWS CDK objects such as props are represented by `null`\. You must explicitly test any value that could be `null` to make sure it contains a value before doing anything with it\. Java does not have "syntactic sugar" to help handle null values as some other languages do\. You may find Apache ObjectUtil's [defaultIfNull](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#defaultIfNull-T-T-) and [firstNonNull](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#firstNonNull-T...-) useful in some situations\. Alternatively, write your own static helper methods to make it easier to handle potentially null values and make your code more readable\. + +## Building, Synthesizing, and Deploying + +Before running, build \(compile\) the app in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn build` at a command prompt while in your project's root directory\. + +The build step reports any syntax or type errors in your code\. Once you can build your application without errors, you're ready to synthesize or deploy\. + +The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md new file mode 100644 index 00000000..34c256e5 --- /dev/null +++ b/doc_source/work-with-cdk-javascript.md @@ -0,0 +1,149 @@ +# Working with the AWS CDK in JavaScript + +JavaScript is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in JavaScript uses familiar tools, including [Node\.js](https://nodejs.org/) and the Node Package Manager \(`npm`\)\. You may also use [Yarn](https://yarnpkg.com/) if you prefer, though the examples in this Guide use NPM\. The modules comprising the AWS Construct Library are distributed via the NPM repository, [npmjs\.org](https://www.npmjs.com/)\. + +You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://github.com/VSCodium/vscodium)\), which has good support for JavaScript\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +JavaScript AWS CDK applications require no additional prerequisites beyond these\. + +## Creating a Project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language javascript +``` + +Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html](https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html) module and its dependencies\. + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +## Managing AWS Construct Library Modules + +Use the Node Package Manager \(`npm`\), included with Node\.js, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. + +AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. + +``` +npm install @aws-cdk/aws-s3 @aws-cdk/aws-lambda +``` + +Your project's dependencies are maintained in `package.json`\. You can edit this file to lock some or all of your dependencies to a specific version or to allow them to be updated to newer versions under certain criteria\. To update your project's dependencies: + +``` +npm update +``` + +**Note** +All AWS Construct Library modules used in your project must be the same version\. + +## AWS CDK Idioms in JavaScript + +### Props + +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the AWS resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. + +Using an IDE or editor that has good JavaScript autocomplete will help avoid misspelling property names\. If a construct is expecting an `encryptionKeys` property, and you spell it `encryptionkeys`, when instantiating the construct, you haven't passed the value you intended\. This can cause an error at synthesis time if the property is required, or cause the property to be silently ignored if it is optional\. In the latter case, you may get a default behavior you intended to override\. Take special care here\. + +When subclassing an AWS Construct Library class \(or overriding a method that takes a props\-like argument\), you may want to accept additional properties for your own use\. These values will be ignored by the parent class or overridden method, because they are never accessed in that code, so you can generally pass on all the props you received\. + +However, we do occasionally add properties to constructs\. If a property we add in a later version happens to have the same name as one you're accepting, passing it up the chain can cause unexpected behavior\. It's safer to pass a shallow copy of the props you received with your property removed or set to undefined\. For example: + +``` +super(scope, name, {...props, encryptionKeys: undefined}); +``` + +Alternatively, name your properties so that it is clear that they belong to your construct\. This way, it is unlikely they will collide with properties in future AWS CDK releases\. If there are many of them, use a single appropriately\-named object to hold them\. + +### Missing Values + +Missing values in an object \(such as `props`\) have the value `undefined` in JavaScript\. The usual techniques apply for dealing with these\. For example, a common idiom for accessing a property of a value that may be undefined is as follows: + +``` +// a may be undefined, but if it is not, it may have an attribute b +// c is undefined if a is undefined, OR if a doesn't have an attribute b +let c = a && a.b; +``` + +However, if `a` could have some other "falsy" value besides `undefined`, it is better to make the test more explicit\. Here, we'll take advantage of the fact that `null` and `undefined` are equal to test for them both at once: + +``` +let c = a == null ? a : a.b; +``` + +A version of the ECMAScript standard currently in development specifies new operators that will simplify the handling of undefined values\. Using them can simplify your code, but you will need a new version of Node\.js to use them\. For more information, see the [optional chaining](https://github.com/tc39/proposal-optional-chaining/blob/master/README.md) and [nullish coalescing](https://github.com/tc39/proposal-nullish-coalescing/blob/master/README.md) proposals\. + +## Synthesizing and Deploying + +The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. + +## Using TypeScript Examples with JavaScript + +[TypeScript](https://www.typescriptlang.org/) is the language we use to develop the AWS CDK, and it was the first language supported for developing applications, so many available AWS CDK code examples are written in TypeScript\. These code examples can be a good resource for JavaScript developers; you just need to remove the TypeScript\-specific parts of the code\. The most commonly\-used features are type annotations and interface declarations\. + +Type annotations may be provided for variables, class members, function parameters, and function return types\. For variables, parameters, and members, types are specified by following the identifier with a colon and the type\. Function return values follow the function signature and consist of a colon and the type\. + +``` +var encrypted: boolean = true; + +class myStack extends core.Stack { + bucket: s3.Bucket; + // ... +} + +function makeEnv(account: string, region: string) : object { + // ... +} +``` + +To convert type\-annotated code to JavaScript, remove the colon and the type\. Class members must have some value in JavaScript; remove them entirely if they only have a type annotation in TypeScript\. + +``` +var encrypted = true; + +class myStack extends core.Stack { + // ... +} + +function makeEnv(account, region) { + // ... +} +``` + +In TypeScript, interfaces are used to give bundles of required and optional properties, and their types, a name\. You can then use the interface name as a type annotation\. TypeScript will make sure that the object you use as, for example, an argument to a function has the required properties of the right types\. + +``` +interface myFuncProps { + code: lambda.Code, + handler?: string +} +``` + +JavaScript does not have an interface feature, so once you've removed the type annotations, delete the interface declarations as well\. + +Knowing how to identify and remove type annotations and interface definitions goes a long way toward adapting short TypeScript snippets to JavaScript\. But it may be impractical to convert longer TypeScript examples in this fashion, since they are more likely to use TypeScript features you're not familiar with\. For these situations, we recommend [Babel](https://babeljs.io/) with the [TypeScript plug\-in](https://babeljs.io/docs/en/babel-plugin-transform-typescript)\. Babel won't complain if code uses an undefined variable, for example, as `tsc` would\. If it is syntactically valid, then with few exceptions, Babel can translate it to JavaScript\. This makes Babel particularly valuable for converting snippets that may not be runnable in on their own\. + +## Migrating to TypeScript + +As their projects get larger and more complex, many JavaScript developers move to [TypeScript](https://www.typescriptlang.org/)\. TypeScript is a superset of JavaScript—all JavaScript code is valid TypeScript code, so no changes to your code are required—and it is also a supported AWS CDK language\. Type annotations and other TypeScript features are optional and can be added to your AWS CDK app as you find value in them\. TypeScript also gives you early access to new JavaScript features, such as optional chaining and nullish coalescing, before they're finalized—and without requiring that you upgrade Node\.js\. + +TypeScript's "shape\-based" interfaces, which define bundles of required and optional properties \(and their types\) within an object, allow common mistakes to be caught while you're writing the code, and make it easier for your IDE to provide robust autocomplete and other real\-time coding advice\. + +Coding in TypeScript does involve an additional step: compiling your app with the TypeScript compiler, `tsc`\. This step can happen automatically whenever you save your source code, or before you run your app\. For typical AWS CDK apps, compilation requires a few seconds at most\. + +The easiest way to migrate an existing JavaScript AWS CDK app to TypeScript is to create a new TypeScript project using `cdk init app --language typescript`, then copy your source files \(and any other necessary files, such as assets like AWS Lambda function source code\) to the new project\. Rename your JavaScript files to end in `.ts` and begin developing in TypeScript\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md new file mode 100644 index 00000000..bb1497b0 --- /dev/null +++ b/doc_source/work-with-cdk-python.md @@ -0,0 +1,147 @@ +# Working with the AWS CDK in Python + +Python is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in Python uses familiar tools, including the standard Python implementation \(dubbed CPython\), `virtualenv`, and `pip`, the Python package installer\. The modules comprising the AWS Construct Library are distributed via [pypi\.org](https://pypi.org/search/?q=aws-cdk)\. The Python version of the AWS CDK even uses Python\-style identifiers \(for example, `snake_case` method names\)\. + +You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://github.com/VSCodium/vscodium)\), which has good support for Python via an [official extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python), though the simple IDLE editor included with Python will suffice to get started\. The Python modules for the AWS CDK do have type hints, so you may prefer a linting tool or an IDE that supports type validation\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +Python AWS CDK applications require Python 3\.6 or later\. If you don't already have it installed, [download a compatible version](https://www.python.org/downloads/) for your platform at [python\.org](https://www.python.org/)\. If you run Linux, your system may have come with a compatible version, or you may install it using your distro's package manager \(`yum`, `apt`, etc\.\)\. Mac users may be interested in [Homebrew](https://brew.sh/), a Linux\-style package manager for Mac OS X\. + +The Python package installer, `pip`, and virtual environment manager, `virtualenv`, are also required\. Windows installations of compatible Python versions include these tools\. On Linux, `pip` and `virtualenv` may be provided as separate packages in your package manager\. Alternatively, you may install them with the following commands: + +``` +python -m ensurepip --upgrade +python -m pip install --upgrade pip +python -m pip install --upgrade virtualenv +``` + +If you encounter a permission error, run the above commands using `sudo` \(to install the modules system\-wide\) or add the `--user` flag to each command so that the modules are installed in your user directory\. + +**Note** +It is common for Linux distros to use the executable name `python3` for Python 3\.x, and have `python` refer to a Python 2\.x installation, and similarly for `pip`/`pip3`\. You can adjust the command used to run your application by editing `cdk.json` in the project's main directory\. + +Make sure the `pip` executable \(on Windows, `pip.exe`\) is in a directory included on the system `PATH`\. You should be able to type `pip --version` and see its version, not an error message\. + +## Creating a Project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language python +``` + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +After initializing the project, activate the project's virtual environment\. This allows the project's dependencies to be installed locally in the project folder, instead of globally\. + +``` +source .env/bin/activate +``` + +Then install the app's standard dependencies: + +``` +pip install -r requirements.txt +``` + +**Important** +Activate the project's virtual environment whenever you start working on it\. If you don't, you won't have access to the modules installed there, and modules you install will go in Python's global module directory \(or will result in a permission error\)\. + +## Managing AWS Construct Library Modules + +Use the Python package installer, `pip`, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. `pip` also installs the dependencies for those modules automatically\. + +AWS Construct Library modules are named like `aws-cdk.SERVICE-NAME`\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. + +``` +pip install aws-cdk.aws-s3 aws-cdk.aws-lambda +``` + +After installing a module, update your project's `requirements.txt` file, which maintains your project's dependencies\. You may do this manually, by opening `requirements.txt` in your editor, or by issuing: + +``` +pip freeze > requirements.txt +``` + +`pip freeze` captures the current versions of all modules installed in your virtual environment\. You can edit `requirements.txt` to allow upgrades; simply replace the `==` preceding a version number with `~=` to allow upgrades to a higher compatible version, or remove the version requirement entirely to specify the latest available version of the module\. + +You may want to remove modules that are only installed because they are dependencies of other modules; these will be installed automatically anyway, and by not listing them explicitly you will ensure that you get a version compatible with the version of the module you actually want, and no unnecessary dependencies\. + +With `requirements.txt` edited appropriately to allow upgrades, issue this command to upgrade the installed modules: + +``` +pip install --upgrade -r requirements.txt +``` + +**Note** +All AWS Construct Library modules used in your project must be the same version\. + +## AWS CDK Idioms in Python + +### Props + +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. + +In Python, props are expressed as keyword arguments\. If an argument contains nested data structures, these are expressed using a class which takes its own keyword arguments at instantiation\. The same pattern applies to other method calls that take a single structured argument\. + +For example, in a Amazon S3 bucket's `add_lifecycle_rule` method, the `transitions` property is a list of `Transition` instances\. + +``` +bucket.add_lifecycle_rule( + transitions=[ + Transition( + storage_class=StorageClass.GLACIER, + transition_after=Duration.days(10) + ) + ] +) +``` + +When extending a class or overriding a method, you may want to accept additional arguments for your own purposes that are not understood by the parent class\. In this case you should accept the arguments you don't care about using the `**kwargs` idiom, and use keyword\-only arguments to accept the arguments you're interested in\. When calling the parent's constructor or the overridden method, pass only the arguments it is expecting \(often just `**kwargs`\)\. Passing arguments that the parent class or method doesn't expect results in an error\. + +Future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues for users of your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion\. You can avoid this potential problem by naming your properties so they clearly belong to your construct \(e\.g\. `bob_encryption` rather than just `encryption`, assuming you're Bob\)\. If there are many new properties, bundle them into an appropriately\-named class \(`BobBucketPoperties`?\) and pass it as a single keyword argument\. + +### Missing Values + +When working with `**kwargs`, use the dictionary's `get()` method to provide a default value if a property is not provided\. Avoid using `kwargs[...]`, as this raises `KeyError` for missing values\. + +``` +encrypted = kwargs.get("encrypted") # None if no property "encrypted" exists +encrypted = kwargs.get("encrypted", False) # specify default of False if property is missing +``` + +Some AWS CDK methods \(such as `tryGetContext()` to get a runtime context value\) return `None` to indicate a missing value, which you will need to check for and handle\. + +### Using Interfaces + +Python doesn't have an interface feature as some other languages do\. \(If you're not familiar with the concept, Wikipedia has [a good introduction](https://en.wikipedia.org/wiki/Interface_(computing)#In_object-oriented_languages)\.\) TypeScript, the language in which the AWS CDK is implemented does, however, and constructs and other AWS CDK objects often require an instance that adheres to a particular interface, rather than inheriting from a particular class\. So the AWS CDK provides its own interface feature as part of the [JSII](https://github.com/aws/jsii) layer\. + +To indicate that a class implements a particular interface, you can use the `@jsii.implements` decorator: + +``` +from aws_cdk.core import IAspect, IConstruct +import jsii + +@jsii.implements(IAspect) +class MyAspect(): + def visit(self, node: IConstruct) -> None: + print("Visited", node.node.path) +``` + +## Synthesizing and Deploying + +The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md new file mode 100644 index 00000000..dd777abf --- /dev/null +++ b/doc_source/work-with-cdk-typescript.md @@ -0,0 +1,95 @@ +# Working with the AWS CDK in TypeScript + +TypeScript is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in TypeScript uses familiar tools, including Microsoft's TypeScript compiler \(`tsc`\), [Node\.js](https://nodejs.org/) and the Node Package Manager \(`npm`\)\. You may also use [Yarn](https://yarnpkg.com/) if you prefer, though the examples in this Guide use NPM\. The modules comprising the AWS Construct Library are distributed via the NPM repository, [npmjs\.org](https://www.npmjs.com/)\. + +You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://github.com/VSCodium/vscodium)\), which has excellent support for TypeScript\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +You also need TypeScript itself\. If you don't already have it, you can install it using `npm`\. + +``` +npm install -g typescript +``` + +Keep TypeScript up to date with a regular `npm update -g typescript`\. + +## Creating a Project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language typescript +``` + +Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html](https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html) module and its dependencies\. + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +## Managing AWS Construct Library Modules + +Use the Node Package Manager \(`npm`\), included with Node\.js, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. + +AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. + +``` +npm install @aws-cdk/aws-s3 @aws-cdk/aws-lambda +``` + +Your project's dependencies are maintained in `package.json`\. You can edit this file to lock some or all of your dependencies to a specific version or to allow them to be updated to newer versions under certain criteria\. To update your project's dependencies: + +``` +npm update +``` + +**Note** +All AWS Construct Library modules used in your project must be the same version\. + +## AWS CDK Idioms in TypeScript + +### Props + +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the AWS resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. + +In TypeScript, the shape of `props` is defined using an interface that tells you the required and optional arguments and their types\. Such an interface is defined for each kind of `props` argument, usually specific to a single construct or method\. For example, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct \(in the `@aws-cdk/aws-s3 module`\) specifies a `props` argument conforming to the [BucketProps](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucketprops.html) interface\. + +If a property is itself an object, for example the [websiteRedirect](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucketprops.html#aws_s3_BucketProps_websiteRedirect) property of `BucketProps`, that object will have its own interface to which its shape must conform, in this case [RedirectTarget](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/redirecttarget.html)\. + +If you are subclassing an AWS Construct Library class \(or overriding a method that takes a props\-like argument\), you can inherit from the existing interface to create a new one that specifies any new props your code requires\. When calling the parent class or base method, generally you can pass the entire props argument you received, since any attributes provided in the object but not specified in the interface will be ignored\. + +However, we do occasionally add properties to constructs\. If a property we add in a later version happens to have the same name as one you're accepting, passing it up the chain can cause unexpected behavior\. It's safer to pass a shallow copy of the props you received with your property removed or set to `undefined`\. For example: + +``` +super(scope, name, {...props, encryptionKeys: undefined}); +``` + +Alternatively, name your properties so that it is clear that they belong to your construct\. This way, it is unlikely they will collide with properties in future AWS CDK releases\. If there are many of them, use a single appropriately\-named object to hold them\. + +### Missing Values + +Missing values in an object \(such as props\) have the value `undefined` in TypeScript\. Recent versions of the language include operators that simplify working with these values, making it easier to specify defaults and "short\-circuit" chaining when an undefined value is reached\. For more information on these features, see the [TypeScript 3\.7 Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html), specifically the first two features, Optional Chaining and Nullish Coalescing\. + +## Building, Synthesizing, and Deploying + +Generally, you should be in the project's root directory when building and running your application\. + +Node\.js cannot run TypeScript directly; instead, your application is converted to JavaScript using the TypeScript compiler, `tsc`\. The resulting JavaScript code is then executed\. + +To compile your TypeScript app, issue `npm run build`\. You may also issue `npm run watch` to enter watch mode, in which the TypeScript compiler automatically rebuilds your app whenever you save changes to a source file\. + +The build step reports any syntax or type errors in your code\. Once you can build your application without errors, you're ready to synthesize or deploy\. + +The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with.md b/doc_source/work-with.md new file mode 100644 index 00000000..c029f773 --- /dev/null +++ b/doc_source/work-with.md @@ -0,0 +1,34 @@ +# Working with the AWS CDK + +The AWS Cloud Development Kit \(AWS CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, and C\#\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. + +We develop the AWS CDK in TypeScript and use [JSII](https://github.com/aws/jsii) to provide a "native" experience in other supported languages\. For example, we distribute AWS Construct Library modules using your preferred language's standard repository, and you install them using the language's standard package manager\. Methods and properties are even named using your language's recommended naming patterns\. + +**AWS CDK Prerequisites** +To use the AWS CDK, you need an AWS account and a corresponding access key\. If you don't have an AWS account yet, see [Create and Activate an AWS Account](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)\. To find out how to obtain an access key ID and secret access key for your AWS account, see [Understanding and Getting Your Security Credentials](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html)\. To find out how to configure your workstation so the AWS CDK uses your credentials, see [Setting Credentials in Node\.js](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html)\. + +**Tip** +If you have the [AWS CLI](https://aws.amazon.com/cli/) installed, the simplest way to set up your workstation with your AWS credentials is to open a command prompt and type: + +``` +aws configure +``` + +All AWS CDK applications require Node\.js 10\.3 or later, even when your app is written in Python, Java, or C\#\. You may download a compatible version for your platform at [nodejs\.org](https://nodejs.org/)\. We recommend the [current LTS version](https://nodejs.org/en/about/releases/) \(at this writing, the latest 12\.x release\)\. + +After installing Node\.js, install the AWS CDK Toolkit \(the `cdk` command\): + +``` +npm install -g aws-cdk +``` + +Test the installation by issuing `cdk --version`\. + +The specific language you work in also has its own prerequisites, described in the corresponding topic listed here\. + +**Topics** ++ [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) ++ [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) ++ [Working with the AWS CDK in Python](work-with-cdk-python.md) ++ [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) ++ [Working with the AWS CDK in Java](work-with-cdk-java.md) \ No newline at end of file From 42d49a72da549dd0a68143b905169c8ff359cd7b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 5 Feb 2020 18:10:32 +0000 Subject: [PATCH 097/655] move principals examples to top of article and add short explanation of what principals are --- doc_source/permissions.md | 44 +++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/doc_source/permissions.md b/doc_source/permissions.md index e7584589..7220c7d1 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -2,6 +2,26 @@ The AWS Construct Library uses a few common, widely\-implemented idioms to manage access and permissions\. The IAM module provides you with the tools you need to use these idioms\. +## Principals + +An IAM principal is an entity that can be authenticated in order to access AWS resources, such as a user, a service, or an application\. The AWS Construct Library supports many types of principals, including: + +1. IAM resources such as `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)` + +1. Service principals \(`new iam.[ServicePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ServicePrincipal.html)('service.amazonaws.com')`\) + +1. Federated principals \(`new iam.[FederatedPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.FederatedPrincipal.html)('cognito-identity.amazonaws.com')`\) + +1. Account principals \(`new iam.[AccountPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.AccountPrincipal.html)('0123456789012'))` + +1. Canonical user principals \(`new iam.[CanonicalUserPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CanonicalUserPrincipal.html)('79a59d[...]7ef2be')`\) + +1. AWS organizations principals \(`new iam.[OrganizationPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.OrganizationPrincipal.html)('org-id')`\) + +1. Arbitrary ARN principals \(`new iam.[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ArnPrincipal.html)(res.arn)`\) + +1. An `iam.[CompositePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CompositePrincipal.html)(principal1, principal2, ...)` to trust multiple principals + ## Grants Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` \(Python: `grant_read`, `grant_write`\) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. @@ -14,7 +34,7 @@ Resources that use execution roles, such as `[lambda\.Function](https://docs.aws ## Roles -The IAM package contains a `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)` construct that represents IAM roles\. The following code creates a new role, trusting the Amazon EC2 Service Principal\. +The IAM package contains a `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)` construct that represents IAM roles\. The following code creates a new role, trusting the Amazon EC2 service\. ------ #### [ TypeScript ] @@ -313,24 +333,4 @@ bucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps })); ``` ------- - -## Principals - -The AWS CDK Construct Library supports many types of principals, including: - -1. IAM resources such as `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)` - -1. Service principals \(`new iam.[ServicePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ServicePrincipal.html)('service.amazonaws.com')`\) - -1. Federated principals \(`new iam.[FederatedPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.FederatedPrincipal.html)('cognito-identity.amazonaws.com')`\) - -1. Account principals \(`new iam.[AccountPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.AccountPrincipal.html)('0123456789012'))` - -1. Canonical user principals \(`new iam.[CanonicalUserPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CanonicalUserPrincipal.html)('79a59d[...]7ef2be')`\) - -1. AWS organizations principals \(`new iam.[OrganizationPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.OrganizationPrincipal.html)('org-id')`\) - -1. Arbitrary ARN principals \(`new iam.[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ArnPrincipal.html)(res.arn)`\) - -1. An `iam.[CompositePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CompositePrincipal.html)(principal1, principal2, ...)` to trust multiple principals \ No newline at end of file +------ \ No newline at end of file From 24540150a3368eb5389b2d83f246817627b44967 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 6 Feb 2020 22:57:01 +0000 Subject: [PATCH 098/655] fix bugs in code examples --- doc_source/codepipeline_example.md | 4 ++-- doc_source/constructs.md | 13 +++++++------ doc_source/permissions.md | 10 +++++----- doc_source/testing.md | 16 ++++++++-------- 4 files changed, 22 insertions(+), 21 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 7b17a644..8b1803ad 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -114,7 +114,7 @@ export class LambdaStack extends Stack { constructor(app: App, id: string, props?: StackProps) { super(app, id, props); - this.lambdaCode = lambda.Code.cfnParameters(); + this.lambdaCode = lambda.Code.fromCfnParameters(); const func = new lambda.Function(this, 'Lambda', { code: this.lambdaCode, @@ -150,7 +150,7 @@ class LambdaStack(core.Stack): def __init__(self, app: core.App, id: str, **kwargs): super().__init__(app, id, **kwargs) - self.lambda_code = lambda_.Code.cfn_parameters() + self.lambda_code = lambda_.Code.from_cfn_parameters() func = lambda_.Function(self, "Lambda", code=self.lambda_code, diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 075cdcdd..243bbf97 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -418,7 +418,8 @@ export class NotifyingBucket extends Construct { super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); const topic = new sns.Topic(this, 'topic'); - bucket.addObjectCreatedNotification(topic, { prefix: props.prefix }); + bucket.addObjectCreatedNotification(new s3notify.SnsDestination(topic), + { prefix: props.prefix }); } } ``` @@ -430,10 +431,10 @@ export class NotifyingBucket extends Construct { class NotifyingBucket(core.Construct): def __init__(self, scope: core.Construct, id: str, *, prefix=None, **kwargs): - super().__init__(scope, id, **kwargs) + super().__init__(scope, id) bucket = s3.Bucket(self, "bucket") topic = sns.Topic(self, "topic") - bucket.add_object_created_notification(topic, + bucket.add_object_created_notification(s3notify.SnsDestination(topic), s3.NotificationKeyFilter(prefix=prefix)) ``` @@ -456,7 +457,7 @@ public class NotifyingBucket extends Bucket { } public NotifyingBucket(final Construct scope, final String id, final BucketProps props, final String prefix) { - super(scope, id, props); + super(scope, id); Bucket bucket = new Bucket(this, "bucket"); Topic topic = new Topic(this, "topic"); @@ -473,12 +474,12 @@ public class NotifyingBucket extends Bucket { ``` public class NotifyingBucketProps : BucketProps { - public string Prefix = null; + public string Prefix { get; set; } } public class NotifyingBucket : Construct { - public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id, props) + public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id) { var bucket = new Bucket(this, "bucket"); var topic = new Topic(this, "topic"); diff --git a/doc_source/permissions.md b/doc_source/permissions.md index 7220c7d1..90124a32 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -134,8 +134,8 @@ role.addToPolicy(PolicyStatement.Builder.create() role.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.DENY, - Resources = [bucket.BucketArn, otherRole.RoleArn], - Actions = ["ec2:SomeAction", "s3:Anotheraction"], + Resources = new string[] { bucket.BucketArn, otherRole.RoleArn }, + Actions = new string[] { "ec2:SomeAction", "s3:AnotherAction" }, Conditions = new Dictionary { ["StringEquals"] = new Dictionary @@ -327,9 +327,9 @@ bucket.addToResourcePolicy(PolicyStatement.Builder.create() bucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, - Actions = ["s3:SomeAction"], - Resources = [bucket.BucketArn], - Principals = [role] + Actions = new string[] { "s3:SomeAction" }, + Resources = new string[] { bucket.BucketArn }, + Principals = new IPrincipal[] { role } })); ``` diff --git a/doc_source/testing.md b/doc_source/testing.md index 625ede22..4dfac07c 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -47,7 +47,7 @@ export class DeadLetterQueue extends sqs.Queue { ### Installing the Testing Framework -Since we're using the Jest framework, our next setup step is to install Jest\. We'll also need the AWS CDK assertion module\. +Since we're using the Jest framework, our next setup step is to install Jest\. We'll also need the AWS CDK assert module, which includes helpers for writing tests for CDK libraries, including `assert` and `expect`\. ``` npm install --save-dev jest @types/jest @aws-cdk/assert @@ -216,7 +216,7 @@ When we run the test again, it breaks\. The name we've given the test hints that To avoid needing to review every snapshot whenever you make a change, use the custom assertions in the `@aws-cdk/assert/jest` module to write fine\-grained tests that verify only part of the construct's behavior\. For example, the test we called "dlq creates an alarm" in our example really should assert only that an alarm is created with the appropriate metric\. -The [AWS::CloudWatch::Alarm](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html) resource specification reveals that we're interested in the properties Namespace, MetricName and Dimensions\. We'll use the `expect(stack).toHaveResource(...)` assertion, which is in the `@aws-cdk/assert/jest` module, to make sure these properties have the appropriate values\. +The [AWS::CloudWatch::Alarm](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html) resource specification reveals that we're interested in the properties Namespace, MetricName and Dimensions\. We'll use the `expect(stack).to(haveResource(...))` assertion, which is in the `@aws-cdk/assert/jest` module, to make sure these properties have the appropriate values\. Replace the code in `test/dead-letter-queue.test.ts` with the following\. @@ -231,7 +231,7 @@ test('dlq creates an alarm', () => { new dlq.DeadLetterQueue(stack, 'DLQ'); - expect(stack).toHaveResource('AWS::CloudWatch::Alarm', { + expect(stack).to(haveResource('AWS::CloudWatch::Alarm', { MetricName: "ApproximateNumberOfMessagesVisible", Namespace: "AWS/SQS", Dimensions: [ @@ -240,7 +240,7 @@ test('dlq creates an alarm', () => { Value: { "Fn::GetAtt": [ "DLQ581697C4", "QueueName" ] } } ], - }); + })); }); test('dlq has maximum retention period', () => { @@ -248,9 +248,9 @@ test('dlq has maximum retention period', () => { new dlq.DeadLetterQueue(stack, 'DLQ'); - expect(stack).toHaveResource('AWS::SQS::Queue', { + expect(stack).to(haveResource('AWS::SQS::Queue', { MessageRetentionPeriod: 1209600 - }); + })); }); ``` @@ -314,9 +314,9 @@ test('retention period can be configured', () => { retentionDays: 7 }); - expect(stack).toHaveResource('AWS::SQS::Queue', { + expect(stack).to(haveResource('AWS::SQS::Queue', { MessageRetentionPeriod: 604800 - }); + })); }); test('configurable retention period cannot exceed 14 days', () => { From 5a50204e2395ca22409d1a9488027be4d4a57282 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 10 Feb 2020 19:32:14 +0000 Subject: [PATCH 099/655] minor updates --- doc_source/codepipeline_example.md | 2 +- doc_source/ecs_example.md | 2 +- doc_source/featureflags.md | 2 +- doc_source/getting_started.md | 10 +--------- doc_source/permissions.md | 2 +- doc_source/serverless_example.md | 2 +- 6 files changed, 6 insertions(+), 14 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 8b1803ad..91a7e55c 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -27,7 +27,7 @@ npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/a mkdir pipeline cd pipeline cdk init --language python -source .env/bin/activate || "on Windows, use: .env\Scripts\activate.bat" +source .env/bin/activate pip install -r requirements.txt mkdir Lambda pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index ba27fb21..5c160428 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -47,7 +47,7 @@ cdk init --language typescript mkdir MyEcsConstruct cd MyEcsConstruct cdk init --language python -source .env/bin/activate || "on Windows, use: .env\Scripts\activate.bat" +source .env/bin/activate pip install -r requirements.txt ``` diff --git a/doc_source/featureflags.md b/doc_source/featureflags.md index 96618e53..3293dacf 100644 --- a/doc_source/featureflags.md +++ b/doc_source/featureflags.md @@ -15,4 +15,4 @@ The names of all feature flags begin with the NPM name of the package affected b Feature flags are disabled by default, so existing projects that do not specify the flag will continue to work with later AWS CDK releases\. New projects created using `cdk init` include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the old behavior, or to add flags to enable new behaviors after upgrading the AWS CDK\. -See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. The AWS CDK source file [https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts) provides a complete list of all current feature flags \(look for values beginning with `@aws-cdk`\)\. \ No newline at end of file +See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. The AWS CDK source file [https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts) provides a complete list of all current feature flags\. \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 21a6eeb3..25905c67 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -370,20 +370,12 @@ cdk init --language typescript cdk init --language python ``` -Once the init command finishes, your prompt should show **\(\.env\)**, indicating you are running under virtualenv\. If not, you must perform one or two more tasks, depending upon your operating system\. - -On Linux/MacOS: +Once the init command finishes, your prompt should show **\(\.env\)**, indicating you are running under virtualenv\. If not, activate the virtual environment by issuing the command below\. ``` source .env/bin/activate ``` -On Windows: - -``` -.env\Scripts\activate.bat -``` - Once you've got your virtualenv running, run the following command to install the required dependencies\. ``` diff --git a/doc_source/permissions.md b/doc_source/permissions.md index 90124a32..0f253822 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -28,7 +28,7 @@ Every construct that represents a resource that can be accessed, such as an Amaz The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)`\. -Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other enttites that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. +Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other entities that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly \(`bucket.grantRead(lambda)`, or `grant_read` in Python\) instead of granting access to their role\. diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index d1624492..7316ffd0 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -42,7 +42,7 @@ cdk init --language typescript mkdir MyWidgetService cd MyWidgetService cdk init --language python -source .env/bin/activate || "on Windows, use: .env\Scripts\activate.bat" +source .env/bin/activate pip install -r requirements.txt ``` From 065f54167666ca2d50e01f7bfab7ac14285d6167 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 18 Feb 2020 00:25:30 +0000 Subject: [PATCH 100/655] history update and code tweak --- doc_source/doc-history.md | 3 ++- doc_source/stacks.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 93ae654e..0cd54279 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -16,4 +16,5 @@ The table below represents significant milestones\. We fix errors and improve co | [Version 1\.16\.0](#doc-history) | Add Python code snippets throughout\. Add Troubleshooting and Testing topics\. | November 14, 2019 | | [Version 1\.8\.0](#doc-history) | Updates to reflect improvements to ECS Patterns module\. | September 17, 2019 | | [Version 1\.3\.0](#doc-history) | Update tagging topic to use new API\. | August 13, 2019 | -| [Version 1\.0\.0](#doc-history) | The AWS CDK Developer Guide is released\. | July 11, 2019 | \ No newline at end of file +| [Version 1\.0\.0](#doc-history) | The AWS CDK Developer Guide is released\. | July 11, 2019 | +| [Version 1\.21\.0](#doc-history) | Add "Working with the CDK" articles for the five supported languages\. Various other improvements and fixes\. | February 4, 2019 | \ No newline at end of file diff --git a/doc_source/stacks.md b/doc_source/stacks.md index 81d9fd2d..e2e40604 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -137,7 +137,7 @@ class MyService(Construct): Monitoring(self, "mon") app = App(); -MyService(app, "beta"); +MyService(app, "beta") MyService(app, "prod", prod=True) app.synth() From f949930ffa9bcb607add9d3bb373de60baa2e72a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 19 Feb 2020 21:08:40 +0000 Subject: [PATCH 101/655] add missing line to Java code snippet --- doc_source/cfn_layer.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 57c5c5c6..15312e25 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -171,7 +171,7 @@ cfnBucket.analyticsConfiguration = [ #### [ Python ] ``` -# Get the AWS CloudFormation resources +# Get the AWS CloudFormation resource cfn_bucket = bucket.node.default_child # Change its properties @@ -187,6 +187,9 @@ cfn_bucket.analytics_configuration = [ #### [ Java ] ``` +// Get the AWS CloudFormation resource +CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); + cfnBucket.setAnalyticsConfigurations( Arrays.asList(new HashMap() {{ put("Id", "Config"); @@ -198,6 +201,7 @@ cfnBucket.setAnalyticsConfigurations( #### [ C\# ] ``` +// Get the AWS CloudFormation resource var cfnBucket = (CfnBucket)bucket.Node.DefaultChild; cfnBucket.AnalyticsConfigurations = new List { From d7d1f1f0e2db8510c063ead50b1c7fab132def81 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 21 Feb 2020 18:06:06 +0000 Subject: [PATCH 102/655] add Java code example --- doc_source/cfn_layer.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 15312e25..0779f72e 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -296,6 +296,23 @@ cfn_bucket.add_property_override("VersioningConfiguration.Status", "NewStatus") cfn_bucket.add_property_deletion_override("VersioningConfiguration.Status") ``` +------ +#### [ Java ] + +``` +// Get the AWS CloudFormation resource +CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); + +// Use dot notation to address inside the resource template fragment +cfnBucket.addOverride("Properties.VersioningConfiguration.Status", "NewStatus"); +cfnBucket.addDeletionOverride("Properties.VersioningConfiguration.Status"); + +// addPropertyOverride is a convenience function, which implies the +// path starts with "Properties." +cfnBucket.addPropertyOverride("VersioningConfiguration.Status", "NewStatus"); +cfnBucket.addPropertyDeletionOverride("VersioningConfiguration.Status"); +``` + ------ #### [ C\# ] @@ -307,7 +324,7 @@ var cfnBucket = (CfnBucket)bucket.node.defaultChild; cfnBucket.AddOverride("Properties.VersioningConfiguration.Status", "NewStatus"); cfnBucket.AddDeletionOverride("Properties.VersioningConfiguration.Status"); -// addPropertyOverride is a convenience function, which implies the +// AddPropertyOverride is a convenience function, which implies the // path starts with "Properties." cfnBucket.AddPropertyOverride("VersioningConfiguration.Status", "NewStatus"); cfnBucket.AddPropertyDeletionOverride("VersioningConfiguration.Status"); From f038a7a1deff4c3c2379c039d324a7adabf7a37d Mon Sep 17 00:00:00 2001 From: Livio Bieri Date: Tue, 25 Feb 2020 16:28:46 +0100 Subject: [PATCH 103/655] fix shebang --- doc_source/environments.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index b6fad768..1a5fae70 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -265,7 +265,7 @@ With your stack's environment declared this way, you can now write a short scrip #### [ Linux/Mac OS X ] ``` -#/bin/!bash +#!/bin/bash # cdk-deploy-to.sh export CDK_DEPLOY_ACCOUNT=$1 shift @@ -317,7 +317,7 @@ When deploying to multiple environments, consider whether you want to continue d #### [ Linux/Mac OS X ] ``` -#/bin/!bash +#!/bin/bash # cdk-deploy-to-prod.sh bash cdk-deploy-to.sh 135792468 us-west-1 "$@" || exit bash cdk-deploy-to.sh 246813579 eu-west-1 "$@" @@ -335,4 +335,4 @@ cdk-deploy-to 245813579 eu-west-1 %* ------ -Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. \ No newline at end of file +Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. From b4e1d03c5cd8174ade8accdde7115921958f7dc3 Mon Sep 17 00:00:00 2001 From: kakizaki Date: Wed, 4 Mar 2020 16:18:25 +0900 Subject: [PATCH 104/655] Update stacks.md fixed code example typo --- doc_source/stacks.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/stacks.md b/doc_source/stacks.md index e2e40604..233796a0 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -183,7 +183,7 @@ public class MyApp { super(scope, id); // we might use the prod argument to change how the service is configured - new ControlPlane(this, "data"); + new ControlPlane(this, "cp"); new DataPlane(this, "data"); new Monitoring(this, "mon"); } @@ -225,7 +225,7 @@ public class MyService : Construct public MyService(Construct scope, string id, Boolean prod=false) : base(scope, id) { // we might use the prod argument to change how the service is configured - new ControlPlane(this, "data"); + new ControlPlane(this, "cp"); new DataPlane(this, "data"); new Monitoring(this, "mon"); } From adb507696ede05d975dd88cb6afdd279ca5f5327 Mon Sep 17 00:00:00 2001 From: Jake Itegboje Date: Fri, 6 Mar 2020 16:26:17 -0600 Subject: [PATCH 105/655] Update resources.md --- doc_source/resources.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index f19b9e76..8f7330b1 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -633,7 +633,7 @@ table.Grant(func, "dynamodb:CreateBackup"); Many resources, such as Lambda functions, require a role to be assumed when executing code\. A configuration property enables you to specify an `iam.IRole`\. If no role is specified, the function automatically creates a role specifically for this use\. You can then use grant methods on the resources to add statements to the role\. -The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-iam-readme.html) objects\. Add statements directly to roles \(or a construct's attached role\) using the `addToRolePolicy` method \(Python: `add_to_role_policy`\), or to a resource's policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` \(Python: `add_to_role_policy`\) method\. +The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-iam-readme.html) objects\. Add statements directly to roles \(or a construct's attached role\) using the `addToRolePolicy` method \(Python: `add_to_role_policy`\), or to a resource's policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` \(Python: `add_to_resource_policy`\) method\. ## Metrics and Alarms @@ -914,4 +914,4 @@ var bucket = new s3.Bucket(this, "Bucket"); bucket.AddObjectCreatedNotification(new s3_not.LambdaDestination(handler)); ``` ------- \ No newline at end of file +------ From 8545a34c1541f787f99cd2d6513fa258c8010079 Mon Sep 17 00:00:00 2001 From: Jake Itegboje Date: Fri, 6 Mar 2020 16:37:00 -0600 Subject: [PATCH 106/655] Update resources.md --- doc_source/resources.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index f19b9e76..46ce9c06 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -678,7 +678,7 @@ metric = queue.metric_approximate_number_of_messages_not_visible( # ... ) metric.create_alarm(self, "TooManyMessagesAlarm", - comparison_operator(cw.ComparisonOperator.GREATER_THAN_THRESHOLD + comparison_operator=cw.ComparisonOperator.GREATER_THAN_THRESHOLD, threshold=100, # ... ) @@ -914,4 +914,4 @@ var bucket = new s3.Bucket(this, "Bucket"); bucket.AddObjectCreatedNotification(new s3_not.LambdaDestination(handler)); ``` ------- \ No newline at end of file +------ From 4d33a34459b2bf62dceea612eafe0e318d5cc55d Mon Sep 17 00:00:00 2001 From: Jake Itegboje Date: Fri, 6 Mar 2020 16:46:25 -0600 Subject: [PATCH 107/655] Update resources.md --- doc_source/resources.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index 46ce9c06..72456256 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -753,13 +753,13 @@ You enable data to flow on a given network path by using `allow` methods\. The f import asg = require('@aws-cdk/aws-autoscaling'); import ec2 = require('@aws-cdk/aws-ec2'); -const fleet: asg.AutoScalingGroup = /* ... */ +const fleet1: asg.AutoScalingGroup = /* ... */ // Allow surfing the (secure) web -fleet.connections.allowTo(new ec2.Peer.anyIpv4(), new ec2.Port({ fromPort: 443, toPort: 443 })); +fleet1.connections.allowTo(new ec2.Peer.anyIpv4(), new ec2.Port({ fromPort: 443, toPort: 443 })); const fleet2: asg.AutoScalingGroup = /* ... */; -fleet.connections.allowFrom(fleet, ec2.Port.AllTraffic()); +fleet2.connections.allowFrom(fleet1, ec2.Port.AllTraffic()); ``` ------ @@ -769,14 +769,14 @@ fleet.connections.allowFrom(fleet, ec2.Port.AllTraffic()); import aws_cdk.aws_autoscaling as asg import aws_cdk.aws_ec2 as ec2 -fleet = asg.AutoScalingGroup( ... ) +fleet1 = asg.AutoScalingGroup( ... ) # Allow surfing the (secure) web -fleet.connections.allow_to(ec2.Peer.any_ipv4(), +fleet1.connections.allow_to(ec2.Peer.any_ipv4(), ec2.Port(PortProps(from_port=443, to_port=443))) fleet2 = asg.AutoScalingGroup( ... ) -fleet.connections.allow_from(fleet, ec2.Port.all_traffic()) +fleet2.connections.allow_from(fleet1, ec2.Port.all_traffic()) ``` ------ @@ -787,16 +787,16 @@ import software.amazon.awscdk.services.autoscaling.AutoScalingGroup; import software.amazon.awscdk.services.ec2.Peer; import software.amazon.awscdk.services.ec2.Port; -AutoScalingGroup fleet = AutoScalingGroup.Builder.create(this, "MyFleet") +AutoScalingGroup fleet1 = AutoScalingGroup.Builder.create(this, "MyFleet") /* ... */.build(); // Allow surfing the (secure) Web -fleet.getConnections().allowTo(Peer.anyIpv4(), +fleet1.getConnections().allowTo(Peer.anyIpv4(), Port.Builder.create().fromPort(443).toPort(443).build()); AutoScalingGroup fleet2 = AutoScalingGroup.Builder.create(this, "MyFleet2") /* ... */.build(); -fleet2.getConnections().allowFrom(fleet, Port.allTraffic()); +fleet2.getConnections().allowFrom(fleet1, Port.allTraffic()); ``` ------ From ba5ded33b1f6d23203dbf30b6af05312fff69ee3 Mon Sep 17 00:00:00 2001 From: Jake Itegboje Date: Fri, 6 Mar 2020 16:49:48 -0600 Subject: [PATCH 108/655] updated network traffic example --- doc_source/resources.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index 72456256..dfd60e55 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -759,7 +759,7 @@ const fleet1: asg.AutoScalingGroup = /* ... */ fleet1.connections.allowTo(new ec2.Peer.anyIpv4(), new ec2.Port({ fromPort: 443, toPort: 443 })); const fleet2: asg.AutoScalingGroup = /* ... */; -fleet2.connections.allowFrom(fleet1, ec2.Port.AllTraffic()); +fleet1.connections.allowFrom(fleet2, ec2.Port.AllTraffic()); ``` ------ @@ -776,7 +776,7 @@ fleet1.connections.allow_to(ec2.Peer.any_ipv4(), ec2.Port(PortProps(from_port=443, to_port=443))) fleet2 = asg.AutoScalingGroup( ... ) -fleet2.connections.allow_from(fleet1, ec2.Port.all_traffic()) +fleet1.connections.allow_from(fleet2, ec2.Port.all_traffic()) ``` ------ @@ -796,7 +796,7 @@ fleet1.getConnections().allowTo(Peer.anyIpv4(), AutoScalingGroup fleet2 = AutoScalingGroup.Builder.create(this, "MyFleet2") /* ... */.build(); -fleet2.getConnections().allowFrom(fleet1, Port.allTraffic()); +fleet1.getConnections().allowFrom(fleet2, Port.allTraffic()); ``` ------ @@ -813,7 +813,7 @@ fleet.Connections.AllowTo(ec2.Peer.AnyIpv4(), new ec2.Port(new ec2.PortProps { FromPort = 443, ToPort = 443 }); var fleet2 = new asg.AutoScalingGroup(this, "MyFleet2", new asg.AutoScalingGroupProps { ... }); -fleet2.Connections.AllowFrom(fleet, ec2.Port.AllTraffic()); +fleet1.Connections.AllowFrom(fleet2, ec2.Port.AllTraffic()); ``` ------ From 927774fe229f552b25ac45f91136ef0e0d6cdc99 Mon Sep 17 00:00:00 2001 From: Jake Itegboje Date: Sat, 7 Mar 2020 05:44:14 -0600 Subject: [PATCH 109/655] Update identifiers.md --- doc_source/identifiers.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index 792f388a..0766fd7f 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -44,7 +44,7 @@ class MyStack(Stack): def __init__(self, scope: Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) - s3.Bucket(self, "MyBucket"); + s3.Bucket(self, "MyBucket") app = App() MyStack(app, 'Stack1') @@ -200,4 +200,4 @@ Think of construct IDs as part of your construct's public contract\. If you chan ### Logical ID Stability -Avoid changing the logical ID of a resource between deployments\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID\. \ No newline at end of file +Avoid changing the logical ID of a resource between deployments\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID\. From 361ce14ce3846c07bef0de4f83cce2a3dbc3f452 Mon Sep 17 00:00:00 2001 From: Jake Itegboje Date: Sat, 7 Mar 2020 05:54:27 -0600 Subject: [PATCH 110/655] Update identifiers.md --- doc_source/identifiers.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index 792f388a..ad42df33 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -44,7 +44,7 @@ class MyStack(Stack): def __init__(self, scope: Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) - s3.Bucket(self, "MyBucket"); + s3.Bucket(self, "MyBucket") app = App() MyStack(app, 'Stack1') @@ -156,7 +156,7 @@ string path = myConstruct.Node.Path; ## Unique IDs -Since AWS CloudFormation requires that all logical IDs in a template are unique, the AWS CDK must be able to generate unique identifier for each construct in an application\. Since the AWS CDK already has paths that are globally unique, the AWS CDK generates these unique identifiers by concatenating the elements of the path, and adds an 8\-digit hash\. The hash is necessary, as otherwise two distinct paths, such as `A/B/C` and `A/BC` would result in the same identifier\. The AWS CDK calls this concatenated path elements and hash the *unique ID* of the construct\. +Since AWS CloudFormation requires that all logical IDs in a template are unique, the AWS CDK must be able to generate a unique identifier for each construct in an application\. Since the AWS CDK already has paths that are globally unique, the AWS CDK generates these unique identifiers by concatenating the elements of the path, and adds an 8\-digit hash\. The hash is necessary, as otherwise two distinct paths, such as `A/B/C` and `A/BC` would result in the same identifier\. The AWS CDK calls this concatenated path elements and hash the *unique ID* of the construct\. You can access the unique ID of any construct programmatically, as shown in the following example, which gets the unique ID of `myConstruct` \(or `my_costruct` in Python conventions\)\. Since ids must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. @@ -200,4 +200,4 @@ Think of construct IDs as part of your construct's public contract\. If you chan ### Logical ID Stability -Avoid changing the logical ID of a resource between deployments\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID\. \ No newline at end of file +Avoid changing the logical ID of a resource between deployments\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID\. From 14b49e6bc9b96383f4d4c27639d4ad3d204d13c3 Mon Sep 17 00:00:00 2001 From: Julius Suominen Date: Mon, 9 Mar 2020 13:57:24 +0200 Subject: [PATCH 111/655] Fix typo in environments.md Change anvironments --> environments. --- doc_source/environments.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index b6fad768..8f5f1e51 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -311,7 +311,7 @@ cdk-deploy-to 135792469 us-east-1 %* ------ -When deploying to multiple environments, consider whether you want to continue deploying to other anvironments after a deployment fails\. The following example avoids deploying to the second production environment if the first doesn't succeed\. +When deploying to multiple environments, consider whether you want to continue deploying to other environments after a deployment fails\. The following example avoids deploying to the second production environment if the first doesn't succeed\. ------ #### [ Linux/Mac OS X ] @@ -335,4 +335,4 @@ cdk-deploy-to 245813579 eu-west-1 %* ------ -Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. \ No newline at end of file +Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. From 4c00bc46bfb79a4944c8e3afefe6bd5a548dcd69 Mon Sep 17 00:00:00 2001 From: Jake Itegboje Date: Mon, 9 Mar 2020 15:39:27 -0500 Subject: [PATCH 112/655] corrected typo --- doc_source/home.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/home.md b/doc_source/home.md index e380c74f..effed57c 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -154,7 +154,7 @@ This class produces an AWS CloudFormation [template of more than 500 lines](http + [AWS::EC2::SecurityGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html) + [AWS::EC2::Subnet](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html) + [AWS::EC2::SubnetRouteTableAssociation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html) -+ [AWS::EC2::VCPGatewayAttachment](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html) ++ [AWS::EC2::VPCGatewayAttachment](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html) + [AWS::EC2::VPC](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html) + [AWS::ECS::Cluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-cluster.html) + [AWS::ECS::Service](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html) @@ -220,4 +220,4 @@ Amazon Web Services \(AWS\) is a collection of digital infrastructure services t AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. -To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file +To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. From 663e844c47b0c2573304025c941a889baee3aa4a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 10 Mar 2020 23:12:34 +0000 Subject: [PATCH 113/655] fix typos --- doc_source/environments.md | 2 +- doc_source/home.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index 8f5f1e51..dd12ad46 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -335,4 +335,4 @@ cdk-deploy-to 245813579 eu-west-1 %* ------ -Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. +Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. \ No newline at end of file diff --git a/doc_source/home.md b/doc_source/home.md index effed57c..e743ee81 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -220,4 +220,4 @@ Amazon Web Services \(AWS\) is a collection of digital infrastructure services t AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. -To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. +To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file From ea6d73ccb6b023d4141e4960181e4f55121ef574 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 10 Mar 2020 23:22:25 +0000 Subject: [PATCH 114/655] fix typo --- doc_source/cfn_layer.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 0779f72e..5812785f 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -145,7 +145,7 @@ For more information, see [AWS Resource and Property Types Reference](https://do ## Modifying the AWS CloudFormation Resource behind AWS Constructs -If an Construct is missing a feature or you are trying to work around an issue, you can modify the CFN Resource that is encapsulated by the Construct\. +If a Construct is missing a feature or you are trying to work around an issue, you can modify the CFN Resource that is encapsulated by the Construct\. All Constructs contain within them the corresponding CFN Resource\. For example, the high\-level `Bucket` construct wraps the low\-level `CfnBucket` construct\. Because the `CfnBucket` corresponds directly to the AWS CloudFormation resource, it exposes all features that are available through AWS CloudFormation\. From 11db23bb5d5b42193973b28b53f34ac6c4e7b6f2 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 10 Mar 2020 23:30:51 +0000 Subject: [PATCH 115/655] fix Java CodePipeline example --- doc_source/codepipeline_example.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 91a7e55c..9bfbffef 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -563,7 +563,7 @@ public class PipelineStack extends Stack { public PipelineStack(final App scope, final String id, final StackProps props, final CfnParametersCode lambdaCode) { super(scope, id, props); - Repository code = (Repository)Repository.fromRepositoryName(this, "ImportedRepo", + IRepository code = Repository.fromRepositoryName(this, "ImportedRepo", "NameOfYourCodeCommitRepository"); PipelineProject cdkBuild = PipelineProject.Builder.create(this, "CDKBuild") From ff78330c05e0ca5a324f355923aded91ddeefbe1 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 12 Mar 2020 05:55:39 +0000 Subject: [PATCH 116/655] add Java, C# to troubleshooting --- doc_source/troubleshooting.md | 74 ++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index e3eaad00..c1542136 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -17,7 +17,7 @@ The modules that make up the AWS Construct Library are a matched set\. They are We also update the libraries that are used by the AWS Construct Library from time to time, and different versions of the library modules may have incompatible dependencies\. Synchronizing the versions of the library modules will also address this issue\. -Below, you'll find details on managing the versions of your installed AWS Construct Library modules TypeScript, JavaScript, and Python +Below, you'll find details on managing the versions of your installed AWS Construct Library modules in TypeScript, JavaScript, Python, Java, and C\#\. ------ #### [ TypeScript/JavaScript ] @@ -81,6 +81,42 @@ If your project requires a specific older version of the AWS Construct Library, pip install -r requirements.txt ``` +------ +#### [ Java ] + +Add your project's AWS Construct Library modules as dependencies in your project's `pom.xml`\. You may specify an exact version, or use Maven's [range syntax](https://docs.oracle.com/middleware/1212/core/MAVEN/maven_version.htm#MAVEN402) to specify a range of allowable versions\. + +For example, to specify an exact version of a dependency: + +``` + + software.amazon.awscdk + s3 + 1.23.0 + +``` + +To specify that any 1\.x\.x version is acceptable \(note use of right parenthesis to indicate that the end of the range excludes version 2\.0\.0\): + +``` + + software.amazon.awscdk + s3 + [1.0.0,2.0.0) + +``` + +Maven automatically downloads and installs the latest versions that allow all requirements to be fulfilled when you build your application\. + +If you prefer to pin dependencies to a specific version, you can issue `mvn versions:use-latest-versions` to rewrite the version specifications in `pom.xml` to the latest available versions when you decide to upgrade\. + +------ +#### [ C\# ] + +Use the Visual Studio NuGet GUI \(**Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution**\) to install the desired version of your application's AWS Construct Library modules\. ++ The **Installed** panel shows you what modules are currently installed; you can install any available version of any module from this page\. ++ The **Updates** panel shows you modules for which updates are available, and lets you update some or all of them\. + ------ \([back to list](#troubleshooting_top)\) @@ -250,6 +286,42 @@ class CdkTestStack(cdk.stack): removal_policy=cdk.RemovalPolicy.DESTROY) ``` +------ +#### [ Java ] + +``` +software.amazon.awscdk.core.*; +import software.amazon.awscdk.services.s3.*; + +public class CdkTestStack extends Stack { + public CdkTestStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public CdkTestStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + Bucket.Builder.create(this, "Bucket") + .removalPolicy(RemovalPolicy.DESTROY).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +public CdkTestStack(Construct scope, string id, IStackProps props) : base(scope, id, props) +{ + new Bucket(this, "Bucket", new BucketProps { + RemovalPolicy = RemovalPolicy.DESTROY + }); +} +``` + ------ **Note** From ca156157de0efbc9b729e2d07d33e5c13d3dbf72 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 13 Mar 2020 00:37:40 +0000 Subject: [PATCH 117/655] fix typos, code formatting --- doc_source/constructs.md | 18 +++++++++--------- doc_source/environments.md | 4 ++-- doc_source/identifiers.md | 2 +- doc_source/resources.md | 10 +++++----- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 243bbf97..3edb93d6 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -353,14 +353,14 @@ const createJobLambda = new lambda.Function(this, 'create-job', { ``` jobs_queue = sqs.Queue(self, "jobs") - create_job_lambda = lambda_.Function(self, "create-job", - runtime=lambda_.Runtime.NODEJS_10_X, - handler="index.handler", - code=lambda_.Code.from_asset("./create-job-lambda-code"), - environment=dict( - QUEUE_URL=jobs_queue.queue_url - ) - ) +create_job_lambda = lambda_.Function(self, "create-job", + runtime=lambda_.Runtime.NODEJS_10_X, + handler="index.handler", + code=lambda_.Code.from_asset("./create-job-lambda-code"), + environment=dict( + QUEUE_URL=jobs_queue.queue_url + ) +) ``` ------ @@ -661,7 +661,7 @@ images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); #### [ Python ] ``` -queue = qs.Queue(self, "NewImagesQueue") +queue = sqs.Queue(self, "NewImagesQueue") images = NotifyingBucket(self, prefix="Images") images.topic.add_subscription(sns_sub.SqsSubscription(queue)) ``` diff --git a/doc_source/environments.md b/doc_source/environments.md index 99ee6407..1e13e403 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -198,7 +198,7 @@ new MyDevStack(app, 'dev', { ``` MyDevStack(app, "dev", env=core.Environment( - account=os.environ.get("CDK_DEPLOY_ACCOUNT", os.environ["CDK_DEFAULT_ACCOUNT"]) + account=os.environ.get("CDK_DEPLOY_ACCOUNT", os.environ["CDK_DEFAULT_ACCOUNT"]), region=os.environ.get("CDK_DEPLOY_REGION", os.environ["CDK_DEFAULT_REGION"]) ``` @@ -335,4 +335,4 @@ cdk-deploy-to 245813579 eu-west-1 %* ------ -Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. +Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. \ No newline at end of file diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index ad42df33..54790e6f 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -200,4 +200,4 @@ Think of construct IDs as part of your construct's public contract\. If you chan ### Logical ID Stability -Avoid changing the logical ID of a resource between deployments\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID\. +Avoid changing the logical ID of a resource between deployments\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID\. \ No newline at end of file diff --git a/doc_source/resources.md b/doc_source/resources.md index b6b7252c..f8bd546e 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -300,7 +300,7 @@ var bucket = new Bucket(this, "MyBucket", new BucketProps ## Passing Unique Identifiers -Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. For example, when you are using the low\-level AWS CloudFormation resources, or need to expose resources to the runtime components of an AWS CDK application, such as when referring to Λ functions through environment variables\. +Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. For example, when you are using the low\-level AWS CloudFormation resources, or need to expose resources to the runtime components of an AWS CDK application, such as when referring to Lambda functions through environment variables\. These identifiers are available as attributes on the resources, such as the following\. @@ -808,11 +808,11 @@ using asg = Amazon.CDK.AWS.AutoScaling; using ec2 = Amazon.CDK.AWS.EC2; // Allow surfing the (secure) Web -var fleet = new asg.AutoScalingGroup(this, "MyFleet", new asg.AutoScalingGroupProps { ... }); -fleet.Connections.AllowTo(ec2.Peer.AnyIpv4(), new ec2.Port(new ec2.PortProps +var fleet1 = new asg.AutoScalingGroup(this, "MyFleet", new asg.AutoScalingGroupProps { /* ... */ }); +fleet1.Connections.AllowTo(ec2.Peer.AnyIpv4(), new ec2.Port(new ec2.PortProps { FromPort = 443, ToPort = 443 }); -var fleet2 = new asg.AutoScalingGroup(this, "MyFleet2", new asg.AutoScalingGroupProps { ... }); +var fleet2 = new asg.AutoScalingGroup(this, "MyFleet2", new asg.AutoScalingGroupProps { /* ... */ }); fleet1.Connections.AllowFrom(fleet2, ec2.Port.AllTraffic()); ``` @@ -914,4 +914,4 @@ var bucket = new s3.Bucket(this, "Bucket"); bucket.AddObjectCreatedNotification(new s3_not.LambdaDestination(handler)); ``` ------- +------ \ No newline at end of file From 112f3fed5ef2587e4192f5e9745ffac9ee7dbdce Mon Sep 17 00:00:00 2001 From: Dzhuneyt <1754428+Dzhuneyt@users.noreply.github.com> Date: Sat, 14 Mar 2020 11:55:29 +0200 Subject: [PATCH 118/655] Update codepipeline_example.md The UBUNTU build images are deprecated in favor of the STANDARD_X_X images. --- doc_source/codepipeline_example.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 9bfbffef..97dd2f61 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -338,7 +338,7 @@ export class PipelineStack extends Stack { }, }), environment: { - buildImage: codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1, + buildImage: LinuxBuildImage.STANDARD_2_0, }, }); const lambdaBuild = new codebuild.PipelineProject(this, 'LambdaBuild', { @@ -364,7 +364,7 @@ export class PipelineStack extends Stack { }, }), environment: { - buildImage: codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1, + buildImage: LinuxBuildImage.STANDARD_2_0, }, }); @@ -974,4 +974,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` \ No newline at end of file +``` From 1d5065994cefc5db17e814073e668ec672f3cdd1 Mon Sep 17 00:00:00 2001 From: "Miguel Zenon Nicanor L. Saavedra" Date: Fri, 20 Mar 2020 16:45:07 +0800 Subject: [PATCH 119/655] Fix typo for Python in multistack Fix typo in stack_how_to_create_multiple_stacks.md for python examples --- doc_source/stack_how_to_create_multiple_stacks.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index 923f0fc1..c1a58dac 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -271,7 +271,7 @@ class MultistackStack(core.Stack): # Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). if encrypt_bucket: s3.Bucket(self, "MyGroovyBucket", - encryption=s3BucketEncryption.KMS_MANAGED, + encryption=s3.BucketEncryption.KMS_MANAGED, removal_policy=core.RemovalPolicy.DESTROY) else: s3.Bucket(self, "MyGroovyBucket", @@ -577,4 +577,4 @@ To avoid charges for resources that you deployed, destroy the stack using the fo cdk destroy MyEastCdkStack ``` -The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket's contents, but not the bucket itself, using the AWS Management Console or the AWS CLI before destroying the stack\. \ No newline at end of file +The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket's contents, but not the bucket itself, using the AWS Management Console or the AWS CLI before destroying the stack\. From 94e9a5730926e00489d5cc6c9b5bed04d88e66f7 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sun, 22 Mar 2020 06:01:04 +0000 Subject: [PATCH 120/655] revamp "Multiple Languages" article --- doc_source/home.md | 4 +- doc_source/index.md | 4 +- doc_source/multiple_languages.md | 342 +++++++++++++++++++++++++++---- doc_source/work-with.md | 4 +- 4 files changed, 304 insertions(+), 50 deletions(-) diff --git a/doc_source/home.md b/doc_source/home.md index e743ee81..9c4f66bd 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -179,14 +179,14 @@ Other advantages of the AWS CDK include: ## Developing with the AWS CDK -Unless otherwise indicated, the code examples in this guide are in TypeScript\. To aid you in porting a TypeScript example to a supported programming language, see [AWS CDK in Other Languages ](multiple_languages.md)\. The AWS CDK also includes examples in the supported programming languages\. See [AWS CDK Examples](about_examples.md) for a list of the examples\. +Unless otherwise indicated, the code examples in this guide are in TypeScript\. To aid you in porting a TypeScript example to a supported programming language, see [Translating TypeScript AWS CDK Code to Other Languages ](multiple_languages.md)\. The AWS CDK also includes examples in the supported programming languages\. See [AWS CDK Examples](about_examples.md) for a list of the examples\. The [AWS CDK Tools](tools.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. The [AWS Construct Library](constructs.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to create resources for an Amazon or AWS service\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. **Note** -There is no charge for using the AWS CDK, however you might incur AWS charges for creating or using AWS [chargeable resources](http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Simple Monthly Calculator](http://calculator.s3.amazonaws.com/index.html) to estimate charges for the use of various AWS resources\. +There is no charge for using the AWS CDK, however you might incur AWS charges for creating or using AWS [chargeable resources](http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Pricing Calculator](https://calculator.aws/#/) to estimate charges for the use of various AWS resources\. ## Contributing to the AWS CDK diff --git a/doc_source/index.md b/doc_source/index.md index 1b5d2765..cd44cde0 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -20,8 +20,9 @@ Amazon's trademarks and trade dress may not be used in + [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) + [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) + [Working with the AWS CDK in Python](work-with-cdk-python.md) - + [Working with the AWS CDK in C#](work-with-cdk-csharp.md) + [Working with the AWS CDK in Java](work-with-cdk-java.md) + + [Working with the AWS CDK in C#](work-with-cdk-csharp.md) ++ [Translating TypeScript AWS CDK Code to Other Languages](multiple_languages.md) + [Concepts](core_concepts.md) + [Constructs](constructs.md) + [Apps](apps.md) @@ -38,7 +39,6 @@ Amazon's trademarks and trade dress may not be used in + [Aspects](aspects.md) + [Escape Hatches](cfn_layer.md) + [API Reference](reference.md) - + [AWS CDK in Other Languages](multiple_languages.md) + [Examples](examples.md) + [Creating a Serverless Application Using the AWS CDK](serverless_example.md) + [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 7d9e3231..8b31f04a 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -1,81 +1,335 @@ -# AWS CDK in Other Languages +# Translating TypeScript AWS CDK Code to Other Languages -In some cases the example code in the AWS CDK documentation is available only in TypeScript\. This topic describes how to read TypeScript code and translate it into other languages\. See [Hello World Tutorial](getting_started.md#hello_world_tutorial) for an example of creating an AWS CDK app in a supported language\. +TypeScript was the first language supported for developing AWS CDK applications, and for that reason, there is a substantial amount of example CDK code written in TypeScript\. If you are developing in another language, it may be useful to compare how AWS CDK code is implemented in TypeScript and your language of choice, so you can, with a little effort, make use of these examples\. -## Importing a Module (Package) +For more details on working with the AWS CDK in its supported programming languages, see: ++ [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) ++ [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) ++ [Working with the AWS CDK in Python](work-with-cdk-python.md) ++ [Working with the AWS CDK in Java](work-with-cdk-java.md) ++ [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) -All TypeScript, Python and Java support namespaced module (or package) imports and selective imports\. Module names in Python look like **aws\_cdk\.***xxx*, where *xxx* represents an AWS service name, such as **s3** for Amazon S3 \(we'll use Amazon S3 for our examples\)\. Replace the dashes in the TypeScript module name with underscores to get the Python module name\. Replace the `@aws-cdk` in the TypeScript module name with `software.amazon.awscdk` to get the Java package name. +## Importing a Module -The following is how you import the entire Amazon S3 module or just a `Stack` class in both languages\. +------ +#### [ TypeScript/JavaScript ] +TypeScript supports importing either an entire module, or individual objects from a module\. -| TypeScript | Python | Java | -| --- |--- | --- | -|
// Import entire module
import s3 = require('@aws-cdk/aws-s3')

// Selective import
import { Stack } from '@aws-cdk/core';
|
# Import entire module
import aws_cdk.aws_s3 as s3

# Selective import
from aws_cdk.core import Stack
|
// Import entire package
import software.amazon.awscdk.services.s3.*;

// Selective import
import software.amazon.awscdk.core.Stack;
| +``` +// Import entire module as s3 into current namespace +import * as s3 from '@aws-cdk/aws-s3'; -## Instantiating a Class +// Import an entire module using Node.js require() (generally replaced by above syntax) +const s3 = require('@aws-cdk/aws-s3'); -Classes have the same name in TypeScript, in Python and in Java\. TypeScript and Java uses **new** to instantiate classes, whereas in Python you call the class object directly, like a function\. Props objects at the end of an argument list become keyword\-only arguments in Python, and their names become `snake_case`\. The keyword **this** in TypeScript translates to **self** in Python\. +// Now use s3 to access the S3 types +const bucket = s3.Bucket(...); -The following table shows how you can translate TypeScript class instantiations to Python or Java class instantiations\. +// Selective import of s3.Bucket into current namespace +import { Bucket } from '@aws-cdk/aws-s3'; +// Selective import of Bucket and EventType into current namespace +import { Bucket, EventType } from '@aws-cdk/aws-s3'; -| TypeScript | Python | Java | -| --- |--- | --- | -|
// Instantiate Bucket class
const bucket = new s3.Bucket(this, 'Bucket');
|
# Instantiate Bucket class
bucket = s3.Bucket(self, 'Bucket')
|
// Instantiate Bucket class
Bucket bucket = new Bucket(this, "Bucket");
| -|
// Instantiate Bucket with props
const bucket = new s3.Bucket(this, 'Bucket', {
bucketName: 'my-bucket',
versioned: true,
});
|
# Instantiate Bucket with props
bucket = s3.Bucket(self, 'Bucket',
bucket_name='my-bucket',
versioned=True)
|
// Instantiate Bucket with props
Bucket bucket = new Bucket(this, "Bucket", BucketProps.builder()
.bucketName("my-bucket")
.versioned(true)
.build());
| +// Now use Bucket to instantiate an S3 bucket +const bucket = Bucket(...); +``` -## Methods +------ -Methods and argument names in TypeScript or Java are `camelCased`, whereas in Python they are `snake_cased`\. Props objects at the end of an argument list in TypeScript are translated into keyword\-only arguments in Python, and their names become `snake_case`\. Java used [Builder pattern](https://en.wikipedia.org/wiki/Builder_pattern) to generate props object. +------ +#### [ Python ] -The following table shows how you can translate TypeScript methods to Python methods or Java methods\. +Like TypeScript, Python supports namespaced module imports and selective imports\. Module names in Python look like **aws\_cdk\.***xxx*, where *xxx* represents an AWS service name, such as **s3** for Amazon S3 \(we'll use Amazon S3 for our examples\)\. +``` +# Import entire module as s3 into current namespace +import aws_cdk.aws_s3 as s3 -| TypeScript | Python | Java | -| --- |--- | --- | -|
// Call method
bucket.addCorsRule({
allowedOrigins: ['*'],
allowedMethods: [],
});
|
# Call method
bucket.add_cors_rule(
allowed_origins=['*'],
allowed_methods=[]
)
|
// Call method
bucket.addCorsRule(CorsRule.builder()
.allowedOrigins(List.of("*"))
.allowedMethods(List.of())
.build());
| +# s3 can now be used to access classes it contains +bucket = s3.Bucket(...) -## Enum Constants +# Selective import of s3.Bucket into current namespace +from aws_cdk.s3 import Bucket + +# Selective import of Bucket and EventType into current namespace +from aws_cdk.s3 import Bucket, EventType + +# Bucket can now be used to instantiate a bucket +bucket = Bucket(...) +``` + +------ +#### [ Java ] + +Java's imports work differently from TypeScript's\. Each import statement imports either a single class name from a given package, or all classes defined in that package \(using `*`\)\. After importing, classes may be accessed using either the class name by itself or \(in case of name conflicts\) the *qualified* class name including its package\. + +Packages are named like `software.amazon.awscdk.services.xxx` for AWS Construct Library packages \(the core module is `software.amazon.awscdk.core`\)\. The Maven group ID is for AWS CDK packages `software.amazon.awscdk`\. + +``` +// Make all Amazon S3 construct library classes available +import software.amazon.awscdk.services.s3.*; + +// Make only Bucket and EventType classes available +import software.amazon.awscdk.services.s3.Bucket; +import software.amazon.awscdk.services.s3.EventType; + +// An imported class may now be accessed using the simple class name (assuming that name +// does not conflict with another class) +Bucket bucket = new Bucket(...); + +// We can always use the qualified name of a class (including its package) even without an +// import directive +software.amazon.awscdk.services.s3.Bucket bucket = + new software.amazon.awscdk.services.s3.Bucket(...); +``` + +------ +#### [ C\# ] + +In C\#, you import types with the `using` directive\. There are two styles, which give you access either all the types in the specified namespace using their plain names, or to refer to the namespace itself using an alias\. + +Packages are named like `Amazon.CDK.AWS.xxx` for AWS Construct Library packages \(the core module is `Amazon.CDK`\)\. + +``` +// Make all Amazon S3 construct library classes available +using Amazon.CDK.AWS.S3; + +// Now we can access any S3 type using its name +var bucket = new Bucket(...); + +// Import the S3 namespace under an alias +using s3 = Amazon.CDK.AWS.S3; + +// Now we can access an S3 type through the namespace alias +var bucket = new s3.Bucket(...); + +// We can always use the qualified name of a type (including its namespace) even without a +// using directive +var bucket = new Amazon.CDK.AWS.S3.Bucket(...) +``` + +------ + +## Instantiating a Construct + +AWS CDK construct classes have the same name in all supported languages\. Most languages use the `new` keyword to instantiate a class \(Python is the only one that doesn't\)\. Also, in most languages, the keyword `this` refers to the current instance\. Python, again, is the exception \(it uses `self` by convention\)\. You should pass a reference to the current instance as the `scope` parameter to every construct you create\. + + The third argument to a AWS CDK construct is `props`, an object containing attributes needed to build the construct\. This argument may be optional, but when it is required, the supported languages handle it in idiomatic ways\. The names of the attributes are also adapted to the language's standard naming patterns\. + +------ +#### [ TypeScript/JavaScript ] + +``` +// Instantiate default Bucket +const bucket = new s3.Bucket(this, 'MyBucket'); + +// Instantiate Bucket with bucketName and versioned properties +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket', + versioned: true, +}); + +// Instantiate Bucket with redirectTarget, which has its own sub-properties +const bucket = new s3.Bucket(this, 'MyBucket', { + redirectTarget: {host: 'aws.amazon.com'}}); +``` + +------ + +------ +#### [ Python ] + +Python doesn't use a `new` keyword when instantiating a class\. The properties argument is represented using keyword arguments, and the arguments are named using `snake_case`\. + +If a props value is itself a bundle of attributes, it is represented by a class named after the property, which accepts keyword arguments for the sub\-properties\. + +In Python, the current instance is passed to methods as the first argument, which is named `self` by convention\. + +``` +# Instantiate default Bucket +bucket = s3.Bucket(self, "MyBucket") + +# Instantiate Bucket with bucket_name and versioned properties +bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=true) + +# Instantiate Bucket with redirect_target, which has its own sub-properties +bucket = s3.Bucket(self, "MyBucket", redirect_target=s3.RedirectTarget( + host_name="aws.amazon.com")) +``` + +------ +#### [ Java ] -Enum constants are scoped to a class, and have uppercase names with underscores in all languages \(sometimes referred to as `SCREAMING_SNAKE_CASE`\)\. TypeScript enum constants, Python enum constants and Java enum constants are identical\. +In Java, the props argument is represented by a class named `XxxxProps` \(for example, `BucketProps` for the `Bucket` construct's props\)\. You build the props argument using a builder pattern\. +Each `XxxxProps` class has a builder, and there is also a convenient builder for each construct that builds the props and the construct in one step, as shown here\. -| TypeScript | Python | Java | -| --- |--- | --- | -|
s3.BucketEncryption.KMS_MANAGED
|
s3.BucketEncryption.KMS_MANAGED
|
BucketEncryption.KMS_MANAGED
| +Props are named the same as in TypeScript, using `camelCase`\. -## Defining Constructs +``` +// Instantiate default Bucket +Bucket bucket = Bucket(self, "MyBucket"); -In TypeScript, a construct's props are defined with a shape\-based interface, whereas Python takes keyword \(or keyword\-only, see [PEP3102](https://www.python.org/dev/peps/pep-3102/)\) arguments\. Java's props object should be a POJO and provided [Builder pattern](https://en.wikipedia.org/wiki/Builder_pattern) to define props object\. (Using [Lombok](https://projectlombok.org/) will be most convenient for you.) +// Instantiate Bucket with bucketName and versioned properties +Bucket bucket = Bucket.Builder.create(self, "MyBucket") + .bucketName("my-bucket").versioned(true) + .build(); -The following table shows how TypeScript construct definitions translate to Python construct definitions or Java construct definitions\. +# Instantiate Bucket with redirectTarget, which has its own sub-properties +Bucket bucket = Bucket.Builder.create(self, "MyBucket") + .redirectTarget(new RedirectTarget.Builder() + .hostName("aws.amazon.com").build()) + .build(); +``` +------ +#### [ C\# ] -| TypeScript | Python | Java | -| --- |--- | --- | -|
interface MyConstructProps {
prop1: number;
prop2?: number;
}

class MyConstruct extends Construct {
constructor(scope: Construct, id: string, props: MyConstructProps) {
super(scope, id);
const prop2 = props.prop2 !== undefined ? props.prop2 : 10;

// Construct contents here

}
}
|
class MyConstruct(Construct):

def __init__(scope, id, *, prop1, prop2=10):
super().__init__(scope, id)

# Construct contents here
|
@lombok.Getter
@lombok.Builder
public class MyConstructProps {
private int prop1;
@lombok.Builder.Default
private int prop2 = 10;
}

public class MyConstruct extends Construct {
public MyConstruct(Construct scope, String id, MyConstructProps props) {
super(scope, id);

// Construct contents here
}
}
| +In C\#, props are specified using an object initializer to a class named `XxxxProps` \(for example, `BucketProps` for the `Bucket` construct's props\)\. -## Structs \(Interfaces\) +Props are named similarly to TypeScript, except using `PascalCase`\. -Structs are TypeScript interfaces that represent a set of values\. You can recognize them because their name doesn't start with an `I`, and all of their fields are **read\-only**\. +It is convenient to use the `var` keyword when instantiating a construct, so you don't need to type the class name twice\. However, your local code style guide may vary\.\. -In TypeScript, structs are passed as object literals\. In Python, if the struct is the last argument to a method, its fields are lifted into the method call itself\. If the argument list contains nested structs, wrap them in a class named after the struct\. In Java, structs are passed as object directly\. +``` +// Instantiate default Bucket +var bucket = Bucket(self, "MyBucket"); -The following table shows how to call a method with two levels of structs\. +// Instantiate Bucket with BucketName and versioned properties +var bucket = Bucket(self, "MyBucket", new BucketProps { + BucketName = "my-bucket", + Versioned = true}); +# Instantiate Bucket with RedirectTarget, which has its own sub-properties +var bucket = Bucket(self, "MyBucket", new BucketProps { + RedirectTarget = new RedirectTarget { + HostName = "aws.amazon.com" + }}); +``` -| TypeScript | Python | Java | -| --- |--- | --- | -|
bucket.addLifecycleRule({
transitions: [
{
storageClass: StorageClass.GLACIER,
transitionAfter: Duration.days(10)
}
]
});
|
bucket.add_lifecycle_rule(
transitions=[
Transition(
storage_class=StorageClass.GLACIER,
transition_after=Duration.days(10)
)
]
)
|
bucket.addLifecycleRule(LifecycleRule.builder()
.transitions(List.of(Transition.builder()
.storageClass(StorageClass.GLACIER)
.transitionAfter(Duration.days(10))
.build()))
.build());
| +------ + +## Accessing Members + +It is common to refer to attributes or properties of constructs and other AWS CDK classes and use these values as, for examples, inputs to build other constructs\. The naming differences described above for methods apply\. Furthermore, in Java, it is not possible to access members directly; instead, a getter method is provided\. + +------ +#### [ TypeScript/JavaScript ] + +Names are `camelCase`\. + +``` +bucket.bucketArn +``` + +------ + +------ +#### [ Python ] + +Names are `snake_case`\. + +``` +bucket.bucket_arn +``` + +------ + +------ +#### [ Java ] + +A getter method is provided for each property; these names are `camelCase`\. + +``` +bucket.getBucketArn() +``` + +------ + +------ +#### [ C\# ] + +Names are `PascalCase`\. + +``` +bucket.BucketArn +``` + +------ + +## Enum Constants + +Enum constants are scoped to a class, and have uppercase names with underscores in all languages \(sometimes referred to as `SCREAMING_SNAKE_CASE`\)\. Since class names also use the same casing in all supported languages, qualified enum names are also the same\. + +``` +s3.BucketEncryption.KMS_MANAGED +``` ## Object Interfaces -The AWS CDK uses TypeScript and Java object interfaces to indicate that a class implements an expected set of methods and properties\. You can recognize an object interface because its name starts with `I`\. +The AWS CDK uses TypeScript object interfaces to indicate that a class implements an expected set of methods and properties\. You can recognize an object interface because its name starts with `I`\. A concrete class indicates the interface\(s\) it implements using the `implements` keyword\. + +------ +#### [ TypeScript/JavaScript ] + +**Note** +JavaScript doesn't have an interface feature\. You can ignore the `implements` keyword and the class names following it\. + +``` +import { IAspect, IConstruct } from '@aws-cdk/core'; + +class MyAspect implements IAspect { + public visit(node: IConstruct) { + console.log('Visited', node.node.path); + } +} +``` + +------ + +------ +#### [ Python ] + +Python doesn't have an interface feature\. However, for the AWS CDK you can indicate interface implementation by decorating your class with `@jsii.implements(interface)`\. + +``` +from aws_cdk.core import IAspect, IConstruct + +@jsii.implements(IAspect) +class MyAspect(): + def visit(self, node: IConstruct) -> None: + print("Visited", node.node.path) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.core.IAspect; +import software.amazon.awscdk.core.IConstruct; + +public class MyAspect implements IAspect { + public void visit(IConstruct node) { + System.out.format("Visited %s", node.getNode().getPath()); + } +} +``` + +------ +#### [ C\# ] -Typically, Python users don't explicitly indicate that a class implements an interface\. However, for the AWS CDK you can do this by decorating your class with `@jsii.implements(interface)`\. +``` +using Amazon.CDK; +public class MyAspect : IAspect +{ + public void Visit(IConstruct node) + { + System.Console.WriteLine($"Visited ${node.Node.Path}"); + } +} +``` -| TypeScript | Python | Java | -| --- |--- | --- | -|
import {IAspect, IConstruct } from '@aws-cdk/core';

class MyAspect implements IAspect {
public visit(node: IConstruct) {
console.log('Visited', node.node.path);
}
}
|
from aws_cdk.core import IAspect, IConstruct

@jsii.implements(IAspect)
class MyAspect():
def visit(self, node: IConstruct) -> None:
print("Visited", node.node.path)
|
import software.amazon.awscdk.core.IAspect;
import software.amazon.awscdk.core.IConstruct;

public class MyAspect implements IAspect {
@Override
public void visit(IConstruct node) {
System.out.println("Visited " + node.getNode().getPath());
}
}
| +------ \ No newline at end of file diff --git a/doc_source/work-with.md b/doc_source/work-with.md index c029f773..15cc1d97 100644 --- a/doc_source/work-with.md +++ b/doc_source/work-with.md @@ -30,5 +30,5 @@ The specific language you work in also has its own prerequisites, described in t + [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) + [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) + [Working with the AWS CDK in Python](work-with-cdk-python.md) -+ [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) -+ [Working with the AWS CDK in Java](work-with-cdk-java.md) \ No newline at end of file ++ [Working with the AWS CDK in Java](work-with-cdk-java.md) ++ [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) \ No newline at end of file From 8f80a40e2087d770742e0b8397ba8a928e7e3f64 Mon Sep 17 00:00:00 2001 From: lukehedger Date: Thu, 26 Mar 2020 12:45:46 +0000 Subject: [PATCH 121/655] Update testing doc to show usage of toHaveResource Jest matcher --- doc_source/testing.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/doc_source/testing.md b/doc_source/testing.md index 4dfac07c..539c3e7d 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -216,7 +216,7 @@ When we run the test again, it breaks\. The name we've given the test hints that To avoid needing to review every snapshot whenever you make a change, use the custom assertions in the `@aws-cdk/assert/jest` module to write fine\-grained tests that verify only part of the construct's behavior\. For example, the test we called "dlq creates an alarm" in our example really should assert only that an alarm is created with the appropriate metric\. -The [AWS::CloudWatch::Alarm](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html) resource specification reveals that we're interested in the properties Namespace, MetricName and Dimensions\. We'll use the `expect(stack).to(haveResource(...))` assertion, which is in the `@aws-cdk/assert/jest` module, to make sure these properties have the appropriate values\. +The [AWS::CloudWatch::Alarm](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html) resource specification reveals that we're interested in the properties Namespace, MetricName and Dimensions\. We'll use the `expect(stack).toHaveResource(...)` assertion, which is in the `@aws-cdk/assert/jest` module, to make sure these properties have the appropriate values\. Replace the code in `test/dead-letter-queue.test.ts` with the following\. @@ -231,7 +231,7 @@ test('dlq creates an alarm', () => { new dlq.DeadLetterQueue(stack, 'DLQ'); - expect(stack).to(haveResource('AWS::CloudWatch::Alarm', { + expect(stack).toHaveResource('AWS::CloudWatch::Alarm', { MetricName: "ApproximateNumberOfMessagesVisible", Namespace: "AWS/SQS", Dimensions: [ @@ -240,7 +240,7 @@ test('dlq creates an alarm', () => { Value: { "Fn::GetAtt": [ "DLQ581697C4", "QueueName" ] } } ], - })); + }); }); test('dlq has maximum retention period', () => { @@ -248,9 +248,9 @@ test('dlq has maximum retention period', () => { new dlq.DeadLetterQueue(stack, 'DLQ'); - expect(stack).to(haveResource('AWS::SQS::Queue', { + expect(stack).toHaveResource('AWS::SQS::Queue', { MessageRetentionPeriod: 1209600 - })); + }); }); ``` @@ -314,9 +314,9 @@ test('retention period can be configured', () => { retentionDays: 7 }); - expect(stack).to(haveResource('AWS::SQS::Queue', { + expect(stack).toHaveResource('AWS::SQS::Queue', { MessageRetentionPeriod: 604800 - })); + }); }); test('configurable retention period cannot exceed 14 days', () => { @@ -351,4 +351,4 @@ Tests: 4 passed, 4 total Remember, your tests will live just as long as the code they test, and be read and modified just as often, so it pays to take a moment to consider how best to write them\. Don't copy and paste setup lines or common assertions, for example; refactor this logic into helper functions\. Use good names that reflect what each test actually tests\. -Don't assert too much in one test\. Preferably, a test should test one and only one behavior\. If you accidentally break that behavior, exactly one test should fail, and the name of the test should tell you exactly what failed\. This is more an ideal to be striven for, however; sometimes you will unavoidably \(or inadvertently\) write tests that test more than one behavior\. Snapshot tests are, for reasons we've already described, especially prone to this problem, so use them sparingly\. \ No newline at end of file +Don't assert too much in one test\. Preferably, a test should test one and only one behavior\. If you accidentally break that behavior, exactly one test should fail, and the name of the test should tell you exactly what failed\. This is more an ideal to be striven for, however; sometimes you will unavoidably \(or inadvertently\) write tests that test more than one behavior\. Snapshot tests are, for reasons we've already described, especially prone to this problem, so use them sparingly\. From 07fb6039e28cdfaeaded527f69db5ea560d0603e Mon Sep 17 00:00:00 2001 From: Polonsky Date: Tue, 31 Mar 2020 02:42:14 +0300 Subject: [PATCH 122/655] added cli compatibility section --- doc_source/reference.md | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/doc_source/reference.md b/doc_source/reference.md index f2ae5008..98e4265a 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -4,9 +4,36 @@ The [API Reference](https://docs.aws.amazon.com/cdk/api/latest) contains informa Each library contains information about how to use the library\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) library demonstrates how to set default encryption on an Amazon S3 bucket\. -## Versioning and Stability Model +## Versioning -Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs, which is described in the next section, are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs, are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. + +## AWS CDK CLI Compatibility + +Following is the expected behavior of the CLI in relation to different versions of the framework libraries. + +- CLI versions are **always** compatible with framework libraries of a semantically **lower** version number. This means that CLI upgardes are safe. +Note that `major` version exceptions still apply. That is, CDK CLI version 2.1.0 is not necessarily compatible with a framework library of version 1.56.0. + +- CLI versions are **not always** compatible with framework libraries of a semantically **higher** version number. This is determined by whether or not the `cloud-assembly-schema` version has changed. + + #### What is the cloud-assembly-schema? + + The AWS CDK API framework produces a *cloud-assembly* directory during `synthesis`. This assembly is then consumed by the CDK CLI in order to deploy it assembly to the cloud. + + In essence, this *cloud-assembly* acts as a protocol between the framework and the CLI, and as such, it is versioned. + + For more details, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/epolon/cli-framework-compatibility/packages/%40aws-cdk/cloud-assembly-schema#versioning). + + + This means that you might see the following message when upgrading framework libraries: + + ```console + Cloud assembly schema version mismatch: actual('3.0.0') > expected('2.0.0'). Consider upgrading your CLI version. + ``` + + This message means that the framework you are using is producing assembilies with version `3.0.0`, but the CLI you have installed is expecting version `2.0.0`. + To fix this, you can simply upgrade the CLI to the latest version. ### AWS CDK Stability Index From e67503934f30af5f367770a9e44fc9b507281661 Mon Sep 17 00:00:00 2001 From: Polonsky Date: Thu, 2 Apr 2020 13:15:59 +0300 Subject: [PATCH 123/655] some rephrasing --- doc_source/reference.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/doc_source/reference.md b/doc_source/reference.md index 98e4265a..7553049c 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -6,13 +6,15 @@ Each library contains information about how to use the library\. For example, th ## Versioning -Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs, are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs, are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. + +**Note that this compatibility promise does not apply for *Experimental* API's, see [AWS CDK Stability Index](#aws_construct_lib_versioning_stability) for more details.** ## AWS CDK CLI Compatibility Following is the expected behavior of the CLI in relation to different versions of the framework libraries. -- CLI versions are **always** compatible with framework libraries of a semantically **lower** version number. This means that CLI upgardes are safe. +- CLI versions are **always** compatible with framework libraries of a semantically **lower** or **equal** version number. This means that CLI upgardes are safe. Note that `major` version exceptions still apply. That is, CDK CLI version 2.1.0 is not necessarily compatible with a framework library of version 1.56.0. - CLI versions are **not always** compatible with framework libraries of a semantically **higher** version number. This is determined by whether or not the `cloud-assembly-schema` version has changed. @@ -25,16 +27,12 @@ Note that `major` version exceptions still apply. That is, CDK CLI version 2.1.0 For more details, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/epolon/cli-framework-compatibility/packages/%40aws-cdk/cloud-assembly-schema#versioning). - This means that you might see the following message when upgrading framework libraries: ```console Cloud assembly schema version mismatch: actual('3.0.0') > expected('2.0.0'). Consider upgrading your CLI version. ``` - This message means that the framework you are using is producing assembilies with version `3.0.0`, but the CLI you have installed is expecting version `2.0.0`. - To fix this, you can simply upgrade the CLI to the latest version. - ### AWS CDK Stability Index However, certain APIs do not adhere to the semantic versioning model\. The AWS CDK team has added a stability index to help developers determine which APIs deviate from the semantic versioning model\. @@ -48,7 +46,7 @@ CloudFormation Only These APIs are automatically built from the AWS CloudFormation resource specification and are subject to any changes introduced by AWS CloudFormation\. Experimental -The API is still under active development and subject to non\-backward\-compatible changes or removal in any future version\. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. +The API is still under active development and subject to non\-backward\-compatible changes or removal in any future version\. Such changes will be announed under the **BREAKING\-CHANGES** section in our release notes. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. Deprecated The API may emit warnings\. We do not guarantee backward compatibility\. From 88b03bc538049a4f93f73124d17e01b9849c75df Mon Sep 17 00:00:00 2001 From: Polonsky Date: Thu, 2 Apr 2020 13:18:00 +0300 Subject: [PATCH 124/655] fix phrasing --- doc_source/reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/reference.md b/doc_source/reference.md index 7553049c..d8070e75 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -8,7 +8,7 @@ Each library contains information about how to use the library\. For example, th Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs, are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. -**Note that this compatibility promise does not apply for *Experimental* API's, see [AWS CDK Stability Index](#aws_construct_lib_versioning_stability) for more details.** +**Note that this compatibility promise does not apply to *Experimental* API's, see [AWS CDK Stability Index](#aws_construct_lib_versioning_stability) for more details.** ## AWS CDK CLI Compatibility From 61e7961e0e53a861a30b61af0baa84b73e561796 Mon Sep 17 00:00:00 2001 From: Polonsky Date: Thu, 2 Apr 2020 13:20:54 +0300 Subject: [PATCH 125/655] change error message --- doc_source/reference.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doc_source/reference.md b/doc_source/reference.md index d8070e75..6ff3254c 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -30,7 +30,8 @@ Note that `major` version exceptions still apply. That is, CDK CLI version 2.1.0 This means that you might see the following message when upgrading framework libraries: ```console - Cloud assembly schema version mismatch: actual('3.0.0') > expected('2.0.0'). Consider upgrading your CLI version. + Cloud assembly schema version mismatch: Maximum schema version supported is 3.0.0, but found 4.0.0. + Please upgrade your CLI in order to interact with this app. ``` ### AWS CDK Stability Index From dd43a7b7c97b3e90478ca408f67d21f6fe2f75fd Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 7 Apr 2020 00:01:51 +0000 Subject: [PATCH 126/655] modernize TypeScript imports, fix code and typos --- doc_source/assets.md | 18 +++--- doc_source/codepipeline_example.md | 34 +++++------ doc_source/constructs.md | 56 +++++++------------ doc_source/context.md | 4 +- doc_source/ecs_example.md | 6 +- doc_source/environments.md | 10 ++-- doc_source/get_env_var.md | 8 +-- doc_source/get_secrets_manager_value.md | 2 +- doc_source/get_ssm_value.md | 4 +- doc_source/getting_started.md | 20 +++---- doc_source/how_to_set_cw_alarm.md | 3 + doc_source/identifiers.md | 2 +- doc_source/multiple_languages.md | 13 ++--- doc_source/permissions.md | 4 +- doc_source/resources.md | 14 ++--- doc_source/serverless_example.md | 10 ++-- .../stack_how_to_create_multiple_stacks.md | 12 ++-- doc_source/tagging.md | 2 +- doc_source/testing.md | 10 ++-- doc_source/tools.md | 2 +- doc_source/troubleshooting.md | 6 +- doc_source/use_cfn_template.md | 4 +- 22 files changed, 113 insertions(+), 131 deletions(-) diff --git a/doc_source/assets.md b/doc_source/assets.md index ecdbe7d2..b7dd1119 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -137,9 +137,9 @@ The code for the main AWS CDK app should look like the following\. #### [ TypeScript ] ``` -import cdk = require('@aws-cdk/core'); -import lambda = require('@aws-cdk/aws-lambda'); -import path = require('path'); +import * as cdk from '@aws-cdk/core'; +import * as lambda from '@aws-cdk/aws-lambda'; +import * as path from 'path'; export class HelloAssetStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { @@ -241,7 +241,7 @@ The following example uses deploy\-time attributes to pass the location of an im ``` import { Asset } from '@aws-cdk/aws-s3-assets'; -import path = require('path'); +import * as path from 'path'; const imageAsset = new Asset(this, "SampleAsset", { path: path.join(__dirname, "images/my-image.png") @@ -359,7 +359,7 @@ The following example grants an IAM group read permissions on a file asset\. ``` import { Asset } from '@aws-cdk/aws-s3-assets'; -import path = require('path'); +import * as path from 'path'; const asset = new Asset(this, 'MyFile', { path: path.join(__dirname, 'my-image.png') @@ -497,8 +497,8 @@ A common use case is to create an Amazon ECS [TaskDefinition](https://docs.aws.a #### [ TypeScript ] ``` -import ecs = require('@aws-cdk/aws-ecs'); -import path = require('path'); +import * as ecs from '@aws-cdk/aws-ecs'; +import * as path from 'path'; const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { memoryLimitMiB: 1024, @@ -578,8 +578,8 @@ The following example shows how to use the deploy\-time attributes `repository` #### [ TypeScript ] ``` -import ecs = require('@aws-cdk/aws-ecs'); -import path = require('path'); +import * as ecs from '@aws-cdk/aws-ecs'; +import * as path from 'path'; import { DockerImageAsset } from '@aws-cdk/aws-ecr-assets'; const asset = new DockerImageAsset(this, 'my-image', { diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 97dd2f61..bd036665 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -104,8 +104,8 @@ If the Lambda function needs any other resources when executing, such as an Amaz File: `lib/lambda-stack.ts` ``` -import codedeploy = require('@aws-cdk/aws-codedeploy'); -import lambda = require('@aws-cdk/aws-lambda'); +import * as codedeploy from '@aws-cdk/aws-codedeploy'; +import * as lambda from '@aws-cdk/aws-lambda'; import { App, Stack, StackProps } from '@aws-cdk/core'; export class LambdaStack extends Stack { @@ -297,12 +297,12 @@ We also change the name of the stack that will be deployed, from `LambdaStack` t File: `lib/pipeline-stack.ts` ``` -import codebuild = require('@aws-cdk/aws-codebuild'); -import codecommit = require('@aws-cdk/aws-codecommit'); -import codepipeline = require('@aws-cdk/aws-codepipeline'); -import codepipeline_actions = require('@aws-cdk/aws-codepipeline-actions'); -import lambda = require('@aws-cdk/aws-lambda'); -import s3 = require('@aws-cdk/aws-s3'); +import * as codebuild from '@aws-cdk/aws-codebuild'; +import * as codecommit from '@aws-cdk/aws-codecommit'; +import * as codepipeline from '@aws-cdk/aws-codepipeline'; +import * as codepipeline_actions from '@aws-cdk/aws-codepipeline-actions'; +import * as lambda from '@aws-cdk/aws-lambda'; +import * as s3 from '@aws-cdk/aws-s3'; import { App, Stack, StackProps } from '@aws-cdk/core'; export interface PipelineStackProps extends StackProps { @@ -338,7 +338,7 @@ export class PipelineStack extends Stack { }, }), environment: { - buildImage: LinuxBuildImage.STANDARD_2_0, + buildImage: codebuild.LinuxBuildImage.STANDARD_2_0, }, }); const lambdaBuild = new codebuild.PipelineProject(this, 'LambdaBuild', { @@ -364,7 +364,7 @@ export class PipelineStack extends Stack { }, }), environment: { - buildImage: LinuxBuildImage.STANDARD_2_0, + buildImage: codebuild.LinuxBuildImage.STANDARD_2_0, }, }); @@ -456,7 +456,7 @@ class PipelineStack(core.Stack): "files": [ "LambdaStack.template.json"]}, environment=dict(buildImage= - codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1)))) + codebuild.LinuxBuildImage.STANDARD_2_0)))) lambda_build = codebuild.PipelineProject(self, 'LambdaBuild', build_spec=codebuild.BuildSpec.from_object(dict( @@ -474,7 +474,7 @@ class PipelineStack(core.Stack): "index.js", "node_modules/**/*"]}, environment=dict(buildImage= - codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1)))) + codebuild.LinuxBuildImage.STANDARD_2_0)))) source_output = codepipeline.Artifact() cdk_build_output = codepipeline.Artifact("CdkBuildOutput") @@ -584,7 +584,7 @@ public class PipelineStack extends Stack { put("files", Arrays.asList("LambdaStack.template.json")); }})) .environment(BuildEnvironment.builder().buildImage( - LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1).build()) + LinuxBuildImage.STANDARD_2_0).build()) .build(); PipelineProject lambdaBuild = PipelineProject.Builder.create(this, "LambdaBuild") @@ -604,7 +604,7 @@ public class PipelineStack extends Stack { }}); }})) .environment(BuildEnvironment.builder().buildImage( - LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1).build()) + LinuxBuildImage.STANDARD_2_0).build()) .build(); Artifact sourceOutput = new Artifact(); @@ -711,7 +711,7 @@ namespace Pipeline }), Environment = new BuildEnvironment { - BuildImage = LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1 + BuildImage = LinuxBuildImage.STANDARD_2_0 } }); @@ -747,7 +747,7 @@ namespace Pipeline }), Environment = new BuildEnvironment { - BuildImage = LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1 + BuildImage = LinuxBuildImage.STANDARD_2_0 } }); @@ -974,4 +974,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` +``` \ No newline at end of file diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 50144058..3a789b8d 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -42,13 +42,13 @@ We call your CDK application an *app*, which is represented by the AWS CDK class ``` import { App, Stack, StackProps } from '@aws-cdk/core'; -import { Bucket } from '@aws-cdk/aws-s3'; +import * as s3 from '@aws-cdk/aws-s3'; class HelloCdkStack extends Stack { constructor(scope: App, id: string, props?: StackProps) { super(scope, id, props); - new Bucket(this, 'MyFirstBucket', { + new s3.Bucket(this, 'MyFirstBucket', { versioned: true }); } @@ -183,10 +183,10 @@ Once you have defined a stack, you can populate it with resources\. The followin #### [ TypeScript ] ``` -import { Bucket } from '@aws-cdk/aws-s3'; +import * as s3 from '@aws-cdk/aws-s3'; // "this" is HelloCdkStack -new Bucket(this, 'MyFirstBucket', { +new s3.Bucket(this, 'MyFirstBucket', { versioned: true }); ``` @@ -249,10 +249,8 @@ Most constructs accept `props` as their third argument \(or in Python, keyword a #### [ TypeScript ] ``` -import { Bucket, BucketEncryption } from '@aws-cdk/aws-s3'; - -new Bucket(this, 'MyEncryptedBucket', { - encryption: BucketEncryption.KMS, +new s3.Bucket(this, 'MyEncryptedBucket', { + encryption: s3.BucketEncryption.KMS, websiteIndexDocument: 'index.html' }); ``` @@ -299,11 +297,8 @@ For example, almost all AWS constructs have a set of [grant](permissions.md#perm #### [ TypeScript ] ``` -import { Group } from '@aws-cdk/aws-iam'; -import { Bucket } from '@aws-cdk/aws-s3'; - -const rawData = new Bucket(this, 'raw-data'); -const dataScience = new Group(this, 'data-science'); +const rawData = new s3.Bucket(this, 'raw-data'); +const dataScience = new iam.Group(this, 'data-science'); rawData.grantRead(dataScience); ``` @@ -342,14 +337,11 @@ Another common pattern is for AWS constructs to set one of the resource's attrib #### [ TypeScript ] ``` -import { Function, Runtime, Code } from '@aws-cdk/aws-lambda'; -import { Queue } from '@aws-cdk/aws-sqs'; - -const jobsQueue = new Queue(this, 'jobs'); -const createJobLambda = new Function(this, 'create-job', { - runtime: Runtime.NODEJS_10_X, +const jobsQueue = new sqs.Queue(this, 'jobs'); +const createJobLambda = new lambda.Function(this, 'create-job', { + runtime: lambda.Runtime.NODEJS_10_X, handler: 'index.handler', - code: Code.fromAsset('./create-job-lambda-code'), + code: lambda.Code.fromAsset('./create-job-lambda-code'), environment: { QUEUE_URL: jobsQueue.queueUrl } @@ -417,11 +409,6 @@ For example, you could declare a construct that represents an Amazon S3 bucket w #### [ TypeScript ] ``` -import { Construct } from '@aws-cdk/core'; -import { Bucket } from '@aws-cdk/aws-s3'; -import { SnsDestination } from '@aws-cdk/aws-s3-notifications'; -import { Topic } from '@aws-cdk/aws-sns'; - export interface NotifyingBucketProps { prefix?: string; } @@ -580,15 +567,13 @@ Typically, you would also want to expose some properties or methods on your cons ``` export class NotifyingBucket extends Construct { - public readonly topic: Topic; + public readonly topic: sns.Topic; constructor(scope: Construct, id: string, props: NotifyingBucketProps) { super(scope, id); - - const bucket = new Bucket(this, 'bucket'); - this.topic = new Topic(this, 'topic'); - const snsDestination = new SnsDestination(snsTopic); - bucket.addObjectCreatedNotification(snsDestination, { prefix: props.prefix }); + const bucket = new s3.Bucket(this, 'bucket'); + this.topic = new sns.Topic(this, 'topic'); + bucket.addObjectCreatedNotification(this.topic, { prefix: props.prefix }); } } ``` @@ -667,12 +652,9 @@ Now, consumers can subscribe to the topic, for example: #### [ TypeScript ] ``` -import { Queue } from '@aws-cdk/aws-sqs'; -import { SqsSubscription } from '@aws-cdk/aws-sns-subscriptions'; - -const queue = new Queue(this, 'NewImagesQueue'); +const queue = new sqs.Queue(this, 'NewImagesQueue'); const images = new NotifyingBucket(this, 'Images'); -images.topic.addSubscription(new SqsSubscription(queue)); +images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); ``` ------ @@ -704,4 +686,4 @@ var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketP images.topic.AddSubscription(new SqsSubscription(queue)); ``` ------- +------ \ No newline at end of file diff --git a/doc_source/context.md b/doc_source/context.md index ca6248a4..49e7f317 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -96,8 +96,8 @@ Below is an example of importing an existing Amazon VPC using AWS CDK context\. #### [ TypeScript ] ``` -import cdk = require('@aws-cdk/core'); -import ec2 = require('@aws-cdk/aws-ec2'); +import * as cdk from '@aws-cdk/core'; +import * as ec2 from '@aws-cdk/aws-ec2'; export class ExistsVpcStack extends cdk.Stack { diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 5c160428..c9d54dee 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -188,9 +188,9 @@ Add the following AWS Construct Library module imports to the indicated file\. File: `lib/my_ecs_construct-stack.ts` ``` -import ec2 = require("@aws-cdk/aws-ec2"); -import ecs = require("@aws-cdk/aws-ecs"); -import ecs_patterns = require("@aws-cdk/aws-ecs-patterns"); +import * as ec2 from "@aws-cdk/aws-ec2"; +import * as ecs from "@aws-cdk/aws-ecs"; +import * as ecs_patterns from "@aws-cdk/aws-ecs-patterns"; ``` ------ diff --git a/doc_source/environments.md b/doc_source/environments.md index 1e13e403..b86e726f 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -18,8 +18,8 @@ For production stacks, we recommend that you explicitly specify the environment const envEU = { account: '2383838383', region: 'eu-west-1' }; const envUSA = { account: '8373873873', region: 'us-west-2' }; -new MyFirstStack(app, 'first-stack-us', { env: envUSA, encryption: false }); -new MyFirstStack(app, 'first-stack-eu', { env: envEU, encryption: true }); +new MyFirstStack(app, 'first-stack-us', { env: envUSA }); +new MyFirstStack(app, 'first-stack-eu', { env: envEU }); ``` ------ @@ -29,8 +29,8 @@ new MyFirstStack(app, 'first-stack-eu', { env: envEU, encryption: true }); env_EU = core.Environment(account="8373873873", region="eu-west-1") env_USA = core.Environment(account="2383838383", region="us-west-2") -MyFirstStack(app, "first-stack-us", env=env_USA, encryption=False) -MyFirstStack(app, "first-stack-eu", env=env_EU, encryption=True) +MyFirstStack(app, "first-stack-us", env=env_USA) +MyFirstStack(app, "first-stack-eu", env=env_EU) ``` ------ @@ -176,7 +176,7 @@ new MyDevStack(app, "dev", new StackProps { Env = makeEnv() }); ------ -The AWS CDK distinguishes between not specifying the `env` property at all and specifying it using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. Constructs that are defined in such a stack cannot use any information about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options) \(Python: `from_lookup`\), which need to query your AWS account\. +The AWS CDK distinguishes between not specifying the `env` property at all and specifying it using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. Constructs that are defined in such a stack cannot use any information about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options) \(Python: `from_lookup`\), which need to query your AWS account\. These features do not work at all without an explicit environment specified; to use them, you must specify `env`\. When you pass in your environment using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, the stack will be deployed in the account and Region determined by the AWS CDK CLI at the time of synthesis\. This allows environment\-dependent code to work, but it also means that the synthesized template could be different based on the machine, user, or session under which it is synthesized\. This behavior is often acceptable or even desirable during development, but it would probably be an anti\-pattern for production use\. diff --git a/doc_source/get_env_var.md b/doc_source/get_env_var.md index 91fa2357..3e2f5488 100644 --- a/doc_source/get_env_var.md +++ b/doc_source/get_env_var.md @@ -19,14 +19,14 @@ const bucket_name = process.env.MYBUCKET || "DefaultName"; ``` import os -# Throws error if environment variable doesn't exist -bucket_name = os.env["MYBUCKET"] +# Raises KeyError if environment variable doesn't exist +bucket_name = os.environ["MYBUCKET"] # Sets bucket_name to None if environment variable doesn't exist -bucket_name = os.env.get("MYBUCKET") +bucket_name = os.getenv("MYBUCKET") # Sets bucket_name to a default if env var doesn't exist -bucket_name = os.env.get("MYBUCKET", "DefaultName") +bucket_name = os.getenv("MYBUCKET", "DefaultName") ``` ------ diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index ee7578bf..def4add7 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -6,7 +6,7 @@ To use values from AWS Secrets Manager in your CDK app, use the [fromSecretAttri #### [ TypeScript ] ``` -import sm = require("@aws-cdk/aws-secretsmanager"); +import * as sm from "@aws-cdk/aws-secretsmanager"; export class SecretsManagerStack extends core.Stack { constructor(scope: core.App, id: string, props?: core.StackProps) { diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 8eecf6e3..f2fe3534 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -15,7 +15,7 @@ To read values from the Systems Manager Parameter Store, use the [valueForString #### [ TypeScript ] ``` -import ssm = require('@aws-cdk/aws-ssm'); +import * as ssm from '@aws-cdk/aws-ssm'; // Get latest version or specified version of plain string attribute const latestStringToken = ssm.StringParameter.valueForStringParameter( @@ -91,7 +91,7 @@ To read a value from the Systems Manager parameter store at synthesis time, use #### [ TypeScript ] ``` -import ssm = require('@aws-cdk/aws-ssm'); +import * as ssm from '@aws-cdk/aws-ssm'; const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index c29e5b2b..43f3589a 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -513,14 +513,14 @@ Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represente In `lib/hello-cdk-stack.ts`: ``` -import { App, Stack, StackProps, Construct } from '@aws-cdk/core'; -import { Bucket } from '@aws-cdk/aws-s3'; +import * as core = from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; -export class HelloCdkStack extends Stack { - constructor(scope: App, id: string, props?: StackProps) { +export class HelloCdkStack extends core.Stack { + constructor(scope: core.App, id: string, props?: core.StackProps) { super(scope, id, props); - new Bucket(this, 'MyFirstBucket', { + new s3.Bucket(this, 'MyFirstBucket', { versioned: true }); } @@ -644,7 +644,7 @@ or press F6 in Visual Studio ### Synthesizing an AWS CloudFormation Template -Synthesize an AWS CloudFormation template for the app, as follows\. If you get an error like "\-\-app is required\.\.\.", it's because you are running the command from a subirectory of your project directory\. Navigate to the project directory and try again\. +Synthesize an AWS CloudFormation template for the app, as follows\. If you get an error like "\-\-app is required\.\.\.", it's because you are running the command from a subdirectory of your project directory\. Navigate to the project directory and try again\. ``` cdk synth @@ -695,11 +695,9 @@ Configure the bucket to use AWS Key Management Service \(AWS KMS\) managed encry Update `lib/hello-cdk-stack.ts` ``` -import { Bucket, BucketEncryption } from "@aws-cdk/aws-s3"; - -new Bucket(this, 'MyFirstBucket', { +new s3.Bucket(this, 'MyFirstBucket', { versioned: true, - encryption: BucketEncryption.KMS_MANAGED + encryption: s3.BucketEncryption.KMS_MANAGED }); ``` @@ -831,4 +829,4 @@ Destroy the app's resources to avoid incurring any costs from the resources crea cdk destroy ``` -Enter y to approve the changes and delete any stack resources\. In some cases this command fails, such as when a resource isn't empty and must be empty before it can be destroyed\. See [Delete Stack Fails](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#troubleshooting-errors-delete-stack-fails) in the *AWS CloudFormation User Guide* for details\. +Enter y to approve the changes and delete any stack resources\. In some cases this command fails, such as when a resource isn't empty and must be empty before it can be destroyed\. See [Delete Stack Fails](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#troubleshooting-errors-delete-stack-fails) in the *AWS CloudFormation User Guide* for details\. \ No newline at end of file diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index 7906d050..8c99bf63 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -31,6 +31,7 @@ alarm = cloudwatch.Alarm(self, "Alarm", ``` import software.amazon.awscdk.services.cloudwatch.Alarm; +import software.amazon.awscdk.services.cloudwatch.Metric; Alarm alarm = Alarm.Builder.create(this, "Alarm") .metric(metric) // see below @@ -141,6 +142,8 @@ cloudwatch.Alarm(self, "Alarm", #### [ Java ] ``` +Metric qMetric = queue.metric("ApproximateNumberOfMessagesVisible"); + Alarm.Builder.create(this, "Alarm") .metric(qMetric) .threshold(100) diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index 54790e6f..96d183c4 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -17,7 +17,7 @@ Lets look at an example where we have two constructs with the identifier `MyBuck ``` import { App, Construct, Stack, StackProps } from '@aws-cdk/core'; -import s3 = require('@aws-cdk/aws-s3'); +import * as s3 from '@aws-cdk/aws-s3'; class MyStack extends Stack { constructor(scope: Construct, id: string, props: StackProps = {}) { diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 8b31f04a..ef2fb8bc 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -20,9 +20,12 @@ TypeScript supports importing either an entire module, or individual objects fro // Import entire module as s3 into current namespace import * as s3 from '@aws-cdk/aws-s3'; -// Import an entire module using Node.js require() (generally replaced by above syntax) +// Import an entire module using Node.js require() (import * as s3 generally preferred) const s3 = require('@aws-cdk/aws-s3'); +// TypeScript version of require() (again, import * as s3 generally preferred) +import s3 = require('@aws-cdk/aws-3'); + // Now use s3 to access the S3 types const bucket = s3.Bucket(...); @@ -191,7 +194,7 @@ In C\#, props are specified using an object initializer to a class named `XxxxPr Props are named similarly to TypeScript, except using `PascalCase`\. -It is convenient to use the `var` keyword when instantiating a construct, so you don't need to type the class name twice\. However, your local code style guide may vary\.\. +It is convenient to use the `var` keyword when instantiating a construct, so you don't need to type the class name twice\. However, your local code style guide may vary\. ``` // Instantiate default Bucket @@ -202,7 +205,7 @@ var bucket = Bucket(self, "MyBucket", new BucketProps { BucketName = "my-bucket", Versioned = true}); -# Instantiate Bucket with RedirectTarget, which has its own sub-properties +// Instantiate Bucket with RedirectTarget, which has its own sub-properties var bucket = Bucket(self, "MyBucket", new BucketProps { RedirectTarget = new RedirectTarget { HostName = "aws.amazon.com" @@ -235,8 +238,6 @@ Names are `snake_case`\. bucket.bucket_arn ``` ------- - ------ #### [ Java ] @@ -246,8 +247,6 @@ A getter method is provided for each property; these names are `camelCase`\. bucket.getBucketArn() ``` ------- - ------ #### [ C\# ] diff --git a/doc_source/permissions.md b/doc_source/permissions.md index 0f253822..1e623454 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -40,7 +40,7 @@ The IAM package contains a `[Role](https://docs.aws.amazon.com/cdk/api/latest/do #### [ TypeScript ] ``` -import iam = require('@aws-cdk/aws-iam'); +import * as iam from '@aws-cdk/aws-iam'; const role = new iam.Role(this, 'Role', { assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'), // required @@ -156,7 +156,7 @@ If you're using a construct that requires a role to function correctly, you can #### [ TypeScript ] ``` -import codebuild = require('@aws-cdk/aws-codebuild'); +import * as codebuild from '@aws-cdk/aws-codebuild'; // imagine roleOrUndefined is a function that might return a Role object // under some conditions, and undefined under other conditions diff --git a/doc_source/resources.md b/doc_source/resources.md index f8bd546e..5e7f237b 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -8,7 +8,7 @@ Defining AWS resources in your CDK app is exactly like defining any other constr #### [ TypeScript ] ``` -import sqs = require('@aws-cdk/aws-sqs'); +import * as sqs from '@aws-cdk/aws-sqs'; new sqs.Queue(this, 'MyQueue', { encryption: sqs.QueueEncryption.KMS_MANAGED @@ -58,7 +58,7 @@ Most resources in the AWS Construct Library expose attributes, which are resolve #### [ TypeScript ] ``` -import sqs = require('@aws-cdk/aws-sqs'); +import * as sqs from '@aws-cdk/aws-sqs'; const queue = new sqs.Queue(this, 'MyQueue'); const url = queue.queueUrl; // => A string representing a deploy-time value @@ -645,8 +645,8 @@ The following example shows how to define an alarm when the `ApproximateNumberOf #### [ TypeScript ] ``` -import cw = require('@aws-cdk/aws-cloudwatch'); -import sqs = require('@aws-cdk/aws-sqs'); +import * as cw from '@aws-cdk/aws-cloudwatch'; +import * as sqs from '@aws-cdk/aws-sqs'; import { Duration } from '@aws-cdk/core'; const queue = new sqs.Queue(this, 'MyQueue'); @@ -750,8 +750,8 @@ You enable data to flow on a given network path by using `allow` methods\. The f #### [ TypeScript ] ``` -import asg = require('@aws-cdk/aws-autoscaling'); -import ec2 = require('@aws-cdk/aws-ec2'); +import * as asg from '@aws-cdk/aws-autoscaling'; +import * as ec2 from '@aws-cdk/aws-ec2'; const fleet1: asg.AutoScalingGroup = /* ... */ @@ -870,7 +870,7 @@ The following example shows how to trigger a Lambda function when an object is a #### [ TypeScript ] ``` -import s3nots = require('@aws-cdk/aws-s3-notifications'); +import * s3nots from '@aws-cdk/aws-s3-notifications'; const handler = new lambda.Function(this, 'Handler', { /*…*/ }); const bucket = new s3.Bucket(this, 'Bucket'); diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 7316ffd0..c58cc8cf 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -293,10 +293,10 @@ Create a new source file to define the widget service with the source code shown File: `lib/widget_service.ts` ``` -import core = require("@aws-cdk/core"); -import apigateway = require("@aws-cdk/aws-apigateway"); -import lambda = require("@aws-cdk/aws-lambda"); -import s3 = require("@aws-cdk/aws-s3"); +import * as core from "@aws-cdk/core"; +import * as apigateway from "@aws-cdk/aws-apigateway"; +import * as lambda from "@aws-cdk/aws-lambda"; +import * as s3 from "@aws-cdk/aws-s3"; export class WidgetService extends core.Construct { constructor(scope: core.Construct, id: string) { @@ -527,7 +527,7 @@ File: `lib/my_widget_service-stack.ts` Add the following line of code after the existing `import` statement\. ``` -import widget_service = require('../lib/widget_service'); +import * as widget_service from '../lib/widget_service'; ``` Replace the comment in the constructor with the following line of code\. diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index c1a58dac..cffce5de 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -108,8 +108,8 @@ So open the indicated source file in your IDE or editor and add the new interfac File: `lib/multistack-stack.ts` ``` -import cdk = require('@aws-cdk/core'); -import s3 = require('@aws-cdk/aws-s3'); +import * as cdk from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; interface MultiStackProps extends cdk.StackProps { encryptBucket?: boolean; @@ -222,8 +222,8 @@ The new property is optional\. If `encryptBucket` \(Python: `encrypt_bucket`\) i File: `lib/multistack-stack.ts` ``` -import cdk = require('@aws-cdk/core'); -import s3 = require('@aws-cdk/aws-s3'); +import * as cdk from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; interface MultistackProps extends cdk.StackProps { encryptBucket?: boolean; @@ -383,7 +383,7 @@ File: `bin/multistack.ts` ``` #!/usr/bin/env node import 'source-map-support/register'; -import cdk = require('@aws-cdk/core'); +import * as cdk from '@aws-cdk/core'; import { MultistackStack } from '../lib/multistack-stack'; const app = new cdk.App(); @@ -577,4 +577,4 @@ To avoid charges for resources that you deployed, destroy the stack using the fo cdk destroy MyEastCdkStack ``` -The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket's contents, but not the bucket itself, using the AWS Management Console or the AWS CLI before destroying the stack\. +The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket's contents, but not the bucket itself, using the AWS Management Console or the AWS CLI before destroying the stack\. \ No newline at end of file diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 94369392..dc6aa7f3 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -241,7 +241,7 @@ The following example adds the tag key **StackType** with value **TheBest** to a #### [ TypeScript ] ``` -import { App, Stack, Tag } from require('@aws-cdk/core'); +import { App, Stack, Tag } from '@aws-cdk/core'; const app = new App(); const theBestStack = new Stack(app, 'MarketingSystem'); diff --git a/doc_source/testing.md b/doc_source/testing.md index 539c3e7d..19a50f12 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -24,8 +24,8 @@ npm install @aws-cdk/aws-sqs @aws-cdk/aws-cloudwatch Place the following code in `lib/dead-letter-queue.ts`: ``` -import cloudwatch = require('@aws-cdk/aws-cloudwatch'); -import sqs = require('@aws-cdk/aws-sqs'); +import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; +import * as sqs from '@aws-cdk/aws-sqs'; import { Construct, Duration } from '@aws-cdk/core'; export class DeadLetterQueue extends sqs.Queue { @@ -88,7 +88,7 @@ Add a snapshot test by placing the following code in `test/dead-letter-queue.tes import { SynthUtils } from '@aws-cdk/assert'; import { Stack } from '@aws-cdk/core'; -import dlq = require('../lib/dead-letter-queue'); +import * as dlq from '../lib/dead-letter-queue'; test('dlq creates an alarm', () => { const stack = new Stack(); @@ -224,7 +224,7 @@ Replace the code in `test/dead-letter-queue.test.ts` with the following\. import { Stack } from '@aws-cdk/core'; import '@aws-cdk/assert/jest'; -import dlq = require('../lib/dead-letter-queue'); +import * as dlq from '../lib/dead-letter-queue'; test('dlq creates an alarm', () => { const stack = new Stack(); @@ -351,4 +351,4 @@ Tests: 4 passed, 4 total Remember, your tests will live just as long as the code they test, and be read and modified just as often, so it pays to take a moment to consider how best to write them\. Don't copy and paste setup lines or common assertions, for example; refactor this logic into helper functions\. Use good names that reflect what each test actually tests\. -Don't assert too much in one test\. Preferably, a test should test one and only one behavior\. If you accidentally break that behavior, exactly one test should fail, and the name of the test should tell you exactly what failed\. This is more an ideal to be striven for, however; sometimes you will unavoidably \(or inadvertently\) write tests that test more than one behavior\. Snapshot tests are, for reasons we've already described, especially prone to this problem, so use them sparingly\. +Don't assert too much in one test\. Preferably, a test should test one and only one behavior\. If you accidentally break that behavior, exactly one test should fail, and the name of the test should tell you exactly what failed\. This is more an ideal to be striven for, however; sometimes you will unavoidably \(or inadvertently\) write tests that test more than one behavior\. Snapshot tests are, for reasons we've already described, especially prone to this problem, so use them sparingly\. \ No newline at end of file diff --git a/doc_source/tools.md b/doc_source/tools.md index 8246d0f6..65acf827 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -305,7 +305,7 @@ This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda fu 1. Add a Lambda reference to `lib/cdk-sam-example-stack.ts`: ``` - import lambda = require('@aws-cdk/aws-lambda'); + import * as lambda from '@aws-cdk/aws-lambda'; ``` 1. Replace the comment in `lib/cdk-sam-example-stack.ts` with the following Lambda function: diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index c1542136..1a67dd87 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -220,7 +220,7 @@ You can count the resources in your synthesized output using the following short // invoke with: node rescount.js // e.g. node rescount.js cdk.out/MyStack.template.json -const fs = require('fs'); +import * as fs from 'fs'; const path = process.argv[2]; if (path) fs.readFile(path, 'utf8', function(err, contents) { @@ -257,8 +257,8 @@ If you set a resource's removal policy to `DESTROY`, that resource will be delet #### [ TypeScript ] ``` -import cdk = require('@aws-cdk/core'); -import s3 = require('@aws-cdk/aws-s3') +import * as cdk from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; export class CdkTestStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 64054c19..003dd74a 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -19,8 +19,8 @@ You can include this bucket in your AWS CDK app, as shown in the following examp #### [ TypeScript ] ``` -import cdk = require("@aws-cdk/core"); -import fs = require("fs"); +import * as cdk from "@aws-cdk/core"; +import * as fs from "fs"; new cdk.CfnInclude(this, "ExistingInfrastructure", { template: JSON.parse(fs.readFileSync("my-template.json").toString()) From 4e0774a6545ffd2cba86023a6dc78ae5aed4fb75 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 8 Apr 2020 20:45:23 +0000 Subject: [PATCH 127/655] add Parameters topic, update .NET Core requirement --- doc_source/getting_started.md | 2 +- doc_source/index.md | 1 + doc_source/parameters.md | 177 +++++++++++++++++++++++++++++ doc_source/tokens.md | 2 +- doc_source/tools.md | 2 + doc_source/work-with-cdk-csharp.md | 2 +- 6 files changed, 183 insertions(+), 3 deletions(-) create mode 100644 doc_source/parameters.md diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 43f3589a..729e4f02 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -35,7 +35,7 @@ TypeScript >= 2\.7 #### [ C\# ] \.NET standard 2\.1 compatible implementation: -+ \.NET Core >= 3\.0 \(3\.1 upon its release\) ++ \.NET Core >= 3\.1 + \.NET Framework >= 4\.6\.1, or + Mono >= 5\.4 diff --git a/doc_source/index.md b/doc_source/index.md index cd44cde0..c9668fef 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -31,6 +31,7 @@ Amazon's trademarks and trade dress may not be used in + [Resources](resources.md) + [Identifiers](identifiers.md) + [Tokens](tokens.md) + + [Parameters](parameters.md) + [Tagging](tagging.md) + [Assets](assets.md) + [Permissions](permissions.md) diff --git a/doc_source/parameters.md b/doc_source/parameters.md new file mode 100644 index 00000000..3125b395 --- /dev/null +++ b/doc_source/parameters.md @@ -0,0 +1,177 @@ +# Parameters + +AWS CloudFormation templates can contain [parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html)—custom values that are supplied at deployment time and incorporated into the template\. Since the AWS CDK synthesizes AWS CloudFormation templates, it too offers support for deployment\-time parameters\. + +Using the AWS CDK, you can both define parameters, which can then be used in the properties of constructs you create, and you can also deploy stacks containing parameters\. + +When deploying the AWS CloudFormation template using the AWS CDK Toolkit, you provide the parameter values on the command line\. If you deploy the template through the AWS CloudFormation console, you are prompted for the parameter values\. + +In general, we recommend against using AWS CloudFormation parameters with the AWS CDK\. Parameter values are not available at synthesis time and thus cannot be easily used in other parts of your AWS CDK app, particularly for control flow\. + +**Note** +To do control flow with parameters, you can use [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnCondition.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnCondition.html) constructs, although this is awkward compared to native `if` statements\. + +Using parameters requires you to be mindful of how the code you're writing behaves at deployment time, as well as at synthesis time\. This makes it harder to understand and reason about your AWS CDK application, in many cases for little benefit\. + +It is better, again in general, to have your CDK app accept any necessary information from the user and use it directly to declare constructs in your CDK app\. An ideal AWS CDK\-generated AWS CloudFormation template is concrete, with no values remaining to be specified at deployment time\. + +There are, however, use cases to which AWS CloudFormation parameters are uniquely suited\. If you have separate teams defining and deploying infrastructure, for example, you can use parameters to make the generated templates more widely useful\. Additionally, the AWS CDK's support for AWS CloudFormation parameters lets you use the AWS CDK with AWS services that use AWS CloudFormation templates \(such as AWS Service Catalog\), which use parameters to configure the template being deployed\. + +## Defining Parameters + +Use the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnParameter.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnParameter.html) class to define a parameter\. You'll want to specify at least a type and a description for most parameters, though both are technically optional\. The description appears when the user is prompted to enter the parameter's value in the AWS CloudFormation console\. + +**Note** +We recommend defining parameters at the stack level to ensure that their logical ID does not change when you refactor your code\. + +------ +#### [ TypeScript ] + +``` +const uploadBucketName = new CfnParameter(this, "uploadBucketName", {type: "String", + description: "The name of the Amazon S3 bucket where uploaded files will be stored."}); +``` + +------ +#### [ Python ] + +``` +upload_bucket_name = CfnParameter(self, "uploadBucketName", type="String", + description="The name of the Amazon S3 bucket where uploaded files will be stored.") +``` + +------ +#### [ Java ] + +``` +CfnParameter uploadBucketName = CfnParameter.Builder.create(this, "uploadBucketName") + .type("String") + .description("The name of the Amazon S3 bucket where uploaded files will be stored") + .build(); +``` + +------ +#### [ C\# ] + +``` +var uploadBucketName = new CfnParameter(this, "uploadBucketName", new CfnParameterProps +{ + Type = "String", + Description = "The name of the Amazon S3 bucket where uploaded files will be stored" +}); +``` + +------ + +## Using Parameters + +A `CfnParameter` instance exposes its value to your AWS CDK app via a [token](tokens.md)\. Like all tokens, the parameter's token is resolved at synthesis time, but it resolves to a reference to the parameter defined in the AWS CloudFormation template, which will be resolved at deploy time, rather than to a concrete value\. + +You can retrieve the token as an instance of the `Token` class, or in string, string list, or numeric encoding, depending on the type of value required by the class or method you want to use the parameter with\. + +------ +#### [ TypeScript ] + + +| Property | Kind of value | +| --- |--- | +| value | Token class instance | +| valueAsList | The token represented as a string list | +| valueAsNumber | The token represented as a number | +| valueAsString | The token represented as a string | + +------ +#### [ Python ] + + +| Property | Kind of value | +| --- |--- | +| value | Token class instance | +| value\_as\_list | The token represented as a string list | +| value\_as\_number | The token represented as a number | +| value\_as\_string | The token represented as a string | + +------ +#### [ Java ] + + +| Property | Kind of value | +| --- |--- | +| getValue\(\) | Token class instance | +| getValueAsList\(\) | The token represented as a string list | +| getValueAsNumber\(\) | The token represented as a number | +| getValueAsString\(\) | The token represented as a string | + +------ +#### [ C\# ] + + +| Property | Kind of value | +| --- |--- | +| Value | Token class instance | +| ValueAsList | The token represented as a string list | +| ValueAsNumber | The token represented as a number | +| ValueAsString | The token represented as a string | + +------ + +For example, to use a parameter in a Bucket definition: + +------ +#### [ TypeScript ] + +``` +const bucket = new Bucket(this, "myBucket", + {bucketName: uploadBucketName.valueAsString}); +``` + +------ +#### [ Python ] + +``` +bucket = Bucket(self, "myBucket", + bucket_name=upload_bucket_name.value_as_string) +``` + +------ +#### [ Java ] + +``` +Bucket bucket = Bucket.Builder.create(this, "myBucket") + .bucketName(uploadBucketName.getValueAsString()) + .build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new Bucket(this, "myBucket") +{ + BucketName = uploadBucketName.ValueAsString +}; +``` + +------ + +## Deploying with Parameters + +A generated template containing parameters can be deployed in the usual way through the AWS CloudFormation console; you are prompted for the values of each parameter\. + +The AWS CDK Toolkit \(`cdk` command\-line tool\) also supports specifying parameters at deployment\. You may provide these on the command line following the `--parameters` flag\. You might deploy a stack that uses the `uploadBucketName` parameter like this\. + +``` +cdk deploy MyStack --parameters uploadBucketName=UploadBucket +``` + +To define multiple parameters, use multiple `--parameters` flags\. + +``` +cdk deploy MyStack --parameters uploadBucketName=UpBucket --parameters downloadBucketName=DownBucket +``` + +If you are deploying multiple stacks, you can specify a different value of each parameter for each stack by prefixing the name of the parameter with the stack name and a colon\. + +``` +cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket --parameters YourStack:uploadBucketName=UpBucket +``` \ No newline at end of file diff --git a/doc_source/tokens.md b/doc_source/tokens.md index 6407cd74..14487102 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -221,7 +221,7 @@ As with list tokens, you cannot modify the number value, as doing so is likely t ## Lazy Values -In addition to representing deploy\-time values, such as AWS CloudFormation attributes\), Tokens are also commonly used to represent synthesis\-time lazy values\. These are values for which the final value will be determined before synthesis has completed, just not at the point where the value is constructed\. Use tokens to pass a literal string or number value to another construct, while the actual value at synthesis time may depend on some calculation that has yet to occur\. +In addition to representing deploy\-time values, such as AWS CloudFormation [parameters](parameters.md), Tokens are also commonly used to represent synthesis\-time lazy values\. These are values for which the final value will be determined before synthesis has completed, just not at the point where the value is constructed\. Use tokens to pass a literal string or number value to another construct, while the actual value at synthesis time may depend on some calculation that has yet to occur\. You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.stringValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-string-valueproducer-options) \(Python: `Lazy.string_value`\) and [Lazy\.numberValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-number-valueproducer) \(Python: `Lazy.number_value`\. These methods accept an object whose `producer` property is a function that accepts a context argument and returns the final value when called\. diff --git a/doc_source/tools.md b/doc_source/tools.md index 65acf827..de201596 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -166,6 +166,8 @@ Options: autodetection. [boolean] [default: false] --notification-arns ARNs of SNS topics that CloudFormation will notify with stack related events [array] + --parameters Additional parameters passed to CloudFormation at deploy + time (STACK:KEY=VALUE) [array] [default: {}] --tags, -t Tags to add to the stack (KEY=VALUE) [array] --execute Whether to execute ChangeSet (--no-execute will NOT execute the ChangeSet) [boolean] [default: true] diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 8621711f..5dde34bd 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -11,7 +11,7 @@ We suggest using [Visual Studio 2019](https://visualstudio.microsoft.com/downloa To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. C\# AWS CDK applications require a \.NET Standard 2\.1 compatible implementation\. Suitable implementations include: -+ \.NET Core v3\.0 or later \(v3\.1 or later preferred\) ++ \.NET Core v3\.1 or later + \.NET Framework v4\.6\.1 or later + Mono v5\.4 or later on Linux or Mac OS X; [download here](https://www.mono-project.com/download/stable/) From 8baeadce6f2a8d069b09a20eb740cf09323e0069 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 14 Apr 2020 19:50:16 +0000 Subject: [PATCH 128/655] add JavaScript code snippets throughout --- doc_source/apps.md | 35 +++ doc_source/aspects.md | 41 +++- doc_source/assets.md | 138 ++++++++++++ doc_source/cfn_layer.md | 74 +++++++ doc_source/codepipeline_example.md | 204 ++++++++++++++++++ doc_source/constructs.md | 133 ++++++++++++ doc_source/context.md | 27 +++ doc_source/ecs_example.md | 72 ++++++- doc_source/environments.md | 37 +++- doc_source/get_context_var.md | 15 ++ doc_source/get_env_var.md | 15 +- doc_source/get_secrets_manager_value.md | 18 ++ doc_source/get_ssm_value.md | 26 +++ doc_source/getting_started.md | 103 ++++++++- doc_source/home.md | 33 ++- doc_source/how_to_set_cw_alarm.md | 37 ++++ doc_source/identifiers.md | 34 +++ doc_source/parameters.md | 35 ++- doc_source/permissions.md | 66 ++++++ doc_source/reference.md | 32 +-- doc_source/resources.md | 204 +++++++++++++++++- doc_source/serverless_example.md | 137 ++++++++++++ .../stack_how_to_create_multiple_stacks.md | 80 +++++++ doc_source/stacks.md | 49 +++++ doc_source/tagging.md | 72 +++++++ doc_source/tokens.md | 65 ++++++ doc_source/troubleshooting.md | 18 ++ doc_source/use_cfn_template.md | 19 ++ doc_source/work-with-cdk-javascript.md | 4 +- 29 files changed, 1769 insertions(+), 54 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index f58418f3..d319fb9c 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -17,6 +17,19 @@ class MyFirstStack extends Stack { } ``` +------ +#### [ JavaScript ] + +``` +class MyFirstStack extends Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket'); + } +} +``` + ------ #### [ Python ] @@ -74,6 +87,15 @@ new MyFirstStack(app, 'hello-cdk'); app.synth(); ``` +------ +#### [ JavaScript ] + +``` +const app = new App(); +new MyFirstStack(app, 'hello-cdk'); +app.synth(); +``` + ------ #### [ Python ] @@ -120,6 +142,19 @@ class MyApp extends App { new MyApp().synth(); ``` +------ +#### [ JavaScript ] + +``` +class MyApp extends App { + constructor() { + new MyFirstStack(this, 'hello-cdk'); + } +} + +new MyApp().synth(); +``` + ------ #### [ Python ] diff --git a/doc_source/aspects.md b/doc_source/aspects.md index 4f5a6182..b95bdf04 100644 --- a/doc_source/aspects.md +++ b/doc_source/aspects.md @@ -8,7 +8,14 @@ To apply an aspect to a construct and all constructs in the same scope, call [no #### [ TypeScript ] ``` -myConstruct.node.applyAspect(new SomeAspect(...)); +myConstruct.node.applyAspect(new SomeAspect(/*...*/)); +``` + +------ +#### [ JavaScript ] + +``` +myConstruct.node.applyAspect(new SomeAspect(/*...*/)); ``` ------ @@ -48,10 +55,15 @@ interface IAspect { visit(node: IConstruct): void;} ``` +------ +#### [ JavaScript ] + +JavaScript doesn't have interfaces as a language feature, so an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. + ------ #### [ Python ] - Python doesn't have interfaces as a language feature, so an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. +Python doesn't have interfaces as a language feature, so an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. ------ #### [ Java ] @@ -98,7 +110,30 @@ class BucketVersioningChecker implements IAspect { if (!node.versioningConfiguration || (!Tokenization.isResolvable(node.versioningConfiguration) && node.versioningConfiguration.status !== 'Enabled')) { - + node.node.addError('Bucket versioning is not enabled'); + } + } + } +} + +// Apply to the stack +stack.node.applyAspect(new BucketVersioningChecker()); +``` + +------ +#### [ JavaScript ] + +``` +class BucketVersioningChecker { + visit(node) { + // See that we're dealing with a CfnBucket + if (node instanceof s3.CfnBucket) { + + // Check for versioning property, exclude the case where the property + // can be a token (IResolvable). + if (!node.versioningConfiguration + || !Tokenization.isResolvable(node.versioningConfiguration) + && node.versioningConfiguration.status !== 'Enabled') { node.node.addError('Bucket versioning is not enabled'); } } diff --git a/doc_source/assets.md b/doc_source/assets.md index b7dd1119..80ba3d77 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -53,6 +53,23 @@ const fileAsset = new Asset(this, 'SampleSingleFileAsset', { }); ``` +------ +#### [ JavaScript ] + +``` +import { Asset } from '@aws-cdk/aws-s3-assets'; + +// Archived and uploaded to Amazon S3 as a .zip file +const directoryAsset = new Asset(this, "SampleZippedDirAsset", { + path: path.join(__dirname, "sample-asset-directory") +}); + +// Uploaded to Amazon S3 as-is +const fileAsset = new Asset(this, 'SampleSingleFileAsset', { + path: path.join(__dirname, 'file-asset.txt') +}); +``` + ------ #### [ Python ] @@ -154,6 +171,27 @@ export class HelloAssetStack extends cdk.Stack { } ``` +------ +#### [ JavaScript ] + +``` +import * as cdk from '@aws-cdk/core'; +import * as lambda from '@aws-cdk/aws-lambda'; +import * as path from 'path'; + +export class HelloAssetStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new lambda.Function(this, 'myLambdaFunction', { + code: lambda.Code.fromAsset(path.join(__dirname, 'handler')), + runtime: lambda.Runtime.PYTHON_3_6, + handler: 'index.lambda_handler' + }); + } +} +``` + ------ #### [ Python ] @@ -259,6 +297,29 @@ new lambda.Function(this, "myLambdaFunction", { }); ``` +------ +#### [ JavaScript ] + +``` +import { Asset } from '@aws-cdk/aws-s3-assets'; +import * as path from 'path'; + +const imageAsset = new Asset(this, "SampleAsset", { + path: path.join(__dirname, "images/my-image.png") +}); + +new lambda.Function(this, "myLambdaFunction", { + code: lambda.Code.asset(path.join(__dirname, "handler")), + runtime: lambda.Runtime.PYTHON_3_6, + handler: "index.lambda_handler", + environment: { + 'S3_BUCKET_NAME': imageAsset.s3BucketName, + 'S3_OBJECT_KEY': imageAsset.s3ObjectKey, + 'S3_URL': imageAsset.s3Url + } +}); +``` + ------ #### [ Python ] @@ -369,6 +430,21 @@ const group = new iam.Group(this, 'MyUserGroup'); asset.grantRead(group); ``` +------ +#### [ JavaScript ] + +``` +import { Asset } from '@aws-cdk/aws-s3-assets'; +import * as path from 'path'; + +const asset = new Asset(this, 'MyFile', { + path: path.join(__dirname, 'my-image.png') +}); + +const group = new iam.Group(this, 'MyUserGroup'); +asset.grantRead(group); +``` + ------ #### [ Python ] @@ -447,6 +523,17 @@ const asset = new DockerImageAsset(this, 'MyBuildImage', { }); ``` +------ +#### [ JavaScript ] + +``` +import { DockerImageAsset } from '@aws-cdk/aws-ecr-assets'; + +const asset = new DockerImageAsset(this, 'MyBuildImage', { + directory: path.join(__dirname, 'my-image') +}); +``` + ------ #### [ Python ] @@ -510,6 +597,23 @@ taskDefinition.addContainer("my-other-container", { }); ``` +------ +#### [ JavaScript ] + +``` +import * as ecs from '@aws-cdk/aws-ecs'; +import * as path from 'path'; + +const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { + memoryLimitMiB: 1024, + cpu: 512 +}); + +taskDefinition.addContainer("my-other-container", { + image: ecs.ContainerImage.fromAsset(path.join(__dirname, "..", "demo-image")) +}); +``` + ------ #### [ Python ] @@ -596,6 +700,28 @@ taskDefinition.addContainer("my-other-container", { }); ``` +------ +#### [ JavaScript ] + +``` +import * as ecs from '@aws-cdk/aws-ecs'; +import * as path from 'path'; +import { DockerImageAsset } from '@aws-cdk/aws-ecr-assets'; + +const asset = new DockerImageAsset(this, 'my-image', { + directory: path.join(__dirname, "..", "demo-image") +}); + +const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { + memoryLimitMiB: 1024, + cpu: 512 +}); + +taskDefinition.addContainer("my-other-container", { + image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri) +}); +``` + ------ #### [ Python ] @@ -684,6 +810,18 @@ const asset = new DockerImageAsset(this, 'MyBuildImage', { }); ``` +------ +#### [ JavaScript ] + +``` +const asset = new DockerImageAsset(this, 'MyBuildImage', { + directory: path.join(__dirname, 'my-image'), + buildArgs: { + HTTP_PROXY: 'http://10.20.30.2:1234' + } +}); +``` + ------ #### [ Python ] diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 5812785f..bafd18db 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -27,6 +27,20 @@ new s3.CfnBucket(this, 'MyBucket', { }); ``` +------ +#### [ JavaScript ] + +``` +new s3.CfnBucket(this, 'MyBucket', { + analyticsConfigurations: [ + { + id: 'Config' + // ... + } + ] +}); +``` + ------ #### [ Python ] @@ -86,6 +100,24 @@ new cdk.CfnResource(this, 'MyBucket', { }); ``` +------ +#### [ JavaScript ] + +``` +new cdk.CfnResource(this, 'MyBucket', { + type: 'AWS::S3::Bucket', + properties: { + // Note the PascalCase here! These are CloudFormation identifiers. + AnalyticsConfigurations: [ + { + Id: 'Config' + // ... + } + ] + } +}); +``` + ------ #### [ Python ] @@ -167,6 +199,22 @@ cfnBucket.analyticsConfiguration = [ ]; ``` +------ +#### [ JavaScript ] + +``` +// Get the AWS CloudFormation resource +const cfnBucket = bucket.node.defaultChild; + +// Change its properties +cfnBucket.analyticsConfiguration = [ + { + id: 'Config' + // ... + } +]; +``` + ------ #### [ Python ] @@ -226,6 +274,15 @@ cfnBucket.cfnOptions.metadata = { }; ``` +------ +#### [ JavaScript ] + +``` +cfnBucket.cfnOptions.metadata = { + MetadataKey: 'MetadataValue' +}; +``` + ------ #### [ Python ] @@ -279,6 +336,23 @@ cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); ``` +------ +#### [ JavaScript ] + +``` +// Get the AWS CloudFormation resource +const cfnBucket = bucket.node.defaultChild; + +// Use dot notation to address inside the resource template fragment +cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); +cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); + +// addPropertyOverride is a convenience function, which implies the +// path starts with "Properties." +cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); +cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); +``` + ------ #### [ Python ] diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index bd036665..ca33cc24 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -20,6 +20,18 @@ npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 ``` +------ +#### [ JavaScript ] + +``` +mkdir pipeline +cd pipeline +cdk init --language javascript +mkdir Lambda +npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild +npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 +``` + ------ #### [ Python ] @@ -136,6 +148,44 @@ export class LambdaStack extends Stack { } ``` +------ +#### [ JavaScript ] + +File: `lib/lambda-stack.js` + +``` +import * as codedeploy from '@aws-cdk/aws-codedeploy'; +import * as lambda from '@aws-cdk/aws-lambda'; +import { Stack } from '@aws-cdk/core'; + +export class LambdaStack extends Stack { + + + constructor(app, id, props) { + super(app, id, props); + + this.lambdaCode = lambda.Code.fromCfnParameters(); + + const func = new lambda.Function(this, 'Lambda', { + code: this.lambdaCode, + handler: 'index.handler', + runtime: lambda.Runtime.NODEJS_10_X + }); + + const version = func.addVersion(new Date().toISOString()); + const alias = new lambda.Alias(this, 'LambdaAlias', { + aliasName: 'Prod', + version + }); + + new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', { + alias, + deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE + }); + } +} +``` + ------ #### [ Python ] @@ -421,6 +471,133 @@ export class PipelineStack extends Stack { } ``` +------ +#### [ JavaScript ] + +File: `lib/pipeline-stack.js` + +``` +import * as codebuild from '@aws-cdk/aws-codebuild'; +import * as codecommit from '@aws-cdk/aws-codecommit'; +import * as codepipeline from '@aws-cdk/aws-codepipeline'; +import * as codepipeline_actions from '@aws-cdk/aws-codepipeline-actions'; + +import { Stack } from '@aws-cdk/core'; + + + +export class PipelineStack extends Stack { + constructor(app, id, props) { + super(app, id, props); + + const code = codecommit.Repository.fromRepositoryName(this, 'ImportedRepo', + 'NameOfYourCodeCommitRepository'); + + const cdkBuild = new codebuild.PipelineProject(this, 'CdkBuild', { + buildSpec: codebuild.BuildSpec.fromObject({ + version: '0.2', + phases: { + install: { + commands: 'npm install' + }, + build: { + commands: [ + 'npm run build', + 'npm run cdk synth -- -o dist' + ] + } + }, + artifacts: { + 'base-directory': 'dist', + files: [ + 'LambdaStack.template.json' + ] + } + }), + environment: { + buildImage: codebuild.LinuxBuildImage.STANDARD_2_0 + } + }); + const lambdaBuild = new codebuild.PipelineProject(this, 'LambdaBuild', { + buildSpec: codebuild.BuildSpec.fromObject({ + version: '0.2', + phases: { + install: { + commands: [ + 'cd lambda', + 'npm install' + ] + }, + build: { + commands: 'npm run build' + } + }, + artifacts: { + 'base-directory': 'lambda', + files: [ + 'index.js', + 'node_modules/**/*' + ] + } + }), + environment: { + buildImage: codebuild.LinuxBuildImage.STANDARD_2_0 + } + }); + + const sourceOutput = new codepipeline.Artifact(); + const cdkBuildOutput = new codepipeline.Artifact('CdkBuildOutput'); + const lambdaBuildOutput = new codepipeline.Artifact('LambdaBuildOutput'); + new codepipeline.Pipeline(this, 'Pipeline', { + stages: [ + { + stageName: 'Source', + actions: [ + new codepipeline_actions.CodeCommitSourceAction({ + actionName: 'CodeCommit_Source', + repository: code, + output: sourceOutput + }) + ] + }, + { + stageName: 'Build', + actions: [ + new codepipeline_actions.CodeBuildAction({ + actionName: 'Lambda_Build', + project: lambdaBuild, + input: sourceOutput, + outputs: [lambdaBuildOutput] + }), + new codepipeline_actions.CodeBuildAction({ + actionName: 'CDK_Build', + project: cdkBuild, + input: sourceOutput, + outputs: [cdkBuildOutput] + }) + ] + }, + { + stageName: 'Deploy', + actions: [ + new codepipeline_actions.CloudFormationCreateUpdateStackAction({ + actionName: 'Lambda_CFN_Deploy', + templatePath: cdkBuildOutput.atPath('LambdaStack.template.json'), + stackName: 'LambdaDeploymentStack', + adminPermissions: true, + parameterOverrides: { + ...props.lambdaCode.assign(lambdaBuildOutput.s3Location) + }, + extraInputs: [lambdaBuildOutput] + }) + ] + } + ] + }); + } +} +``` + ------ #### [ Python ] @@ -845,6 +1022,28 @@ new PipelineStack(app, 'PipelineDeployingLambdaStack', { app.synth(); ``` +------ +#### [ JavaScript ] + +File: `bin/pipeline.ts` + +``` +#!/usr/bin/env node + +import { App } from '@aws-cdk/core'; +import { LambdaStack } from '../lib/lambda-stack'; +import { PipelineStack } from '../lib/pipeline-stack'; + +const app = new App(); + +const lambdaStack = new LambdaStack(app, 'LambdaStack'); +new PipelineStack(app, 'PipelineDeployingLambdaStack', { + lambdaCode: lambdaStack.lambdaCode +}); + +app.synth(); +``` + ------ #### [ Python ] @@ -929,6 +1128,11 @@ The final steps are building the code and deploying the pipeline\. npm run build ``` +------ +#### [ JavaScript ] + +No build step is necessary\. + ------ #### [ Python ] diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 3a789b8d..73f7d841 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -58,6 +58,27 @@ const app = new App(); new HelloCdkStack(app, "HelloCdkStack"); ``` +------ +#### [ JavaScript ] + +``` +import { App, Stack } from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; + +class HelloCdkStack extends Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} + +const app = new App(); +new HelloCdkStack(app, "HelloCdkStack"); +``` + ------ #### [ Python ] @@ -131,6 +152,19 @@ class HelloCdkStack extends Stack { } ``` +------ +#### [ JavaScript ] + +``` +class HelloCdkStack extends Stack { + constructor(scope, id, props) { + super(scope, id, props); + + //... + } +} +``` + ------ #### [ Python ] @@ -191,6 +225,18 @@ new s3.Bucket(this, 'MyFirstBucket', { }); ``` +------ +#### [ JavaScript ] + +``` +import * as s3 from '@aws-cdk/aws-s3'; + +// "this" is HelloCdkStack +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true +}); +``` + ------ #### [ Python ] @@ -255,6 +301,16 @@ new s3.Bucket(this, 'MyEncryptedBucket', { }); ``` +------ +#### [ JavaScript ] + +``` +new s3.Bucket(this, 'MyEncryptedBucket', { + encryption: s3.BucketEncryption.KMS, + websiteIndexDocument: 'index.html' +}); +``` + ------ #### [ Python ] @@ -302,6 +358,15 @@ const dataScience = new iam.Group(this, 'data-science'); rawData.grantRead(dataScience); ``` +------ +#### [ JavaScript ] + +``` +const rawData = new s3.Bucket(this, 'raw-data'); +const dataScience = new iam.Group(this, 'data-science'); +rawData.grantRead(dataScience); +``` + ------ #### [ Python ] @@ -348,6 +413,21 @@ const createJobLambda = new lambda.Function(this, 'create-job', { }); ``` +------ +#### [ JavaScript ] + +``` +const jobsQueue = new sqs.Queue(this, 'jobs'); +const createJobLambda = new lambda.Function(this, 'create-job', { + runtime: lambda.Runtime.NODEJS_10_X, + handler: 'index.handler', + code: lambda.Code.fromAsset('./create-job-lambda-code'), + environment: { + QUEUE_URL: jobsQueue.queueUrl + } +}); +``` + ------ #### [ Python ] @@ -424,6 +504,21 @@ export class NotifyingBucket extends Construct { } ``` +------ +#### [ JavaScript ] + +``` +export class NotifyingBucket extends Construct { + constructor(scope, id, props = {}) { + super(scope, id); + const bucket = new s3.Bucket(this, 'bucket'); + const topic = new sns.Topic(this, 'topic'); + bucket.addObjectCreatedNotification(new s3notify.SnsDestination(topic), + { prefix: props.prefix }); + } +} +``` + ------ #### [ Python ] @@ -502,6 +597,13 @@ The `NotifyingBucket` constructors have signature compatible with the base `Cons new NotifyingBucket(this, 'MyNotifyingBucket'); ``` +------ +#### [ JavaScript ] + +``` +new NotifyingBucket(this, 'MyNotifyingBucket'); +``` + ------ #### [ Python ] @@ -534,6 +636,13 @@ Or you could use `props` \(in Java, an additional parameter\) to specify the pat new NotifyingBucket(this, 'MyNotifyingBucket', { prefix: 'images/' }); ``` +------ +#### [ JavaScript ] + +``` +new NotifyingBucket(this, 'MyNotifyingBucket', { prefix: 'images/'}); +``` + ------ #### [ Python ] @@ -578,6 +687,21 @@ export class NotifyingBucket extends Construct { } ``` +------ +#### [ JavaScript ] + +``` +export class NotifyingBucket extends Construct { + + constructor(scope, id, props) { + super(scope, id); + const bucket = new s3.Bucket(this, 'bucket'); + this.topic = new sns.Topic(this, 'topic'); + bucket.addObjectCreatedNotification(this.topic, { prefix: props.prefix }); + } +} +``` + ------ #### [ Python ] @@ -657,6 +781,15 @@ const images = new NotifyingBucket(this, 'Images'); images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); ``` +------ +#### [ JavaScript ] + +``` +const queue = new sqs.Queue(this, 'NewImagesQueue'); +const images = new NotifyingBucket(this, 'Images'); +images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); +``` + ------ #### [ Python ] diff --git a/doc_source/context.md b/doc_source/context.md index 49e7f317..c41c2fef 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -119,6 +119,33 @@ export class ExistsVpcStack extends cdk.Stack { } ``` +------ +#### [ JavaScript ] + +``` +import * as cdk from '@aws-cdk/core'; +import * as ec2 from '@aws-cdk/aws-ec2'; + +export class ExistsVpcStack extends cdk.Stack { + + constructor(scope, id, props) { + + super(scope, id, props); + + const vpcid = this.node.tryGetContext('vpcid'); + const vpc = ec2.Vpc.fromLookup(this, 'VPC', { + vpcId: vpcid + }); + + const pubsubnets = vpc.selectSubnets({ subnetType: ec2.SubnetType.PUBLIC }); + + new cdk.CfnOutput(this, 'publicsubnets', { + value: pubsubnets.subnetIds.toString() + }); + } +} +``` + ------ #### [ Python ] diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index c9d54dee..93743161 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -40,6 +40,15 @@ cd MyEcsConstruct cdk init --language typescript ``` +------ +#### [ JavaScript ] + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language javascript +``` + ------ #### [ Python ] @@ -85,6 +94,13 @@ npm run build cdk synth ``` +------ +#### [ JavaScript ] + +``` +cdk synth +``` + ------ #### [ Python ] @@ -137,6 +153,13 @@ Install the AWS construct library modules for Amazon EC2 and Amazon ECS\. npm install @aws-cdk/aws-ec2 @aws-cdk/aws-ecs @aws-cdk/aws-ecs-patterns ``` +------ +#### [ JavaScript ] + +``` +npm install @aws-cdk/aws-ec2 @aws-cdk/aws-ecs @aws-cdk/aws-ecs-patterns +``` + ------ #### [ Python ] @@ -193,6 +216,17 @@ import * as ecs from "@aws-cdk/aws-ecs"; import * as ecs_patterns from "@aws-cdk/aws-ecs-patterns"; ``` +------ +#### [ JavaScript ] + +File: `lib/my_ecs_construct-stack.js` + +``` +import * as ec2 from "@aws-cdk/aws-ec2"; +import * as ecs from "@aws-cdk/aws-ecs"; +import * as ecs_patterns from "@aws-cdk/aws-ecs-patterns"; +``` + ------ #### [ Python ] @@ -252,6 +286,29 @@ Replace the comment at the end of the constructor with the following code\. }); ``` +------ +#### [ JavaScript ] + +``` + const vpc = new ec2.Vpc(this, "MyVpc", { + maxAzs: 3 // Default is all AZs in region + }); + + const cluster = new ecs.Cluster(this, "MyCluster", { + vpc: vpc + }); + + // Create a load-balanced Fargate service and make it public + new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { + cluster: cluster, // Required + cpu: 512, // Default is 256 + desiredCount: 6, // Default is 1 + taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, + memoryLimitMiB: 2048, // Default is 512 + publicLoadBalancer: true // Default is false + }); +``` + ------ #### [ Python ] @@ -334,14 +391,21 @@ Save it and make sure it builds and creates a stack\. ``` npm run build -cdk deploy +cdk synth +``` + +------ +#### [ JavaScript ] + +``` +cdk synth ``` ------ #### [ Python ] ``` -cdk deploy +cdk synth ``` ------ @@ -349,7 +413,7 @@ cdk deploy ``` mvn compile -cdk deploy +cdk synth ``` **Note** @@ -360,7 +424,7 @@ Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. ``` dotnet build src -cdk deploy +cdk synth ``` **Note** diff --git a/doc_source/environments.md b/doc_source/environments.md index b86e726f..6f126ca8 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -22,6 +22,17 @@ new MyFirstStack(app, 'first-stack-us', { env: envUSA }); new MyFirstStack(app, 'first-stack-eu', { env: envEU }); ``` +------ +#### [ JavaScript ] + +``` +const envEU = { account: '2383838383', region: 'eu-west-1'}; +const envUSA = { account: '8373873873', region: 'us-west-2'}; + +new MyFirstStack(app, 'first-stack-us', { env: envUSA}); +new MyFirstStack(app, 'first-stack-eu', { env: envEU}); +``` + ------ #### [ Python ] @@ -109,6 +120,19 @@ new MyDevStack(app, 'dev', { }}); ``` +------ +#### [ JavaScript ] + +Access environment variables via the `process` object\. + +``` +new MyDevStack(app, 'dev', { + env: { + account: process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEFAULT_REGION + }}); +``` + ------ #### [ Python ] @@ -193,6 +217,17 @@ new MyDevStack(app, 'dev', { }}); ``` +------ +#### [ JavaScript ] + +``` +new MyDevStack(app, 'dev', { + env: { + account: process.env.CDK_DEPLOY_ACCOUNT || process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEPLOY_REGION || process.env.CDK_DEFAULT_REGION + }}); +``` + ------ #### [ Python ] @@ -275,7 +310,7 @@ cdk deploy "$@" ``` ------ -#### [ Windows ] +#### [ Windows ] ``` @echo off diff --git a/doc_source/get_context_var.md b/doc_source/get_context_var.md index eb0f9e30..81c3c5e7 100644 --- a/doc_source/get_context_var.md +++ b/doc_source/get_context_var.md @@ -27,6 +27,13 @@ To get the value of a context variable in your app, use code like the following const bucket_name = this.node.tryGetContext('bucket_name'); ``` +------ +#### [ JavaScript ] + +``` +const bucket_name = this.node.tryGetContext('bucket_name'); +``` + ------ #### [ Python ] @@ -60,6 +67,14 @@ const app = new cdk.App(); const bucket_name = app.node.tryGetContext('bucket_name') ``` +------ +#### [ JavaScript ] + +``` +const app = new cdk.App(); +const bucket_name = app.node.tryGetContext('bucket_name'); +``` + ------ #### [ Python ] diff --git a/doc_source/get_env_var.md b/doc_source/get_env_var.md index 3e2f5488..d55ff86d 100644 --- a/doc_source/get_env_var.md +++ b/doc_source/get_env_var.md @@ -7,10 +7,21 @@ To get the value of an environment variable, use code like the following\. This ``` // Sets bucket_name to undefined if environment variable not set -const bucket_name = process.env.MYBUCKET; +var bucket_name = process.env.MYBUCKET; // Sets bucket_name to a default if env var doesn't exist -const bucket_name = process.env.MYBUCKET || "DefaultName"; +var bucket_name = process.env.MYBUCKET || "DefaultName"; +``` + +------ +#### [ JavaScript ] + +``` +// Sets bucket_name to undefined if environment variable not set +var bucket_name = process.env.MYBUCKET; + +// Sets bucket_name to a default if env var doesn't exist +var bucket_name = process.env.MYBUCKET || "DefaultName"; ``` ------ diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index def4add7..38358943 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -20,6 +20,24 @@ export class SecretsManagerStack extends core.Stack { }); ``` +------ +#### [ JavaScript ] + +``` +import * as sm from "@aws-cdk/aws-secretsmanager"; + +export class SecretsManagerStack extends core.Stack { + constructor(scope: core.App, id: string, props?: core.StackProps) { + super(scope, id, props); + + const secret = sm.Secret.fromSecretAttributes(this, "ImportedSecret", { + secretArn: + "arn:aws:secretsmanager:::secret:-" + // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: + // encryptionKey: ... + }); +``` + ------ #### [ Python ] diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index f2fe3534..2cb65490 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -28,6 +28,23 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` +------ +#### [ JavaScript ] + +``` +import * as ssm from '@aws-cdk/aws-ssm'; + +// Get latest version or specified version of plain string attribute +const latestStringToken = ssm.StringParameter.valueForStringParameter( +this, 'my-plain-parameter-name'); // latest version +const versionOfStringToken = ssm.StringParameter.valueForStringParameter( +this, 'my-plain-parameter-name', 1); // version 1 + +// Get specified version of secure string attribute +const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( +this, 'my-secure-parameter-name', 1); // must specify version +``` + ------ #### [ Python ] @@ -96,6 +113,15 @@ import * as ssm from '@aws-cdk/aws-ssm'; const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` +------ +#### [ JavaScript ] + +``` +import * as ssm from '@aws-cdk/aws-ssm'; + +const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); +``` + ------ #### [ Python ] diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 729e4f02..770209f6 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -10,7 +10,7 @@ The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode ## Prerequisites -All CDK developers need to install [Node\.js](https://nodejs.org/en/download) \(>= 10\.3\.0\), even those working in languages other than TypeScript or JavaScript\. The AWS CDK Toolkit \(`cdk` command\-line tool\) and the AWS Construct Library are developed in TypeScript and run on Node\.js\. The bindings for other supported languages use this backend and toolset\. +All CDK developers need to install [Node\.js](https://nodejs.org/en/download) >= 10\.3\.0, even those working in languages other than TypeScript or JavaScript\. The AWS CDK Toolkit \(`cdk` command\-line tool\) and the AWS Construct Library are developed in TypeScript and run on Node\.js\. The bindings for other supported languages use this backend and toolset\. You must provide your credentials and an AWS Region to use the AWS CDK CLI, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. @@ -21,14 +21,19 @@ Other prerequisites depend on your development language, as follows\. TypeScript >= 2\.7 +------ +#### [ JavaScript ] + +none + ------ #### [ Python ] + Python >= 3\.6 ------ #### [ Java ] -+ Maven 3\.5\.4 or later and Java 8 -+ A Java IDE is preferred \(the examples in this guide may refer to Eclipse\)\. `cdk init` creates a Maven project; most IDEs can import this style of project\. Some IDEs may need to be configured to use Java 8 \(also known as 1\.8\)\. ++ Maven = 3\.5 and Java >= 8 ++ A Java IDE is preferred \(the examples in this guide may refer to Eclipse\)\. `cdk init` creates a Maven project, which most IDEs can import\. Some IDEs may need to be configured to use Java 8 \(also known as 1\.8\)\. + Set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine ------ @@ -68,6 +73,13 @@ If you get an error message that your language framework is out of date, use one npx npm-check-updates -u ``` +------ +#### [ JavaScript ] + +``` +npx npm-check-updates -u +``` + ------ #### [ Python ] @@ -111,6 +123,18 @@ new MyStack(app, 'MyStack', { }); ``` +------ +#### [ JavaScript ] + +``` +new MyStack(app, 'MyStack', { + env: { + region: 'REGION', + account: 'ACCOUNT' + } +}); +``` + ------ #### [ Python ] @@ -162,6 +186,18 @@ new MyStack(app, 'Stack-Three-W', { env: { account: 'THREE', region: 'us-west-2' new MyStack(app, 'Stack-Three-E', { env: { account: 'THREE', region: 'us-east-1' }}); ``` +------ +#### [ JavaScript ] + +``` +new MyStack(app, 'Stack-One-W', { env: { account: 'ONE', region: 'us-west-2' }}); +new MyStack(app, 'Stack-One-E', { env: { account: 'ONE', region: 'us-east-1' }}); +new MyStack(app, 'Stack-Two-W', { env: { account: 'TWO', region: 'us-west-2' }}); +new MyStack(app, 'Stack-Two-E', { env: { account: 'TWO', region: 'us-east-1' }}); +new MyStack(app, 'Stack-Three-W', { env: { account: 'THREE', region: 'us-west-2' }}); +new MyStack(app, 'Stack-Three-E', { env: { account: 'THREE', region: 'us-east-1' }}); +``` + ------ #### [ Python ] @@ -363,6 +399,13 @@ For Hello World, you can just use the default template\. cdk init --language typescript ``` +------ +#### [ JavaScript ] + +``` +cdk init --language javascript +``` + ------ #### [ Python ] @@ -415,6 +458,11 @@ Compile your program, as follows\. npm run build ``` +------ +#### [ JavaScript ] + +Nothing to compile\. + ------ #### [ Python ] @@ -470,6 +518,13 @@ Install the `@aws-cdk/aws-s3` package\. npm install @aws-cdk/aws-s3 ``` +------ +#### [ JavaScript ] + +``` +npm install @aws-cdk/aws-s3 +``` + ------ #### [ Python ] @@ -527,6 +582,26 @@ export class HelloCdkStack extends core.Stack { } ``` +------ +#### [ JavaScript ] + +In `lib/hello-cdk-stack.js`: + +``` +import * as core from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; + +export class HelloCdkStack extends core.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} +``` + ------ #### [ Python ] @@ -614,6 +689,11 @@ Compile your program, as follows\. npm run build ``` +------ +#### [ JavaScript ] + +Nothing to compile\. + ------ #### [ Python ] @@ -701,6 +781,18 @@ new s3.Bucket(this, 'MyFirstBucket', { }); ``` +------ +#### [ JavaScript ] + +Update `lib/hello-cdk-stack.js`\. + +``` +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true, + encryption: s3.BucketEncryption.KMS_MANAGED +}); +``` + ------ #### [ Python ] @@ -751,6 +843,11 @@ Compile your program, as follows\. npm run build ``` +------ +#### [ JavaScript ] + +Nothing to compile\. + ------ #### [ Python ] diff --git a/doc_source/home.md b/doc_source/home.md index 9c4f66bd..c370ac22 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -47,6 +47,35 @@ export class MyEcsConstructStack extends core.Stack { } ``` +------ +#### [ JavaScript ] + +``` +export class MyEcsConstructStack extends core.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const vpc = new ec2.Vpc(this, "MyVpc", { + maxAzs: 3 // Default is all AZs in region + }); + + const cluster = new ecs.Cluster(this, "MyCluster", { + vpc: vpc + }); + + // Create a load-balanced Fargate service and make it public + new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { + cluster: cluster, // Required + cpu: 512, // Default is 256 + desiredCount: 6, // Default is 1 + taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, + memoryLimitMiB: 2048, // Default is 512 + publicLoadBalancer: true // Default is false + }); + } +} +``` + ------ #### [ Python ] @@ -179,14 +208,14 @@ Other advantages of the AWS CDK include: ## Developing with the AWS CDK -Unless otherwise indicated, the code examples in this guide are in TypeScript\. To aid you in porting a TypeScript example to a supported programming language, see [Translating TypeScript AWS CDK Code to Other Languages ](multiple_languages.md)\. The AWS CDK also includes examples in the supported programming languages\. See [AWS CDK Examples](about_examples.md) for a list of the examples\. +Code snippets and longer examples are available in the AWS CDK's supported programming languages: TypeScript, JavaScript, Python, Java, and C\#\. See [AWS CDK Examples](about_examples.md) for a list of the examples\. The [AWS CDK Tools](tools.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. The [AWS Construct Library](constructs.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to create resources for an Amazon or AWS service\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. **Note** -There is no charge for using the AWS CDK, however you might incur AWS charges for creating or using AWS [chargeable resources](http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Pricing Calculator](https://calculator.aws/#/) to estimate charges for the use of various AWS resources\. +There is no charge for using the AWS CDK, but you might incur AWS charges for creating or using AWS [chargeable resources](http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Pricing Calculator](https://calculator.aws/#/) to estimate charges for the use of various AWS resources\. ## Contributing to the AWS CDK diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index 8c99bf63..176b7922 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -14,6 +14,18 @@ const alarm = new cloudwatch.Alarm(this, 'Alarm', { }); ``` +------ +#### [ JavaScript ] + +``` +const alarm = new cloudwatch.Alarm(this, 'Alarm', { + metric: metric, // see below + threshold: 100, + evaluationPeriods: 3, + datapointsToAlarm: 2 +}); +``` + ------ #### [ Python ] @@ -68,6 +80,17 @@ const metric = new cloudwatch.Metric({ }); ``` +------ +#### [ JavaScript ] + +``` +const metric = new cloudwatch.Metric({ + namespace: 'MyNamespace', + metricName: 'MyMetric', + dimensions: { MyDimension: 'MyDimensionValue' } +}); +``` + ------ #### [ Python ] @@ -124,6 +147,20 @@ Many AWS CDK packages contain functionality to enable setting an alarm based on }); ``` +------ +#### [ JavaScript ] + +``` + const qMetric = queue.metric("ApproximateNumberOfMessagesVisible"); + + new cloudwatch.Alarm(this, "Alarm", { + metric: qMetric, + threshold: 100, + evaluationPeriods: 3, + datapointsToAlarm: 2 + }); +``` + ------ #### [ Python ] diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index 96d183c4..54b59bd5 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -32,6 +32,26 @@ new MyStack(app, 'Stack1'); new MyStack(app, 'Stack2'); ``` +------ +#### [ JavaScript ] + +``` +import { App, Stack } from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; + +class MyStack extends Stack { + constructor(scope, id, props = {}) { + super(scope, id, props); + + new s3.Bucket(this, 'MyBucket'); + } +} + +const app = new App(); +new MyStack(app, 'Stack1'); +new MyStack(app, 'Stack2'); +``` + ------ #### [ Python ] @@ -131,6 +151,13 @@ You can access the path of any construct programmatically, as shown in the follo const path: string = myConstruct.node.path; ``` +------ +#### [ JavaScript ] + +``` +const path = myConstruct.node.path; +``` + ------ #### [ Python ] @@ -167,6 +194,13 @@ You can access the unique ID of any construct programmatically, as shown in the const uid: string = myConstruct.node.uniqueId; ``` +------ +#### [ JavaScript ] + +``` +const uid = myConstruct.node.uniqueId; +``` + ------ #### [ Python ] diff --git a/doc_source/parameters.md b/doc_source/parameters.md index 3125b395..bd0223a5 100644 --- a/doc_source/parameters.md +++ b/doc_source/parameters.md @@ -28,8 +28,18 @@ We recommend defining parameters at the stack level to ensure that their logical #### [ TypeScript ] ``` -const uploadBucketName = new CfnParameter(this, "uploadBucketName", {type: "String", - description: "The name of the Amazon S3 bucket where uploaded files will be stored."}); +const uploadBucketName = new CfnParameter(this, "uploadBucketName", { + type: "String", + description: "The name of the Amazon S3 bucket where uploaded files will be stored."}); +``` + +------ +#### [ JavaScript ] + +``` +const uploadBucketName = new CfnParameter(this, "uploadBucketName", { + type: "String", + description: "The name of the Amazon S3 bucket where uploaded files will be stored."}); ``` ------ @@ -73,6 +83,17 @@ You can retrieve the token as an instance of the `Token` class, or in string, st #### [ TypeScript ] +| Property | Kind of value | +| --- |--- | +| value | Token class instance | +| valueAsList | The token represented as a string list | +| valueAsNumber | The token represented as a number | +| valueAsString | The token represented as a string | + +------ +#### [ JavaScript ] + + | Property | Kind of value | | --- |--- | | value | Token class instance | @@ -122,7 +143,15 @@ For example, to use a parameter in a Bucket definition: ``` const bucket = new Bucket(this, "myBucket", - {bucketName: uploadBucketName.valueAsString}); + { bucketName: uploadBucketName.valueAsString}); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = new Bucket(this, "myBucket", + { bucketName: uploadBucketName.valueAsString}); ``` ------ diff --git a/doc_source/permissions.md b/doc_source/permissions.md index 1e623454..b4e01c75 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -47,6 +47,17 @@ const role = new iam.Role(this, 'Role', { }); ``` +------ +#### [ JavaScript ] + +``` +import * as iam from '@aws-cdk/aws-iam'; + +const role = new iam.Role(this, 'Role', { + assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com') // required +}); +``` + ------ #### [ Python ] @@ -99,6 +110,19 @@ role.addToPolicy(new iam.PolicyStatement({ }}})); ``` +------ +#### [ JavaScript ] + +``` +role.addToPolicy(new iam.PolicyStatement({ + effect: iam.Effect.DENY, + resources: [bucket.bucketArn, otherRole.roleArn], + actions: ['ec2:SomeAction', 's3:AnotherAction'], + conditions: { StringEquals: { + 'ec2:AuthorizedService': 'codebuild.amazonaws.com' +}}})); +``` + ------ #### [ Python ] @@ -169,6 +193,23 @@ const project = new codebuild.Project(this, 'Project', { }); ``` +------ +#### [ JavaScript ] + +``` +import * as codebuild from '@aws-cdk/aws-codebuild'; + +// imagine roleOrUndefined is a function that might return a Role object +// under some conditions, and undefined under other conditions +const someRole = roleOrUndefined(); + +const project = new codebuild.Project(this, 'Project', { + // if someRole is undefined, the Project creates a new default role, + // trusting the codebuild.amazonaws.com service principal + role: someRole +}); +``` + ------ #### [ Python ] @@ -237,6 +278,19 @@ project.addToRolePolicy(new iam.PolicyStatement({ })); ``` +------ +#### [ JavaScript ] + +``` +// project is imported into the CDK application +const project = codebuild.Project.fromProjectName(this, 'Project', 'ProjectName'); + +// project is imported, so project.role is undefined, and this call has no effect +project.addToRolePolicy(new iam.PolicyStatement({ + effect: iam.Effect.ALLOW // ... and so on defining the policy +})); +``` + ------ #### [ Python ] @@ -297,6 +351,18 @@ bucket.addToResourcePolicy(new iam.PolicyStatement({ })); ``` +------ +#### [ JavaScript ] + +``` +bucket.addToResourcePolicy(new iam.PolicyStatement({ + effect: iam.Effect.ALLOW, + actions: ['s3:SomeAction'], + resources: [bucket.bucketArn], + principals: [role] +})); +``` + ------ #### [ Python ] diff --git a/doc_source/reference.md b/doc_source/reference.md index 6ff3254c..f2ae5008 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -4,35 +4,9 @@ The [API Reference](https://docs.aws.amazon.com/cdk/api/latest) contains informa Each library contains information about how to use the library\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) library demonstrates how to set default encryption on an Amazon S3 bucket\. -## Versioning +## Versioning and Stability Model -Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs, are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. - -**Note that this compatibility promise does not apply to *Experimental* API's, see [AWS CDK Stability Index](#aws_construct_lib_versioning_stability) for more details.** - -## AWS CDK CLI Compatibility - -Following is the expected behavior of the CLI in relation to different versions of the framework libraries. - -- CLI versions are **always** compatible with framework libraries of a semantically **lower** or **equal** version number. This means that CLI upgardes are safe. -Note that `major` version exceptions still apply. That is, CDK CLI version 2.1.0 is not necessarily compatible with a framework library of version 1.56.0. - -- CLI versions are **not always** compatible with framework libraries of a semantically **higher** version number. This is determined by whether or not the `cloud-assembly-schema` version has changed. - - #### What is the cloud-assembly-schema? - - The AWS CDK API framework produces a *cloud-assembly* directory during `synthesis`. This assembly is then consumed by the CDK CLI in order to deploy it assembly to the cloud. - - In essence, this *cloud-assembly* acts as a protocol between the framework and the CLI, and as such, it is versioned. - - For more details, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/epolon/cli-framework-compatibility/packages/%40aws-cdk/cloud-assembly-schema#versioning). - - This means that you might see the following message when upgrading framework libraries: - - ```console - Cloud assembly schema version mismatch: Maximum schema version supported is 3.0.0, but found 4.0.0. - Please upgrade your CLI in order to interact with this app. - ``` +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs, which is described in the next section, are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. ### AWS CDK Stability Index @@ -47,7 +21,7 @@ CloudFormation Only These APIs are automatically built from the AWS CloudFormation resource specification and are subject to any changes introduced by AWS CloudFormation\. Experimental -The API is still under active development and subject to non\-backward\-compatible changes or removal in any future version\. Such changes will be announed under the **BREAKING\-CHANGES** section in our release notes. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. +The API is still under active development and subject to non\-backward\-compatible changes or removal in any future version\. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. Deprecated The API may emit warnings\. We do not guarantee backward compatibility\. diff --git a/doc_source/resources.md b/doc_source/resources.md index 5e7f237b..2376dc1d 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -15,6 +15,17 @@ new sqs.Queue(this, 'MyQueue', { }); ``` +------ +#### [ JavaScript ] + +``` +import * as sqs from '@aws-cdk/aws-sqs'; + +new sqs.Queue(this, 'MyQueue', { + encryption: sqs.QueueEncryption.KMS_MANAGED +}); +``` + ------ #### [ Python ] @@ -64,6 +75,16 @@ const queue = new sqs.Queue(this, 'MyQueue'); const url = queue.queueUrl; // => A string representing a deploy-time value ``` +------ +#### [ JavaScript ] + +``` +import * as sqs from '@aws-cdk/aws-sqs'; + +const queue = new sqs.Queue(this, 'MyQueue'); +const url = queue.queueUrl; // => A string representing a deploy-time value +``` + ------ #### [ Python ] @@ -115,6 +136,15 @@ const cluster = new ecs.Cluster(this, 'Cluster', { /* ... */ }); const service = new ecs.Ec2Service(this, 'Service', { cluster: cluster }); ``` +------ +#### [ JavaScript ] + +``` +const cluster = new ecs.Cluster(this, 'Cluster', { /* ... */}); + +const service = new ecs.Ec2Service(this, 'Service', { cluster: cluster}); +``` + ------ #### [ Python ] @@ -162,6 +192,21 @@ const stack2 = new StackThatExpectsABucket(app, 'Stack2', { }); ``` +------ +#### [ JavaScript ] + +``` +const prod = { account: '123456789012', region: 'us-east-1'}; + +const stack1 = new StackThatProvidesABucket(app, 'Stack1', { env: prod}); + +// stack2 will take a property { bucket: IBucket } +const stack2 = new StackThatExpectsABucket(app, 'Stack2', { + bucket: stack1.bucket, + env: prod +}); +``` + ------ #### [ Python ] @@ -235,6 +280,15 @@ const bucket = new s3.Bucket(this, 'MyBucket', { }); ``` +------ +#### [ JavaScript ] + +``` +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket-name' +}); +``` + ------ #### [ Python ] @@ -272,6 +326,15 @@ const bucket = new s3.Bucket(this, 'MyBucket', { }); ``` +------ +#### [ JavaScript ] + +``` +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: core.PhysicalName.GENERATE_IF_NEEDED +}); +``` + ------ #### [ Python ] @@ -313,6 +376,15 @@ lambdaFunc.functionArn securityGroup.groupArn ``` +------ +#### [ JavaScript ] + +``` +bucket.bucketName +lambdaFunc.functionArn +securityGroup.groupArn +``` + ------ #### [ Python ] @@ -353,13 +425,27 @@ The following example shows how to pass a generated bucket name to an AWS Lambda const bucket = new s3.Bucket(this, 'Bucket'); new lambda.Function(this, 'MyLambda', { - /* ... */, + /* ... */ environment: { BUCKET_NAME: bucket.bucketName, }, }); ``` +------ +#### [ JavaScript ] + +``` +const bucket = new s3.Bucket(this, 'Bucket'); + +new lambda.Function(this, 'MyLambda', { + /* ... */ + environment: { + BUCKET_NAME: bucket.bucketName + } +}); +``` + ------ #### [ Python ] @@ -420,6 +506,22 @@ ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { }); ``` +------ +#### [ JavaScript ] + +``` +// Construct a resource (bucket) just by its name (must be same account) +s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); + +// Construct a resource (bucket) by its full ARN (can be cross account) +s3.Bucket.fromArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); + +// Construct a resource by giving attribute(s) (complex resources) +ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { + vpcId: 'vpc-1234567890abcde' +}); +``` + ------ #### [ Python ] @@ -482,6 +584,15 @@ ec2.Vpc.fromLookup(this, 'DefaultVpc', { }); ``` +------ +#### [ JavaScript ] + +``` +ec2.Vpc.fromLookup(this, 'DefaultVpc', { + isDefault: true +}); +``` + ------ #### [ Python ] @@ -517,7 +628,14 @@ You can use the `tags` property to query by tag\. Tags may be added to the VPC a ``` ec2.Vpc.fromLookup(this, 'PublicVpc', {tags: {'aws-cdk:subnet-type': "Public"}}); -}); +``` + +------ +#### [ JavaScript ] + +``` +ec2.Vpc.fromLookup(this, 'PublicVpc', +{ tags: { 'aws-cdk:subnet-type': "Public" }}); ``` ------ @@ -566,6 +684,15 @@ if (bucket.grantReadWrite(func).success) { } ``` +------ +#### [ JavaScript ] + +``` +if (bucket.grantReadWrite(func).success) { + // ... +} +``` + ------ #### [ Python ] @@ -608,6 +735,13 @@ The following example shows how to grant a Lambda function access to the Amazon table.grant(func, 'dynamodb:CreateBackup'); ``` +------ +#### [ JavaScript ] + +``` +table.grant(func, 'dynamodb:CreateBackup'); +``` + ------ #### [ Python ] @@ -663,6 +797,28 @@ metric.createAlarm(this, 'TooManyMessagesAlarm', { }); ``` +------ +#### [ JavaScript ] + +``` +import * as cw from '@aws-cdk/aws-cloudwatch'; +import * as sqs from '@aws-cdk/aws-sqs'; +import { Duration } from '@aws-cdk/core'; + +const queue = new sqs.Queue(this, 'MyQueue'); + +const metric = queue.metricApproximateNumberOfMessagesNotVisible({ + label: 'Messages Visible (Approx)', + period: Duration.minutes(5) + // ... +}); +metric.createAlarm(this, 'TooManyMessagesAlarm', { + comparisonOperator: cw.ComparisonOperator.GREATER_THAN_THRESHOLD, + threshold: 100 + // ... +}); +``` + ------ #### [ Python ] @@ -670,7 +826,7 @@ metric.createAlarm(this, 'TooManyMessagesAlarm', { import aws_cdk.aws_cloudwatch as cw import aws_cdk.aws_sqs as sqs from aws_cdk.core import Duration - + queue = sqs.Queue(self, "MyQueue") metric = queue.metric_approximate_number_of_messages_not_visible( label="Messages Visible (Approx)", @@ -753,12 +909,28 @@ You enable data to flow on a given network path by using `allow` methods\. The f import * as asg from '@aws-cdk/aws-autoscaling'; import * as ec2 from '@aws-cdk/aws-ec2'; -const fleet1: asg.AutoScalingGroup = /* ... */ +const fleet1: asg.AutoScalingGroup = asg.AutoScalingGroup(/* ... */); // Allow surfing the (secure) web fleet1.connections.allowTo(new ec2.Peer.anyIpv4(), new ec2.Port({ fromPort: 443, toPort: 443 })); -const fleet2: asg.AutoScalingGroup = /* ... */; +const fleet2: asg.AutoScalingGroup = asg.AutoScalingGroup(/* ... */); +fleet1.connections.allowFrom(fleet2, ec2.Port.AllTraffic()); +``` + +------ +#### [ JavaScript ] + +``` +import * as asg from '@aws-cdk/aws-autoscaling'; +import * as ec2 from '@aws-cdk/aws-ec2'; + +const fleet1 = asg.AutoScalingGroup(); + +// Allow surfing the (secure) web +fleet1.connections.allowTo(new ec2.Peer.anyIpv4(), new ec2.Port({ fromPort: 443, toPort: 443})); + +const fleet2 = asg.AutoScalingGroup(); fleet1.connections.allowFrom(fleet2, ec2.Port.AllTraffic()); ``` @@ -831,6 +1003,15 @@ listener.connections.allowDefaultPortFromAnyIpv4('Allow public access'); fleet.connections.allowToDefaultPort(rdsDatabase, 'Fleet can access database'); ``` +------ +#### [ JavaScript ] + +``` +listener.connections.allowDefaultPortFromAnyIpv4('Allow public access'); + +fleet.connections.allowToDefaultPort(rdsDatabase, 'Fleet can access database'); +``` + ------ #### [ Python ] @@ -870,13 +1051,24 @@ The following example shows how to trigger a Lambda function when an object is a #### [ TypeScript ] ``` -import * s3nots from '@aws-cdk/aws-s3-notifications'; +import * as s3nots from '@aws-cdk/aws-s3-notifications'; const handler = new lambda.Function(this, 'Handler', { /*…*/ }); const bucket = new s3.Bucket(this, 'Bucket'); bucket.addObjectCreatedNotification(new s3nots.LambdaDestination(handler)); ``` +------ +#### [ JavaScript ] + +``` +import * as s3nots from '@aws-cdk/aws-s3-notifications'; + +const handler = new lambda.Function(this, 'Handler', { /*…*/}); +const bucket = new s3.Bucket(this, 'Bucket'); +bucket.addObjectCreatedNotification(new s3nots.LambdaDestination(handler)); +``` + ------ #### [ Python ] diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index c58cc8cf..c5d6267d 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -35,6 +35,15 @@ cd MyWidgetService cdk init --language typescript ``` +------ +#### [ JavaScript ] + +``` +mkdir MyWidgetService +cd MyWidgetService +cdk init --language javascript +``` + ------ #### [ Python ] @@ -77,6 +86,11 @@ The important files in the blank project are as follows\. \(We will also be addi + `bin/my_widget_service.ts` – Main entry point for the application + `lib/my_widget_service-stack.ts` – Defines the widget service stack +------ +#### [ JavaScript ] ++ `bin/my_widget_service.js` – Main entry point for the application ++ `lib/my_widget_service-stack.js` – Defines the widget service stack + ------ #### [ Python ] + `app.py` – Main entry point for the application @@ -104,6 +118,13 @@ npm run build cdk synth ``` +------ +#### [ JavaScript ] + +``` +cdk synth +``` + ------ #### [ Python ] @@ -208,6 +229,13 @@ npm run build cdk synth ``` +------ +#### [ JavaScript ] + +``` +cdk synth +``` + ------ #### [ Python ] @@ -250,6 +278,13 @@ Add the API Gateway, Lambda, and Amazon S3 packages to the app\. npm install @aws-cdk/aws-apigateway @aws-cdk/aws-lambda @aws-cdk/aws-s3 ``` +------ +#### [ JavaScript ] + +``` +npm install @aws-cdk/aws-apigateway @aws-cdk/aws-lambda @aws-cdk/aws-s3 +``` + ------ #### [ Python ] @@ -329,6 +364,48 @@ export class WidgetService extends core.Construct { } ``` +------ +#### [ JavaScript ] + +File: `lib/widget_service.js` + +``` +import * as core from "@aws-cdk/core"; +import * as apigateway from "@aws-cdk/aws-apigateway"; +import * as lambda from "@aws-cdk/aws-lambda"; +import * as s3 from "@aws-cdk/aws-s3"; + +export class WidgetService extends core.Construct { + constructor(scope: core.Construct, id: string) { + super(scope, id); + + const bucket = new s3.Bucket(this, "WidgetStore"); + + const handler = new lambda.Function(this, "WidgetHandler", { + runtime: lambda.Runtime.NODEJS_10_X, // So we can use async in widget.js + code: lambda.Code.asset("resources"), + handler: "widgets.main", + environment: { + BUCKET: bucket.bucketName + } + }); + + bucket.grantReadWrite(handler); // was: handler.role); + + const api = new apigateway.RestApi(this, "widgets-api", { + restApiName: "Widget Service", + description: "This service serves widgets." + }); + + const getWidgetsIntegration = new apigateway.LambdaIntegration(handler, { + requestTemplates: { "application/json": '{ "statusCode": "200" }' } + }); + + api.root.addMethod("GET", getWidgetsIntegration); // GET / + } +} +``` + ------ #### [ Python ] @@ -484,6 +561,13 @@ npm run build cdk synth ``` +------ +#### [ JavaScript ] + +``` +cdk synth +``` + ------ #### [ Python ] @@ -536,6 +620,23 @@ Replace the comment in the constructor with the following line of code\. new widget_service.WidgetService(this, 'Widgets'); ``` +------ +#### [ JavaScript ] + +File: `lib/my_widget_service-stack.js` + +Add the following line of code after the existing `import` statement\. + +``` +import * as widget_service from '../lib/widget_service'; +``` + +Replace the comment in the constructor with the following line of code\. + +``` + new widget_service.WidgetService(this, 'Widgets'); +``` + ------ #### [ Python ] @@ -587,6 +688,13 @@ npm run build cdk synth ``` +------ +#### [ JavaScript ] + +``` +cdk synth +``` + ------ #### [ Python ] @@ -794,6 +902,28 @@ File: `lib/widget_service.ts` widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} ``` +------ +#### [ JavaScript ] + +File: `lib/widget_service.js` + +``` + const widget = api.root.addResource("{id}"); + + // Add new widget to bucket with: POST /{id} + const postWidgetIntegration = new apigateway.LambdaIntegration(handler); + + // Get a specific widget from bucket with: GET /{id} + const getWidgetIntegration = new apigateway.LambdaIntegration(handler); + + // Remove a specific widget from the bucket with: DELETE /{id} + const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); + + widget.addMethod("POST", postWidgetIntegration); // POST /{id} + widget.addMethod("GET", getWidgetIntegration); // GET /{id} + widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} +``` + ------ #### [ Python ] @@ -870,6 +1000,13 @@ npm run build cdk deploy ``` +------ +#### [ JavaScript ] + +``` +cdk deploy +``` + ------ #### [ Python ] diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index cffce5de..ad5c20e0 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -19,6 +19,15 @@ cd multistack cdk init --language=typescript ``` +------ +#### [ JavaScript ] + +``` +mkdir multistack +cd multistack +cdk init --language=javascript +``` + ------ #### [ Python ] @@ -63,6 +72,13 @@ Finally, install the `core` and `s3` AWS Construct Library modules\. We use thes npm install @aws-cdk/core @aws-cdk/aws-s3 ``` +------ +#### [ JavaScript ] + +``` +npm install @aws-cdk/core @aws-cdk/aws-s3 +``` + ------ #### [ Python ] @@ -124,6 +140,11 @@ export class MultistackStack extends cdk.Stack { } ``` +------ +#### [ JavaScript ] + +JavaScript does not have an interface feature, so we don't need to make any changes\. + ------ #### [ Python ] @@ -249,6 +270,36 @@ export class MultistackStack extends cdk.Stack { } ``` +------ +#### [ JavaScript ] + +File: `lib/multistack-stack.js` + +``` +import * as cdk from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; + +export class MultistackStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + // Add a Boolean property "encryptBucket" to the stack constructor. + // If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. + // Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). + if (props && props.encryptBucket) { + new s3.Bucket(this, "MyGroovyBucket", { + encryption: s3.BucketEncryption.KMS_MANAGED, + removalPolicy: cdk.RemovalPolicy.DESTROY + }); + } else { + new s3.Bucket(this, "MyGroovyBucket", { + removalPolicy: cdk.RemovalPolicy.DESTROY }); + } + } +} +>>> +``` + ------ #### [ Python ] @@ -399,6 +450,30 @@ new MultistackStack(app, "MyEastCdkStack", { }); ``` +------ +#### [ JavaScript ] + +File: `bin/multistack.js` + +``` +#!/usr/bin/env node +import 'source-map-support/register'; +import * as cdk from '@aws-cdk/core'; +import { MultistackStack } from '../lib/multistack-stack'; + +const app = new cdk.App(); + +new MultistackStack(app, "MyWestCdkStack", { + env: { region: "us-west-1" }, + encryptBucket: false +}); + +new MultistackStack(app, "MyEastCdkStack", { + env: { region: "us-east-1" }, + encryptBucket: true +}); +``` + ------ #### [ Python ] @@ -505,6 +580,11 @@ Now you can deploy stacks from the app\. First, build the project, if necessary\ npm run build ``` +------ +#### [ JavaScript ] + +No build step is necessary\. + ------ #### [ Python ] diff --git a/doc_source/stacks.md b/doc_source/stacks.md index 233796a0..83062504 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -20,6 +20,18 @@ new MySecondStack(app, 'stack2'); app.synth(); ``` +------ +#### [ JavaScript ] + +``` +const app = new App(); + +new MyFirstStack(app, 'stack1'); +new MySecondStack(app, 'stack2'); + +app.synth(); +``` + ------ #### [ Python ] @@ -114,6 +126,36 @@ new MyService(app, "prod", { prod: true }); app.synth(); ``` +------ +#### [ JavaScript ] + +``` +import { App, Construct, Stack } from "@aws-cdk/core"; + +// imagine these stacks declare a bunch of related resources +class ControlPlane extends Stack {} +class DataPlane extends Stack {} +class Monitoring extends Stack {} + +class MyService extends Construct { + + constructor(scope, id, props) { + + super(scope, id); + + // we might use the prod argument to change how the service is configured + new ControlPlane(this, "cp"); + new DataPlane(this, "data"); + new Monitoring(this, "mon"); } +} + +const app = new App(); +new MyService(app, "beta"); +new MyService(app, "prod", { prod: true}); + +app.synth(); +``` + ------ #### [ Python ] @@ -268,6 +310,13 @@ The physical names of the AWS CloudFormation stacks are automatically determined new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name' }); ``` +------ +#### [ JavaScript ] + +``` +new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name'}); +``` + ------ #### [ Python ] diff --git a/doc_source/tagging.md b/doc_source/tagging.md index dc6aa7f3..a7f11b04 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -16,6 +16,13 @@ Let's look at a couple of examples\. The following example applies the tag **key Tag.add(myConstruct, 'key', 'value'); ``` +------ +#### [ JavaScript ] + +``` +Tag.add(myConstruct, 'key', 'value'); +``` + ------ #### [ Python ] @@ -48,6 +55,13 @@ The following example deletes the tag **key** from a construct\. Tag.remove(my_construct, 'key'); ``` +------ +#### [ JavaScript ] + +``` +Tag.remove(my_construct, 'key'); +``` + ------ #### [ Python ] @@ -84,6 +98,15 @@ Tag.add(myConstruct, 'key', 'value', { }); ``` +------ +#### [ JavaScript ] + +``` +Tag.add(myConstruct, 'key', 'value', { + priority: 300 +}); +``` + ------ #### [ Python ] @@ -126,6 +149,18 @@ Tag.add(myConstruct, 'tagname', 'value', { }); ``` +------ +#### [ JavaScript ] + +``` +Tag.add(myConstruct, 'tagname', 'value', { + applyToLaunchedInstances: false, + includeResourceTypes: ['AWS::Xxx::Yyy'], + excludeResourceTypes: ['AWS::Xxx::Zzz'], + priority: 100 +}); +``` + ------ #### [ Python ] @@ -191,6 +226,17 @@ Tag.remove(myConstruct, 'tagname', { }); ``` +------ +#### [ JavaScript ] + +``` +Tag.remove(myConstruct, 'tagname', { + includeResourceTypes: ['AWS::Xxx::Yyy'], + excludeResourceTypes: ['AWS::Xxx::Zzz'], + priority: 200 +}); +``` + ------ #### [ Python ] @@ -255,6 +301,24 @@ Tag.remove(theBestStack, 'StackType', { }); ``` +------ +#### [ JavaScript ] + +``` +import { App, Stack, Tag } from '@aws-cdk/core'; + +const app = new App(); +const theBestStack = new Stack(app, 'MarketingSystem'); + +// Add a tag to all constructs in the stack +Tag.add(theBestStack, 'StackType', 'TheBest'); + +// Remove the tag from all resources except subnet resources +Tag.remove(theBestStack, 'StackType', { + excludeResourceTypes: ['AWS::EC2::Subnet'] +}); +``` + ------ #### [ Python ] @@ -319,6 +383,14 @@ Tag.add(theBestStack, 'StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet']}); ``` +------ +#### [ JavaScript ] + +``` +Tag.add(theBestStack, 'StackType', 'TheBest', + { includeResourceTypes: ['AWS::EC2::Subnet']}); +``` + ------ #### [ Python ] diff --git a/doc_source/tokens.md b/doc_source/tokens.md index 14487102..130125cb 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -24,6 +24,20 @@ const fn = new lambda.Function(stack, 'MyLambda', { }); ``` +------ +#### [ JavaScript ] + +``` +const bucket = new s3.Bucket(this, 'MyBucket'); + +const fn = new lambda.Function(stack, 'MyLambda', { + // ... + environment: { + BUCKET_NAME: bucket.bucketName + } +}); +``` + ------ #### [ Python ] @@ -94,6 +108,15 @@ if (!Token.isUnresolved(name) && name.length > 10) { } ``` +------ +#### [ JavaScript ] + +``` +if (!Token.isUnresolved(name) && name.length > 10) { + throw new Error(`Maximum length for name is 10 characters`); +} +``` + ------ #### [ Python ] @@ -142,6 +165,13 @@ They can be passed around like regular strings, and can be concatenated, as show const functionName = bucket.bucketName + 'Function'; ``` +------ +#### [ JavaScript ] + +``` +const functionName = bucket.bucketName + 'Function'; +``` + ------ #### [ Python ] @@ -174,6 +204,13 @@ You can also use string interpolation, if your language supports it, as shown in const functionName = `${bucket.bucketName}Function`; ``` +------ +#### [ JavaScript ] + +``` +const functionName = `${bucket.bucketName}Function`; +``` + ------ #### [ Python ] @@ -245,6 +282,24 @@ new AutoScalingGroup(this, 'Group', { actualValue = 10; ``` +------ +#### [ JavaScript ] + +``` +let actualValue; + +new AutoScalingGroup(this, 'Group', { + desiredCapacity: Lazy.numberValue({ + produce(context) { + return actualValue; + } + }) +}); + +// At some later point +actualValue = 10; +``` + ------ #### [ Python ] @@ -330,6 +385,16 @@ const stack = Stack.of(this); }); ``` +------ +#### [ JavaScript ] + +``` +const stack = Stack.of(this); +const str = stack.toJsonString({ + value: bucket.bucketName +}); +``` + ------ #### [ Python ] diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 1a67dd87..8773abef 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -271,6 +271,24 @@ export class CdkTestStack extends cdk.Stack { } ``` +------ +#### [ JavaScript ] + +``` +import * as cdk from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; + +export class CdkTestStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const bucket = new s3.Bucket(this, 'Bucket', { + removalPolicy: cdk.RemovalPolicy.DESTROY + }); + } +} +``` + ------ #### [ Python ] diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 003dd74a..b066ca89 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -27,6 +27,18 @@ new cdk.CfnInclude(this, "ExistingInfrastructure", { }); ``` +------ +#### [ JavaScript ] + +``` +import * as cdk from "@aws-cdk/core"; +import * as fs from "fs"; + +new cdk.CfnInclude(this, "ExistingInfrastructure", { + template: JSON.parse(fs.readFileSync("my-template.json").toString()) +}); +``` + ------ #### [ Python ] @@ -78,6 +90,13 @@ Then to access an attribute of the resource, such as the bucket's ARN: const bucketArn = cdk.Fn.getAtt("S3Bucket", "Arn"); ``` +------ +#### [ JavaScript ] + +``` +const bucketArn = cdk.Fn.getAtt("S3Bucket", "Arn"); +``` + ------ #### [ Python ] diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 34c256e5..c40fc51d 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -136,7 +136,9 @@ interface myFuncProps { JavaScript does not have an interface feature, so once you've removed the type annotations, delete the interface declarations as well\. -Knowing how to identify and remove type annotations and interface definitions goes a long way toward adapting short TypeScript snippets to JavaScript\. But it may be impractical to convert longer TypeScript examples in this fashion, since they are more likely to use TypeScript features you're not familiar with\. For these situations, we recommend [Babel](https://babeljs.io/) with the [TypeScript plug\-in](https://babeljs.io/docs/en/babel-plugin-transform-typescript)\. Babel won't complain if code uses an undefined variable, for example, as `tsc` would\. If it is syntactically valid, then with few exceptions, Babel can translate it to JavaScript\. This makes Babel particularly valuable for converting snippets that may not be runnable in on their own\. +Finally, TypeScript supports the access modifiers `public`, `protected`, and `private` for members of classes\. All class members in JavaScript are public\. Simply remove these modifiers wherever you see them\. + +Knowing how to identify and remove these three TypeScript features goes a long way toward adapting short TypeScript snippets to JavaScript\. But it may be impractical to convert longer TypeScript examples in this fashion, since they are more likely to use TypeScript features you're not familiar with\. For these situations, we recommend [Babel](https://babeljs.io/) with the [TypeScript plug\-in](https://babeljs.io/docs/en/babel-plugin-transform-typescript)\. Babel won't complain if code uses an undefined variable, for example, as `tsc` would\. If it is syntactically valid, then with few exceptions, Babel can translate it to JavaScript\. This makes Babel particularly valuable for converting snippets that may not be runnable in on their own\. ## Migrating to TypeScript From e3a16b48477e635e4d1b5e6d14f5f8cc7a4eae9d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 16 Apr 2020 03:46:00 +0000 Subject: [PATCH 129/655] removal policies, nested stacks, more on TS to JS, code tweaks --- doc_source/resources.md | 152 +++++++++++++++++++++++++++++++++- doc_source/stacks.md | 15 +++- doc_source/troubleshooting.md | 2 +- 3 files changed, 166 insertions(+), 3 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index 2376dc1d..73db65df 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1106,4 +1106,154 @@ var bucket = new s3.Bucket(this, "Bucket"); bucket.AddObjectCreatedNotification(new s3_not.LambdaDestination(handler)); ``` ------- \ No newline at end of file +------ + +## Removal Policies + +Resources that maintain persistent data, such as databases and Amazon S3 buckets, have a *removal policy* that indicates whether to delete persistent object when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the AWS CDK `core` module\. + + +| Value | Meaning | +| --- |--- | +| RemovalPolicy\.RETAIN | Keep the contents of the resource when destroying the stack \(default\)\. The resource is orphaned from the stack; if you attempt to re\-deploy the stack, you will receive an error message because the resource already exists\. | +| RemovalPolicy\.DESTROY | The resource will be destroyed along with the stack\. | + +AWS CloudFormation does not remove Amazon S3 buckets that contain files even if their removal policy is set to `DESTROY`\. Attempting to do so is a AWS CloudFormation error\. Delete the files from the bucket before destroying the stack\. You can automate this using a custom resource; see the third\-party construct [https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda](https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda) for an example\. + +Following is an example of creating an Amazon S3 bucket with `RemovalPolicy.DESTROY`\. + +------ +#### [ TypeScript ] + +``` +import * as cdk from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; + +export class CdkTestStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const bucket = new s3.Bucket(this, 'Bucket', { + removalPolicy: cdk.RemovalPolicy.DESTROY, + }); + } +} +``` + +------ +#### [ JavaScript ] + +``` +import * as cdk from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; + +export class CdkTestStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const bucket = new s3.Bucket(this, 'Bucket', { + removalPolicy: cdk.RemovalPolicy.DESTROY + }); + } +} +``` + +------ +#### [ Python ] + +``` +import aws_cdk.core as cdk +import aws_cdk.aws_s3 as s3 + +class CdkTestStack(cdk.stack): + def __init__(self, scope: cdk.Construct, id: str, **kwargs): + super().__init__(scope, id, **kwargs) + + bucket = s3.Bucket(self, "Bucket", + removal_policy=cdk.RemovalPolicy.DESTROY) +``` + +------ +#### [ Java ] + +``` +software.amazon.awscdk.core.*; +import software.amazon.awscdk.services.s3.*; + +public class CdkTestStack extends Stack { + public CdkTestStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public CdkTestStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + Bucket.Builder.create(this, "Bucket") + .removalPolicy(RemovalPolicy.DESTROY).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +public CdkTestStack(Construct scope, string id, IStackProps props) : base(scope, id, props) +{ + new Bucket(this, "Bucket", new BucketProps { + RemovalPolicy = RemovalPolicy.DESTROY + }); +} +``` + +------ + +You can also apply a removal policy directly to the underlying AWS CloudFormation resource via the `applyRemovalPolicy()` method\. + +------ +#### [ TypeScript ] + +``` +const resource = bucket.node.findChild('Resource') as cdk.CfnResource; +resource.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY); +``` + +------ +#### [ JavaScript ] + +``` +const resource = bucket.node.findChild('Resource') as cdk.CfnResource; +resource.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY); +``` + +------ +#### [ Python ] + +``` +resource = bucket.node.find_child('Resource') +resource.apply_removal_policy(cdk.RemovalPolicy.DESTROY); +``` + +------ +#### [ Java ] + +``` +CfnResource resource = (CfnResource)bucket.node.findChild("Resource"); +resource.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY); +``` + +------ +#### [ C\# ] + +``` +var resource = (CfnResource)bucket.node.findChild('Resource'); +resource.ApplyRemovalPolicy(cdk.RemovalPolicy.DESTROY); +``` + +------ + +**Note** +The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. \ No newline at end of file diff --git a/doc_source/stacks.md b/doc_source/stacks.md index 83062504..522a71dc 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -356,4 +356,17 @@ The [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack + `stack.availabilityZones` \(Python: `availability_zones`\) – Returns the set of Availability Zones available in the environment in which this stack is deployed\. For environment\-agnostic stacks, this always returns an array with two Availability Zones, but for environment\-specific stacks, the AWS CDK queries the environment and returns the exact set of Availability Zones available in the region you specified\. + `stack.parseArn(arn)` and `stack.formatArn(comps)` \(Python: `parse_arn`, `format_arn`\) – Can be used to work with Amazon Resource Names \(ARNs\)\. + `stack.toJsonString(obj)` \(Python: `to_json_string`\) – Can be used to format an arbitrary object as a JSON string that can be embedded in an AWS CloudFormation template\. The object can include tokens, attributes, and references, which are only resolved during deployment\. -+ `stack.templateOptions` \(Python: `template_options`\) – Enables you to specify AWS CloudFormation template options, such as Transform, Description, and Metadata, for your stack\. \ No newline at end of file ++ `stack.templateOptions` \(Python: `template_options`\) – Enables you to specify AWS CloudFormation template options, such as Transform, Description, and Metadata, for your stack\. + +## Nested Stacks + +The [NestedStack](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudformation.NestedStack.html) construct offers a way around the AWS CloudFormation 200\-resource limit for stacks\. A nested stack counts as only one resource in the stack that contains it, but can itself contain up to 200 resources, including additional nested stacks\. + +The scope of a nested stack must be a `Stack` or `NestedStack` construct\. The nested stack needn't be declared lexically inside its parent stack; it is necessary only to pass the parent stack as the first parameter \(`scope`\) when instantiating the nested stack\. Aside from this restriction, defining constructs in a nested stack works exactly the same as in an ordinary stack\. + +At synthesis time, the nested stack is synthesized to its own AWS CloudFormation template, which is uploaded to the AWS CDK staging bucket at deployment\. Nested stacks are bound to their parent stack and are not treated as independent deployment artifacts; they are not listed by `cdk list` nor can they be deployed by `cdk deploy`\. + + References between parent stacks and nested stacks are automatically translated to stack parameters and outputs in the generated AWS CloudFormation templates\. + +**Warning** +Changes in security posture are not displayed before deployment for nested stacks\. This information is displayed only for top\-level stacks\. \ No newline at end of file diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 8773abef..07ef5dc1 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -232,7 +232,7 @@ if (path) fs.readFile(path, 'utf8', function(err, contents) { As your stack's resource count approaches 200, consider re\-architecting to reduce the number of resources your stack contains, for example by combining some Lambda functions, or to break it up into multiple stacks\. The CDK supports [references between stacks](https://docs.aws.amazon.com/cdk/latest/guide/resources.html#resource_stack), so it is straightforward to separate your app's functionality into different stacks in whatever way makes the most sense to you\. **Note** -AWS CloudFormation experts often suggest the use of nested stacks as a solution to the 200 resource limit\. The AWS CDK supports this approach via the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudformation.NestedStack.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudformation.NestedStack.html) construct\. +AWS CloudFormation experts often suggest the use of nested stacks as a solution to the 200 resource limit\. The AWS CDK supports this approach via the [`NestedStack`](stacks.md#stack_nesting) construct\. \([back to list](#troubleshooting_top)\) From 5bc9d45bafba56f9c31ef374c7092154f2703847 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 16 Apr 2020 16:49:45 +0000 Subject: [PATCH 130/655] improve RETAIN explanation --- doc_source/resources.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index 73db65df..8321c2ed 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1110,12 +1110,12 @@ bucket.AddObjectCreatedNotification(new s3_not.LambdaDestination(handler)); ## Removal Policies -Resources that maintain persistent data, such as databases and Amazon S3 buckets, have a *removal policy* that indicates whether to delete persistent object when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the AWS CDK `core` module\. +Resources that maintain persistent data, such as databases and Amazon S3 buckets, have a *removal policy* that indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the AWS CDK `core` module\. | Value | Meaning | | --- |--- | -| RemovalPolicy\.RETAIN | Keep the contents of the resource when destroying the stack \(default\)\. The resource is orphaned from the stack; if you attempt to re\-deploy the stack, you will receive an error message because the resource already exists\. | +| RemovalPolicy\.RETAIN | Keep the contents of the resource when destroying the stack \(default\)\. The resource is orphaned from the stack and must be deleted manually\. If you attempt to re\-deploy the stack while the resource still exists, you will receive an error message due to a name conflict\. | | RemovalPolicy\.DESTROY | The resource will be destroyed along with the stack\. | AWS CloudFormation does not remove Amazon S3 buckets that contain files even if their removal policy is set to `DESTROY`\. Attempting to do so is a AWS CloudFormation error\. Delete the files from the bucket before destroying the stack\. You can automate this using a custom resource; see the third\-party construct [https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda](https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda) for an example\. From 43915700e6503f8806df49453356822841800f95 Mon Sep 17 00:00:00 2001 From: Hitendra Nishar Date: Thu, 16 Apr 2020 16:07:47 -0400 Subject: [PATCH 131/655] Update version reporting to include AWS Solutions Konstruk modules --- doc_source/tools.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/tools.md b/doc_source/tools.md index de201596..67cf2fdb 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -263,7 +263,7 @@ The setting can also be configured in the `cdk.json` file\. To gain insight into how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. -The AWS CDK reports the name and version of `npm` modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. +The AWS CDK reports the name and version of AWS CDK and AWS Solutions Konstruk `npm` modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. The `AWS::CDK::Metadata` resource looks like the following\. @@ -271,7 +271,7 @@ The `AWS::CDK::Metadata` resource looks like the following\. CDKMetadata: Type: "AWS::CDK::Metadata" Properties: - Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,lodash=4.17.10" + Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,@aws-solutions-konstruk/aws-apigateway-lambda=0.8.0" ``` ### Opting Out from Version Reporting From 76cb625382909da5738cc87567c982e8a5950df3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 17 Apr 2020 16:13:19 +0000 Subject: [PATCH 132/655] improve wording around version reporting --- doc_source/tools.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/doc_source/tools.md b/doc_source/tools.md index 67cf2fdb..049ab294 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -263,7 +263,10 @@ The setting can also be configured in the `cdk.json` file\. To gain insight into how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. -The AWS CDK reports the name and version of AWS CDK and AWS Solutions Konstruk `npm` modules that are loaded into the application at synthesis time, unless their `package.json` file contains the `"private": true` attribute\. +By default, the AWS CDK reports the name and version of the following NPM modules that are loaded at synthesis time: ++ AWS CDK core module ++ AWS Construct Library modules ++ AWS Solutions Konstruk module The `AWS::CDK::Metadata` resource looks like the following\. From 0a72e6d583d3018c5a3e2b9d66d87627fa05be26 Mon Sep 17 00:00:00 2001 From: Arturo Romero Date: Sat, 18 Apr 2020 13:32:01 -0700 Subject: [PATCH 133/655] Update codepipeline_example.md Fixes JS examples --- doc_source/codepipeline_example.md | 42 ++++++++++++++++-------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index ca33cc24..0a6abe76 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -29,7 +29,7 @@ cd pipeline cdk init --language javascript mkdir Lambda npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild -npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 +npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 @aws-cdk/aws-codepipeline ``` ------ @@ -154,11 +154,11 @@ export class LambdaStack extends Stack { File: `lib/lambda-stack.js` ``` -import * as codedeploy from '@aws-cdk/aws-codedeploy'; -import * as lambda from '@aws-cdk/aws-lambda'; -import { Stack } from '@aws-cdk/core'; +const codedeploy = require("@aws-cdk/aws-codedeploy"); +const lambda = require("@aws-cdk/aws-lambda"); +const { Stack } = require("@aws-cdk/core"); -export class LambdaStack extends Stack { +class LambdaStack extends Stack { constructor(app, id, props) { @@ -184,6 +184,8 @@ export class LambdaStack extends Stack { }); } } + +exports.LambdaStack = LambdaStack; ``` ------ @@ -477,16 +479,15 @@ export class PipelineStack extends Stack { File: `lib/pipeline-stack.js` ``` -import * as codebuild from '@aws-cdk/aws-codebuild'; -import * as codecommit from '@aws-cdk/aws-codecommit'; -import * as codepipeline from '@aws-cdk/aws-codepipeline'; -import * as codepipeline_actions from '@aws-cdk/aws-codepipeline-actions'; - -import { Stack } from '@aws-cdk/core'; +const codebuild = require("@aws-cdk/aws-codebuild"); +const codecommit = require("@aws-cdk/aws-codecommit"); +const codepipeline = require("@aws-cdk/aws-codepipeline"); +const codepipeline_actions = require("@aws-cdk/aws-codepipeline-actions"); +const { Stack } = require("@aws-cdk/core"); -export class PipelineStack extends Stack { +class PipelineStack extends Stack { constructor(app, id, props) { super(app, id, props); @@ -596,6 +597,8 @@ export class PipelineStack extends Stack { }); } } + +exports.PipelineStack = PipelineStack; ``` ------ @@ -1030,18 +1033,19 @@ File: `bin/pipeline.ts` ``` #!/usr/bin/env node -import { App } from '@aws-cdk/core'; -import { LambdaStack } from '../lib/lambda-stack'; -import { PipelineStack } from '../lib/pipeline-stack'; +const { App } = require("@aws-cdk/core"); +const { LambdaStack } = require("../lib/lambda-stack"); +const { PipelineStack } = require("../lib/pipeline-stack"); const app = new App(); -const lambdaStack = new LambdaStack(app, 'LambdaStack'); -new PipelineStack(app, 'PipelineDeployingLambdaStack', { - lambdaCode: lambdaStack.lambdaCode +const lambdaStack = new LambdaStack(app, "LambdaStack"); +new PipelineStack(app, "PipelineDeployingLambdaStack", { + lambdaCode: lambdaStack.lambdaCode, }); app.synth(); + ``` ------ @@ -1178,4 +1182,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` \ No newline at end of file +``` From f03f4b17750f98d1b5697ded46658cd152f166d5 Mon Sep 17 00:00:00 2001 From: Polonsky Date: Mon, 20 Apr 2020 12:29:59 +0300 Subject: [PATCH 134/655] cli compat section --- doc_source/reference.md | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/doc_source/reference.md b/doc_source/reference.md index f2ae5008..6ff3254c 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -4,9 +4,35 @@ The [API Reference](https://docs.aws.amazon.com/cdk/api/latest) contains informa Each library contains information about how to use the library\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) library demonstrates how to set default encryption on an Amazon S3 bucket\. -## Versioning and Stability Model +## Versioning -Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs, which is described in the next section, are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs, are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. + +**Note that this compatibility promise does not apply to *Experimental* API's, see [AWS CDK Stability Index](#aws_construct_lib_versioning_stability) for more details.** + +## AWS CDK CLI Compatibility + +Following is the expected behavior of the CLI in relation to different versions of the framework libraries. + +- CLI versions are **always** compatible with framework libraries of a semantically **lower** or **equal** version number. This means that CLI upgardes are safe. +Note that `major` version exceptions still apply. That is, CDK CLI version 2.1.0 is not necessarily compatible with a framework library of version 1.56.0. + +- CLI versions are **not always** compatible with framework libraries of a semantically **higher** version number. This is determined by whether or not the `cloud-assembly-schema` version has changed. + + #### What is the cloud-assembly-schema? + + The AWS CDK API framework produces a *cloud-assembly* directory during `synthesis`. This assembly is then consumed by the CDK CLI in order to deploy it assembly to the cloud. + + In essence, this *cloud-assembly* acts as a protocol between the framework and the CLI, and as such, it is versioned. + + For more details, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/epolon/cli-framework-compatibility/packages/%40aws-cdk/cloud-assembly-schema#versioning). + + This means that you might see the following message when upgrading framework libraries: + + ```console + Cloud assembly schema version mismatch: Maximum schema version supported is 3.0.0, but found 4.0.0. + Please upgrade your CLI in order to interact with this app. + ``` ### AWS CDK Stability Index @@ -21,7 +47,7 @@ CloudFormation Only These APIs are automatically built from the AWS CloudFormation resource specification and are subject to any changes introduced by AWS CloudFormation\. Experimental -The API is still under active development and subject to non\-backward\-compatible changes or removal in any future version\. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. +The API is still under active development and subject to non\-backward\-compatible changes or removal in any future version\. Such changes will be announed under the **BREAKING\-CHANGES** section in our release notes. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. Deprecated The API may emit warnings\. We do not guarantee backward compatibility\. From 952415ac352433a3abf1e72310593f5b41357390 Mon Sep 17 00:00:00 2001 From: Polonsky Date: Mon, 20 Apr 2020 12:37:38 +0300 Subject: [PATCH 135/655] fix link to cloud-assembly-schema and error message --- doc_source/reference.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/reference.md b/doc_source/reference.md index 6ff3254c..e417627a 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -25,13 +25,13 @@ Note that `major` version exceptions still apply. That is, CDK CLI version 2.1.0 In essence, this *cloud-assembly* acts as a protocol between the framework and the CLI, and as such, it is versioned. - For more details, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/epolon/cli-framework-compatibility/packages/%40aws-cdk/cloud-assembly-schema#versioning). + For more details, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/cloud-assembly-schema#versioning). This means that you might see the following message when upgrading framework libraries: ```console - Cloud assembly schema version mismatch: Maximum schema version supported is 3.0.0, but found 4.0.0. - Please upgrade your CLI in order to interact with this app. + Cloud assembly schema version mismatch: Maximum schema version supported is 2.0.0, but found 3.0.0. + Please upgrade your CLI in order to interact with this app. ``` ### AWS CDK Stability Index From 1937ce3adc9a09523e8420b286690cb168f0f341 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 20 Apr 2020 16:25:57 +0000 Subject: [PATCH 136/655] versioning updates --- doc_source/reference.md | 45 ++++++++++++------------------ doc_source/work-with-cdk-csharp.md | 4 +-- doc_source/work-with-cdk-java.md | 2 +- 3 files changed, 21 insertions(+), 30 deletions(-) diff --git a/doc_source/reference.md b/doc_source/reference.md index e417627a..f6198908 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -6,53 +6,44 @@ Each library contains information about how to use the library\. For example, th ## Versioning -Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs, are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. -**Note that this compatibility promise does not apply to *Experimental* API's, see [AWS CDK Stability Index](#aws_construct_lib_versioning_stability) for more details.** +**Note** +This compatibility promise does not apply to APIs designated as experimental\. See [AWS CDK Stability Index](#aws_construct_lib_stability) for more details\. -## AWS CDK CLI Compatibility +### AWS CDK Toolkit \(CLI\) Compatibility -Following is the expected behavior of the CLI in relation to different versions of the framework libraries. +The AWS CDK Toolkit \(that is, the `cli` command line command\) is *always* compatible with construct libraries of a semantically *lower* or *equal* version number\. It is, therefore, always safe to upgrade the AWS CDK Toolkit within the same major version\. -- CLI versions are **always** compatible with framework libraries of a semantically **lower** or **equal** version number. This means that CLI upgardes are safe. -Note that `major` version exceptions still apply. That is, CDK CLI version 2.1.0 is not necessarily compatible with a framework library of version 1.56.0. +The AWS CDK Toolkit may be, but is *not always*, compatible with construct libraries of a semantically *higher* version, depending on whether the same cloud assembly schema version is employed by the two components\. The AWS CDK framework generates a cloud assembly during synthesis; the AWS CDK Toolkit consumes it for deployment\. The schema that defines the format of the cloud assembly is strictly specified and versioned\. AWS construct libraries using a given cloud assembly schema version are compatible with AWS CDK toolkit versions using that schema version or later, which may include releases of the AWS CDK Toolkit *older than* a given construct library release\. -- CLI versions are **not always** compatible with framework libraries of a semantically **higher** version number. This is determined by whether or not the `cloud-assembly-schema` version has changed. +When the cloud assembly version required by the construct library is not compatible with the version supported by the AWS CDK Toolkit, you receive an error message like this one\. - #### What is the cloud-assembly-schema? +``` +Cloud assembly schema version mismatch: Maximum schema version supported is 3.0.0, but found 4.0.0. + Please upgrade your CLI in order to interact with this app. +``` - The AWS CDK API framework produces a *cloud-assembly* directory during `synthesis`. This assembly is then consumed by the CDK CLI in order to deploy it assembly to the cloud. +**Note** +For more details on the cloud assembly schema, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/cloud-assembly-schema#versioning)\. - In essence, this *cloud-assembly* acts as a protocol between the framework and the CLI, and as such, it is versioned. +### AWS CDK Stability Index - For more details, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/cloud-assembly-schema#versioning). - - This means that you might see the following message when upgrading framework libraries: - - ```console - Cloud assembly schema version mismatch: Maximum schema version supported is 2.0.0, but found 3.0.0. - Please upgrade your CLI in order to interact with this app. - ``` - -### AWS CDK Stability Index - -However, certain APIs do not adhere to the semantic versioning model\. The AWS CDK team has added a stability index to help developers determine which APIs deviate from the semantic versioning model\. - -There are three levels of stability in the AWS CDK Construct Library: +Certain APIs do not adhere to the semantic versioning model\. There are three levels of stability in the AWS Construct Library, which define the level of semantic versioning that applies to each module\. Stable The API is subject to the semantic versioning model\. We will not introduce non\-backward\-compatible changes or remove the API in a subsequent patch or feature release\. CloudFormation Only -These APIs are automatically built from the AWS CloudFormation resource specification and are subject to any changes introduced by AWS CloudFormation\. +These APIs are automatically built from the AWS CloudFormation resource specification and are subject only to changes introduced by AWS CloudFormation\. Experimental -The API is still under active development and subject to non\-backward\-compatible changes or removal in any future version\. Such changes will be announed under the **BREAKING\-CHANGES** section in our release notes. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. +The API is still under active development and subject to non\-backward\-compatible changes or removal in any future version\. Such changes are announced in the AWS CDK release notes under *BREAKING CHANGES*\. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. Deprecated The API may emit warnings\. We do not guarantee backward compatibility\. -Experimental and stable modules receive the same level of support from AWS\. The only difference is that we might change experimental APIs within a major version\. Although we don't recommend using experimental APIs in production, we vet them the same way as we vet stable APIs before we include them in an AWS CDK release\. +Experimental and stable modules receive the same level of support from AWS\. The only difference is that we might change experimental APIs within a major version\. Although we don't recommend using experimental APIs in production, we vet them the same way as we vet stable APIs before we include them in a release\. ### Identifying the Support Level of an API diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 5dde34bd..835a8073 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -47,7 +47,7 @@ NuGet has four standard, mostly\-equivalent interfaces; you can use the one that Visual Studio's NuGet tools are accessible from **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution**\. Use the **Browse** tab to find the AWS Construct Library packages you want to install\. You can choose the desired version, including pre\-release versions \(mark the **Include prerelease** checkbox\) and add them to any of the open projects\. **Note** -All AWS Construct Library modules deemed "experimental" \(see [Versioning and Stability Model](reference.md#versioning)\) are flagged as pre\-release in NuGet\. +All AWS Construct Library modules deemed "experimental" \(see [Versioning](reference.md#versioning)\) are flagged as pre\-release in NuGet\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/visual-studio-nuget.png) @@ -73,7 +73,7 @@ You may issue the command from another directory by including the path to the pr dotnet add src/PROJECT-DIR package Amazon.CDK.AWS.S3 ``` -To install a specific version of a package, include the `-v` flag and the desired version\. AWS Construct Library modules that are deemed "experimental" \(see [Versioning and Stability Model](reference.md#versioning)\) are flagged as pre\-release in NuGet, and must be installed using an explicit version number\. +To install a specific version of a package, include the `-v` flag and the desired version\. AWS Construct Library modules that are deemed "experimental" \(see [Versioning](reference.md#versioning)\) are flagged as pre\-release in NuGet, and must be installed using an explicit version number\. ``` dotnet add package Amazon.CDK.AWS.S3 -v VERSION-NUMBER diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index c046b665..8e8b0d3e 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -71,7 +71,7 @@ If you are not using an IDE, or just want full control over the versions of your ``` -The version specifier `[1.0,2.0)` in this example indicates that the latest version between 1\.0 \(inclusive\) and 2\.0 \(exclusive\) will be installed\. Since the AWS CDK uses semantic versioning for stable AWS Construct Library modules, \(see [Versioning and Stability Model](reference.md#versioning)\), this ensures that only newer versions without breaking API changes will be installed\. +The version specifier `[1.0,2.0)` in this example indicates that the latest version between 1\.0 \(inclusive\) and 2\.0 \(exclusive\) will be installed\. Since the AWS CDK uses semantic versioning for stable AWS Construct Library modules, \(see [Versioning](reference.md#versioning)\), this ensures that only newer versions without breaking API changes will be installed\. Maven automatically downloads a version of your dependencies that will match the requirements in `pom.xml`, if necessary, the next time you build your project\. From a74a55bc85e42897abdbab633d048d911b1e5170 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 22 Apr 2020 23:42:23 +0000 Subject: [PATCH 137/655] redo JavaScript snippets with Node-compatible import/export --- doc_source/apps.md | 29 ++-- doc_source/aspects.md | 12 +- doc_source/assets.md | 32 ++-- doc_source/cfn_layer.md | 18 +-- doc_source/codepipeline_example.md | 147 +++++++++--------- doc_source/constructs.md | 20 ++- doc_source/context.md | 22 ++- doc_source/ecs_example.md | 6 +- doc_source/environments.md | 39 +++-- doc_source/get_secrets_manager_value.md | 10 +- doc_source/get_ssm_value.md | 10 +- doc_source/getting_started.md | 30 ++-- doc_source/home.md | 32 ++-- doc_source/how_to_set_cw_alarm.md | 2 +- doc_source/identifiers.md | 4 +- doc_source/parameters.md | 2 +- doc_source/permissions.md | 14 +- doc_source/resources.md | 70 +++++---- doc_source/serverless_example.md | 20 +-- .../stack_how_to_create_multiple_stacks.md | 64 +++++--- doc_source/stacks.md | 14 +- doc_source/tagging.md | 4 +- doc_source/tokens.md | 16 +- doc_source/troubleshooting.md | 12 +- doc_source/use_cfn_template.md | 4 +- 25 files changed, 342 insertions(+), 291 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index d319fb9c..734dc099 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -21,12 +21,12 @@ class MyFirstStack extends Stack { #### [ JavaScript ] ``` -class MyFirstStack extends Stack { - constructor(scope, id, props) { - super(scope, id, props); - - new s3.Bucket(this, 'MyFirstBucket'); - } +class MyFirstStack extends Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket'); + } } ``` @@ -146,10 +146,10 @@ new MyApp().synth(); #### [ JavaScript ] ``` -class MyApp extends App { - constructor() { - new MyFirstStack(this, 'hello-cdk'); - } +class MyApp extends App { + constructor() { + new MyFirstStack(this, 'hello-cdk'); + } } new MyApp().synth(); @@ -269,6 +269,15 @@ The \-\-app option instructs the CLI to run your AWS CDK app, and its contents d } ``` +------ +#### [ JavaScript ] + +``` +{ + "app": "node bin/my-app.js" +} +``` + ------ #### [ Python ] diff --git a/doc_source/aspects.md b/doc_source/aspects.md index b95bdf04..a86a0d3b 100644 --- a/doc_source/aspects.md +++ b/doc_source/aspects.md @@ -15,7 +15,7 @@ myConstruct.node.applyAspect(new SomeAspect(/*...*/)); #### [ JavaScript ] ``` -myConstruct.node.applyAspect(new SomeAspect(/*...*/)); +myConstruct.node.applyAspect(new SomeAspect()); ``` ------ @@ -58,7 +58,7 @@ interface IAspect { ------ #### [ JavaScript ] -JavaScript doesn't have interfaces as a language feature, so an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. +JavaScript doesn't have interfaces as a language feature, so an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. ------ #### [ Python ] @@ -125,15 +125,15 @@ stack.node.applyAspect(new BucketVersioningChecker()); ``` class BucketVersioningChecker { - visit(node) { + visit(node) { // See that we're dealing with a CfnBucket - if (node instanceof s3.CfnBucket) { + if ( node instanceof s3.CfnBucket) { // Check for versioning property, exclude the case where the property // can be a token (IResolvable). - if (!node.versioningConfiguration + if ( !node.versioningConfiguration || !Tokenization.isResolvable(node.versioningConfiguration) - && node.versioningConfiguration.status !== 'Enabled') { + && node.versioningConfiguration.status !== 'Enabled') { node.node.addError('Bucket versioning is not enabled'); } } diff --git a/doc_source/assets.md b/doc_source/assets.md index 80ba3d77..00650866 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -57,7 +57,7 @@ const fileAsset = new Asset(this, 'SampleSingleFileAsset', { #### [ JavaScript ] ``` -import { Asset } from '@aws-cdk/aws-s3-assets'; +const { Asset } = require('@aws-cdk/aws-s3-assets'); // Archived and uploaded to Amazon S3 as a .zip file const directoryAsset = new Asset(this, "SampleZippedDirAsset", { @@ -175,11 +175,11 @@ export class HelloAssetStack extends cdk.Stack { #### [ JavaScript ] ``` -import * as cdk from '@aws-cdk/core'; -import * as lambda from '@aws-cdk/aws-lambda'; -import * as path from 'path'; +const cdk = require('@aws-cdk/core'); +const lambda = require('@aws-cdk/aws-lambda'); +const path = require('path'); -export class HelloAssetStack extends cdk.Stack { +class HelloAssetStack extends cdk.Stack { constructor(scope, id, props) { super(scope, id, props); @@ -190,6 +190,8 @@ export class HelloAssetStack extends cdk.Stack { }); } } + +module.exports = { HelloAssetStack } ``` ------ @@ -301,8 +303,8 @@ new lambda.Function(this, "myLambdaFunction", { #### [ JavaScript ] ``` -import { Asset } from '@aws-cdk/aws-s3-assets'; -import * as path from 'path'; +const { Asset } = require('@aws-cdk/aws-s3-assets'); +const path = require('path'); const imageAsset = new Asset(this, "SampleAsset", { path: path.join(__dirname, "images/my-image.png") @@ -434,8 +436,8 @@ asset.grantRead(group); #### [ JavaScript ] ``` -import { Asset } from '@aws-cdk/aws-s3-assets'; -import * as path from 'path'; +const { Asset } = require('@aws-cdk/aws-s3-assets'); +const path = require('path'); const asset = new Asset(this, 'MyFile', { path: path.join(__dirname, 'my-image.png') @@ -527,7 +529,7 @@ const asset = new DockerImageAsset(this, 'MyBuildImage', { #### [ JavaScript ] ``` -import { DockerImageAsset } from '@aws-cdk/aws-ecr-assets'; +const { DockerImageAsset } = require('@aws-cdk/aws-ecr-assets'); const asset = new DockerImageAsset(this, 'MyBuildImage', { directory: path.join(__dirname, 'my-image') @@ -601,8 +603,8 @@ taskDefinition.addContainer("my-other-container", { #### [ JavaScript ] ``` -import * as ecs from '@aws-cdk/aws-ecs'; -import * as path from 'path'; +const ecs = require('@aws-cdk/aws-ecs'); +const path = require('path'); const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { memoryLimitMiB: 1024, @@ -704,9 +706,9 @@ taskDefinition.addContainer("my-other-container", { #### [ JavaScript ] ``` -import * as ecs from '@aws-cdk/aws-ecs'; -import * as path from 'path'; -import { DockerImageAsset } from '@aws-cdk/aws-ecr-assets'; +const ecs = require('@aws-cdk/aws-ecs'); +const path = require('path'); +const { DockerImageAsset } = require('@aws-cdk/aws-ecr-assets'); const asset = new DockerImageAsset(this, 'my-image', { directory: path.join(__dirname, "..", "demo-image") diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index bafd18db..ffe538a7 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -33,10 +33,10 @@ new s3.CfnBucket(this, 'MyBucket', { ``` new s3.CfnBucket(this, 'MyBucket', { analyticsConfigurations: [ - { + { id: 'Config' - // ... - } + // ... + } ] }); ``` @@ -107,13 +107,13 @@ new cdk.CfnResource(this, 'MyBucket', { new cdk.CfnResource(this, 'MyBucket', { type: 'AWS::S3::Bucket', properties: { - // Note the PascalCase here! These are CloudFormation identifiers. + // Note the PascalCase here! These are CloudFormation identifiers. AnalyticsConfigurations: [ { Id: 'Config' // ... } - ] + ] } }); ``` @@ -208,10 +208,10 @@ const cfnBucket = bucket.node.defaultChild; // Change its properties cfnBucket.analyticsConfiguration = [ - { + { id: 'Config' - // ... - } + // ... + } ]; ``` @@ -341,7 +341,7 @@ cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); ``` // Get the AWS CloudFormation resource -const cfnBucket = bucket.node.defaultChild; +const cfnBucket = bucket.node.defaultChild ; // Use dot notation to address inside the resource template fragment cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index ca33cc24..168cddf7 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -26,7 +26,7 @@ npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/a ``` mkdir pipeline cd pipeline -cdk init --language javascript +cdk init ‐-language javascript mkdir Lambda npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 @@ -154,36 +154,37 @@ export class LambdaStack extends Stack { File: `lib/lambda-stack.js` ``` -import * as codedeploy from '@aws-cdk/aws-codedeploy'; -import * as lambda from '@aws-cdk/aws-lambda'; -import { Stack } from '@aws-cdk/core'; - -export class LambdaStack extends Stack { - +const codedeploy = require('@aws-cdk/aws-codedeploy'); +const lambda = require('@aws-cdk/aws-lambda'); +const { Stack } = require('@aws-cdk/core'); + +class LambdaStack extends Stack { constructor(app, id, props) { super(app, id, props); - + this.lambdaCode = lambda.Code.fromCfnParameters(); - + const func = new lambda.Function(this, 'Lambda', { code: this.lambdaCode, handler: 'index.handler', runtime: lambda.Runtime.NODEJS_10_X }); - + const version = func.addVersion(new Date().toISOString()); const alias = new lambda.Alias(this, 'LambdaAlias', { aliasName: 'Prod', version }); - + new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', { alias, deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE }); } } + +module.exports = { LambdaStack } ``` ------ @@ -477,21 +478,19 @@ export class PipelineStack extends Stack { File: `lib/pipeline-stack.js` ``` -import * as codebuild from '@aws-cdk/aws-codebuild'; -import * as codecommit from '@aws-cdk/aws-codecommit'; -import * as codepipeline from '@aws-cdk/aws-codepipeline'; -import * as codepipeline_actions from '@aws-cdk/aws-codepipeline-actions'; - -import { Stack } from '@aws-cdk/core'; - +const codebuild = require('@aws-cdk/aws-codebuild'); +const codecommit = require('@aws-cdk/aws-codecommit'); +const codepipeline = require('@aws-cdk/aws-codepipeline'); +const codepipeline_actions = require('@aws-cdk/aws-codepipeline-actions'); +const { Stack } = require('@aws-cdk/core'); -export class PipelineStack extends Stack { +class PipelineStack extends Stack { constructor(app, id, props) { super(app, id, props); const code = codecommit.Repository.fromRepositoryName(this, 'ImportedRepo', - 'NameOfYourCodeCommitRepository'); + 'NameOfYourCodeCommitRepository'); const cdkBuild = new codebuild.PipelineProject(this, 'CdkBuild', { buildSpec: codebuild.BuildSpec.fromObject({ @@ -502,15 +501,15 @@ export class PipelineStack extends Stack { }, build: { commands: [ - 'npm run build', - 'npm run cdk synth -- -o dist' + 'npm run build', + 'npm run cdk synth -- -o dist' ] } }, artifacts: { 'base-directory': 'dist', files: [ - 'LambdaStack.template.json' + 'LambdaStack.template.json' ] } }), @@ -524,8 +523,8 @@ export class PipelineStack extends Stack { phases: { install: { commands: [ - 'cd lambda', - 'npm install' + 'cd lambda', + 'npm install' ] }, build: { @@ -535,8 +534,8 @@ export class PipelineStack extends Stack { artifacts: { 'base-directory': 'lambda', files: [ - 'index.js', - 'node_modules/**/*' + 'index.js', + 'node_modules/**/*' ] } }), @@ -550,52 +549,54 @@ export class PipelineStack extends Stack { const lambdaBuildOutput = new codepipeline.Artifact('LambdaBuildOutput'); new codepipeline.Pipeline(this, 'Pipeline', { stages: [ - { - stageName: 'Source', - actions: [ - new codepipeline_actions.CodeCommitSourceAction({ - actionName: 'CodeCommit_Source', - repository: code, - output: sourceOutput - }) - ] - }, - { - stageName: 'Build', - actions: [ - new codepipeline_actions.CodeBuildAction({ - actionName: 'Lambda_Build', - project: lambdaBuild, - input: sourceOutput, - outputs: [lambdaBuildOutput] - }), - new codepipeline_actions.CodeBuildAction({ - actionName: 'CDK_Build', - project: cdkBuild, - input: sourceOutput, - outputs: [cdkBuildOutput] - }) - ] - }, - { - stageName: 'Deploy', - actions: [ - new codepipeline_actions.CloudFormationCreateUpdateStackAction({ - actionName: 'Lambda_CFN_Deploy', - templatePath: cdkBuildOutput.atPath('LambdaStack.template.json'), - stackName: 'LambdaDeploymentStack', - adminPermissions: true, - parameterOverrides: { - ...props.lambdaCode.assign(lambdaBuildOutput.s3Location) - }, - extraInputs: [lambdaBuildOutput] - }) - ] - } + { + stageName: 'Source', + actions: [ + new codepipeline_actions.CodeCommitSourceAction({ + actionName: 'CodeCommit_Source', + repository: code, + output: sourceOutput + }) + ] + }, + { + stageName: 'Build', + actions: [ + new codepipeline_actions.CodeBuildAction({ + actionName: 'Lambda_Build', + project: lambdaBuild, + input: sourceOutput, + outputs: [lambdaBuildOutput] + }), + new codepipeline_actions.CodeBuildAction({ + actionName: 'CDK_Build', + project: cdkBuild, + input: sourceOutput, + outputs: [cdkBuildOutput] + }) + ] + }, + { + stageName: 'Deploy', + actions: [ + new codepipeline_actions.CloudFormationCreateUpdateStackAction({ + actionName: 'Lambda_CFN_Deploy', + templatePath: cdkBuildOutput.atPath('LambdaStack.template.json'), + stackName: 'LambdaDeploymentStack', + adminPermissions: true, + parameterOverrides: { + ...props.lambdaCode.assign(lambdaBuildOutput.s3Location) + }, + extraInputs: [lambdaBuildOutput] + }) + ] + } ] }); } } + +module.exports = { PipelineStack } ``` ------ @@ -1025,14 +1026,14 @@ app.synth(); ------ #### [ JavaScript ] -File: `bin/pipeline.ts` +File: `bin/pipeline.js` ``` #!/usr/bin/env node -import { App } from '@aws-cdk/core'; -import { LambdaStack } from '../lib/lambda-stack'; -import { PipelineStack } from '../lib/pipeline-stack'; +const { App } = require('@aws-cdk/core'); +const { LambdaStack } = require('../lib/lambda-stack'); +const { PipelineStack } = require('../lib/pipeline-stack'); const app = new App(); diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 73f7d841..971460fd 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -62,8 +62,8 @@ new HelloCdkStack(app, "HelloCdkStack"); #### [ JavaScript ] ``` -import { App, Stack } from '@aws-cdk/core'; -import * as s3 from '@aws-cdk/aws-s3'; +const { App , Stack } = require('@aws-cdk/core'); +const s3 = require('@aws-cdk/aws-s3'); class HelloCdkStack extends Stack { constructor(scope, id, props) { @@ -229,7 +229,7 @@ new s3.Bucket(this, 'MyFirstBucket', { #### [ JavaScript ] ``` -import * as s3 from '@aws-cdk/aws-s3'; +const s3 = require('@aws-cdk/aws-s3'); // "this" is HelloCdkStack new s3.Bucket(this, 'MyFirstBucket', { @@ -508,15 +508,17 @@ export class NotifyingBucket extends Construct { #### [ JavaScript ] ``` -export class NotifyingBucket extends Construct { +class NotifyingBucket extends Construct { constructor(scope, id, props = {}) { super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); const topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(new s3notify.SnsDestination(topic), - { prefix: props.prefix }); + { prefix: props.prefix }); } } + +module.exports = { NotifyingBucket } ``` ------ @@ -588,7 +590,7 @@ public class NotifyingBucket : Construct ------ -The `NotifyingBucket` constructors have signature compatible with the base `Construct` class: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. This means that you could define an instance of this construct in your app without `props`, for example: +The `NotifyingBucket` constructor has a signature compatible with the base `Construct` class: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. This means that you could define an instance of this construct in your app without `props`, for example: ------ #### [ TypeScript ] @@ -640,7 +642,7 @@ new NotifyingBucket(this, 'MyNotifyingBucket', { prefix: 'images/' }); #### [ JavaScript ] ``` -new NotifyingBucket(this, 'MyNotifyingBucket', { prefix: 'images/'}); +new NotifyingBucket(this, 'MyNotifyingBucket', { prefix: 'images/' }); ``` ------ @@ -691,7 +693,7 @@ export class NotifyingBucket extends Construct { #### [ JavaScript ] ``` -export class NotifyingBucket extends Construct { +class NotifyingBucket extends Construct { constructor(scope, id, props) { super(scope, id); @@ -700,6 +702,8 @@ export class NotifyingBucket extends Construct { bucket.addObjectCreatedNotification(this.topic, { prefix: props.prefix }); } } + +module.exports = { NotifyingBucket } ``` ------ diff --git a/doc_source/context.md b/doc_source/context.md index c41c2fef..1d19adce 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -78,10 +78,6 @@ Therefore, if you want to update to the latest version of the Amazon Linux AMI, $ cdk synth ``` -``` -... -``` - To clear all of the stored context values for your app, run cdk context \-\-clear, as follows\. ``` @@ -123,27 +119,29 @@ export class ExistsVpcStack extends cdk.Stack { #### [ JavaScript ] ``` -import * as cdk from '@aws-cdk/core'; -import * as ec2 from '@aws-cdk/aws-ec2'; +const cdk = require('@aws-cdk/core'); +const ec2 = require('@aws-cdk/aws-ec2'); -export class ExistsVpcStack extends cdk.Stack { +class ExistsVpcStack extends cdk.Stack { constructor(scope, id, props) { - + super(scope, id, props); - + const vpcid = this.node.tryGetContext('vpcid'); const vpc = ec2.Vpc.fromLookup(this, 'VPC', { vpcId: vpcid }); - - const pubsubnets = vpc.selectSubnets({ subnetType: ec2.SubnetType.PUBLIC }); - + + const pubsubnets = vpc.selectSubnets({subnetType: ec2.SubnetType.PUBLIC}); + new cdk.CfnOutput(this, 'publicsubnets', { value: pubsubnets.subnetIds.toString() }); } } + +module.exports = { ExistsVpcStack } ``` ------ diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 93743161..36f60a2d 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -222,9 +222,9 @@ import * as ecs_patterns from "@aws-cdk/aws-ecs-patterns"; File: `lib/my_ecs_construct-stack.js` ``` -import * as ec2 from "@aws-cdk/aws-ec2"; -import * as ecs from "@aws-cdk/aws-ecs"; -import * as ecs_patterns from "@aws-cdk/aws-ecs-patterns"; +const ec2 = require("@aws-cdk/aws-ec2"); +const ecs = require("@aws-cdk/aws-ecs"); +const ecs_patterns = require("@aws-cdk/aws-ecs-patterns"); ``` ------ diff --git a/doc_source/environments.md b/doc_source/environments.md index 6f126ca8..635eda35 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -26,11 +26,11 @@ new MyFirstStack(app, 'first-stack-eu', { env: envEU }); #### [ JavaScript ] ``` -const envEU = { account: '2383838383', region: 'eu-west-1'}; -const envUSA = { account: '8373873873', region: 'us-west-2'}; +const envEU = { account: '2383838383', region: 'eu-west-1' }; +const envUSA = { account: '8373873873', region: 'us-west-2' }; -new MyFirstStack(app, 'first-stack-us', { env: envUSA}); -new MyFirstStack(app, 'first-stack-eu', { env: envEU}); +new MyFirstStack(app, 'first-stack-us', { env: envUSA }); +new MyFirstStack(app, 'first-stack-eu', { env: envEU }); ``` ------ @@ -125,12 +125,19 @@ new MyDevStack(app, 'dev', { Access environment variables via the `process` object\. +**Note** +TypeScript users must install the DefinitelyTyped NodeJS module with NPM to be able to use `process`\. `cdk init` now installs this module for you, but if you are working with a project created before it was added, or didn't set up your project using `cdk init`, install it manually\. + ``` -new MyDevStack(app, 'dev', { - env: { - account: process.env.CDK_DEFAULT_ACCOUNT, - region: process.env.CDK_DEFAULT_REGION - }}); +npm install @types/node +``` + +``` +new MyDevStack(app, 'dev', { + env: { + account: process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEFAULT_REGION +}}); ``` ------ @@ -221,11 +228,11 @@ new MyDevStack(app, 'dev', { #### [ JavaScript ] ``` -new MyDevStack(app, 'dev', { - env: { - account: process.env.CDK_DEPLOY_ACCOUNT || process.env.CDK_DEFAULT_ACCOUNT, - region: process.env.CDK_DEPLOY_REGION || process.env.CDK_DEFAULT_REGION - }}); +new MyDevStack(app, 'dev', { + env: { + account: process.env.CDK_DEPLOY_ACCOUNT || process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEPLOY_REGION || process.env.CDK_DEFAULT_REGION +}}); ``` ------ @@ -336,7 +343,7 @@ bash cdk-deploy-to.sh 123457689 us-east-1 "$@" ``` ------ -#### [ Windows ] +#### [ Windows ] ``` @echo off @@ -359,7 +366,7 @@ bash cdk-deploy-to.sh 246813579 eu-west-1 "$@" ``` ------ -#### [ Windows ] +#### [ Windows ] ``` @echo off diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index 38358943..fabe32b0 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -24,10 +24,10 @@ export class SecretsManagerStack extends core.Stack { #### [ JavaScript ] ``` -import * as sm from "@aws-cdk/aws-secretsmanager"; +const sm = require("@aws-cdk/aws-secretsmanager"); -export class SecretsManagerStack extends core.Stack { - constructor(scope: core.App, id: string, props?: core.StackProps) { +class SecretsManagerStack extends core.Stack { + constructor(scope, id, props) { super(scope, id, props); const secret = sm.Secret.fromSecretAttributes(this, "ImportedSecret", { @@ -36,6 +36,10 @@ export class SecretsManagerStack extends core.Stack { // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: // encryptionKey: ... }); + } +} + +module.exports = { SecretsManagerStack } ``` ------ diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 2cb65490..8c0447f4 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -32,17 +32,17 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( #### [ JavaScript ] ``` -import * as ssm from '@aws-cdk/aws-ssm'; +const ssm = require('@aws-cdk/aws-ssm'); // Get latest version or specified version of plain string attribute const latestStringToken = ssm.StringParameter.valueForStringParameter( -this, 'my-plain-parameter-name'); // latest version + this, 'my-plain-parameter-name'); // latest version const versionOfStringToken = ssm.StringParameter.valueForStringParameter( -this, 'my-plain-parameter-name', 1); // version 1 + this, 'my-plain-parameter-name', 1); // version 1 // Get specified version of secure string attribute const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( -this, 'my-secure-parameter-name', 1); // must specify version + this, 'my-secure-parameter-name', 1); // must specify version ``` ------ @@ -117,7 +117,7 @@ const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-paramete #### [ JavaScript ] ``` -import * as ssm from '@aws-cdk/aws-ssm'; +const ssm = require('@aws-cdk/aws-ssm'); const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 770209f6..20a291b6 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -24,7 +24,7 @@ TypeScript >= 2\.7 ------ #### [ JavaScript ] -none +No additional prerequisites ------ #### [ Python ] @@ -32,7 +32,7 @@ none ------ #### [ Java ] -+ Maven = 3\.5 and Java >= 8 ++ Maven <= 3\.5 and Java >= 8 + A Java IDE is preferred \(the examples in this guide may refer to Eclipse\)\. `cdk init` creates a Maven project, which most IDEs can import\. Some IDEs may need to be configured to use Java 8 \(also known as 1\.8\)\. + Set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine @@ -128,10 +128,10 @@ new MyStack(app, 'MyStack', { ``` new MyStack(app, 'MyStack', { - env: { - region: 'REGION', - account: 'ACCOUNT' - } + env: { + region: 'REGION', + account: 'ACCOUNT' + } }); ``` @@ -190,10 +190,10 @@ new MyStack(app, 'Stack-Three-E', { env: { account: 'THREE', region: 'us-east-1' #### [ JavaScript ] ``` -new MyStack(app, 'Stack-One-W', { env: { account: 'ONE', region: 'us-west-2' }}); -new MyStack(app, 'Stack-One-E', { env: { account: 'ONE', region: 'us-east-1' }}); -new MyStack(app, 'Stack-Two-W', { env: { account: 'TWO', region: 'us-west-2' }}); -new MyStack(app, 'Stack-Two-E', { env: { account: 'TWO', region: 'us-east-1' }}); +new MyStack(app, 'Stack-One-W', { env: { account: 'ONE', region: 'us-west-2' }}); +new MyStack(app, 'Stack-One-E', { env: { account: 'ONE', region: 'us-east-1' }}); +new MyStack(app, 'Stack-Two-W', { env: { account: 'TWO', region: 'us-west-2' }}); +new MyStack(app, 'Stack-Two-E', { env: { account: 'TWO', region: 'us-east-1' }}); new MyStack(app, 'Stack-Three-W', { env: { account: 'THREE', region: 'us-west-2' }}); new MyStack(app, 'Stack-Three-E', { env: { account: 'THREE', region: 'us-east-1' }}); ``` @@ -403,7 +403,7 @@ cdk init --language typescript #### [ JavaScript ] ``` -cdk init --language javascript +cdk init ‐-language javascript ``` ------ @@ -588,10 +588,10 @@ export class HelloCdkStack extends core.Stack { In `lib/hello-cdk-stack.js`: ``` -import * as core from '@aws-cdk/core'; -import * as s3 from '@aws-cdk/aws-s3'; +const core = require('@aws-cdk/core'); +const s3 = require('@aws-cdk/aws-s3'); -export class HelloCdkStack extends core.Stack { +class HelloCdkStack extends core.Stack { constructor(scope, id, props) { super(scope, id, props); @@ -600,6 +600,8 @@ export class HelloCdkStack extends core.Stack { }); } } + +module.exports = { HelloCdkStack } ``` ------ diff --git a/doc_source/home.md b/doc_source/home.md index c370ac22..4d2be2f6 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -51,29 +51,31 @@ export class MyEcsConstructStack extends core.Stack { #### [ JavaScript ] ``` -export class MyEcsConstructStack extends core.Stack { - constructor(scope, id, props) { - super(scope, id, props); - - const vpc = new ec2.Vpc(this, "MyVpc", { +class MyEcsConstructStack extends core.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const vpc = new ec2.Vpc(this, "MyVpc", { maxAzs: 3 // Default is all AZs in region - }); - - const cluster = new ecs.Cluster(this, "MyCluster", { - vpc: vpc - }); - + }); + + const cluster = new ecs.Cluster(this, "MyCluster", { + vpc: vpc + }); + // Create a load-balanced Fargate service and make it public - new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { + new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { cluster: cluster, // Required cpu: 512, // Default is 256 desiredCount: 6, // Default is 1 - taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, + taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, memoryLimitMiB: 2048, // Default is 512 publicLoadBalancer: true // Default is false - }); - } + }); + } } + +module.exports = { MyEcsConstructStack } ``` ------ diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index 176b7922..40f0be3a 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -19,7 +19,7 @@ const alarm = new cloudwatch.Alarm(this, 'Alarm', { ``` const alarm = new cloudwatch.Alarm(this, 'Alarm', { - metric: metric, // see below + metric: metric, // see below threshold: 100, evaluationPeriods: 3, datapointsToAlarm: 2 diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index 54b59bd5..54ca5042 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -36,8 +36,8 @@ new MyStack(app, 'Stack2'); #### [ JavaScript ] ``` -import { App, Stack } from '@aws-cdk/core'; -import * as s3 from '@aws-cdk/aws-s3'; +const { App , Stack } = require('@aws-cdk/core'); +const s3 = require('@aws-cdk/aws-s3'); class MyStack extends Stack { constructor(scope, id, props = {}) { diff --git a/doc_source/parameters.md b/doc_source/parameters.md index bd0223a5..7747baed 100644 --- a/doc_source/parameters.md +++ b/doc_source/parameters.md @@ -150,7 +150,7 @@ const bucket = new Bucket(this, "myBucket", #### [ JavaScript ] ``` -const bucket = new Bucket(this, "myBucket", +const bucket = new Bucket(this, "myBucket", { bucketName: uploadBucketName.valueAsString}); ``` diff --git a/doc_source/permissions.md b/doc_source/permissions.md index b4e01c75..fa67bab8 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -51,10 +51,10 @@ const role = new iam.Role(this, 'Role', { #### [ JavaScript ] ``` -import * as iam from '@aws-cdk/aws-iam'; +const iam = require('@aws-cdk/aws-iam'); const role = new iam.Role(this, 'Role', { - assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com') // required + assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com') // required }); ``` @@ -118,8 +118,8 @@ role.addToPolicy(new iam.PolicyStatement({ effect: iam.Effect.DENY, resources: [bucket.bucketArn, otherRole.roleArn], actions: ['ec2:SomeAction', 's3:AnotherAction'], - conditions: { StringEquals: { - 'ec2:AuthorizedService': 'codebuild.amazonaws.com' + conditions: {StringEquals: { + 'ec2:AuthorizedService': 'codebuild.amazonaws.com' }}})); ``` @@ -197,14 +197,14 @@ const project = new codebuild.Project(this, 'Project', { #### [ JavaScript ] ``` -import * as codebuild from '@aws-cdk/aws-codebuild'; +const codebuild = require('@aws-cdk/aws-codebuild'); // imagine roleOrUndefined is a function that might return a Role object // under some conditions, and undefined under other conditions const someRole = roleOrUndefined(); const project = new codebuild.Project(this, 'Project', { - // if someRole is undefined, the Project creates a new default role, + // if someRole is undefined, the Project creates a new default role, // trusting the codebuild.amazonaws.com service principal role: someRole }); @@ -287,7 +287,7 @@ const project = codebuild.Project.fromProjectName(this, 'Project', 'ProjectName' // project is imported, so project.role is undefined, and this call has no effect project.addToRolePolicy(new iam.PolicyStatement({ - effect: iam.Effect.ALLOW // ... and so on defining the policy + effect: iam.Effect.ALLOW // ... and so on defining the policy })); ``` diff --git a/doc_source/resources.md b/doc_source/resources.md index 8321c2ed..97239a99 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -19,10 +19,10 @@ new sqs.Queue(this, 'MyQueue', { #### [ JavaScript ] ``` -import * as sqs from '@aws-cdk/aws-sqs'; - +const sqs = require('@aws-cdk/aws-sqs'); + new sqs.Queue(this, 'MyQueue', { - encryption: sqs.QueueEncryption.KMS_MANAGED + encryption: sqs.QueueEncryption.KMS_MANAGED }); ``` @@ -79,8 +79,8 @@ const url = queue.queueUrl; // => A string representing a deploy-time value #### [ JavaScript ] ``` -import * as sqs from '@aws-cdk/aws-sqs'; - +const sqs = require('@aws-cdk/aws-sqs'); + const queue = new sqs.Queue(this, 'MyQueue'); const url = queue.queueUrl; // => A string representing a deploy-time value ``` @@ -131,7 +131,7 @@ Because every resource implements its corresponding interface, you can directly #### [ TypeScript ] ``` -const cluster = new ecs.Cluster(this, 'Cluster', { /* ... */ }); +const cluster = new ecs.Cluster(this, 'Cluster', { /*...*/ }); const service = new ecs.Ec2Service(this, 'Service', { cluster: cluster }); ``` @@ -140,9 +140,9 @@ const service = new ecs.Ec2Service(this, 'Service', { cluster: cluster }); #### [ JavaScript ] ``` -const cluster = new ecs.Cluster(this, 'Cluster', { /* ... */}); +const cluster = new ecs.Cluster(this, 'Cluster', { /*...*/ }); -const service = new ecs.Ec2Service(this, 'Service', { cluster: cluster}); +const service = new ecs.Ec2Service(this, 'Service', { cluster: cluster }); ``` ------ @@ -196,13 +196,13 @@ const stack2 = new StackThatExpectsABucket(app, 'Stack2', { #### [ JavaScript ] ``` -const prod = { account: '123456789012', region: 'us-east-1'}; +const prod = { account: '123456789012', region: 'us-east-1' }; -const stack1 = new StackThatProvidesABucket(app, 'Stack1', { env: prod}); +const stack1 = new StackThatProvidesABucket(app, 'Stack1' , { env: prod }); // stack2 will take a property { bucket: IBucket } const stack2 = new StackThatExpectsABucket(app, 'Stack2', { - bucket: stack1.bucket, + bucket: stack1.bucket, env: prod }); ``` @@ -425,7 +425,7 @@ The following example shows how to pass a generated bucket name to an AWS Lambda const bucket = new s3.Bucket(this, 'Bucket'); new lambda.Function(this, 'MyLambda', { - /* ... */ + // ... environment: { BUCKET_NAME: bucket.bucketName, }, @@ -439,7 +439,7 @@ new lambda.Function(this, 'MyLambda', { const bucket = new s3.Bucket(this, 'Bucket'); new lambda.Function(this, 'MyLambda', { - /* ... */ + // ... environment: { BUCKET_NAME: bucket.bucketName } @@ -588,8 +588,8 @@ ec2.Vpc.fromLookup(this, 'DefaultVpc', { #### [ JavaScript ] ``` -ec2.Vpc.fromLookup(this, 'DefaultVpc', { - isDefault: true +ec2.Vpc.fromLookup(this, 'DefaultVpc', { + isDefault: true }); ``` @@ -634,8 +634,8 @@ ec2.Vpc.fromLookup(this, 'PublicVpc', #### [ JavaScript ] ``` -ec2.Vpc.fromLookup(this, 'PublicVpc', -{ tags: { 'aws-cdk:subnet-type': "Public" }}); +ec2.Vpc.fromLookup(this, 'PublicVpc', + {tags: {'aws-cdk:subnet-type': "Public"}}); ``` ------ @@ -688,7 +688,7 @@ if (bucket.grantReadWrite(func).success) { #### [ JavaScript ] ``` -if (bucket.grantReadWrite(func).success) { +if ( bucket.grantReadWrite(func).success) { // ... } ``` @@ -801,9 +801,9 @@ metric.createAlarm(this, 'TooManyMessagesAlarm', { #### [ JavaScript ] ``` -import * as cw from '@aws-cdk/aws-cloudwatch'; -import * as sqs from '@aws-cdk/aws-sqs'; -import { Duration } from '@aws-cdk/core'; +const cw = require('@aws-cdk/aws-cloudwatch'); +const sqs = require('@aws-cdk/aws-sqs'); +const { Duration } = require('@aws-cdk/core'); const queue = new sqs.Queue(this, 'MyQueue'); @@ -909,12 +909,12 @@ You enable data to flow on a given network path by using `allow` methods\. The f import * as asg from '@aws-cdk/aws-autoscaling'; import * as ec2 from '@aws-cdk/aws-ec2'; -const fleet1: asg.AutoScalingGroup = asg.AutoScalingGroup(/* ... */); +const fleet1: asg.AutoScalingGroup = asg.AutoScalingGroup(/*...*/); // Allow surfing the (secure) web fleet1.connections.allowTo(new ec2.Peer.anyIpv4(), new ec2.Port({ fromPort: 443, toPort: 443 })); -const fleet2: asg.AutoScalingGroup = asg.AutoScalingGroup(/* ... */); +const fleet2: asg.AutoScalingGroup = asg.AutoScalingGroup(/*...*/); fleet1.connections.allowFrom(fleet2, ec2.Port.AllTraffic()); ``` @@ -922,13 +922,13 @@ fleet1.connections.allowFrom(fleet2, ec2.Port.AllTraffic()); #### [ JavaScript ] ``` -import * as asg from '@aws-cdk/aws-autoscaling'; -import * as ec2 from '@aws-cdk/aws-ec2'; +const asg = require('@aws-cdk/aws-autoscaling'); +const ec2 = require('@aws-cdk/aws-ec2'); const fleet1 = asg.AutoScalingGroup(); // Allow surfing the (secure) web -fleet1.connections.allowTo(new ec2.Peer.anyIpv4(), new ec2.Port({ fromPort: 443, toPort: 443})); +fleet1.connections.allowTo(new ec2.Peer.anyIpv4(), new ec2.Port({ fromPort: 443, toPort: 443 })); const fleet2 = asg.AutoScalingGroup(); fleet1.connections.allowFrom(fleet2, ec2.Port.AllTraffic()); @@ -1062,9 +1062,9 @@ bucket.addObjectCreatedNotification(new s3nots.LambdaDestination(handler)); #### [ JavaScript ] ``` -import * as s3nots from '@aws-cdk/aws-s3-notifications'; +const s3nots = require('@aws-cdk/aws-s3-notifications'); -const handler = new lambda.Function(this, 'Handler', { /*…*/}); +const handler = new lambda.Function(this, 'Handler', { /*…*/ }); const bucket = new s3.Bucket(this, 'Bucket'); bucket.addObjectCreatedNotification(new s3nots.LambdaDestination(handler)); ``` @@ -1144,18 +1144,20 @@ export class CdkTestStack extends cdk.Stack { #### [ JavaScript ] ``` -import * as cdk from '@aws-cdk/core'; -import * as s3 from '@aws-cdk/aws-s3'; - -export class CdkTestStack extends cdk.Stack { +const cdk = require('@aws-cdk/core'); +const s3 = require('@aws-cdk/aws-s3'); + +class CdkTestStack extends cdk.Stack { constructor(scope, id, props) { super(scope, id, props); - + const bucket = new s3.Bucket(this, 'Bucket', { removalPolicy: cdk.RemovalPolicy.DESTROY }); } } + +module.exports = { CdkTestStack } ``` ------ @@ -1225,7 +1227,7 @@ resource.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY); #### [ JavaScript ] ``` -const resource = bucket.node.findChild('Resource') as cdk.CfnResource; +const resource = bucket.node.findChild('Resource'); resource.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY); ``` diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index c5d6267d..0e870953 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -41,7 +41,7 @@ cdk init --language typescript ``` mkdir MyWidgetService cd MyWidgetService -cdk init --language javascript +cdk init ‐-language javascript ``` ------ @@ -370,13 +370,13 @@ export class WidgetService extends core.Construct { File: `lib/widget_service.js` ``` -import * as core from "@aws-cdk/core"; -import * as apigateway from "@aws-cdk/aws-apigateway"; -import * as lambda from "@aws-cdk/aws-lambda"; -import * as s3 from "@aws-cdk/aws-s3"; +const core = require("@aws-cdk/core"); +const apigateway = require("@aws-cdk/aws-apigateway"); +const lambda = require("@aws-cdk/aws-lambda"); +const s3 = require("@aws-cdk/aws-s3"); -export class WidgetService extends core.Construct { - constructor(scope: core.Construct, id: string) { +class WidgetService extends core.Construct { + constructor(scope, id) { super(scope, id); const bucket = new s3.Bucket(this, "WidgetStore"); @@ -404,6 +404,8 @@ export class WidgetService extends core.Construct { api.root.addMethod("GET", getWidgetsIntegration); // GET / } } + +module.exports = { WidgetService } ``` ------ @@ -625,10 +627,10 @@ Replace the comment in the constructor with the following line of code\. File: `lib/my_widget_service-stack.js` -Add the following line of code after the existing `import` statement\. +Add the following line of code after the existing `require()` line\. ``` -import * as widget_service from '../lib/widget_service'; +const widget_service = require('../lib/widget_service'); ``` Replace the comment in the constructor with the following line of code\. diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index ad5c20e0..32cb9df9 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -143,7 +143,23 @@ export class MultistackStack extends cdk.Stack { ------ #### [ JavaScript ] -JavaScript does not have an interface feature, so we don't need to make any changes\. +File: `lib/multistack-stack.js` + +JavaScript doesn't have an interface feature; we don't need to add any code\. + +``` +const cdk = require('@aws-cdk/core'); + +class MultistackStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + // The code that defines your stack goes here + } +} + +module.exports = { MultistackStack } +``` ------ #### [ Python ] @@ -276,28 +292,29 @@ export class MultistackStack extends cdk.Stack { File: `lib/multistack-stack.js` ``` -import * as cdk from '@aws-cdk/core'; -import * as s3 from '@aws-cdk/aws-s3'; +const cdk = require('@aws-cdk/core'); +const s3 = require('@aws-cdk/aws-s3'); -export class MultistackStack extends cdk.Stack { - constructor(scope, id, props) { - super(scope, id, props); +class MultistackStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); // Add a Boolean property "encryptBucket" to the stack constructor. // If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. // Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). - if (props && props.encryptBucket) { - new s3.Bucket(this, "MyGroovyBucket", { + if ( props && props.encryptBucket) { + new s3.Bucket(this, "MyGroovyBucket", { encryption: s3.BucketEncryption.KMS_MANAGED, - removalPolicy: cdk.RemovalPolicy.DESTROY - }); - } else { - new s3.Bucket(this, "MyGroovyBucket", { - removalPolicy: cdk.RemovalPolicy.DESTROY }); - } - } + removalPolicy: cdk.RemovalPolicy.DESTROY + }); + } else { + new s3.Bucket(this, "MyGroovyBucket", { + removalPolicy: cdk.RemovalPolicy.DESTROY}); + } + } } ->>> + +module.exports = { MultistackStack } ``` ------ @@ -457,20 +474,19 @@ File: `bin/multistack.js` ``` #!/usr/bin/env node -import 'source-map-support/register'; -import * as cdk from '@aws-cdk/core'; -import { MultistackStack } from '../lib/multistack-stack'; +const cdk = require('@aws-cdk/core'); +const { MultistackStack } = require('../lib/multistack-stack'); const app = new cdk.App(); new MultistackStack(app, "MyWestCdkStack", { - env: { region: "us-west-1" }, - encryptBucket: false + env: {region: "us-west-1"}, + encryptBucket: false }); - + new MultistackStack(app, "MyEastCdkStack", { - env: { region: "us-east-1" }, - encryptBucket: true + env: {region: "us-east-1"}, + encryptBucket: true }); ``` diff --git a/doc_source/stacks.md b/doc_source/stacks.md index 522a71dc..a04a2082 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -130,7 +130,7 @@ app.synth(); #### [ JavaScript ] ``` -import { App, Construct, Stack } from "@aws-cdk/core"; +const { App , Construct , Stack } = require("@aws-cdk/core"); // imagine these stacks declare a bunch of related resources class ControlPlane extends Stack {} @@ -140,18 +140,18 @@ class Monitoring extends Stack {} class MyService extends Construct { constructor(scope, id, props) { - + super(scope, id); - - // we might use the prod argument to change how the service is configured + + // we might use the prod argument to change how the service is configured new ControlPlane(this, "cp"); new DataPlane(this, "data"); - new Monitoring(this, "mon"); } + new Monitoring(this, "mon"); } } const app = new App(); new MyService(app, "beta"); -new MyService(app, "prod", { prod: true}); +new MyService(app, "prod", { prod: true }); app.synth(); ``` @@ -314,7 +314,7 @@ new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name' }); #### [ JavaScript ] ``` -new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name'}); +new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name' }); ``` ------ diff --git a/doc_source/tagging.md b/doc_source/tagging.md index a7f11b04..a3303d53 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -305,7 +305,7 @@ Tag.remove(theBestStack, 'StackType', { #### [ JavaScript ] ``` -import { App, Stack, Tag } from '@aws-cdk/core'; +const { App , Stack , Tag } = require('@aws-cdk/core'); const app = new App(); const theBestStack = new Stack(app, 'MarketingSystem'); @@ -387,7 +387,7 @@ Tag.add(theBestStack, 'StackType', 'TheBest', #### [ JavaScript ] ``` -Tag.add(theBestStack, 'StackType', 'TheBest', +Tag.add(theBestStack, 'StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet']}); ``` diff --git a/doc_source/tokens.md b/doc_source/tokens.md index 130125cb..c484dc28 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -112,8 +112,8 @@ if (!Token.isUnresolved(name) && name.length > 10) { #### [ JavaScript ] ``` -if (!Token.isUnresolved(name) && name.length > 10) { - throw new Error(`Maximum length for name is 10 characters`); +if ( !Token.isUnresolved(name) && name.length > 10) { + throw ( new Error(`Maximum length for name is 10 characters`)); } ``` @@ -290,9 +290,9 @@ let actualValue; new AutoScalingGroup(this, 'Group', { desiredCapacity: Lazy.numberValue({ - produce(context) { - return actualValue; - } + produce(context) { + return (actualValue); + } }) }); @@ -380,9 +380,9 @@ Sometimes you want to produce a JSON string of arbitrary data, and you may not k ``` const stack = Stack.of(this); - const str = stack.toJsonString({ - value: bucket.bucketName - }); +const str = stack.toJsonString({ + value: bucket.bucketName +}); ``` ------ diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 07ef5dc1..a48fb072 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -275,18 +275,20 @@ export class CdkTestStack extends cdk.Stack { #### [ JavaScript ] ``` -import * as cdk from '@aws-cdk/core'; -import * as s3 from '@aws-cdk/aws-s3'; - -export class CdkTestStack extends cdk.Stack { +const cdk = require('@aws-cdk/core'); +const s3 = require('@aws-cdk/aws-s3'); + +class CdkTestStack extends cdk.Stack { constructor(scope, id, props) { super(scope, id, props); - + const bucket = new s3.Bucket(this, 'Bucket', { removalPolicy: cdk.RemovalPolicy.DESTROY }); } } + +module.exports = { CdkTestStack } ``` ------ diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index b066ca89..f1e75f0b 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -31,8 +31,8 @@ new cdk.CfnInclude(this, "ExistingInfrastructure", { #### [ JavaScript ] ``` -import * as cdk from "@aws-cdk/core"; -import * as fs from "fs"; +const cdk = require("@aws-cdk/core"); +const fs = require("fs"); new cdk.CfnInclude(this, "ExistingInfrastructure", { template: JSON.parse(fs.readFileSync("my-template.json").toString()) From 2b762dbb5c2a3d7dc87c6f288551cb3321f0009b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 23 Apr 2020 16:50:28 +0000 Subject: [PATCH 138/655] replace with autogenerated JS snippet --- doc_source/codepipeline_example.md | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 99f2d97d..168cddf7 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -29,7 +29,7 @@ cd pipeline cdk init ‐-language javascript mkdir Lambda npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild -npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 @aws-cdk/aws-codepipeline +npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 ``` ------ @@ -154,10 +154,10 @@ export class LambdaStack extends Stack { File: `lib/lambda-stack.js` ``` -const codedeploy = require("@aws-cdk/aws-codedeploy"); -const lambda = require("@aws-cdk/aws-lambda"); -const { Stack } = require("@aws-cdk/core"); - +const codedeploy = require('@aws-cdk/aws-codedeploy'); +const lambda = require('@aws-cdk/aws-lambda'); +const { Stack } = require('@aws-cdk/core'); + class LambdaStack extends Stack { constructor(app, id, props) { @@ -184,7 +184,7 @@ class LambdaStack extends Stack { } } -exports.LambdaStack = LambdaStack; +module.exports = { LambdaStack } ``` ------ @@ -483,7 +483,7 @@ const codecommit = require('@aws-cdk/aws-codecommit'); const codepipeline = require('@aws-cdk/aws-codepipeline'); const codepipeline_actions = require('@aws-cdk/aws-codepipeline-actions'); -const { Stack } = require('@aws-cdk/core'); +const { Stack } = require('@aws-cdk/core'); class PipelineStack extends Stack { constructor(app, id, props) { @@ -1037,13 +1037,12 @@ const { PipelineStack } = require('../lib/pipeline-stack'); const app = new App(); -const lambdaStack = new LambdaStack(app, "LambdaStack"); -new PipelineStack(app, "PipelineDeployingLambdaStack", { - lambdaCode: lambdaStack.lambdaCode, +const lambdaStack = new LambdaStack(app, 'LambdaStack'); +new PipelineStack(app, 'PipelineDeployingLambdaStack', { + lambdaCode: lambdaStack.lambdaCode }); app.synth(); - ``` ------ @@ -1180,4 +1179,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` +``` \ No newline at end of file From bc715947ade48dd5e467c4e55f220b4cedd73e77 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 23 Apr 2020 23:16:05 +0000 Subject: [PATCH 139/655] improve some JavaScript formatting --- doc_source/codepipeline_example.md | 2 +- doc_source/constructs.md | 2 +- doc_source/identifiers.md | 2 +- doc_source/resources.md | 2 +- doc_source/stack_how_to_create_multiple_stacks.md | 2 +- doc_source/stacks.md | 3 ++- doc_source/tagging.md | 2 +- 7 files changed, 8 insertions(+), 7 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 168cddf7..3fe2dd41 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -483,7 +483,7 @@ const codecommit = require('@aws-cdk/aws-codecommit'); const codepipeline = require('@aws-cdk/aws-codepipeline'); const codepipeline_actions = require('@aws-cdk/aws-codepipeline-actions'); -const { Stack } = require('@aws-cdk/core'); +const { Stack } = require('@aws-cdk/core'); class PipelineStack extends Stack { constructor(app, id, props) { diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 971460fd..25c187a7 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -62,7 +62,7 @@ new HelloCdkStack(app, "HelloCdkStack"); #### [ JavaScript ] ``` -const { App , Stack } = require('@aws-cdk/core'); +const { App , Stack } = require('@aws-cdk/core'); const s3 = require('@aws-cdk/aws-s3'); class HelloCdkStack extends Stack { diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index 54ca5042..3923b81c 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -36,7 +36,7 @@ new MyStack(app, 'Stack2'); #### [ JavaScript ] ``` -const { App , Stack } = require('@aws-cdk/core'); +const { App , Stack } = require('@aws-cdk/core'); const s3 = require('@aws-cdk/aws-s3'); class MyStack extends Stack { diff --git a/doc_source/resources.md b/doc_source/resources.md index 97239a99..708cbe7a 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -803,7 +803,7 @@ metric.createAlarm(this, 'TooManyMessagesAlarm', { ``` const cw = require('@aws-cdk/aws-cloudwatch'); const sqs = require('@aws-cdk/aws-sqs'); -const { Duration } = require('@aws-cdk/core'); +const { Duration } = require('@aws-cdk/core'); const queue = new sqs.Queue(this, 'MyQueue'); diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index 32cb9df9..db61370a 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -475,7 +475,7 @@ File: `bin/multistack.js` ``` #!/usr/bin/env node const cdk = require('@aws-cdk/core'); -const { MultistackStack } = require('../lib/multistack-stack'); +const { MultistackStack } = require('../lib/multistack-stack'); const app = new cdk.App(); diff --git a/doc_source/stacks.md b/doc_source/stacks.md index a04a2082..a43669d7 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -146,7 +146,8 @@ class MyService extends Construct { // we might use the prod argument to change how the service is configured new ControlPlane(this, "cp"); new DataPlane(this, "data"); - new Monitoring(this, "mon"); } + new Monitoring(this, "mon"); + } } const app = new App(); diff --git a/doc_source/tagging.md b/doc_source/tagging.md index a3303d53..070a4258 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -305,7 +305,7 @@ Tag.remove(theBestStack, 'StackType', { #### [ JavaScript ] ``` -const { App , Stack , Tag } = require('@aws-cdk/core'); +const { App , Stack , Tag } = require('@aws-cdk/core'); const app = new App(); const theBestStack = new Stack(app, 'MarketingSystem'); From 9d7d01aa3a48ae35421a88fae7d9b54e607a9d41 Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Fri, 24 Apr 2020 09:17:34 -0700 Subject: [PATCH 140/655] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index af1b0163..652e671c 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ so the community can see, comment, and contribute. > :memo: **NOTE** - > The Markdown files in this repository are an *output* of the AWS CDK Developer Guide build process, not the actual source files. Periodically, we update the Markdown files here from our builds. This means that changes may appear on docs.aws.amazon.com before they appear -here. Also, sometimes we may close a PR instead of merging it, even if we have in fact integrated your submission into the Guide. +here. ## Other Documentation Issues From a71cc7c21a448068fd9fc670a376f2d997a427f3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 27 Apr 2020 19:57:12 +0000 Subject: [PATCH 141/655] improve JS/Python tapics --- doc_source/work-with-cdk-javascript.md | 82 ++++++++++++++++++++++++-- doc_source/work-with-cdk-python.md | 14 ++++- 2 files changed, 90 insertions(+), 6 deletions(-) diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index c40fc51d..522eddbb 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -94,10 +94,78 @@ For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](too ## Using TypeScript Examples with JavaScript -[TypeScript](https://www.typescriptlang.org/) is the language we use to develop the AWS CDK, and it was the first language supported for developing applications, so many available AWS CDK code examples are written in TypeScript\. These code examples can be a good resource for JavaScript developers; you just need to remove the TypeScript\-specific parts of the code\. The most commonly\-used features are type annotations and interface declarations\. +[TypeScript](https://www.typescriptlang.org/) is the language we use to develop the AWS CDK, and it was the first language supported for developing applications, so many available AWS CDK code examples are written in TypeScript\. These code examples can be a good resource for JavaScript developers; you just need to remove the TypeScript\-specific parts of the code\. + +TypeScript snippets often use the newer ECMAScript `import` and `export` keywords to import objects from other modules and to declare the objects to be made available outside the current module\. Node\.js has just begun supporting these keywords in its latest releases\. Depending on the version of Node\.js you're using, you might rewrite imports and exports to use the older syntax\. + +Imports can be replaced with calls to the `require()` function\. + +------ +#### [ TypeScript ] + +``` +import * as cdk from '@aws-cdk/core'; +import { Bucket, BucketPolicy } from '@aws-cdk/aws-s3'; +``` + +------ +#### [ JavaScript ] + +``` +const cdk = require('@aws-cdk/core'); +const { Bucket, BucketPolicy } = require('@aws-cdk/aws-s3'); +``` + +------ + +Exports can be assigned to the `module.exports` object\. + +------ +#### [ TypeScript ] + +``` +export class Stack1 extends cdk.Stack { + // ... +} + +export class Stack2 extends cdk.Stack { + // ... +} +``` + +------ +#### [ JavaScript ] + +``` +class Stack1 extends cdk.Stack { + // ... +} + +class Stack2 extends cdk.Stack { + // ... +} + +module.exports = { Stack1, Stack2 } +``` + +------ + +**Note** +An alternative to using the old\-style imports and exports is to use the [https://www.npmjs.com/package/esm](https://www.npmjs.com/package/esm) module\. + +Once you've got the imports and exports sorted, you can dig into the actual code\. You may run into these commonly\-used TypeScript features: ++ Type annotations ++ Interface definitions ++ Type conversions/casts ++ Access modifiers Type annotations may be provided for variables, class members, function parameters, and function return types\. For variables, parameters, and members, types are specified by following the identifier with a colon and the type\. Function return values follow the function signature and consist of a colon and the type\. +To convert type\-annotated code to JavaScript, remove the colon and the type\. Class members must have some value in JavaScript; set them to `undefined` if they only have a type annotation in TypeScript\. + +------ +#### [ TypeScript ] + ``` var encrypted: boolean = true; @@ -111,12 +179,14 @@ function makeEnv(account: string, region: string) : object { } ``` -To convert type\-annotated code to JavaScript, remove the colon and the type\. Class members must have some value in JavaScript; remove them entirely if they only have a type annotation in TypeScript\. +------ +#### [ JavaScript ] ``` var encrypted = true; class myStack extends core.Stack { + bucket = undefined; // ... } @@ -125,6 +195,8 @@ function makeEnv(account, region) { } ``` +------ + In TypeScript, interfaces are used to give bundles of required and optional properties, and their types, a name\. You can then use the interface name as a type annotation\. TypeScript will make sure that the object you use as, for example, an argument to a function has the required properties of the right types\. ``` @@ -134,11 +206,13 @@ interface myFuncProps { } ``` -JavaScript does not have an interface feature, so once you've removed the type annotations, delete the interface declarations as well\. +JavaScript does not have an interface feature, so once you've removed the type annotations, delete the interface declarations entirely\. + +When a function or method returns a general\-purpose type \(such as `object`\), but you want to treat that value as a more specific child type to access properties or methods that are not part of the more general type's interface, TypeScript lets you *cast* the value using `as` followed by a type or interface name\. JavaScript doesn't support \(or need\) this, so simply remove `as` and the following identifier\. A less\-common cast syntax is to use a type name in brackets, ``; these casts, too, must be removed\. Finally, TypeScript supports the access modifiers `public`, `protected`, and `private` for members of classes\. All class members in JavaScript are public\. Simply remove these modifiers wherever you see them\. -Knowing how to identify and remove these three TypeScript features goes a long way toward adapting short TypeScript snippets to JavaScript\. But it may be impractical to convert longer TypeScript examples in this fashion, since they are more likely to use TypeScript features you're not familiar with\. For these situations, we recommend [Babel](https://babeljs.io/) with the [TypeScript plug\-in](https://babeljs.io/docs/en/babel-plugin-transform-typescript)\. Babel won't complain if code uses an undefined variable, for example, as `tsc` would\. If it is syntactically valid, then with few exceptions, Babel can translate it to JavaScript\. This makes Babel particularly valuable for converting snippets that may not be runnable in on their own\. +Knowing how to identify and remove these TypeScript features goes a long way toward adapting short TypeScript snippets to JavaScript\. But it may be impractical to convert longer TypeScript examples in this fashion, since they are more likely to use other TypeScript features\. For these situations, we recommend [Babel](https://babeljs.io/) with the [TypeScript plug\-in](https://babeljs.io/docs/en/babel-plugin-transform-typescript)\. Babel won't complain if code uses an undefined variable, for example, as `tsc` would\. If it is syntactically valid, then with few exceptions, Babel can translate it to JavaScript\. This makes Babel particularly valuable for converting snippets that may not be runnable on their own\. ## Migrating to TypeScript diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index bb1497b0..b8064160 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -85,9 +85,9 @@ All AWS Construct Library modules used in your project must be the same version\ ### Props -All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. +Natively, all AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. -In Python, props are expressed as keyword arguments\. If an argument contains nested data structures, these are expressed using a class which takes its own keyword arguments at instantiation\. The same pattern applies to other method calls that take a single structured argument\. +In Python, props are expressed as keyword arguments\. If an argument contains nested data structures, these are expressed using a class which takes its own keyword arguments at instantiation\. The same pattern is applied to other method calls that take a single structured argument\. For example, in a Amazon S3 bucket's `add_lifecycle_rule` method, the `transitions` property is a list of `Transition` instances\. @@ -133,6 +133,16 @@ class MyAspect(): print("Visited", node.node.path) ``` +### Type Pitfalls + +Python natively uses dynamic typing, where variables may refer to a value of any type\. Parameters and return values may be annotated with types, but these are "hints" and are not enforced\. This means that in Python, it is easy to pass the incorrect type of value to a AWS CDK construct\. Instead of getting a type error during build, as you would from a statically\-typed language, you may instead get a runtime error when the JSII layer \(which translates between Python and the AWS CDK's TypeScript core\) is unable to deal with the unexpected type\. + +In our experience, the type errors Python programmers make tend to fall into these categories\. Be especially alert to these pitfalls\. ++ Passing a single value where a construct expects a container \(Python list or dictionary\) or vice versa\. ++ Passing a value of a type associated with a Level 1 \(`CfnXxxxxx`\) construct to a higher\-level construct, or vice versa\. + +The AWS CDK Python modules do include type annotations\. If you are not using an IDE that supports these, such as [PyCharm](https://www.jetbrains.com/pycharm/), you might want to call the [MyPy](http://mypy-lang.org/) type validator as a step in your build process\. There are also runtime type checkers that can improve errror messages for type\-related errors\. + ## Synthesizing and Deploying The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. From 5f623d2299cecc24496489562dceb7f28b2bf0b8 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 28 Apr 2020 21:18:35 +0000 Subject: [PATCH 142/655] fix some bugs --- doc_source/codepipeline_example.md | 10 ++++++---- doc_source/getting_started.md | 4 +++- doc_source/identifiers.md | 2 +- doc_source/testing.md | 8 ++++---- doc_source/troubleshooting.md | 4 +++- 5 files changed, 17 insertions(+), 11 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 3fe2dd41..2aa00d83 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -16,7 +16,7 @@ mkdir pipeline cd pipeline cdk init --language typescript mkdir Lambda -npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild +npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 ``` @@ -28,7 +28,7 @@ mkdir pipeline cd pipeline cdk init ‐-language javascript mkdir Lambda -npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild +npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 ``` @@ -42,7 +42,7 @@ cdk init --language python source .env/bin/activate pip install -r requirements.txt mkdir Lambda -pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild +pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_s3 ``` @@ -64,6 +64,7 @@ lambda codedeploy codebuild codecommit +codepipeline codepipeline-actions s3 ``` @@ -86,6 +87,7 @@ Amazon.CDK.AWS.CodeDeploy Amazon.CDK.AWS.Lambda Amazon.CDK.AWS.CodeBuild Amazon.CDK.AWS.CodeCommit +Amazon.CDK.AWS.CodePipeline Amazon.CDK.AWS.CodePipeline.Actions Amazon.CDK.AWS.S3 ``` @@ -1178,5 +1180,5 @@ Try making a change, such as to your `LambdaStack` AWS CDK code or to your Lambd To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done with this exercise\. ``` -cdk destroy +cdk destroy * ``` \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 20a291b6..8218e54a 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -139,7 +139,9 @@ new MyStack(app, 'MyStack', { #### [ Python ] ``` -MyStack(app, "MyStack", env=core.Environment(region="REGION",account="ACCOUNT") +MyStack(app, "MyStack", env=core.Environment( + region="REGION", + account="ACCOUNT")) ``` ------ diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index 3923b81c..7b5c614e 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -185,7 +185,7 @@ string path = myConstruct.Node.Path; Since AWS CloudFormation requires that all logical IDs in a template are unique, the AWS CDK must be able to generate a unique identifier for each construct in an application\. Since the AWS CDK already has paths that are globally unique, the AWS CDK generates these unique identifiers by concatenating the elements of the path, and adds an 8\-digit hash\. The hash is necessary, as otherwise two distinct paths, such as `A/B/C` and `A/BC` would result in the same identifier\. The AWS CDK calls this concatenated path elements and hash the *unique ID* of the construct\. -You can access the unique ID of any construct programmatically, as shown in the following example, which gets the unique ID of `myConstruct` \(or `my_costruct` in Python conventions\)\. Since ids must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. +You can access the unique ID of any construct programmatically, as shown in the following example, which gets the unique ID of `myConstruct` \(or `my_construct` in Python conventions\)\. Since ids must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. ------ #### [ TypeScript ] diff --git a/doc_source/testing.md b/doc_source/testing.md index 19a50f12..0e356e46 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -21,7 +21,7 @@ cdk init --language=typescript lib npm install @aws-cdk/aws-sqs @aws-cdk/aws-cloudwatch ``` - Place the following code in `lib/dead-letter-queue.ts`: + Place the following code in `lib/index.ts`: ``` import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; @@ -88,7 +88,7 @@ Add a snapshot test by placing the following code in `test/dead-letter-queue.tes import { SynthUtils } from '@aws-cdk/assert'; import { Stack } from '@aws-cdk/core'; -import * as dlq from '../lib/dead-letter-queue'; +import * as dlq from '../lib/index'; test('dlq creates an alarm', () => { const stack = new Stack(); @@ -132,7 +132,7 @@ Object { ### Testing the Test -To make sure the test works, change the construct so that it generates different AWS CloudFormation output, then build and test again\. For example, add a `period` property of 1 minute to override the default of 5 minutes\. The boldface line below shows the code that needs to be added to `dead-letter-queue.ts`\. +To make sure the test works, change the construct so that it generates different AWS CloudFormation output, then build and test again\. For example, add a `period` property of 1 minute to override the default of 5 minutes\. The boldface line below shows the code that needs to be added to `index.ts`\. ``` this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { @@ -224,7 +224,7 @@ Replace the code in `test/dead-letter-queue.test.ts` with the following\. import { Stack } from '@aws-cdk/core'; import '@aws-cdk/assert/jest'; -import * as dlq from '../lib/dead-letter-queue'; +import * as dlq from '../lib/index'; test('dlq creates an alarm', () => { const stack = new Stack(); diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index a48fb072..ec77f458 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -13,10 +13,12 @@ This topic describes how to troubleshoot the following issues with the AWS CDK\. **After updating the AWS CDK, code that used to work fine now results in errors** Errors in code that used to work is typically a symptom of having mismatched versions of AWS Construct Library modules\. Make sure all library modules are the same version and up\-to\-date\. -The modules that make up the AWS Construct Library are a matched set\. They are released together and are intended to be used together\. Interfaces between modules are considered private; we may change them when necessary to implement new features in the library\. +The modules that make up the AWS Construct Library are a matched set\. They are released together and are intended to be used together\. Interfaces between modules are considered private; we may change them when necessary to implement new features in the library\. We also update the libraries that are used by the AWS Construct Library from time to time, and different versions of the library modules may have incompatible dependencies\. Synchronizing the versions of the library modules will also address this issue\. +[JSII](https://github.com/aws/jsii) is an important AWS CDK dependency, especially if you are using the AWS CDK in a language other than TypeScript or JavaScript\. You do not ordinarily have to concern yourself with the JSII versions, since it is a declared dependency of all AWS CDK modules\. If a compatible version is not installed, however, you can see unexpected type\-relatd errors, such as `'undefined' is not a valid TargetType`\. Making sure all AWS CDK modules are the same version will resolve JSII compatibility issues, since they will all depend on the same JSII version\. + Below, you'll find details on managing the versions of your installed AWS Construct Library modules in TypeScript, JavaScript, Python, Java, and C\#\. ------ From ccff2935f0730247657dedb76cfc62ce6fc81c01 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 29 Apr 2020 22:13:03 +0000 Subject: [PATCH 143/655] update cdk CLI help --- doc_source/tools.md | 439 ++++++++++++++++++++++++++++++-------------- 1 file changed, 300 insertions(+), 139 deletions(-) diff --git a/doc_source/tools.md b/doc_source/tools.md index 049ab294..b267d8fd 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -29,71 +29,113 @@ You can also use npx cdk instead of just cdk\. npx cdk looks for a locally\-inst Here are the actions you can take on your AWS CDK app \(this is the output of the cdk \-\-help command\)\. ``` -Usage: cdk -a COMMAND - -Commands: - cdk list [STACKS..] Lists all stacks in the app [aliases: ls] - cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation - template for this stack [aliases: synth] - cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS - environment - cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your - AWS account - cdk destroy [STACKS..] Destroy the stack(s) named STACKS - cdk diff [STACKS..] Compares the specified stack with the deployed - stack or a local template file, and returns - with status 1 if any difference is found - cdk metadata [STACK] Returns all metadata associated with this - stack - cdk init [TEMPLATE] Create a new, empty CDK project from a - template. Invoked without TEMPLATE, the app - template will be used. - cdk context Manage cached context values - cdk docs Opens the reference documentation in a browser - [aliases: doc] - cdk doctor Check your set-up for potential problems - -Options: - --app, -a REQUIRED: command-line for executing your app or a cloud - assembly directory (e.g. "node bin/my-app.js") [string] - --context, -c Add contextual string parameter (KEY=VALUE) [array] - --plugin, -p Name or path of a node package that extend the CDK - features. Can be specified multiple times [array] - --trace Print trace for stack warnings [boolean] - --strict Do not construct stacks with warnings [boolean] - --ignore-errors Ignores synthesis errors, which will likely produce an - invalid output [boolean] [default: false] - --json, -j Use JSON output instead of YAML when templates are - printed to STDOUT [boolean] [default: false] - --verbose, -v Show debug logs [boolean] [default: false] - --profile Use the indicated AWS profile as the default environment - [string] - --proxy Use the indicated proxy. Will read from HTTPS_PROXY - environment variable if not specified. [string] - --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: - guess EC2 instance status. [boolean] - --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized - templates (enabled by default) [boolean] - --path-metadata Include "aws:cdk:path" CloudFormation metadata for each - resource (enabled by default) [boolean] [default: true] - --asset-metadata Include "aws:asset:*" CloudFormation metadata for - resources that user assets (enabled by default) - [boolean] [default: true] - --role-arn, -r ARN of Role to use when invoking CloudFormation [string] - --toolkit-stack-name The name of the CDK toolkit stack [string] - --staging Copy assets to the output directory (use --no-staging to - disable, needed for local debugging the source files - with SAM CLI) [boolean] [default: true] - --output, -o Emits the synthesized cloud assembly into a directory - (default: cdk.out) [string] - --no-color Removes colors and other style from console output - [boolean] [default: false] - --version Show version number [boolean] - -h, --help Show help [boolean] - -If your app has a single stack, there is no need to specify the stack name - -If one of cdk.json or ~/.cdk.json exists, options specified there will be used +Usage: cdk -a COMMAND + +Commands: + + cdk list [STACKS..] Lists all stacks in the app [aliases: ls] + + cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation + template for this stack [aliases: synth] + + + cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS + environment + + cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your + AWS account + + cdk destroy [STACKS..] Destroy the stack(s) named STACKS + + cdk diff [STACKS..] Compares the specified stack with the deployed + stack or a local template file, and returns + with status 1 if any difference is found + + cdk metadata [STACK] Returns all metadata associated with this + stack + + cdk init [TEMPLATE] Create a new, empty CDK project from a + template. Invoked without TEMPLATE, the app + template will be used. + + cdk context Manage cached context values + + cdk docs Opens the reference documentation in a browser + [aliases: doc] + + + cdk doctor Check your set-up for potential problems + +Options: + + --app, -a REQUIRED: command-line for executing your app or a cloud + assembly directory (e.g. "node bin/my-app.js") [string] + + --context, -c Add contextual string parameter (KEY=VALUE) [array] + + --plugin, -p Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] + + --trace Print trace for stack warnings [boolean] + + --strict Do not construct stacks with warnings [boolean] + + --ignore-errors Ignores synthesis errors, which will likely produce an + invalid output [boolean] [default: false] + + --json, -j Use JSON output instead of YAML when templates are + printed to STDOUT [boolean] [default: false] + + --verbose, -v Show debug logs [boolean] [default: false] + + --profile Use the indicated AWS profile as the default environment + [string] + + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified. [string] + + --ca-bundle-path Path to CA certificate to use when validating HTTPS + requests. Will read from AWS_CA_BUNDLE environment + variable if not specified. [string] + + --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: + guess EC2 instance status. [boolean] + + --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized + templates (enabled by default) [boolean] + + --path-metadata Include "aws:cdk:path" CloudFormation metadata for each + resource (enabled by default) [boolean] [default: true] + + --asset-metadata Include "aws:asset:*" CloudFormation metadata for + resources that user assets (enabled by default) + [boolean] [default: true] + + --role-arn, -r ARN of Role to use when invoking CloudFormation [string] + + --toolkit-stack-name The name of the CDK toolkit stack [string] + + --staging Copy assets to the output directory (use --no-staging to + disable, needed for local debugging the source files + with SAM CLI) [boolean] [default: true] + + --output, -o Emits the synthesized cloud assembly into a directory + (default: cdk.out) [string] + + --no-color Removes colors and other style from console output + [boolean] [default: false] + + --fail Fail with exit code 1 in case of diff + [boolean] [default: false] + + --version Show version number [boolean] + + -h, --help Show help [boolean] + + +If your app has a single stack, there is no need to specify the stack name + +If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` @@ -106,24 +148,26 @@ The AWS CDK CLI supports several distinct commands\. Help for each \(including o #### `cdk list` \(`ls`\) ``` -cdk list [STACKS..] - -Lists all stacks in the app - -Options: - --long, -l Display environment information for each stack +cdk list [STACKS..] + +Lists all stacks in the app + +Options: + + --long, -l Display environment information for each stack [boolean] [default: false] ``` #### `cdk synthesize` \(`synth`\) ``` -cdk synthesize [STACKS..] - -Synthesizes and prints the CloudFormation template for this stack - -Options: - --exclusively, -e Only synthesize requested stacks, don't include +cdk synthesize [STACKS..] + +Synthesizes and prints the CloudFormation template for this stack + +Options: + + --exclusively, -e Only synthesize requested stacks, don't include dependencies [boolean] ``` @@ -132,45 +176,155 @@ If your app has a single stack, you don't have to specify the stack name\. #### `cdk bootstrap` ``` -cdk bootstrap [ENVIRONMENTS..] - -Deploys the CDK toolkit stack into an AWS environment - -Options: - --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket - --toolkit-bucket-name [string] - --bootstrap-kms-key-id AWS KMS master key ID used for the - SSE-KMS encryption [string] - --tags, -t Tags to add for the stack - (KEY=VALUE) [array] [default: []] - --execute Whether to execute ChangeSet - (--no-execute will NOT execute the - ChangeSet) [boolean] [default: true] +cdk bootstrap [ENVIRONMENTS..] + +Deploys the CDK toolkit stack into an AWS environment + +Options: + + +Deploys the CDK toolkit stack into an AWS environment + +Options: + --app, -a REQUIRED: command-line for executing + your app or a cloud assembly + directory (e.g. "node + bin/my-app.js") [string] + + --context, -c Add contextual string parameter + (KEY=VALUE) [array] + + --plugin, -p Name or path of a node package that + extend the CDK features. Can be + specified multiple times [array] + + --trace Print trace for stack warnings + [boolean] + + --strict Do not construct stacks with + warnings [boolean] + + --ignore-errors Ignores synthesis errors, which will + likely produce an invalid output + [boolean] [default: false] + + --json, -j Use JSON output instead of YAML when + templates are printed to STDOUT + [boolean] [default: false] + + --verbose, -v Show debug logs + [boolean] [default: false] + + --profile Use the indicated AWS profile as the + default environment [string] + + --proxy Use the indicated proxy. Will read + from HTTPS_PROXY environment + variable if not specified. [string] + + --ca-bundle-path Path to CA certificate to use when + validating HTTPS requests. Will read + from AWS_CA_BUNDLE environment + variable if not specified. [string] + + --ec2creds, -i Force trying to fetch EC2 instance + credentials. Default: guess EC2 + instance status. [boolean] + + --version-reporting Include the "AWS::CDK::Metadata" + resource in synthesized templates + (enabled by default) [boolean] + + --path-metadata Include "aws:cdk:path" + CloudFormation metadata for each + resource (enabled by default) + [boolean] [default: true] + + --asset-metadata Include "aws:asset:*" CloudFormation + metadata for resources that user + assets (enabled by default) + [boolean] [default: true] + + --role-arn, -r ARN of Role to use when invoking + CloudFormation [string] + + --toolkit-stack-name The name of the CDK toolkit stack + [string] + + --staging Copy assets to the output directory + (use --no-staging to disable, needed + for local debugging the source files + with SAM CLI) + [boolean] [default: true] + + --output, -o Emits the synthesized cloud assembly + into a directory (default: cdk.out) + [string] + + --no-color Removes colors and other style from + console output + [boolean] [default: false] + + --fail Fail with exit code 1 in case of + diff [boolean] [default: false] + + --version Show version number [boolean] + + --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket + --toolkit-bucket-name [string] + + --bootstrap-kms-key-id AWS KMS master key ID used for the + SSE-KMS encryption [string] + + --tags, -t Tags to add for the stack + (KEY=VALUE) [array] [default: []] + + --execute Whether to execute ChangeSet + (--no-execute will NOT execute the + ChangeSet) [boolean] [default: true] + + --force, -f Always bootstrap even if it would + downgrade template version + [boolean] [default: false] ``` #### `cdk deploy` ``` -cdk deploy [STACKS..] - -Deploys the stack(s) named STACKS into your AWS account - -Options: - --build-exclude, -E Do not rebuild asset with the given ID. Can be specified - multiple times. [array] [default: []] - --exclusively, -e Only deploy requested stacks, don't include dependencies - [boolean] - --require-approval What security-sensitive changes need manual approval - [string] [choices: "never", "any-change", "broadening"] - --ci Force CI detection. Use --no-ci to disable CI - autodetection. [boolean] [default: false] - --notification-arns ARNs of SNS topics that CloudFormation will notify with - stack related events [array] - --parameters Additional parameters passed to CloudFormation at deploy - time (STACK:KEY=VALUE) [array] [default: {}] - --tags, -t Tags to add to the stack (KEY=VALUE) [array] - --execute Whether to execute ChangeSet (--no-execute will NOT - execute the ChangeSet) [boolean] [default: true] +cdk deploy [STACKS..] + +Deploys the stack(s) named STACKS into your AWS account + +Options: + + --build-exclude, -E Do not rebuild asset with the given ID. Can be specified + multiple times. [array] [default: []] + + --exclusively, -e Only deploy requested stacks, don't include dependencies + [boolean] + + --require-approval What security-sensitive changes need manual approval + [string] [choices: "never", "any-change", "broadening"] + + --ci Force CI detection (deprecated) + [boolean] [default: false] + + --notification-arns ARNs of SNS topics that CloudFormation will notify with + stack related events [array] + + --tags, -t Tags to add to the stack (KEY=VALUE) [array] + + --execute Whether to execute ChangeSet (--no-execute will NOT + execute the ChangeSet) [boolean] [default: true] + + --force, -f Always deploy stack even if templates are identical + [boolean] [default: false] + + --parameters Additional parameters passed to CloudFormation at deploy + time (STACK:KEY=VALUE) [array] [default: {}] + + --outputs-file, -O Path to file where stack outputs will be written as JSON + [string] ``` If your app has a single stack, you don't have to specify the stack name\. @@ -178,14 +332,16 @@ If your app has a single stack, you don't have to specify the stack name\. #### `cdk destroy` ``` -cdk destroy [STACKS..] - -Destroy the stack(s) named STACKS - -Options: - --exclusively, -e Only destroy requested stacks, don't include dependees - [boolean] - --force, -f Do not ask for confirmation before destroying the stacks +cdk destroy [STACKS..] + +Destroy the stack(s) named STACKS + +Options: + + --exclusively, -e Only destroy requested stacks, don't include dependees + [boolean] + + --force, -f Do not ask for confirmation before destroying the stacks [boolean] ``` @@ -194,32 +350,37 @@ If your app has a single stack, you don't have to specify the stack name\. #### `cdk init` ``` -cdk init [TEMPLATE] - -Create a new, empty CDK project from a template. Invoked without TEMPLATE, the -app template will be used. - -Options: - --language, -l The language to be used for the new project (default can - be configured in ~/.cdk.json) - [string] [choices: "csharp", "fsharp", "java", "javascript", "python", - "typescript"] - --list List the available templates [boolean] - --generate-only If true, only generates project files, without executing - additional operations such as setting up a git repo, - installing dependencies or compiling the project +cdk init [TEMPLATE] + +Create a new, empty CDK project from a template. Invoked without TEMPLATE, the +app template will be used. + +Options: + + --language, -l The language to be used for the new project (default can + be configured in ~/.cdk.json) + [string] [choices: "csharp", "fsharp", "java", "javascript", "python", + "typescript"] + + --list List the available templates [boolean] + + --generate-only If true, only generates project files, without executing + additional operations such as setting up a git repo, + installing dependencies or compiling the project [boolean] [default: false] ``` #### `cdk context` ``` -cdk context - -Manage cached context values - -Options: - --reset, -e The context key (or its index) to reset [string] +cdk context + +Manage cached context values + +Options: + + --reset, -e The context key (or its index) to reset [string] + --clear Clear all context [boolean] ``` From 54fa8e76ae580d5007e776c1e64efc431a5b01b3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 5 May 2020 14:55:11 +0000 Subject: [PATCH 144/655] update to toolkit help --- doc_source/tools.md | 97 +-------------------------------------------- 1 file changed, 1 insertion(+), 96 deletions(-) diff --git a/doc_source/tools.md b/doc_source/tools.md index b267d8fd..6cff11c5 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -38,7 +38,6 @@ Commands: cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation template for this stack [aliases: synth] - cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS environment @@ -63,7 +62,6 @@ Commands: cdk docs Opens the reference documentation in a browser [aliases: doc] - cdk doctor Check your set-up for potential problems Options: @@ -132,7 +130,6 @@ Options: -h, --help Show help [boolean] - If your app has a single stack, there is no need to specify the stack name If one of cdk.json or ~/.cdk.json exists, options specified there will be used @@ -182,94 +179,6 @@ Deploys the CDK toolkit stack into an AWS environment Options: - -Deploys the CDK toolkit stack into an AWS environment - -Options: - --app, -a REQUIRED: command-line for executing - your app or a cloud assembly - directory (e.g. "node - bin/my-app.js") [string] - - --context, -c Add contextual string parameter - (KEY=VALUE) [array] - - --plugin, -p Name or path of a node package that - extend the CDK features. Can be - specified multiple times [array] - - --trace Print trace for stack warnings - [boolean] - - --strict Do not construct stacks with - warnings [boolean] - - --ignore-errors Ignores synthesis errors, which will - likely produce an invalid output - [boolean] [default: false] - - --json, -j Use JSON output instead of YAML when - templates are printed to STDOUT - [boolean] [default: false] - - --verbose, -v Show debug logs - [boolean] [default: false] - - --profile Use the indicated AWS profile as the - default environment [string] - - --proxy Use the indicated proxy. Will read - from HTTPS_PROXY environment - variable if not specified. [string] - - --ca-bundle-path Path to CA certificate to use when - validating HTTPS requests. Will read - from AWS_CA_BUNDLE environment - variable if not specified. [string] - - --ec2creds, -i Force trying to fetch EC2 instance - credentials. Default: guess EC2 - instance status. [boolean] - - --version-reporting Include the "AWS::CDK::Metadata" - resource in synthesized templates - (enabled by default) [boolean] - - --path-metadata Include "aws:cdk:path" - CloudFormation metadata for each - resource (enabled by default) - [boolean] [default: true] - - --asset-metadata Include "aws:asset:*" CloudFormation - metadata for resources that user - assets (enabled by default) - [boolean] [default: true] - - --role-arn, -r ARN of Role to use when invoking - CloudFormation [string] - - --toolkit-stack-name The name of the CDK toolkit stack - [string] - - --staging Copy assets to the output directory - (use --no-staging to disable, needed - for local debugging the source files - with SAM CLI) - [boolean] [default: true] - - --output, -o Emits the synthesized cloud assembly - into a directory (default: cdk.out) - [string] - - --no-color Removes colors and other style from - console output - [boolean] [default: false] - - --fail Fail with exit code 1 in case of - diff [boolean] [default: false] - - --version Show version number [boolean] - --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket --toolkit-bucket-name [string] @@ -281,11 +190,7 @@ Options: --execute Whether to execute ChangeSet (--no-execute will NOT execute the - ChangeSet) [boolean] [default: true] - - --force, -f Always bootstrap even if it would - downgrade template version - [boolean] [default: false] + ChangeSet) [boolean] [default: true] ``` #### `cdk deploy` From a4d9363052860ba2a5d6f0b784b1d23a5777011d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 5 May 2020 17:13:16 +0000 Subject: [PATCH 145/655] update cdk bootstrap help --- doc_source/tools.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/doc_source/tools.md b/doc_source/tools.md index 6cff11c5..6568df40 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -179,8 +179,9 @@ Deploys the CDK toolkit stack into an AWS environment Options: - --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket - --toolkit-bucket-name [string] + --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket; + --toolkit-bucket-name bucket will be created and must not + exist [string] --bootstrap-kms-key-id AWS KMS master key ID used for the SSE-KMS encryption [string] @@ -190,7 +191,11 @@ Options: --execute Whether to execute ChangeSet (--no-execute will NOT execute the - ChangeSet) [boolean] [default: true] + ChangeSet) [boolean] [default: true] + + --force, -f Always bootstrap even if it would + downgrade template version + [boolean] [default: false] ``` #### `cdk deploy` From 1f5b0c0906bb9ead9a7d5e25cef18e58e424ff2f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 5 May 2020 21:25:52 +0000 Subject: [PATCH 146/655] fix Maven requirement --- doc_source/getting_started.md | 2 +- doc_source/work-with-cdk-java.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 8218e54a..cec43cdc 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -32,7 +32,7 @@ No additional prerequisites ------ #### [ Java ] -+ Maven <= 3\.5 and Java >= 8 ++ Maven >= 3\.5 and Java >= 8 + A Java IDE is preferred \(the examples in this guide may refer to Eclipse\)\. `cdk init` creates a Maven project, which most IDEs can import\. Some IDEs may need to be configured to use Java 8 \(also known as 1\.8\)\. + Set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 8e8b0d3e..33d21fe7 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -10,7 +10,7 @@ It is possible to write AWS CDK applications in JVM\-hosted languages other than To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. -Java AWS CDK applications require Java 8 \(v1\.8\) or later\. We recommend [Amazon Corretto](https://aws.amazon.com/corretto/), but you can use any OpenJDK distribution or [Oracle's JDK](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)\. You will also need [Apache Maven](https://maven.apache.org/download.cgi) 3\.5\.4 or later\. You can also use tools such as Gradle, but the application skeletons generated by the AWS CDK Toolkit are Maven projects\. +Java AWS CDK applications require Java 8 \(v1\.8\) or later\. We recommend [Amazon Corretto](https://aws.amazon.com/corretto/), but you can use any OpenJDK distribution or [Oracle's JDK](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)\. You will also need [Apache Maven](https://maven.apache.org/download.cgi) 3\.5 or later\. You can also use tools such as Gradle, but the application skeletons generated by the AWS CDK Toolkit are Maven projects\. ## Creating a Project From f7adf574e39054121023688b21301dd55b29a7f2 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 5 May 2020 21:42:33 +0000 Subject: [PATCH 147/655] rewrite a sentence a reader referred to as a "massacre" --- doc_source/identifiers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index 7b5c614e..f6a51d51 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -138,7 +138,7 @@ class Program ## Paths -As the constructs in an AWS CDK application form a hierarchy, we refer to the collection of IDs from a given construct, then of its parent construct, then grandparent construct, and so on up to the root of the construct tree, which is an instance of the `App` class, as a *path*\. +The constructs in an AWS CDK application form a hierarchy rooted in the `App` class\. We refer to the collection of IDs from a given construct, its parent construct, its grandparent, and so on to the root of the construct tree, as a *path*\. The AWS CDK typically displays paths in your templates as a string, with the IDs from the levels separated by slashes, starting at the node just below the root `App` instance, which is usually a stack\. For example, the paths of the two Amazon S3 bucket resources in the previous code example are `Stack1/MyBucket` and `Stack2/MyBucket`\. From b01d2e3e0938783c68c48dfe800ed405eac2a07e Mon Sep 17 00:00:00 2001 From: sunnyp1227 Date: Thu, 7 May 2020 01:42:51 -0700 Subject: [PATCH 148/655] fix typo in multiple_languages.md --- doc_source/multiple_languages.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index ef2fb8bc..31b2c38c 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -24,7 +24,7 @@ import * as s3 from '@aws-cdk/aws-s3'; const s3 = require('@aws-cdk/aws-s3'); // TypeScript version of require() (again, import * as s3 generally preferred) -import s3 = require('@aws-cdk/aws-3'); +import s3 = require('@aws-cdk/aws-s3'); // Now use s3 to access the S3 types const bucket = s3.Bucket(...); @@ -331,4 +331,4 @@ public class MyAspect : IAspect } ``` ------- \ No newline at end of file +------ From 9bc4f9b2af79b2a0ba706e0e6b809f4423345dfd Mon Sep 17 00:00:00 2001 From: Graham Lea Date: Fri, 8 May 2020 20:52:14 +1000 Subject: [PATCH 149/655] Correct and expand on Java building * Fix reference to 'mvn buid' * Add instructions about running tests * Add note about always compiling before running cdk --- doc_source/work-with-cdk-java.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 33d21fe7..ec8e65ec 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -109,9 +109,12 @@ In Java, missing values in AWS CDK objects such as props are represented by `nul ## Building, Synthesizing, and Deploying -Before running, build \(compile\) the app in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn build` at a command prompt while in your project's root directory\. +Before running, build \(compile\) the app in your IDE \(for example, press Control\-B in Eclipse\) or by running `mvn compile` at a command prompt while in your project's root directory\. +The build step reports any syntax or type errors in your code\. -The build step reports any syntax or type errors in your code\. Once you can build your application without errors, you're ready to synthesize or deploy\. +Run any tests you've written by running `mvn test` at a command prompt\. + +Once you've built your application and run tests without errors, you're ready to synthesize or deploy\. The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. @@ -122,4 +125,8 @@ You can specify the names of multiple stacks to be synthesized or deployed in a **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file +**NOTE** +Whenever you change your application code, you need to run `mvn compile` or `mvn test` before using the `cdk` command\. +If you run CDK commands _without_ re-compiling the application, the `cdk` command will use the previously compiled version of your application code\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. From 8759b1a70ef18b2257bdb1ff82fe4cd965fa8716 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 8 May 2020 22:50:59 +0000 Subject: [PATCH 150/655] fix syntax in code sample, add note about removalPolicy on other kinds of resources --- doc_source/getting_started.md | 2 +- doc_source/resources.md | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index cec43cdc..a3f83ebf 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -570,7 +570,7 @@ Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represente In `lib/hello-cdk-stack.ts`: ``` -import * as core = from '@aws-cdk/core'; +import * as core from '@aws-cdk/core'; import * as s3 from '@aws-cdk/aws-s3'; export class HelloCdkStack extends core.Stack { diff --git a/doc_source/resources.md b/doc_source/resources.md index 708cbe7a..3a155875 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1112,6 +1112,9 @@ bucket.AddObjectCreatedNotification(new s3_not.LambdaDestination(handler)); Resources that maintain persistent data, such as databases and Amazon S3 buckets, have a *removal policy* that indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the AWS CDK `core` module\. +**Note** +Resources besides those that store data persistently may also have a `removalPolicy` that is used for a different purpose\. For example, a Lambda function version uses a `removalPolicy` attribute to determine whether a given version is retained when a new version is deployed\. These have different meanings and defaults compared to hte removal policy on an Amazon S3 bucket or DynamoDB table\. + | Value | Meaning | | --- |--- | From 9342e9c6d786edaec8b995a65a41d17c0281bc79 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 9 May 2020 04:45:25 +0000 Subject: [PATCH 151/655] improve Java instructions and fix a typo --- doc_source/multiple_languages.md | 2 +- doc_source/work-with-cdk-java.md | 16 +++++++--------- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 31b2c38c..72913fdc 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -331,4 +331,4 @@ public class MyAspect : IAspect } ``` ------- +------ \ No newline at end of file diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index ec8e65ec..26ae013c 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -109,12 +109,14 @@ In Java, missing values in AWS CDK objects such as props are represented by `nul ## Building, Synthesizing, and Deploying -Before running, build \(compile\) the app in your IDE \(for example, press Control\-B in Eclipse\) or by running `mvn compile` at a command prompt while in your project's root directory\. -The build step reports any syntax or type errors in your code\. +Before running, build \(compile\) the app in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn compile` at a command prompt while in your project's root directory\. -Run any tests you've written by running `mvn test` at a command prompt\. +The build step reports any syntax or type errors in your code\. Once you can build your application without errors, you're ready to synthesize or deploy\. -Once you've built your application and run tests without errors, you're ready to synthesize or deploy\. +**Note** +Every time you change your application code, re\-compile \(e\.g\. `mvn compile` or `mvn test`\) before using the `cdk` command\. Otherwise, the `cdk` command uses the previously compiled version of your application code\. + +Run any tests you've written by running `mvn test` at a command prompt\. The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. @@ -125,8 +127,4 @@ You can specify the names of multiple stacks to be synthesized or deployed in a **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. -**NOTE** -Whenever you change your application code, you need to run `mvn compile` or `mvn test` before using the `cdk` command\. -If you run CDK commands _without_ re-compiling the application, the `cdk` command will use the previously compiled version of your application code\. - -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file From 2247c579394c0a9d5a57db33376ce966c55e9590 Mon Sep 17 00:00:00 2001 From: Roshan Arvind Sivakumar <45235760+sivarosh@users.noreply.github.com> Date: Sun, 10 May 2020 18:58:48 +0530 Subject: [PATCH 152/655] Fixing a small typo Changed 'hte' to 'the' --- doc_source/resources.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index 3a155875..c7f5b62b 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1113,7 +1113,7 @@ bucket.AddObjectCreatedNotification(new s3_not.LambdaDestination(handler)); Resources that maintain persistent data, such as databases and Amazon S3 buckets, have a *removal policy* that indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the AWS CDK `core` module\. **Note** -Resources besides those that store data persistently may also have a `removalPolicy` that is used for a different purpose\. For example, a Lambda function version uses a `removalPolicy` attribute to determine whether a given version is retained when a new version is deployed\. These have different meanings and defaults compared to hte removal policy on an Amazon S3 bucket or DynamoDB table\. +Resources besides those that store data persistently may also have a `removalPolicy` that is used for a different purpose\. For example, a Lambda function version uses a `removalPolicy` attribute to determine whether a given version is retained when a new version is deployed\. These have different meanings and defaults compared to the removal policy on an Amazon S3 bucket or DynamoDB table\. | Value | Meaning | @@ -1261,4 +1261,4 @@ resource.ApplyRemovalPolicy(cdk.RemovalPolicy.DESTROY); ------ **Note** -The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. \ No newline at end of file +The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. From 669d931589b52980d6ae22763c2d5c74afcec05f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 13 May 2020 16:46:13 +0000 Subject: [PATCH 153/655] change to sentence-case headings throughout (new AWS style) --- doc_source/about_examples.md | 2 +- doc_source/apps.md | 8 +-- doc_source/aspects.md | 2 +- doc_source/assets.md | 22 ++++---- doc_source/cfn_layer.md | 10 ++-- doc_source/codepipeline_example.md | 12 ++-- doc_source/compliance-validation.md | 2 +- doc_source/constructs.md | 14 ++--- doc_source/context.md | 8 +-- doc_source/doc-history.md | 2 +- doc_source/ecs_example.md | 10 ++-- doc_source/examples.md | 6 +- doc_source/featureflags.md | 4 +- doc_source/get_cfn_param.md | 4 +- doc_source/get_context_var.md | 4 +- doc_source/get_env_var.md | 2 +- doc_source/get_secrets_manager_value.md | 2 +- doc_source/get_ssm_value.md | 12 ++-- doc_source/getting_started.md | 40 ++++++------- doc_source/home.md | 16 +++--- doc_source/how_to_set_cw_alarm.md | 2 +- doc_source/how_tos.md | 2 +- doc_source/identifiers.md | 2 +- doc_source/index.md | 56 +++++++++---------- doc_source/infrastructure-security.md | 2 +- doc_source/multiple_languages.md | 12 ++-- doc_source/parameters.md | 16 +++--- doc_source/permissions.md | 2 +- doc_source/pgp-keys.md | 6 +- doc_source/reference.md | 14 ++--- doc_source/resources.md | 24 ++++---- doc_source/security-iam.md | 2 +- doc_source/security.md | 6 +- doc_source/serverless_example.md | 18 +++--- .../stack_how_to_create_multiple_stacks.md | 16 +++--- doc_source/stacks.md | 2 +- doc_source/testing.md | 20 +++---- doc_source/tokens.md | 12 ++-- doc_source/tools.md | 14 ++--- doc_source/troubleshooting.md | 4 +- doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-csharp.md | 16 +++--- doc_source/work-with-cdk-java.md | 12 ++-- doc_source/work-with-cdk-javascript.md | 12 ++-- doc_source/work-with-cdk-python.md | 14 ++--- doc_source/work-with-cdk-typescript.md | 10 ++-- doc_source/work-with.md | 2 +- 47 files changed, 241 insertions(+), 241 deletions(-) diff --git a/doc_source/about_examples.md b/doc_source/about_examples.md index af8a112e..4ebced7b 100644 --- a/doc_source/about_examples.md +++ b/doc_source/about_examples.md @@ -1,4 +1,4 @@ -# AWS CDK Examples +# AWS CDK examples For more examples of AWS CDK stacks and apps in your favorite supported programming language, see: + The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repository on GitHub diff --git a/doc_source/apps.md b/doc_source/apps.md index 734dc099..a7df08fc 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -74,7 +74,7 @@ public class MyFirstStack : Stack ------ -## The App Construct +## The app construct To define the previous stack within the scope of an application, use the [App](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/app.html) construct\. The following example app instantiates a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. @@ -217,7 +217,7 @@ class Program These two methods are equivalent\. -## App Lifecycle +## App lifecycle The following diagram shows the phases that the AWS CDK goes through when you call the cdk deploy\. This command deploys the resources that your app defines\. @@ -235,7 +235,7 @@ All constructs that have implemented the `prepare` method participate in a final All constructs that have implemented the `validate` method can validate themselves to ensure that they're in a state that will correctly deploy\. You will get notified of any validation failures that happen during this phase\. Generally, we recommend that you perform validation as soon as possible \(usually as soon as you get some input\) and throw exceptions as early as possible\. Performing validation early improves diagnosability as stack traces will be more accurate, and ensures that your code can continue to execute safely\. 4\. Synthesis -This is the final stage of the execution of your AWS CDK app\. It's triggered by a call to `app.synth()`, and it traverses the construct tree and invokes the `synthesize` method on all constructs\. Constructs that implement `synthesize` can participate in synthesis and emit deployment artifacts to the resulting cloud assembly\. These constructs include AWS CloudFormation templates, AWS Lambda application bundles, file and Docker image assets, and other deployment artifacts\. [Cloud Assemblies](#apps_cloud_assembly) describes the output of this phase\. In most cases, you won't need to implement the `synthesize` method +This is the final stage of the execution of your AWS CDK app\. It's triggered by a call to `app.synth()`, and it traverses the construct tree and invokes the `synthesize` method on all constructs\. Constructs that implement `synthesize` can participate in synthesis and emit deployment artifacts to the resulting cloud assembly\. These constructs include AWS CloudFormation templates, AWS Lambda application bundles, file and Docker image assets, and other deployment artifacts\. [Cloud assemblies](#apps_cloud_assembly) describes the output of this phase\. In most cases, you won't need to implement the `synthesize` method 5\. Deployment In this phase, the AWS CDK CLI takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. @@ -244,7 +244,7 @@ By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS + The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. + The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)` \(Python: `is_token`\)\. See [Tokens](tokens.md) for details\. -## Cloud Assemblies +## Cloud assemblies The call to `app.synth()` is what tells the AWS CDK to synthesize a cloud assembly from an app\. Typically you don't interact directly with cloud assemblies\. They are files that include everything needed to deploy your app to a cloud environment\. For example, it includes an AWS CloudFormation template for each stack in your app, and a copy of any file assets or Docker images that you reference in your app\. diff --git a/doc_source/aspects.md b/doc_source/aspects.md index a86a0d3b..080bb27e 100644 --- a/doc_source/aspects.md +++ b/doc_source/aspects.md @@ -43,7 +43,7 @@ myConstruct.Node.ApplyAspect(new SomeAspect(...)); The AWS CDK currently uses aspects only to [tag resources](tagging.md), but the framework is extensible and can also be used for other purposes\. For example, you can use it to validate or change the AWS CloudFormation resources that are defined for you\. -## Aspects in Detail +## Aspects in detail The AWS CDK implements tagging using a more generic system, called *aspects*, which is an instance of the visitor pattern\. An aspect is a class that implements the following interface\. diff --git a/doc_source/assets.md b/doc_source/assets.md index 00650866..19c668ec 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -4,13 +4,13 @@ Assets are local files, directories, or Docker images that can be bundled into A You typically reference assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html#code) property lets you pass an [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function's code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-assetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. -## Assets in Detail +## Assets in detail When you refer to an asset in your app, the [cloud assembly](apps.md#apps_cloud_assembly) synthesized from your application includes metadata information with instructions for the AWS CDK CLI on where to find the asset on the local disk, and what type of bundling to perform based on the type of asset, such as a directory to compress \(zip\) or a Docker image to build\. The AWS CDK generates a source hash for assets and can be used at construction time to determine whether the contents of an asset have changed\. -By default, the AWS CDK creates a copy of the asset in the cloud assembly directory, which defaults to `cdk.out`, under the source hash\. This is so that the cloud assembly is self\-contained and moved over to a different host for deployment\. See [Cloud Assemblies](apps.md#apps_cloud_assembly) for details\. +By default, the AWS CDK creates a copy of the asset in the cloud assembly directory, which defaults to `cdk.out`, under the source hash\. This is so that the cloud assembly is self\-contained and moved over to a different host for deployment\. See [Cloud assemblies](apps.md#apps_cloud_assembly) for details\. The AWS CDK also synthesizes AWS CloudFormation parameters that the AWS CDK CLI specifies during deployment\. The AWS CDK uses those parameters to refer to the deploy\-time values of the asset\. @@ -18,7 +18,7 @@ When the AWS CDK deploys an app that references assets \(either directly by the This section describes the low\-level APIs available in the framework\. -## Asset Types +## Asset types The AWS CDK supports the following types of assets: @@ -30,7 +30,7 @@ These are Docker images that the AWS CDK uploads to Amazon ECR\. These asset types are explained in the following sections\. -### Amazon S3 Assets +### Amazon S3 assets You can define local files and directories as assets, and the AWS CDK packages and uploads them to Amazon S3 through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-assets-readme.html) module\. @@ -134,7 +134,7 @@ var fileAsset = new Asset(this, "SampleSingleFileAsset", new AssetProps In most cases, you don't need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods that enable you to use assets\. For Lambda functions, the [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) property enables you to specify a directory or a \.zip file in the local file system\. -#### Lambda Function Example +#### Lambda function example A common use case is to create AWS Lambda functions with the handler code, which is the entry point for the function, as an Amazon S3 asset\. @@ -270,7 +270,7 @@ public class HelloAssetStack : Stack The `Function` method uses assets to bundle the contents of the directory and use it for the function's code\. -#### Deploy\-Time Attributes Example +#### Deploy\-time attributes example Amazon S3 asset types also expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. @@ -508,7 +508,7 @@ asset.GrantRead(group); ------ -### Docker Image Assets +### Docker image assets The AWS CDK supports bundling local Docker images as assets through the [aws\-ecr\-assets](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecr-assets-readme.html) module\. @@ -578,7 +578,7 @@ var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps The `my-image` directory must include a Dockerfile\. The AWS CDK CLI builds a Docker image from `my-image`, pushes it to an Amazon ECR repository, and specifies the name of the repository as an AWS CloudFormation parameter to your stack\. Docker image asset types expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. -#### Amazon ECS Task Definition Example +#### Amazon ECS task definition example A common use case is to create an Amazon ECS [TaskDefinition](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.TaskDefinition.html) to run docker containers\. The following example specifies the location of a Docker image asset that the AWS CDK builds locally and pushes to Amazon ECR\. @@ -676,7 +676,7 @@ taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions ------ -#### Deploy\-Time Attributes Example +#### Deploy\-time attributes example The following example shows how to use the deploy\-time attributes `repository` and `imageUri` to create an Amazon ECS task definition with the AWS Fargate launch type\. @@ -796,7 +796,7 @@ taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions ------ -#### Build Arguments Example +#### Build arguments example You can provide customized build arguments for the Docker build step through the `buildArgs` \(Python: `build_args`\) property option when the AWS CDK CLI builds the image during deployment\. @@ -865,7 +865,7 @@ If you use a module that supports Docker image assets, such as [aws\-ecs](https: In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecr.Repository.html#grant-pullgrantee) method \(Python: `grant_pull`\. This modifies the IAM policy of the principal to enable it to pull images from this repository\. If the principal that is pulling the image is not in the same account or is an AWS service, such as AWS CodeBuild, that does not assume a role in your account, you must grant pull permissions on the resource policy and not on the principal's policy\. Use the [asset\.repository\.addToResourcePolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecr.Repository.html#add-to-resource-policystatement) method \(Python: `add_to_resource_policy`\) to grant the appropriate principal permissions\. -## AWS CloudFormation Resource Metadata +## AWS CloudFormation resource metadata **Note** This section is relevant only for construct authors\. In certain situations, tools need to know that a certain CFN resource is using a local asset\. For example, you can use the AWS SAM CLI to invoke Lambda functions locally for debugging purposes\. See [SAM CLI](tools.md#sam) for details\. diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index ffe538a7..e97e37b6 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -1,4 +1,4 @@ -# Escape Hatches +# Escape hatches It's possible that neither the high\-level constructs nor the low\-level CFN Resource constructs have a specific feature you are looking for\. There are three possible reasons for this lack of functionality: + The AWS service feature is available through AWS CloudFormation, but there are no Construct classes for the service\. @@ -7,7 +7,7 @@ It's possible that neither the high\-level constructs nor the low\-level CFN Res To determine whether a feature is available through AWS CloudFormation, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. -## Using AWS CloudFormation Constructs Directly +## Using AWS CloudFormation constructs directly If there are no Construct classes available for the service, you can fall back to the automatically generated CFN Resources, which map 1:1 onto all available AWS CloudFormation resources and properties\. These resources can be recognized by their name starting with `Cfn`, such as `CfnBucket` or `CfnRole`\. You instantiate them exactly as you would use the equivalent AWS CloudFormation resource\. For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. @@ -175,7 +175,7 @@ new CfnResource(this, "MyBucket", new CfnResourceProps For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. -## Modifying the AWS CloudFormation Resource behind AWS Constructs +## Modifying the AWS CloudFormation resource behind AWS constructs If a Construct is missing a feature or you are trying to work around an issue, you can modify the CFN Resource that is encapsulated by the Construct\. @@ -313,7 +313,7 @@ cfnBucket.CfnOptions.Metadata = new Dictionary ------ -## Raw Overrides +## Raw overrides If there are properties that are missing from the CFN Resource, you can bypass all typing using raw overrides\. This also makes it possible to delete synthesized properties\. @@ -406,7 +406,7 @@ cfnBucket.AddPropertyDeletionOverride("VersioningConfiguration.Status"); ------ -## Custom Resources +## Custom resources If the feature isn't available through AWS CloudFormation, but only through a direct API call, the only solution is to write an AWS CloudFormation Custom Resource to make the API call you need\. Don't worry, the AWS CDK makes it easier to write these, and wrap them up into a regular construct interface, so from another user's perspective the feature feels native\. diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 2aa00d83..ce803e09 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -1,4 +1,4 @@ -# Creating a Code Pipeline Using the AWS CDK +# Creating a code pipeline using the AWS CDK This example creates a code pipeline using the AWS CDK\. @@ -98,7 +98,7 @@ For a better experience, also add the `Amazon.Jsii.Analyzers` package to provide ------ -## Lambda Stack +## Lambda stack The first step is to define the AWS CloudFormation stack that will create the Lambda function\. This is the stack that we'll deploy in our pipeline\. @@ -328,7 +328,7 @@ namespace Pipeline ------ -## Pipeline Stack +## Pipeline stack The second class, `PipelineStack`, is the stack that contains our pipeline\. @@ -997,7 +997,7 @@ namespace Pipeline ------ -## Main Program +## Main program Finally, we have our main AWS CDK entry point file, which contains our app\. @@ -1120,7 +1120,7 @@ namespace Pipeline ------ -## Creating the Pipeline +## Creating the pipeline The final steps are building the code and deploying the pipeline\. @@ -1175,7 +1175,7 @@ After the deployment finishes, you should have a three\-stage pipeline that look Try making a change, such as to your `LambdaStack` AWS CDK code or to your Lambda function code, and push it to the repository\. The pipeline should pick up your change, build it, and deploy it automatically, without any human intervention\. -## Cleaning Up +## Cleaning up To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done with this exercise\. diff --git a/doc_source/compliance-validation.md b/doc_source/compliance-validation.md index faf24183..67d4b7a1 100644 --- a/doc_source/compliance-validation.md +++ b/doc_source/compliance-validation.md @@ -1,4 +1,4 @@ -# Compliance Validation for the AWS Cloud Development Kit \(AWS CDK\) +# Compliance validation for the AWS Cloud Development Kit \(AWS CDK\) The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 25c187a7..dd685404 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -4,7 +4,7 @@ Constructs are the basic building blocks of AWS CDK apps\. A construct represent A construct can represent a single resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can represent a higher\-level component consisting of multiple AWS CDK resources\. Examples of such components include a worker queue with its associated compute capacity, a cron job with monitoring resources and a dashboard, or even an entire app spanning multiple AWS accounts and regions\. -## AWS Construct Library +## AWS Construct library The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html), which contains constructs representing AWS resources\. @@ -27,13 +27,13 @@ Composition of constructs means that you can define reusable components and shar ## Initialization Constructs are implemented in classes that extend the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html) base class\. You define a construct by instantiating the class\. All constructs take three parameters when they are initialized: -+ **scope** – The construct within which this construct is defined\. You should almost always pass `this` for the scope, because it represents the current scope in which you are defining the construct\. ++ **Scope** – The construct within which this construct is defined\. You should almost always pass `this` for the scope, because it represents the current scope in which you are defining the construct\. + **id** – An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's encapsulated within the scope's subtree and is used to allocate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. -+ **props** – A set of properties or keyword arguments, depending upon the supported language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. ++ **Props** – A set of properties or keyword arguments, depending upon the supported language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html) or for specifying where the constructs will be deployed\. -## Apps and Stacks +## Apps and stacks We call your CDK application an *app*, which is represented by the AWS CDK class [App](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.App.html)\. The following example defines an app with a single stack that contains a single Amazon S3 bucket with versioning enabled: @@ -209,7 +209,7 @@ public class HelloCdkStack : Stack ------ -## Using Constructs +## Using constructs Once you have defined a stack, you can populate it with resources\. The following example imports the [Amazon S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) module and uses it to define a new Amazon S3 bucket by creating an instance of the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class within the current scope \(`this` or, in Python, `self`\) which, in our case is the `HelloCdkStack` instance\. @@ -343,7 +343,7 @@ new Bucket(this, "MyEncryptedBucket", new BucketProps AWS constructs are designed around the concept of "sensible defaults\." Most constructs have a minimal required configuration, enabling you to quickly get started while also providing full control over the configuration when you need it\. -## Interacting with Constructs +## Interacting with constructs Constructs are classes that extend the base [Construct](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html) class\. After you instantiate a construct, the construct object exposes a set of methods and properties that enable you to interact with the construct and pass it around as a reference to other parts of the system\. The AWS CDK framework doesn't put any restrictions on the APIs of constructs; authors can define any API they wish\. However, the AWS constructs that are included with the AWS Construct Library, such as `s3.Bucket`, follow guidelines and common patterns in order to provide a consistent experience across all AWS resources\. @@ -477,7 +477,7 @@ var createJobLambda = new Function(this, "create-job", new FunctionProps For information about the most common API patterns in the AWS Construct Library, see [Resources](https://docs.aws.amazon.com/cdk/latest/guide/resources.html)\. -## Authoring Constructs +## Authoring constructs In addition to using existing constructs like `s3.Bucket`, you can also author your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct imported from a third\-party library that someone published on npm or Maven or PyPI—or to your company's internal package repository\. diff --git a/doc_source/context.md b/doc_source/context.md index 1d19adce..abe78a47 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -1,10 +1,10 @@ -# Runtime Context +# Runtime context The AWS CDK uses *context* to retrieve information such as the Availability Zones in your account or Amazon Machine Image \(AMI\) IDs used to start your instances\. Context entries are key\-value pairs\. To avoid unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, thus changing your Auto Scaling group, the AWS CDK stores context values in the `cdk.context.json` file within your project\. This ensures that the AWS CDK uses the same context values the next time it synthesizes your app\. Don't forget to put this file under version control\. -## Construct Context +## Construct context Context values are made available to your AWS CDK app in five different ways: + Automatically from the current AWS account\. @@ -17,7 +17,7 @@ Context values are scoped to the construct that created them; they are visible t You can get a context value using the `construct.node.tryGetContext` method\. If the requested entry is not found on the current construct or any of its parents, the result is `undefined` \(or your language's equivalent, such as `None` in Python\)\. -## Context Methods +## Context methods The AWS CDK supports several context methods that enable AWS CDK apps to get contextual information\. For example, you can get a list of Availability Zones that are available in a given AWS account and AWS Region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) method\. @@ -42,7 +42,7 @@ If a given context information isn't available, the AWS CDK app notifies the AWS Don't forget to add the `cdk.context.json` file to your source control repository to ensure that subsequent synth commands will return the same result, and that your AWS account won't be needed when synthesizing from your build system\. -## Viewing and Managing Context +## Viewing and managing context Use the cdk context command to view and manage the information in your `cdk.context.json` file\. To see this information, use the cdk context command without any options\. The output should be something like the following\. diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 0cd54279..3995d4e0 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -1,4 +1,4 @@ -# Document History for the AWS CDK Developer Guide +# Document history for the AWS CDK Developer Guide This document reflects the following release of the AWS Cloud Development Kit \(AWS CDK\)\. + **API version: 1\.18\.0** diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 36f60a2d..d2e4d567 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -1,4 +1,4 @@ -# Creating an AWS Fargate Service Using the AWS CDK +# Creating an AWS Fargate service using the AWS CDK This example walks you through how to create an AWS Fargate service running on an Amazon Elastic Container Service \(Amazon ECS\) cluster that's fronted by an internet\-facing Application Load Balancer from an image on Amazon ECR\. @@ -27,7 +27,7 @@ The Amazon ECS construct used in this tutorial helps you use AWS services by pro See [ECS](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html) for details\. -## Creating the Directory and Initializing the AWS CDK +## Creating the directory and initializing the AWS CDK Let's start by creating a directory to hold the AWS CDK code, and then creating a AWS CDK app in that directory\. @@ -142,7 +142,7 @@ Resources: Modules: aws-cdk=CDK-VERSION,@aws-cdk/core=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,jsii-runtime=node.js/NODE-VERSION ``` -## Add the Amazon EC2 and Amazon ECS Packages +## Add the Amazon EC2 and Amazon ECS packages Install the AWS construct library modules for Amazon EC2 and Amazon ECS\. @@ -195,7 +195,7 @@ For a better experience, also add the `Amazon.Jsii.Analyzers` package to provide ------ -## Create a Fargate Service +## Create a Fargate service There are two different ways to run your container tasks with Amazon ECS: + Use the `Fargate` launch type, where Amazon ECS manages the physical machines that your containers are running on for you\. @@ -444,7 +444,7 @@ AWS CloudFormation displays information about the dozens of steps that it takes That's how easy it is to create a Fargate service to run a Docker image\. -## Clean Up +## Clean up To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done with this exercise\. diff --git a/doc_source/examples.md b/doc_source/examples.md index ca68f8be..513edae3 100644 --- a/doc_source/examples.md +++ b/doc_source/examples.md @@ -1,6 +1,6 @@ # Examples This topic contains the following examples: -+ [Creating a Serverless Application Using the AWS CDK](serverless_example.md) Creates a serverless application using Lambda, API Gateway, and Amazon S3\. -+ [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. -+ [Creating a Code Pipeline Using the AWS CDK](codepipeline_example.md) Creates a CI/CD pipeline\. \ No newline at end of file ++ [Creating a serverless application using the AWS CDK](serverless_example.md) Creates a serverless application using Lambda, API Gateway, and Amazon S3\. ++ [Creating an AWS Fargate service using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. ++ [Creating a code pipeline using the AWS CDK](codepipeline_example.md) Creates a CI/CD pipeline\. \ No newline at end of file diff --git a/doc_source/featureflags.md b/doc_source/featureflags.md index 3293dacf..22fda10d 100644 --- a/doc_source/featureflags.md +++ b/doc_source/featureflags.md @@ -1,6 +1,6 @@ -# Feature Flags +# Feature flags -The AWS CDK uses *feature flags* to enable potentially breaking behaviors in a release\. Flags are stored as [Runtime Context](context.md) values in `cdk.json` \(or `~/.cdk.json`\) as shown here\. +The AWS CDK uses *feature flags* to enable potentially breaking behaviors in a release\. Flags are stored as [Runtime context](context.md) values in `cdk.json` \(or `~/.cdk.json`\) as shown here\. ``` { diff --git a/doc_source/get_cfn_param.md b/doc_source/get_cfn_param.md index 1123db81..5f9582fb 100644 --- a/doc_source/get_cfn_param.md +++ b/doc_source/get_cfn_param.md @@ -1,5 +1,5 @@ -# Use an AWS CloudFormation Parameter +# Use an AWS CloudFormation parameter See [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for information about using the optional *Parameters* section to customize your AWS CloudFormation templates\. -You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [Use an Existing AWS CloudFormation Template](use_cfn_template.md)\. \ No newline at end of file +You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [Use an existing AWS CloudFormation template](use_cfn_template.md)\. \ No newline at end of file diff --git a/doc_source/get_context_var.md b/doc_source/get_context_var.md index 81c3c5e7..c7440748 100644 --- a/doc_source/get_context_var.md +++ b/doc_source/get_context_var.md @@ -1,4 +1,4 @@ -# Get a Value from a Context Variable +# Get a value from a context variable You can specify a context variable either as part of an AWS CDK CLI command, or in `cdk.json`\. @@ -101,4 +101,4 @@ var bucketName = app.Node.TryGetContext("bucket_name"); ------ -For more details on working with context variables, see [Runtime Context](context.md)\. \ No newline at end of file +For more details on working with context variables, see [Runtime context](context.md)\. \ No newline at end of file diff --git a/doc_source/get_env_var.md b/doc_source/get_env_var.md index d55ff86d..77ee780a 100644 --- a/doc_source/get_env_var.md +++ b/doc_source/get_env_var.md @@ -1,4 +1,4 @@ -# Get a Value from an Environment Variable +# Get a value from an environment variable To get the value of an environment variable, use code like the following\. This code gets the value of the environment variable `MYBUCKET`\. diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index fabe32b0..15a2a1b7 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -1,4 +1,4 @@ -# Get a Value from AWS Secrets Manager +# Get a value from AWS Secrets Manager To use values from AWS Secrets Manager in your CDK app, use the [fromSecretAttributes](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-secretsmanager/secret.html#aws_secretsmanager_Secret_fromSecretAttributes) method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 8c0447f4..b79e7d75 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -1,13 +1,13 @@ -# Get a Value from the Systems Manager Parameter Store +# Get a value from the Systems Manager Parameter Store The AWS CDK can retrieve the value of AWS Systems Manager Parameter Store attributes\. During synthesis, the AWS CDK produces a [token](tokens.md) that is resolved by AWS CloudFormation during deployment\. The AWS CDK supports retrieving both plain and secure values\. You may request a specific version of either kind of value\. For plain values only, you may omit the version from your request to receive the latest version\. You must always specify the version when requesting the value of a secure attribute\. **Note** - This topic shows how to read attributes from the AWS Systems Manager Parameter Store\. You can also read secrets from the AWS Secrets Manager \(see [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. + This topic shows how to read attributes from the AWS Systems Manager Parameter Store\. You can also read secrets from the AWS Secrets Manager \(see [Get a value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. -## Reading Systems Manager Values at Deployment Time +## Reading Systems Manager values at deployment time To read values from the Systems Manager Parameter Store, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-string-parameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-secure-string-parameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md), not the actual value\. The value is resolved by AWS CloudFormation during deployment\. @@ -98,11 +98,11 @@ var secureStringToken = StringParameter.ValueForSecureStringParameter( ------ -## Reading Systems Manager Values at Synthesis Time +## Reading Systems Manager values at synthesis time It is sometimes useful to "bake in" a parameter at synthesis time, so that the resulting AWS CloudFormation template always uses the same value, rather than resolving the value during deployment\. -To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime Context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. +To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. ------ #### [ TypeScript ] @@ -153,7 +153,7 @@ var stringValue = StringParameter.ValueFromLookup(this, "my-plain-parameter-name Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. -## Writing Values to Systems Manager +## Writing values to Systems Manager You can use the AWS CLI, the AWS Management Console, or an AWS SDK to set Systems Manager parameter values\. The following examples use the [ssm put\-parameter](https://docs.aws.amazon.com/cli/latest/reference/ssm/put-parameter.html) CLI command\. diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index a3f83ebf..2b1414ab 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -1,4 +1,4 @@ -# Getting Started With the AWS CDK +# Getting started with the AWS CDK This topic describes how to install and configure the AWS CDK and create your first AWS CDK app\. @@ -12,7 +12,7 @@ The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode All CDK developers need to install [Node\.js](https://nodejs.org/en/download) >= 10\.3\.0, even those working in languages other than TypeScript or JavaScript\. The AWS CDK Toolkit \(`cdk` command\-line tool\) and the AWS Construct Library are developed in TypeScript and run on Node\.js\. The bindings for other supported languages use this backend and toolset\. -You must provide your credentials and an AWS Region to use the AWS CDK CLI, as described in [Specifying Your Credentials and Region](#getting_started_credentials)\. +You must provide your credentials and an AWS Region to use the AWS CDK CLI, as described in [Specifying your credentials and Region](#getting_started_credentials)\. Other prerequisites depend on your development language, as follows\. @@ -62,7 +62,7 @@ Run the following command to verify correct installation and print the version n cdk --version ``` -## Updating Your Language Dependencies +## Updating your language dependencies If you get an error message that your language framework is out of date, use one of the following commands to update the components that the AWS CDK needs to support the language\. @@ -107,7 +107,7 @@ Or **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution* ------ -## Using the env Property to Specify Account and Region +## Using the env property to specify account and Region You can use the `env` property on a stack to specify the account and region used when deploying a stack, as shown in the following example, where *REGION* is the region and *ACCOUNT* is the account ID\. @@ -283,14 +283,14 @@ cdk deploy Stack-Two-E **Note** If the existing credentials do not have permission to create resources within the account you specify, the AWS CDK returns an AWS CloudFormation error when you attempt to deploy the stack\. -## Specifying Your Credentials and Region +## Specifying your credentials and Region You must specify your credentials and an AWS Region to use the AWS CDK CLI\. The CDK looks for credentials and region in the following order: + Using the \-\-profile option to cdk commands\. + Using environment variables\. + Using the default profile as set by the AWS Command Line Interface \(AWS CLI\)\. -### Using the \-\-profile Option to Specify Credentials and Region +### Using the \-\-profile option to specify credentials and Region Use the \-\-profile *PROFILE* option to a cdk command to use a specific profile when executing the command\. @@ -314,7 +314,7 @@ The profile must contain the access key, secret access key, and region\. See [Named Profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) in the AWS CLI documentation for details\. -### Using Environment Variables to Specify Credentials and a Region +### Using environment variables to specify credentials and a Region Use environment variables to specify your credentials and region\. + `AWS_ACCESS_KEY_ID` – Specifies your access key\. @@ -335,11 +335,11 @@ set AWS_DEFAULT_REGION=us-east-2 See [Environment Variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-environment.html) in the *AWS Command Line Interface User Guide* for details\. -### Using the AWS CLI to Specify Credentials and a Region +### Using the AWS CLI to specify credentials and a Region Use the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide) aws configure command to specify your default credentials and a region\. -## Hello World Tutorial +## Hello World tutorial The typical workflow for creating a new app is: @@ -361,7 +361,7 @@ And of course, keep your code under version control\. This tutorial walks you through how to create and deploy a simple AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. The app contains one resource, an Amazon S3 bucket\. -### Creating the App Directory +### Creating the app directory Create a directory for your app with an empty Git repository\. @@ -373,7 +373,7 @@ cd hello-cdk **Note** Be sure to use the name `hello-cdk` for your project directory\. The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, you'll need to change some of the code in this article\. -### Initializing the App +### Initializing the app To initialize your new AWS CDK app, you use the `cdk init` command\. @@ -449,7 +449,7 @@ cdk init --language csharp ------ -### Compiling the App +### Compiling the app Compile your program, as follows\. @@ -493,7 +493,7 @@ or press F6 in Visual Studio ------ -### Listing the Stacks in the App +### Listing the stacks in the app List the stacks in the app\. @@ -507,7 +507,7 @@ The result is just the name of the stack\. HelloCdkStack ``` -### Adding an Amazon S3 Bucket +### Adding an Amazon S3 bucket At this point, what can you do with this app? Nothing, because the stack is empty, so there's nothing to deploy\. Let's define an Amazon S3 bucket\. @@ -726,7 +726,7 @@ or press F6 in Visual Studio ------ -### Synthesizing an AWS CloudFormation Template +### Synthesizing an AWS CloudFormation template Synthesize an AWS CloudFormation template for the app, as follows\. If you get an error like "\-\-app is required\.\.\.", it's because you are running the command from a subdirectory of your project directory\. Navigate to the project directory and try again\. @@ -757,9 +757,9 @@ Resources: You can see that the stack contains an `AWS::S3::Bucket` resource with the versioning configuration we want\. **Note** -The AWS CDK CLI automatically adds the **AWS::CDK::Metadata** resource to your template\. The AWS CDK uses metadata to gain insight into how the AWS CDK is used\. One possible benefit is that the CDK team could notify users if a construct is going to be deprecated\. For details, including how to [opt out](tools.md#version_reporting_opt_out) of version reporting, see [Version Reporting](tools.md#version_reporting) \. +The AWS CDK CLI automatically adds the **AWS::CDK::Metadata** resource to your template\. The AWS CDK uses metadata to gain insight into how the AWS CDK is used\. One possible benefit is that the CDK team could notify users if a construct is going to be deprecated\. For details, including how to [opt out](tools.md#version_reporting_opt_out) of version reporting, see [Version reporting](tools.md#version_reporting) \. -### Deploying the Stack +### Deploying the stack Deploy the stack, as follows\. @@ -769,7 +769,7 @@ cdk deploy The deploy command synthesizes an AWS CloudFormation template from the app's stack, and then invokes AWS CloudFormation to deploy it in your AWS account\. If your code would change your infrastructure's security posture, the command displays information about those changes and requires you to confirm them before your stack is deployed\. The command displays information as it completes various steps in the process\. -### Modifying the App +### Modifying the app Configure the bucket to use AWS Key Management Service \(AWS KMS\) managed encryption\. @@ -880,7 +880,7 @@ or press F6 in Visual Studio ------ -### Preparing for Deployment +### Preparing for deployment Before you deploy the updated app, evaluate the difference between the AWS CDK app and the deployed app\. @@ -922,7 +922,7 @@ Stack ARN: arn:aws:cloudformation:REGION:ACCOUNT-ID:stack/HelloCdkStack/ID ``` -### Destroying the App's Resources +### Destroying the app's resources Destroy the app's resources to avoid incurring any costs from the resources created in this tutorial, as follows\. diff --git a/doc_source/home.md b/doc_source/home.md index 4d2be2f6..58635997 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -1,4 +1,4 @@ -# What Is the AWS CDK? +# What is the AWS CDK? Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, which is a software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. @@ -14,9 +14,9 @@ Developers can use one of the supported programming languages to define reusable ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/AppStacks.png) -## Why Use the AWS CDK? +## Why use the AWS CDK? -Let's look at the power of the AWS CDK\. Here is some code in an AWS CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md)\)\. +Let's look at the power of the AWS CDK\. Here is some code in an AWS CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate service using the AWS CDK](ecs_example.md)\)\. ------ #### [ TypeScript ] @@ -210,9 +210,9 @@ Other advantages of the AWS CDK include: ## Developing with the AWS CDK -Code snippets and longer examples are available in the AWS CDK's supported programming languages: TypeScript, JavaScript, Python, Java, and C\#\. See [AWS CDK Examples](about_examples.md) for a list of the examples\. +Code snippets and longer examples are available in the AWS CDK's supported programming languages: TypeScript, JavaScript, Python, Java, and C\#\. See [AWS CDK examples](about_examples.md) for a list of the examples\. -The [AWS CDK Tools](tools.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. +The [AWS CDK tools](tools.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. The [AWS Construct Library](constructs.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to create resources for an Amazon or AWS service\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. @@ -223,7 +223,7 @@ There is no charge for using the AWS CDK, but you might incur AWS charges for cr Because the AWS CDK is open source, the team encourages you contribute to make it an even better tool\. For details, see [Contributing](https://github.com/awslabs/aws-cdk/blob/master/CONTRIBUTING.md)\. -## Additional Documentation and Resources +## Additional documentation and resources In addition to this guide, the following are other resources available to AWS CDK users: + [API Reference](https://docs.aws.amazon.com/cdk/api/latest) @@ -239,8 +239,8 @@ In addition to this guide, the following are other resources available to AWS CD + [Documentation Source](https://github.com/awsdocs/aws-cdk-user-guide/tree/master/doc_source) + [License](https://github.com/awslabs/aws-cdk/blob/master/LICENSE) + [Releases](https://github.com/awslabs/aws-cdk/releases) - + [AWS CDK OpenPGP Key](pgp-keys.md#cdk_pgp_key) - + [JSII OpenPGP Key](pgp-keys.md#jsii_pgp_key) + + [AWS CDK OpenPGP key](pgp-keys.md#cdk_pgp_key) + + [JSII OpenPGP key](pgp-keys.md#jsii_pgp_key) + [AWS CDK Sample for Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/sample-cdk.html) + [AWS CloudFormation Concepts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html) + [AWS Glossary](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html) diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index 40f0be3a..72f9fb64 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -1,4 +1,4 @@ -# Set a CloudWatch Alarm +# Set a CloudWatch alarm The **aws\-cloudwatch** package supports setting CloudWatch alarms on CloudWatch metrics\. The syntax is as follows, where *METRIC* is a CloudWatch metric you have created, and the alarm is raised there are more than 100 of the measured metrics in two of the last three seconds: diff --git a/doc_source/how_tos.md b/doc_source/how_tos.md index c2d16c73..229bd4c7 100644 --- a/doc_source/how_tos.md +++ b/doc_source/how_tos.md @@ -1,3 +1,3 @@ -# AWS CDK HowTos +# AWS CDK how\-tos This section contains short code examples that show you how to accomplish a task using the AWS CDK\. \ No newline at end of file diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index f6a51d51..13b01352 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -232,6 +232,6 @@ For example, the Amazon S3 bucket in the previous example that is created within Think of construct IDs as part of your construct's public contract\. If you change the ID of a construct in your construct tree, AWS CloudFormation will replace the deployed resource instances of that construct, potentially causing service interruption or data loss\. -### Logical ID Stability +### Logical ID stability Avoid changing the logical ID of a resource between deployments\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID\. \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index c9668fef..ea888e5d 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -14,15 +14,15 @@ Amazon's trademarks and trade dress may not be used in ----- ## Contents -+ [What Is the AWS CDK?](home.md) -+ [Getting Started With the AWS CDK](getting_started.md) ++ [What is the AWS CDK?](home.md) ++ [Getting started with the AWS CDK](getting_started.md) + [Working with the AWS CDK](work-with.md) + [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) + [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) + [Working with the AWS CDK in Python](work-with-cdk-python.md) + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Working with the AWS CDK in C#](work-with-cdk-csharp.md) -+ [Translating TypeScript AWS CDK Code to Other Languages](multiple_languages.md) ++ [Translating TypeScript AWS CDK code to other languages](multiple_languages.md) + [Concepts](core_concepts.md) + [Constructs](constructs.md) + [Apps](apps.md) @@ -35,32 +35,32 @@ Amazon's trademarks and trade dress may not be used in + [Tagging](tagging.md) + [Assets](assets.md) + [Permissions](permissions.md) - + [Runtime Context](context.md) - + [Feature Flags](featureflags.md) + + [Runtime context](context.md) + + [Feature flags](featureflags.md) + [Aspects](aspects.md) - + [Escape Hatches](cfn_layer.md) -+ [API Reference](reference.md) + + [Escape hatches](cfn_layer.md) ++ [API reference](reference.md) + [Examples](examples.md) - + [Creating a Serverless Application Using the AWS CDK](serverless_example.md) - + [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md) - + [Creating a Code Pipeline Using the AWS CDK](codepipeline_example.md) - + [AWS CDK Examples](about_examples.md) -+ [AWS CDK HowTos](how_tos.md) - + [Get a Value from an Environment Variable](get_env_var.md) - + [Use an AWS CloudFormation Parameter](get_cfn_param.md) - + [Use an Existing AWS CloudFormation Template](use_cfn_template.md) - + [Get a Value from the Systems Manager Parameter Store](get_ssm_value.md) - + [Get a Value from AWS Secrets Manager](get_secrets_manager_value.md) - + [Create an App with Multiple Stacks](stack_how_to_create_multiple_stacks.md) - + [Set a CloudWatch Alarm](how_to_set_cw_alarm.md) - + [Get a Value from a Context Variable](get_context_var.md) -+ [AWS CDK Tools](tools.md) -+ [Testing Constructs](testing.md) + + [Creating a serverless application using the AWS CDK](serverless_example.md) + + [Creating an AWS Fargate service using the AWS CDK](ecs_example.md) + + [Creating a code pipeline using the AWS CDK](codepipeline_example.md) + + [AWS CDK examples](about_examples.md) ++ [AWS CDK how-tos](how_tos.md) + + [Get a value from an environment variable](get_env_var.md) + + [Use an AWS CloudFormation parameter](get_cfn_param.md) + + [Use an existing AWS CloudFormation template](use_cfn_template.md) + + [Get a value from the Systems Manager Parameter Store](get_ssm_value.md) + + [Get a value from AWS Secrets Manager](get_secrets_manager_value.md) + + [Create an app with multiple stacks](stack_how_to_create_multiple_stacks.md) + + [Set a CloudWatch alarm](how_to_set_cw_alarm.md) + + [Get a value from a context variable](get_context_var.md) ++ [AWS CDK tools](tools.md) ++ [Testing constructs](testing.md) + [Security for the AWS Cloud Development Kit (AWS CDK)](security.md) - + [Identity and Access Management for the AWS Cloud Development Kit (AWS CDK)](security-iam.md) - + [Compliance Validation for the AWS Cloud Development Kit (AWS CDK)](compliance-validation.md) + + [Identity and access management for the AWS Cloud Development Kit (AWS CDK)](security-iam.md) + + [Compliance validation for the AWS Cloud Development Kit (AWS CDK)](compliance-validation.md) + [Resilience for the AWS Cloud Development Kit (AWS CDK)](disaster-recovery-resiliency.md) - + [Infrastructure Security for the AWS Cloud Development Kit (AWS CDK)](infrastructure-security.md) -+ [Troubleshooting Common AWS CDK Issues](troubleshooting.md) -+ [OpenPGP Keys for the AWS CDK and JSII](pgp-keys.md) -+ [Document History for the AWS CDK Developer Guide](doc-history.md) \ No newline at end of file + + [Infrastructure security for the AWS Cloud Development Kit (AWS CDK)](infrastructure-security.md) ++ [Troubleshooting common AWS CDK issues](troubleshooting.md) ++ [OpenPGP keys for the AWS CDK and JSII](pgp-keys.md) ++ [Document history for the AWS CDK Developer Guide](doc-history.md) \ No newline at end of file diff --git a/doc_source/infrastructure-security.md b/doc_source/infrastructure-security.md index f3a2bb42..e2052b67 100644 --- a/doc_source/infrastructure-security.md +++ b/doc_source/infrastructure-security.md @@ -1,3 +1,3 @@ -# Infrastructure Security for the AWS Cloud Development Kit \(AWS CDK\) +# Infrastructure security for the AWS Cloud Development Kit \(AWS CDK\) The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. \ No newline at end of file diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 72913fdc..39e610d0 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -1,4 +1,4 @@ -# Translating TypeScript AWS CDK Code to Other Languages +# Translating TypeScript AWS CDK code to other languages TypeScript was the first language supported for developing AWS CDK applications, and for that reason, there is a substantial amount of example CDK code written in TypeScript\. If you are developing in another language, it may be useful to compare how AWS CDK code is implemented in TypeScript and your language of choice, so you can, with a little effort, make use of these examples\. @@ -9,7 +9,7 @@ For more details on working with the AWS CDK in its supported programming langua + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) -## Importing a Module +## Importing a module ------ #### [ TypeScript/JavaScript ] @@ -115,7 +115,7 @@ var bucket = new Amazon.CDK.AWS.S3.Bucket(...) ------ -## Instantiating a Construct +## Instantiating a construct AWS CDK construct classes have the same name in all supported languages\. Most languages use the `new` keyword to instantiate a class \(Python is the only one that doesn't\)\. Also, in most languages, the keyword `this` refers to the current instance\. Python, again, is the exception \(it uses `self` by convention\)\. You should pass a reference to the current instance as the `scope` parameter to every construct you create\. @@ -214,7 +214,7 @@ var bucket = Bucket(self, "MyBucket", new BucketProps { ------ -## Accessing Members +## Accessing members It is common to refer to attributes or properties of constructs and other AWS CDK classes and use these values as, for examples, inputs to build other constructs\. The naming differences described above for methods apply\. Furthermore, in Java, it is not possible to access members directly; instead, a getter method is provided\. @@ -258,7 +258,7 @@ bucket.BucketArn ------ -## Enum Constants +## Enum constants Enum constants are scoped to a class, and have uppercase names with underscores in all languages \(sometimes referred to as `SCREAMING_SNAKE_CASE`\)\. Since class names also use the same casing in all supported languages, qualified enum names are also the same\. @@ -266,7 +266,7 @@ Enum constants are scoped to a class, and have uppercase names with underscores s3.BucketEncryption.KMS_MANAGED ``` -## Object Interfaces +## Object interfaces The AWS CDK uses TypeScript object interfaces to indicate that a class implements an expected set of methods and properties\. You can recognize an object interface because its name starts with `I`\. A concrete class indicates the interface\(s\) it implements using the `implements` keyword\. diff --git a/doc_source/parameters.md b/doc_source/parameters.md index 7747baed..41c0d172 100644 --- a/doc_source/parameters.md +++ b/doc_source/parameters.md @@ -17,7 +17,7 @@ It is better, again in general, to have your CDK app accept any necessary inform There are, however, use cases to which AWS CloudFormation parameters are uniquely suited\. If you have separate teams defining and deploying infrastructure, for example, you can use parameters to make the generated templates more widely useful\. Additionally, the AWS CDK's support for AWS CloudFormation parameters lets you use the AWS CDK with AWS services that use AWS CloudFormation templates \(such as AWS Service Catalog\), which use parameters to configure the template being deployed\. -## Defining Parameters +## Defining parameters Use the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnParameter.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnParameter.html) class to define a parameter\. You'll want to specify at least a type and a description for most parameters, though both are technically optional\. The description appears when the user is prompted to enter the parameter's value in the AWS CloudFormation console\. @@ -73,7 +73,7 @@ var uploadBucketName = new CfnParameter(this, "uploadBucketName", new CfnParamet ------ -## Using Parameters +## Using parameters A `CfnParameter` instance exposes its value to your AWS CDK app via a [token](tokens.md)\. Like all tokens, the parameter's token is resolved at synthesis time, but it resolves to a reference to the parameter defined in the AWS CloudFormation template, which will be resolved at deploy time, rather than to a concrete value\. @@ -83,7 +83,7 @@ You can retrieve the token as an instance of the `Token` class, or in string, st #### [ TypeScript ] -| Property | Kind of value | +| Property | kind of value | | --- |--- | | value | Token class instance | | valueAsList | The token represented as a string list | @@ -94,7 +94,7 @@ You can retrieve the token as an instance of the `Token` class, or in string, st #### [ JavaScript ] -| Property | Kind of value | +| Property | kind of value | | --- |--- | | value | Token class instance | | valueAsList | The token represented as a string list | @@ -105,7 +105,7 @@ You can retrieve the token as an instance of the `Token` class, or in string, st #### [ Python ] -| Property | Kind of value | +| Property | kind of value | | --- |--- | | value | Token class instance | | value\_as\_list | The token represented as a string list | @@ -116,7 +116,7 @@ You can retrieve the token as an instance of the `Token` class, or in string, st #### [ Java ] -| Property | Kind of value | +| Property | kind of value | | --- |--- | | getValue\(\) | Token class instance | | getValueAsList\(\) | The token represented as a string list | @@ -127,7 +127,7 @@ You can retrieve the token as an instance of the `Token` class, or in string, st #### [ C\# ] -| Property | Kind of value | +| Property | kind of value | | --- |--- | | Value | Token class instance | | ValueAsList | The token represented as a string list | @@ -183,7 +183,7 @@ var bucket = new Bucket(this, "myBucket") ------ -## Deploying with Parameters +## Deploying with parameters A generated template containing parameters can be deployed in the usual way through the AWS CloudFormation console; you are prompted for the values of each parameter\. diff --git a/doc_source/permissions.md b/doc_source/permissions.md index fa67bab8..440c002c 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -333,7 +333,7 @@ project.AddToRolePolicy(new PolicyStatement(new PolicyStatementProps ------ -## Resource Policies +## Resource policies A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. These constructs have an `addToResourcePolicy` method \(Python: `add_to_resource_policy`\), which takes a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` as its argument\. Every policy statement added to a resource policy must specify at least one principal\. diff --git a/doc_source/pgp-keys.md b/doc_source/pgp-keys.md index cfe975af..333f8d9d 100644 --- a/doc_source/pgp-keys.md +++ b/doc_source/pgp-keys.md @@ -1,8 +1,8 @@ -# OpenPGP Keys for the AWS CDK and JSII +# OpenPGP keys for the AWS CDK and JSII This topic contains the OpenPGP keys for the AWS CDK and JSII\. -## AWS CDK OpenPGP Key +## AWS CDK OpenPGP key | | | @@ -48,7 +48,7 @@ EkSlc/RoDqZCpBGgcoy1FFWvV/ZLgNU6OTQlYH6oYOWiylSJnaTDyurrktsxJI6d -----END PGP PUBLIC KEY BLOCK----- ``` -## JSII OpenPGP Key +## JSII OpenPGP key | | | diff --git a/doc_source/reference.md b/doc_source/reference.md index f6198908..d43d16db 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -1,4 +1,4 @@ -# API Reference +# API reference The [API Reference](https://docs.aws.amazon.com/cdk/api/latest) contains information about the AWS CDK libraries\. @@ -9,9 +9,9 @@ Each library contains information about how to use the library\. For example, th Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. **Note** -This compatibility promise does not apply to APIs designated as experimental\. See [AWS CDK Stability Index](#aws_construct_lib_stability) for more details\. +This compatibility promise does not apply to APIs designated as experimental\. See [AWS CDK stability index](#aws_construct_lib_stability) for more details\. -### AWS CDK Toolkit \(CLI\) Compatibility +### AWS CDK Toolkit \(CLI\) compatibility The AWS CDK Toolkit \(that is, the `cli` command line command\) is *always* compatible with construct libraries of a semantically *lower* or *equal* version number\. It is, therefore, always safe to upgrade the AWS CDK Toolkit within the same major version\. @@ -27,7 +27,7 @@ Cloud assembly schema version mismatch: Maximum schema version supported is 3.0. **Note** For more details on the cloud assembly schema, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/cloud-assembly-schema#versioning)\. -### AWS CDK Stability Index +### AWS CDK stability index Certain APIs do not adhere to the semantic versioning model\. There are three levels of stability in the AWS Construct Library, which define the level of semantic versioning that applies to each module\. @@ -45,7 +45,7 @@ The API may emit warnings\. We do not guarantee backward compatibility\. Experimental and stable modules receive the same level of support from AWS\. The only difference is that we might change experimental APIs within a major version\. Although we don't recommend using experimental APIs in production, we vet them the same way as we vet stable APIs before we include them in a release\. -### Identifying the Support Level of an API +### Identifying the support level of an API Each module in the [API Reference](https://docs.aws.amazon.com/cdk/api/latest) starts with a section outlining the module's stability index\. The libraries that include only AWS CloudFormation resources, and no hand\-curated constructs, are labeled with the maturity indicator **CloudFormation\-only**\. @@ -58,12 +58,12 @@ The module level gives an indication of the stability of the majority of the API | Stable | @stable | @stability Stable | @stable | Stability: Stable | Stability: Stable | | Deprecated | @deprecated | @Deprecated | @deprecated | \[Obsolete\] | Stability: Deprecated | -### Language Binding Stability +### Language binding stability In addition to modules of the AWS CDK Construct Library, language support is also subject to a stability indication\. Although the API described in all the languages is the same, the way that API is expressed varies by language and may change as the language support evolves\. For this reason, language bindings are deemed experimental for a time until they are considered ready for production use\. -| Language | Stability | +| Language | stability | | --- |--- | | TypeScript | Stable | | JavaScript | Stable | diff --git a/doc_source/resources.md b/doc_source/resources.md index c7f5b62b..fe214f1d 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -61,7 +61,7 @@ new Queue(this, "MyQueue", new QueueProps Some configuration props are optional, and in many cases have default values\. In some cases, all props are optional, and the last argument can be omitted entirely\. -## Resource Attributes +## Resource attributes Most resources in the AWS Construct Library expose attributes, which are resolved at deployment time by AWS CloudFormation\. Attributes are exposed in the form of properties on the resource classes with the type name as a prefix\. The following example shows how to get the URL of an Amazon SQS queue using the `queueUrl` \(Python: `queue_url`\) property\. @@ -115,7 +115,7 @@ var url = queue.QueueUrl; // => A string representing a deploy-time value See [Tokens](tokens.md) for information about how the AWS CDK encodes deploy\-time attributes as strings\. -## Referencing Resources +## Referencing resources Many AWS CDK classes require properties that are AWS CDK resource objects \(resources\)\. To satisfy these requirements, you can refer to a resource in one of two ways: + By passing the resource directly @@ -173,7 +173,7 @@ var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cl ------ -## Accessing Resources in a Different Stack +## Accessing resources in a different stack You can access resources in a different stack, as long as they are in the same account and AWS Region\. The following example defines the stack `stack1`, which defines an Amazon S3 bucket\. Then it defines a second stack, `stack2`, which takes the bucket from `stack1` as a constructor property\. @@ -263,7 +263,7 @@ var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = p If the AWS CDK determines that the resource is in the same account and Region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. -## Physical Names +## Physical names The logical names of resources in AWS CloudFormation are different from the names of resources that are shown in the AWS Management Console after AWS CloudFormation has deployed the resources\. The AWS CDK calls these final names *physical names*\. @@ -361,7 +361,7 @@ var bucket = new Bucket(this, "MyBucket", new BucketProps ------ -## Passing Unique Identifiers +## Passing unique identifiers Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. For example, when you are using the low\-level AWS CloudFormation resources, or need to expose resources to the runtime components of an AWS CDK application, such as when referring to Lambda functions through environment variables\. @@ -484,7 +484,7 @@ new Function(this, "MyLambda", new FunctionProps ------ -## Importing Existing External Resources +## Importing existing external resources Sometimes you already have a resource in your AWS account and want to use it in your AWS CDK app, for example, a resource that was defined through the console, the AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into an AWS CDK object in the current stack by calling a static factory method on the resource's class\. @@ -669,7 +669,7 @@ Note that `Vpc.fromLookup()` works only in stacks that are defined with an expli Although you can use an imported resource anywhere, you cannot modify the imported resource\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an imported `s3.IBucket` does nothing\. -## Permission Grants +## Permission grants AWS constructs make least\-privilege permissions easy to achieve by offering simple, intent\-based APIs to express permission requirements\. Many AWS constructs offer grant methods that enable you to easily grant an entity, such as an IAM role or a user, permission to work with the resource without having to manually craft one or more IAM permission statements\. @@ -769,7 +769,7 @@ Many resources, such as Lambda functions, require a role to be assumed when exec The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-iam-readme.html) objects\. Add statements directly to roles \(or a construct's attached role\) using the `addToRolePolicy` method \(Python: `add_to_role_policy`\), or to a resource's policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` \(Python: `add_to_resource_policy`\) method\. -## Metrics and Alarms +## Metrics and alarms Many resources emit CloudWatch metrics that can be used to set up monitoring dashboards and alarms\. AWS constructs have metric methods that allow easy access to the metrics without having to look up the correct name to use\. @@ -894,7 +894,7 @@ If there is no method for a particular metric, you can use the general metric me Metrics can also be added to CloudWatch dashboards\. See [CloudWatch](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudwatch-readme.html)\. -## Network Traffic +## Network traffic In many cases, you must enable permissions on a network for an application to work, such as when the compute infrastructure needs to access the persistence layer\. Resources that establish or listen for connections expose methods that enable traffic flows, including setting security group rules or network ACLs\. @@ -1108,7 +1108,7 @@ bucket.AddObjectCreatedNotification(new s3_not.LambdaDestination(handler)); ------ -## Removal Policies +## Removal policies Resources that maintain persistent data, such as databases and Amazon S3 buckets, have a *removal policy* that indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the AWS CDK `core` module\. @@ -1116,7 +1116,7 @@ Resources that maintain persistent data, such as databases and Amazon S3 buckets Resources besides those that store data persistently may also have a `removalPolicy` that is used for a different purpose\. For example, a Lambda function version uses a `removalPolicy` attribute to determine whether a given version is retained when a new version is deployed\. These have different meanings and defaults compared to the removal policy on an Amazon S3 bucket or DynamoDB table\. -| Value | Meaning | +| Value | meaning | | --- |--- | | RemovalPolicy\.RETAIN | Keep the contents of the resource when destroying the stack \(default\)\. The resource is orphaned from the stack and must be deleted manually\. If you attempt to re\-deploy the stack while the resource still exists, you will receive an error message due to a name conflict\. | | RemovalPolicy\.DESTROY | The resource will be destroyed along with the stack\. | @@ -1261,4 +1261,4 @@ resource.ApplyRemovalPolicy(cdk.RemovalPolicy.DESTROY); ------ **Note** -The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. +The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. \ No newline at end of file diff --git a/doc_source/security-iam.md b/doc_source/security-iam.md index 1a57c193..55f220ba 100644 --- a/doc_source/security-iam.md +++ b/doc_source/security-iam.md @@ -1,4 +1,4 @@ -# Identity and Access Management for the AWS Cloud Development Kit \(AWS CDK\) +# Identity and access management for the AWS Cloud Development Kit \(AWS CDK\) AWS Identity and Access Management \(IAM\) is an Amazon Web Services \(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 resources in AWS services\. IAM is an AWS service that you can use with no additional charge\. diff --git a/doc_source/security.md b/doc_source/security.md index b25615eb..bf319928 100644 --- a/doc_source/security.md +++ b/doc_source/security.md @@ -9,7 +9,7 @@ Cloud security at Amazon Web Services \(AWS\) is the highest priority\. As an AW The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. **Topics** -+ [Identity and Access Management](security-iam.md) -+ [Compliance Validation](compliance-validation.md) ++ [Identity and access management](security-iam.md) ++ [Compliance validation](compliance-validation.md) + [Resilience](disaster-recovery-resiliency.md) -+ [Infrastructure Security](infrastructure-security.md) \ No newline at end of file ++ [Infrastructure security](infrastructure-security.md) \ No newline at end of file diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 0e870953..e2d05852 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -1,4 +1,4 @@ -# Creating a Serverless Application Using the AWS CDK +# Creating a serverless application using the AWS CDK This example walks you through how to create the resources for a simple widget dispensing service\. \(For the purpose of this example, a widget is just a name or identifier that can be added to, retrieved from, and deleted from a collection\.\) The example includes: + An AWS Lambda function\. @@ -22,7 +22,7 @@ This tutorial contains the following steps\. + Get a widget by name with GET /\{name\} + Delete a widget by name with DELETE /\{name\} -## Create a AWS CDK App +## Create a AWS CDK app Create the app **MyWidgetService** in the current folder\. @@ -166,7 +166,7 @@ Resources: Modules: "@aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_widget_service=0.1.0" ``` -## Create a Lambda Function to List All Widgets +## Create a Lambda function to list all widgets The next step is to create a Lambda function to list all of the widgets in our Amazon S3 bucket\. We will provide the Lambda function's code in JavaScript\. @@ -267,7 +267,7 @@ Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. ------ -## Creating a Widget Service +## Creating a widget service Add the API Gateway, Lambda, and Amazon S3 packages to the app\. @@ -601,7 +601,7 @@ Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. ------ -## Add the Service to the App +## Add the service to the app To add the widget service to our AWS CDK app, we'll need to modify the source file that defines the stack to instantiate the service construct\. @@ -728,9 +728,9 @@ Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. ------ -## Deploy and Test the App +## Deploy and test the app -Before you can deploy your first AWS CDK app containing a lambda function, you must bootstrap your AWS environment\. This creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see the **bootstrap** section of the [AWS CDK Tools](tools.md) \(if you've already bootstrapped, you'll get a warning and nothing will change\)\. +Before you can deploy your first AWS CDK app containing a lambda function, you must bootstrap your AWS environment\. This creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see the **bootstrap** section of the [AWS CDK tools](tools.md) \(if you've already bootstrapped, you'll get a warning and nothing will change\)\. ``` cdk bootstrap @@ -770,7 +770,7 @@ Because we haven't stored any widgets yet, the output should be similar to the f { "widgets": [] } ``` -## Add the Individual Widget Functions +## Add the individual widget functions The next step is to create Lambda functions to create, show, and delete individual widgets\. @@ -1053,7 +1053,7 @@ curl -X GET 'https://GUID.execute-api-REGION.amazonaws.com/prod' You can also use the API Gateway console to test these functions\. Set the **name** value to the name of a widget, such as **example**\. -## Clean Up +## Clean up To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done with this exercise\. diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index db61370a..382206ec 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -1,12 +1,12 @@ -# Create an App with Multiple Stacks +# Create an app with multiple stacks Most of the other code examples in the *AWS CDK Developer Guide* involve only a single stack\. However, you can create apps containing any number of stacks\. Each stack results in its own AWS CloudFormation template\. Stacks are the *unit of deployment:* each stack in an app can be synthesized and deployed individually using the `cdk deploy` command\. This topic illustrates how to extend the `Stack` class to accept new properties or arguments, how to use these properties affect what resources the stack contains and their configuration, and how to instantiate multiple stacks from this class\. The example uses a Boolean property, named `encryptBucket` \(Python: `encrypt_bucket`\), to indicate whether an Amazon S3 bucket should be encrypted\. If so, the stack enables encryption using a key managed by AWS Key Management Service \(AWS KMS\)\. The app creates two instances of this stack, one with encryption and one without\. -## Before You Begin +## Before you begin -First, install Node\.js and the AWS CDK command line tools, if you haven't already\. See [Getting Started With the AWS CDK](getting_started.md) for details\. +First, install Node\.js and the AWS CDK command line tools, if you haven't already\. See [Getting started with the AWS CDK](getting_started.md) for details\. Next, create an AWS CDK project by entering the following commands at the command line\. @@ -112,7 +112,7 @@ For a better experience, also add the `Amazon.Jsii.Analyzers` package to provide ------ -## Add Optional Parameter +## Add optional parameter The `props` argument of the `Stack` constructor fulfills the interface `StackProps`\. Because we want our stack to accept an additional property to tell us whether to encrypt the Amazon S3 bucket, we should create an interface or class that includes that property\. This allows the compiler to make sure the property has a Boolean value and enables autocompletion for it in your IDE\. @@ -249,7 +249,7 @@ namespace Multistack The new property is optional\. If `encryptBucket` \(Python: `encrypt_bucket`\) is not present, its value is `undefined`, or the local equivalent\. The bucket will be unencrypted by default\. -## Define the Stack Class +## Define the stack class Now let's define our stack class, using our new property\. Make the code look like the following\. The code you need to add or change is shown in boldface\. @@ -439,7 +439,7 @@ namespace Multistack ------ -## Create Two Stack Instances +## Create two stack instances Now we'll add the code to instantiate two separate stacks\. As before, the lines of code shown in boldface are the ones you need to add\. Delete the existing `MultistackStack` definition\. @@ -585,7 +585,7 @@ namespace Multistack + One stack with an encrypted Amazon S3 bucket in the `us-east-1` AWS Region\. + One stack with an unencrypted Amazon S3 bucket in the `us-west-1` AWS Region\. -## Synthesize and Deploy the Stack +## Synthesize and deploy the stack Now you can deploy stacks from the app\. First, build the project, if necessary\. @@ -665,7 +665,7 @@ cdk deploy MyEastCdkStack cdk deploy MyEastCdkStack --profile=PROFILE_NAME ``` -## Clean Up +## Clean up To avoid charges for resources that you deployed, destroy the stack using the following command\. diff --git a/doc_source/stacks.md b/doc_source/stacks.md index a43669d7..d2e015b7 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -359,7 +359,7 @@ The [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack + `stack.toJsonString(obj)` \(Python: `to_json_string`\) – Can be used to format an arbitrary object as a JSON string that can be embedded in an AWS CloudFormation template\. The object can include tokens, attributes, and references, which are only resolved during deployment\. + `stack.templateOptions` \(Python: `template_options`\) – Enables you to specify AWS CloudFormation template options, such as Transform, Description, and Metadata, for your stack\. -## Nested Stacks +## Nested stacks The [NestedStack](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudformation.NestedStack.html) construct offers a way around the AWS CloudFormation 200\-resource limit for stacks\. A nested stack counts as only one resource in the stack that contains it, but can itself contain up to 200 resources, including additional nested stacks\. diff --git a/doc_source/testing.md b/doc_source/testing.md index 0e356e46..44b18391 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -1,4 +1,4 @@ -# Testing Constructs +# Testing constructs With the AWS CDK, your infrastructure can be as testable as any other code you write\. This article illustrates one approach to testing AWS CDK apps written in TypeScript using the [Jest](https://jestjs.io/) test framework\. Currently, TypeScript is the only supported language for testing AWS CDK infrastructure, though we intend to eventually make this capability available in all languages supported by the AWS CDK\. @@ -7,11 +7,11 @@ There are three categories of tests you can write for AWS CDK apps\. + **Fine\-grained assertions** test specific aspects of the generated AWS CloudFormation template, such as "this resource has this property with this value\." These tests help when you're developing new features, since any code you add will cause your snapshot test to fail even if existing features still work\. When this happens, your fine\-grained tests will reassure you that the existing functionality is unaffected\. + **Validation tests** help you "fail fast" by making sure your AWS CDK constructs raise errors when you pass them invalid data\. The ability to do this type of testing is a big advantage of developing your infrastructure in a general\-purpose programming language\. -## Getting Started +## Getting started As an example, we'll create a [dead letter queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) construct\. A dead letter queue holds messages from another queue that have failed delivery for some time\. This usually indicates failure of the message processor, which we want to know about, so our dead letter queue has an alarm that fires when a message arrives\. The user of the construct can hook up actions such as notifying an Amazon SNS topic to this alarm\. -### Creating the Construct +### Creating the construct Start by creating an empty construct library project using the AWS CDK Toolkit and installing the construct libraries we'll need: @@ -45,7 +45,7 @@ export class DeadLetterQueue extends sqs.Queue { } ``` -### Installing the Testing Framework +### Installing the testing framework Since we're using the Jest framework, our next setup step is to install Jest\. We'll also need the AWS CDK assert module, which includes helpers for writing tests for CDK libraries, including `assert` and `expect`\. @@ -80,7 +80,7 @@ These changes are shown in outline below\. Place the new text where indicated in } ``` -## Snapshot Tests +## Snapshot tests Add a snapshot test by placing the following code in `test/dead-letter-queue.test.ts`\. @@ -130,7 +130,7 @@ Object { ... ``` -### Testing the Test +### Testing the test To make sure the test works, change the construct so that it generates different AWS CloudFormation output, then build and test again\. For example, add a `period` property of 1 minute to override the default of 5 minutes\. The boldface line below shows the code that needs to be added to `index.ts`\. @@ -183,7 +183,7 @@ Snapshot Summary › 1 snapshot failed from 1 test suite. Inspect your code changes or run `npm test -- -u` to update them. ``` -### Accepting the New Snapshot +### Accepting the new snapshot Jest has told us that the `Period` attribute of the synthesized AWS CloudFormation template has changed from 300 to 60\. To accept the new snapshot, issue: @@ -212,7 +212,7 @@ export class DeadLetterQueue extends sqs.Queue { When we run the test again, it breaks\. The name we've given the test hints that we are interested mainly in testing whether the alarm is created, but the snapshot test also tests whether the queue is created with default options—along with literally everything else about the synthesized template\. This problem is magnified when a project contains many constructs, each with a snapshot test\. -## Fine\-Grained Assertions +## Fine\-grained assertions To avoid needing to review every snapshot whenever you make a change, use the custom assertions in the `@aws-cdk/assert/jest` module to write fine\-grained tests that verify only part of the construct's behavior\. For example, the test we called "dlq creates an alarm" in our example really should assert only that an alarm is created with the appropriate metric\. @@ -265,7 +265,7 @@ npm run build && npm test **Note** Since we've replaced the snapshot test, the first time we run the new tests, Jest reminds us that we have a snapshot that is not used by any test\. Issue `npm test -- -u` to tell Jest to clean it up\. -## Validation Tests +## Validation tests Suppose we want to make the dead letter queue's retention period configurable\. Of course, we also want to make sure that the value provided by the user of the construct is within an allowable range\. We can write a test to make sure that the validation logic works: pass in invalid values and see what happens\. @@ -347,7 +347,7 @@ Test Suites: 1 passed, 1 total Tests: 4 passed, 4 total ``` -## Tips for Tests +## Tips for tests Remember, your tests will live just as long as the code they test, and be read and modified just as often, so it pays to take a moment to consider how best to write them\. Don't copy and paste setup lines or common assertions, for example; refactor this logic into helper functions\. Use good names that reflect what each test actually tests\. diff --git a/doc_source/tokens.md b/doc_source/tokens.md index c484dc28..3b249284 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -1,6 +1,6 @@ # Tokens -Tokens represent values that can only be resolved at a later time in the lifecycle of an app \(see [App Lifecycle](apps.md#lifecycle)\)\. For example, the name of an Amazon S3 bucket that you define in your AWS CDK app is only allocated by AWS CloudFormation when you deploy your app\. If you print the `bucket.bucketName` attribute, which is a string, you see it contains something like the following\. +Tokens represent values that can only be resolved at a later time in the lifecycle of an app \(see [App lifecycle](apps.md#lifecycle)\)\. For example, the name of an Amazon S3 bucket that you define in your AWS CDK app is only allocated by AWS CloudFormation when you deploy your app\. If you print the `bucket.bucketName` attribute, which is a string, you see it contains something like the following\. ``` ${TOKEN[Bucket.Name.1234]} @@ -78,7 +78,7 @@ var fn = new Function(this, "MyLambda", new FunctionProps { When the AWS CloudFormation template is finally synthesized, the token is rendered as the AWS CloudFormation intrinsic `{ "Ref": "MyBucket" }`\. At deployment time, AWS CloudFormation replaces this intrinsic with the actual name of the bucket that was created\. -## Tokens and Token Encodings +## Tokens and token encodings Tokens are objects that implement the [IResolvable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.IResolvable.html) interface, which contains a single `resolve` method\. The AWS CDK calls this method during synthesis to produce the final value for the AWS CloudFormation template\. Tokens participate in the synthesis process to produce arbitrary values of any type\. @@ -148,7 +148,7 @@ If **name** is a token, validation isn't performed, and the error could occur in **Note** You can use token encodings to escape the type system\. For example, you could string\-encode a token that produces a number value at synthesis time\. If you use these functions, it's your responsibility to ensure that your template resolves to a usable state after synthesis\. -## String\-Encoded Tokens +## String\-encoded tokens String\-encoded tokens look like the following\. @@ -236,7 +236,7 @@ string functionName = $"${bucket.bucketName}Function"; Avoid manipulating the string in other ways\. For example, taking a substring of a string is likely to break the string token\. -## List\-Encoded Tokens +## List\-encoded tokens List\-encoded tokens look like the following @@ -246,7 +246,7 @@ List\-encoded tokens look like the following The only safe thing to do with these lists is pass them directly to other constructs\. Tokens in string list form cannot be concatenated, nor can an element be taken from the token\. The only safe way to manipulate them is by using AWS CloudFormation intrinsic functions like [Fn\.select](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-select.html)\. -## Number\-Encoded Tokens +## Number\-encoded tokens Number\-encoded tokens are a set of tiny negative floating\-point numbers that look like the following\. @@ -256,7 +256,7 @@ Number\-encoded tokens are a set of tiny negative floating\-point numbers that l As with list tokens, you cannot modify the number value, as doing so is likely to break the number token\. The only allowed operation is to pass the value around to another construct\. -## Lazy Values +## Lazy values In addition to representing deploy\-time values, such as AWS CloudFormation [parameters](parameters.md), Tokens are also commonly used to represent synthesis\-time lazy values\. These are values for which the final value will be determined before synthesis has completed, just not at the point where the value is constructed\. Use tokens to pass a literal string or number value to another construct, while the actual value at synthesis time may depend on some calculation that has yet to occur\. diff --git a/doc_source/tools.md b/doc_source/tools.md index 6568df40..0ea0c429 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -1,8 +1,8 @@ -# AWS CDK Tools +# AWS CDK tools This section contains information about AWS CDK tools\. -## AWS Toolkit for Visual Studio Code +## AWS Toolkit for Visual Studio code The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the AWS Toolkit](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. @@ -138,7 +138,7 @@ as defaults. Settings in cdk.json take precedence. If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. -### AWS CDK Toolkit Commands +### AWS CDK toolkit commands The AWS CDK CLI supports several distinct commands\. Help for each \(including only the command\-line options specific to the particular command\) follows\. Commands with no command\-specific options are not listed\. All commands additionally accept the options listed above\. @@ -294,13 +294,13 @@ Options: --clear Clear all context [boolean] ``` -### Bootstrapping your AWS Environment +### Bootstrapping your AWS environment Before you can use the AWS CDK you must bootstrap your AWS environment to create the infrastructure that the AWS CDK CLI needs to deploy your AWS CDK app\. Currently the bootstrap command creates only an Amazon S3 bucket\. You incur any charges for what the AWS CDK stores in the bucket\. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your AWS account\. -### Security\-Related Changes +### Security\-related changes To protect you against unintended changes that affect your security posture, the AWS CDK toolkit prompts you to approve security\-related changes before deploying them\. @@ -330,7 +330,7 @@ The setting can also be configured in the `cdk.json` file\. } ``` -### Version Reporting +### Version reporting To gain insight into how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. @@ -348,7 +348,7 @@ CDKMetadata: Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,@aws-solutions-konstruk/aws-apigateway-lambda=0.8.0" ``` -### Opting Out from Version Reporting +### Opting out from version reporting To opt out of version reporting, use one of the following methods: + Use the cdk command with the \-\-no\-version\-reporting argument\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index ec77f458..fb8904fa 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -1,4 +1,4 @@ -# Troubleshooting Common AWS CDK Issues +# Troubleshooting common AWS CDK issues This topic describes how to troubleshoot the following issues with the AWS CDK\. + [After updating the AWS CDK, code that used to work fine now results in errors](#troubleshooting_modules) @@ -210,7 +210,7 @@ The AWS Construct Library's higher\-level, intent\-based constructs automaticall In our experience, real\-world use of intent\-based constructs results in 1–5 AWS CloudFormation resources per construct, though this can vary\. For serverless applications, 5–8 AWS resources per API endpoint is typical\. -Patterns, which represent a higher level of abstraction, let you define even more AWS resources with even less code\. The AWS CDK code in [Creating an AWS Fargate Service Using the AWS CDK](ecs_example.md), for example, generates more than fifty AWS CloudFormation resources while defining only three constructs\! +Patterns, which represent a higher level of abstraction, let you define even more AWS resources with even less code\. The AWS CDK code in [Creating an AWS Fargate service using the AWS CDK](ecs_example.md), for example, generates more than fifty AWS CloudFormation resources while defining only three constructs\! Synthesize regularly and keep an eye on how many resources your stack contains\. You'll quickly get a feel for how many resources will be generated by the constructs you use most frequently\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index f1e75f0b..200f34a9 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -1,4 +1,4 @@ -# Use an Existing AWS CloudFormation Template +# Use an existing AWS CloudFormation template The AWS CDK provides a mechanism that you can use to incorporate resources from an existing AWS CloudFormation template into your AWS CDK app\. For example, suppose you have a template, `my-template.json`, with the following resource, where *S3Bucket* is the logical ID of the bucket in your template: diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 835a8073..0b66e76c 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -19,7 +19,7 @@ If you have an up\-to\-date Windows 10 installation, you already have a suitable The \.NET Standard toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if you are using Visual Studio, this command is useful for batch operations and for installing AWS Construct Library packages\. -## Creating a Project +## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. @@ -33,7 +33,7 @@ cdk init app --language csharp The resulting project includes a reference to the `Amazon.CDK` NuGet package\. It and its dependencies are installed automatically by NuGet\. -## Managing AWS Construct Library Modules +## Managing AWS construct library modules The \.NET ecosystem uses the NuGet package manager\. AWS Construct Library modules are named like `Amazon.CDK.AWS.SERVICE-NAME`\. For example, the NuGet package name for the Amazon S3 module is `Amazon.CDK.AWS.S3`\. @@ -53,11 +53,11 @@ All AWS Construct Library modules deemed "experimental" \(see [Versioning](refer Look in the **Updates** panel to install new versions of your packages\. -### The NuGet Console +### The NuGet console The NuGet console is a PowerShell\-based interface to NuGet that works in the context of a Visual Studio project\. You can open it in Visual Studio by choosing **Tools** > **NuGet Package Manager** > **Package Manager Console**\. For more information on using this tool, see [Install and Manage Packages with the Package Manager Console in Visual Studio](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-powershell)\. -### The `dotnet` Command +### The `dotnet` command The `dotnet` command is the primary command\-line tool for working with Visual Studio C\# projects\. You can invoke it from any Windows command prompt\. Among its many capabilities, `dotnet` can add NuGet dependencies to a Visual Studio project\. @@ -83,13 +83,13 @@ To update a package, issue the same `dotnet add` command you used to install it\ For more information on managing packages using the `dotnet` command, see [Install and Manage Packages Using the dotnet CLI](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli)\. -### The `nuget` Command +### The `nuget` command The `nuget` command line tool can install and update NuGet packages\. However, it requires your Visual Studio project to be set up differently from the way `cdk init` sets up projects\. \(Technical details: `nuget` works with `Packages.config` projects, while `cdk init` creates a newer\-style `PackageReference` project\.\) We do not recommend the use of the `nuget` tool with AWS CDK projects created by `cdk init`\. If you are using another type of project, and want to use `nuget`, see the [NuGet CLI Reference](https://docs.microsoft.com/en-us/nuget/reference/nuget-exe-cli-reference)\. -## AWS CDK Idioms in C\# +## AWS CDK idioms in C\# ### Props @@ -132,7 +132,7 @@ When calling the parent class's initializer or overridden method, you can genera Keep in mind that future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues using your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion for your construct's users\. You can avoid this potential problem by naming your properties so they clearly belong to your construct \(e\.g\. `BobEncryption` rather than just `encryption`, assuming you're Bob\)\. If there are many new properties, bundle them into an appropriately\-named class \(`BobBucketPoperties`?\) and pass them as a single property\. -### Missing Values +### Missing values In C\#, missing values in AWS CDK objects such as props are represented by `null`\. The null\-conditional member access operator `?.` and the null coalescing operator `??` are convenient for working with these values\. @@ -144,7 +144,7 @@ string mimeType = props?.MimeType; string MimeType = props?.MimeType ?? "text/plain"; ``` -## Building, Synthesizing, and Deploying +## Building, synthesizing, and deploying Before running, build \(compile\) the app by pressing F6 in Visual Studio or by issuing `dotnet build src` from the command line, where `src` is the directory in your project directory that contains the Visual Studio Solution \(`.sln`\) file\. diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 26ae013c..6de2ec11 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -12,7 +12,7 @@ To work with the AWS CDK, you must have an AWS account and credentials and have Java AWS CDK applications require Java 8 \(v1\.8\) or later\. We recommend [Amazon Corretto](https://aws.amazon.com/corretto/), but you can use any OpenJDK distribution or [Oracle's JDK](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)\. You will also need [Apache Maven](https://maven.apache.org/download.cgi) 3\.5 or later\. You can also use tools such as Gradle, but the application skeletons generated by the AWS CDK Toolkit are Maven projects\. -## Creating a Project +## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. @@ -28,7 +28,7 @@ The resulting project includes a reference to the `software.amazon.awscdk.core` If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set ta use Java 8 \(1\.8\)\. -## Managing AWS Construct Library Modules +## Managing AWS construct library modules Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk` and named for their service\. For example, the Maven artifact ID for Amazon S3 is `s3`\. Its Java package name, for use in import statements, is `software.amazon.awscdk.services.s3`\. @@ -59,7 +59,7 @@ You can periodically issue the following command to update your dependencies to mvn versions:use-latest-versions ``` -### Setting Dependencies Manually +### Setting dependencies manually If you are not using an IDE, or just want full control over the versions of your dependencies, you can specify the modules that your application depends on by editing `pom.xml` and adding a new `` element in the `` container\. For example, the following `` element specifies the Amazon S3 construct library module: @@ -75,7 +75,7 @@ The version specifier `[1.0,2.0)` in this example indicates that the latest vers Maven automatically downloads a version of your dependencies that will match the requirements in `pom.xml`, if necessary, the next time you build your project\. -## AWS CDK Idioms in Java +## AWS CDK idioms in Java ### Props @@ -103,11 +103,11 @@ Bucket bucket = Bucket.Builder.create(this, "MyBucket") When deriving your own construct from an existing construct, you may want to accept additional properties\. We recommend that you follow these builder patterns\. However, this isn't as simple as subclassing a construct class\. You must provide the moving parts of the two new `Builder` classes yourself\. Given this fact, you may prefer to simply have your construct accept additional arguments\. In this case, provide additional constructors when an argument is optional\. -### Missing Values +### Missing values In Java, missing values in AWS CDK objects such as props are represented by `null`\. You must explicitly test any value that could be `null` to make sure it contains a value before doing anything with it\. Java does not have "syntactic sugar" to help handle null values as some other languages do\. You may find Apache ObjectUtil's [defaultIfNull](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#defaultIfNull-T-T-) and [firstNonNull](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#firstNonNull-T...-) useful in some situations\. Alternatively, write your own static helper methods to make it easier to handle potentially null values and make your code more readable\. -## Building, Synthesizing, and Deploying +## Building, synthesizing, and deploying Before running, build \(compile\) the app in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn compile` at a command prompt while in your project's root directory\. diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 522eddbb..a21bba54 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -10,7 +10,7 @@ To work with the AWS CDK, you must have an AWS account and credentials and have JavaScript AWS CDK applications require no additional prerequisites beyond these\. -## Creating a Project +## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. @@ -24,7 +24,7 @@ Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest `cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. -## Managing AWS Construct Library Modules +## Managing AWS construct library modules Use the Node Package Manager \(`npm`\), included with Node\.js, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. @@ -43,7 +43,7 @@ npm update **Note** All AWS Construct Library modules used in your project must be the same version\. -## AWS CDK Idioms in JavaScript +## AWS CDK idioms in JavaScript ### Props @@ -61,7 +61,7 @@ super(scope, name, {...props, encryptionKeys: undefined}); Alternatively, name your properties so that it is clear that they belong to your construct\. This way, it is unlikely they will collide with properties in future AWS CDK releases\. If there are many of them, use a single appropriately\-named object to hold them\. -### Missing Values +### Missing values Missing values in an object \(such as `props`\) have the value `undefined` in JavaScript\. The usual techniques apply for dealing with these\. For example, a common idiom for accessing a property of a value that may be undefined is as follows: @@ -79,7 +79,7 @@ let c = a == null ? a : a.b; A version of the ECMAScript standard currently in development specifies new operators that will simplify the handling of undefined values\. Using them can simplify your code, but you will need a new version of Node\.js to use them\. For more information, see the [optional chaining](https://github.com/tc39/proposal-optional-chaining/blob/master/README.md) and [nullish coalescing](https://github.com/tc39/proposal-nullish-coalescing/blob/master/README.md) proposals\. -## Synthesizing and Deploying +## Synthesizing and deploying The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. @@ -92,7 +92,7 @@ You don't need to explicitly synthesize stacks before deploying them; `cdk deplo For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. -## Using TypeScript Examples with JavaScript +## Using TypeScript examples with JavaScript [TypeScript](https://www.typescriptlang.org/) is the language we use to develop the AWS CDK, and it was the first language supported for developing applications, so many available AWS CDK code examples are written in TypeScript\. These code examples can be a good resource for JavaScript developers; you just need to remove the TypeScript\-specific parts of the code\. diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index b8064160..384e8786 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -25,7 +25,7 @@ It is common for Linux distros to use the executable name `python3` for Python 3 Make sure the `pip` executable \(on Windows, `pip.exe`\) is in a directory included on the system `PATH`\. You should be able to type `pip --version` and see its version, not an error message\. -## Creating a Project +## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. @@ -52,7 +52,7 @@ pip install -r requirements.txt **Important** Activate the project's virtual environment whenever you start working on it\. If you don't, you won't have access to the modules installed there, and modules you install will go in Python's global module directory \(or will result in a permission error\)\. -## Managing AWS Construct Library Modules +## Managing AWS construct library modules Use the Python package installer, `pip`, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. `pip` also installs the dependencies for those modules automatically\. @@ -81,7 +81,7 @@ pip install --upgrade -r requirements.txt **Note** All AWS Construct Library modules used in your project must be the same version\. -## AWS CDK Idioms in Python +## AWS CDK idioms in Python ### Props @@ -106,7 +106,7 @@ When extending a class or overriding a method, you may want to accept additional Future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues for users of your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion\. You can avoid this potential problem by naming your properties so they clearly belong to your construct \(e\.g\. `bob_encryption` rather than just `encryption`, assuming you're Bob\)\. If there are many new properties, bundle them into an appropriately\-named class \(`BobBucketPoperties`?\) and pass it as a single keyword argument\. -### Missing Values +### Missing values When working with `**kwargs`, use the dictionary's `get()` method to provide a default value if a property is not provided\. Avoid using `kwargs[...]`, as this raises `KeyError` for missing values\. @@ -117,7 +117,7 @@ encrypted = kwargs.get("encrypted", False) # specify default of False if propert Some AWS CDK methods \(such as `tryGetContext()` to get a runtime context value\) return `None` to indicate a missing value, which you will need to check for and handle\. -### Using Interfaces +### Using interfaces Python doesn't have an interface feature as some other languages do\. \(If you're not familiar with the concept, Wikipedia has [a good introduction](https://en.wikipedia.org/wiki/Interface_(computing)#In_object-oriented_languages)\.\) TypeScript, the language in which the AWS CDK is implemented does, however, and constructs and other AWS CDK objects often require an instance that adheres to a particular interface, rather than inheriting from a particular class\. So the AWS CDK provides its own interface feature as part of the [JSII](https://github.com/aws/jsii) layer\. @@ -133,7 +133,7 @@ class MyAspect(): print("Visited", node.node.path) ``` -### Type Pitfalls +### Type pitfalls Python natively uses dynamic typing, where variables may refer to a value of any type\. Parameters and return values may be annotated with types, but these are "hints" and are not enforced\. This means that in Python, it is easy to pass the incorrect type of value to a AWS CDK construct\. Instead of getting a type error during build, as you would from a statically\-typed language, you may instead get a runtime error when the JSII layer \(which translates between Python and the AWS CDK's TypeScript core\) is unable to deal with the unexpected type\. @@ -143,7 +143,7 @@ In our experience, the type errors Python programmers make tend to fall into the The AWS CDK Python modules do include type annotations\. If you are not using an IDE that supports these, such as [PyCharm](https://www.jetbrains.com/pycharm/), you might want to call the [MyPy](http://mypy-lang.org/) type validator as a step in your build process\. There are also runtime type checkers that can improve errror messages for type\-related errors\. -## Synthesizing and Deploying +## Synthesizing and deploying The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index dd777abf..791df1d7 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -16,7 +16,7 @@ npm install -g typescript Keep TypeScript up to date with a regular `npm update -g typescript`\. -## Creating a Project +## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. @@ -30,7 +30,7 @@ Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest `cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. -## Managing AWS Construct Library Modules +## Managing AWS construct library modules Use the Node Package Manager \(`npm`\), included with Node\.js, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. @@ -49,7 +49,7 @@ npm update **Note** All AWS Construct Library modules used in your project must be the same version\. -## AWS CDK Idioms in TypeScript +## AWS CDK idioms in TypeScript ### Props @@ -69,11 +69,11 @@ super(scope, name, {...props, encryptionKeys: undefined}); Alternatively, name your properties so that it is clear that they belong to your construct\. This way, it is unlikely they will collide with properties in future AWS CDK releases\. If there are many of them, use a single appropriately\-named object to hold them\. -### Missing Values +### Missing values Missing values in an object \(such as props\) have the value `undefined` in TypeScript\. Recent versions of the language include operators that simplify working with these values, making it easier to specify defaults and "short\-circuit" chaining when an undefined value is reached\. For more information on these features, see the [TypeScript 3\.7 Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html), specifically the first two features, Optional Chaining and Nullish Coalescing\. -## Building, Synthesizing, and Deploying +## Building, synthesizing, and deploying Generally, you should be in the project's root directory when building and running your application\. diff --git a/doc_source/work-with.md b/doc_source/work-with.md index 15cc1d97..72015252 100644 --- a/doc_source/work-with.md +++ b/doc_source/work-with.md @@ -4,7 +4,7 @@ The AWS Cloud Development Kit \(AWS CDK\) lets you define your AWS cloud infrast We develop the AWS CDK in TypeScript and use [JSII](https://github.com/aws/jsii) to provide a "native" experience in other supported languages\. For example, we distribute AWS Construct Library modules using your preferred language's standard repository, and you install them using the language's standard package manager\. Methods and properties are even named using your language's recommended naming patterns\. -**AWS CDK Prerequisites** +**AWS CDK prerequisites** To use the AWS CDK, you need an AWS account and a corresponding access key\. If you don't have an AWS account yet, see [Create and Activate an AWS Account](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)\. To find out how to obtain an access key ID and secret access key for your AWS account, see [Understanding and Getting Your Security Credentials](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html)\. To find out how to configure your workstation so the AWS CDK uses your credentials, see [Setting Credentials in Node\.js](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html)\. **Tip** From 3678dff9cb538502f38ecbd3632584f5090f491b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 13 May 2020 18:01:39 +0000 Subject: [PATCH 154/655] update to reflect how context works now --- doc_source/context.md | 23 ++++++++++++++--------- doc_source/featureflags.md | 6 ++++-- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/doc_source/context.md b/doc_source/context.md index abe78a47..e90b07b5 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -1,19 +1,22 @@ # Runtime context -The AWS CDK uses *context* to retrieve information such as the Availability Zones in your account or Amazon Machine Image \(AMI\) IDs used to start your instances\. Context entries are key\-value pairs\. - -To avoid unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, thus changing your Auto Scaling group, the AWS CDK stores context values in the `cdk.context.json` file within your project\. This ensures that the AWS CDK uses the same context values the next time it synthesizes your app\. Don't forget to put this file under version control\. +Context values are key\-value pairs that can be associated with a stack or construct\. The AWS CDK uses context to cache information from your AWS account, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs used to start your instances\. [Feature flags](featureflags.md) are also context values\. You can create your own context values for use by your apps or constructs\. ## Construct context -Context values are made available to your AWS CDK app in five different ways: +Context values are made available to your AWS CDK app in six different ways: + Automatically from the current AWS account\. + Through the \-\-context option to the cdk command\. ++ In the `context` key of the project's `cdk.context.json` file\. + In the `context` key of the project's `cdk.json` file\. -+ In the `context` key of a `~/cdk.json` file\. -+ In code using the `construct.node.setContext` method\. ++ In the `context` key of your `~/cdk.json` file\. ++ In your AWS CDK app using the `construct.node.setContext` method\. + +The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, changing your Auto Scaling group\. The AWS CDK does not write context data to any of the other files listed\. -Context values are scoped to the construct that created them; they are visible to child constructs, but not to siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), either automatically or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in the app\. +We recommend that your project's context files be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. + +Context values are scoped to the construct that created them; they are visible to child constructs, but not to siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), whether automatically, from a file, or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in the app\. You can get a context value using the `construct.node.tryGetContext` method\. If the requested entry is not found on the current construct or any of its parents, the result is `undefined` \(or your language's equivalent, such as `None` in Python\)\. @@ -57,10 +60,10 @@ Context found in cdk.json: │ 2 │ availability-zones:account=123456789012:region=eu-west-1 │ [ "eu-west-1a", "eu-west-1b", "eu-west-1c" ] │ └───┴─────────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────────┘ -Run cdk context --reset KEY_OR_NUMBER to remove a context key. It will be refreshed on the next CDK synthesis run. +Run cdk context --reset KEY_OR_NUMBER to remove a context key. If it is a cached value, it will be refreshed on the next cdk synth. ``` -To remove a context value, run cdk context \-\-reset, specifying the value's corresponding key number\. The following example removes the value that corresponds to the key value of `2` in the preceding example, which is the list of availability zones in the Ireland region\. +To remove a context value, run cdk context \-\-reset, specifying the value's corresponding key or number\. The following example removes the value that corresponds to the second key in the preceding example, which is the list of availability zones in the Ireland region\. ``` $ cdk context --reset 2 @@ -84,6 +87,8 @@ To clear all of the stored context values for your app, run cdk context \-\-clea $ cdk context --clear ``` +Only context values stored in `cdk.context.json` can be reset or cleared\. The AWS CDK does not touch other context files\. To protect a context value from being reset by the AWS CDK using these commands, then, you might copy the value to `cdk.json`\. + ## Example Below is an example of importing an existing Amazon VPC using AWS CDK context\. diff --git a/doc_source/featureflags.md b/doc_source/featureflags.md index 22fda10d..e573847c 100644 --- a/doc_source/featureflags.md +++ b/doc_source/featureflags.md @@ -13,6 +13,8 @@ The AWS CDK uses *feature flags* to enable potentially breaking behaviors in a r The names of all feature flags begin with the NPM name of the package affected by the particular flag\. In the example above, this is `@aws-cdk/core`, the AWS CDK framework itself, since the flag affects stack naming rules, a core AWS CDK function\. AWS Construct Library modules can also use feature flags\. -Feature flags are disabled by default, so existing projects that do not specify the flag will continue to work with later AWS CDK releases\. New projects created using `cdk init` include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the old behavior, or to add flags to enable new behaviors after upgrading the AWS CDK\. +Feature flags are disabled by default, so existing projects that do not specify the flag will continue to work as expected with later AWS CDK releases\. New projects created using cdk init include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the old behavior, or to add flags to enable new behaviors after upgrading the AWS CDK\. -See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. The AWS CDK source file [https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts) provides a complete list of all current feature flags\. \ No newline at end of file +See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. The AWS CDK source file [https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts) provides a complete list of all current feature flags\. + +As feature flags are stored in `cdk.json`, they are not removed by the cdk context \-\-reset or cdk context \-\-reset commands\. \ No newline at end of file From 9492164f8e5f591b9c5f7dfef068b318e363d865 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 13 May 2020 18:04:02 +0000 Subject: [PATCH 155/655] fix incorrect word --- doc_source/featureflags.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/featureflags.md b/doc_source/featureflags.md index e573847c..aa34a875 100644 --- a/doc_source/featureflags.md +++ b/doc_source/featureflags.md @@ -17,4 +17,4 @@ Feature flags are disabled by default, so existing projects that do not specify See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. The AWS CDK source file [https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts) provides a complete list of all current feature flags\. -As feature flags are stored in `cdk.json`, they are not removed by the cdk context \-\-reset or cdk context \-\-reset commands\. \ No newline at end of file +As feature flags are stored in `cdk.json`, they are not removed by the cdk context \-\-reset or cdk context \-\-clear commands\. \ No newline at end of file From 7f6b0db4657919df79ff2f9cd0c432c1fe077def Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 14 May 2020 17:28:09 +0000 Subject: [PATCH 156/655] update CDK help --- doc_source/context.md | 4 ++-- doc_source/tools.md | 36 ++++++++++++++++++++---------------- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/doc_source/context.md b/doc_source/context.md index e90b07b5..6acb498d 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -7,7 +7,7 @@ Context values are key\-value pairs that can be associated with a stack or const Context values are made available to your AWS CDK app in six different ways: + Automatically from the current AWS account\. + Through the \-\-context option to the cdk command\. -+ In the `context` key of the project's `cdk.context.json` file\. ++ In the project's `cdk.context.json` file\. + In the `context` key of the project's `cdk.json` file\. + In the `context` key of your `~/cdk.json` file\. + In your AWS CDK app using the `construct.node.setContext` method\. @@ -87,7 +87,7 @@ To clear all of the stored context values for your app, run cdk context \-\-clea $ cdk context --clear ``` -Only context values stored in `cdk.context.json` can be reset or cleared\. The AWS CDK does not touch other context files\. To protect a context value from being reset by the AWS CDK using these commands, then, you might copy the value to `cdk.json`\. +Only context values stored in `cdk.context.json` can be reset or cleared\. The AWS CDK does not touch other context files\. To protect a context value from being reset using these commands, then, you might copy the value to `cdk.json`\. ## Example diff --git a/doc_source/tools.md b/doc_source/tools.md index 0ea0c429..6ee323cd 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -207,34 +207,38 @@ Deploys the stack(s) named STACKS into your AWS account Options: - --build-exclude, -E Do not rebuild asset with the given ID. Can be specified - multiple times. [array] [default: []] + --build-exclude, -E Do not rebuild asset with the given ID. Can be + specified multiple times. [array] [default: []] - --exclusively, -e Only deploy requested stacks, don't include dependencies - [boolean] + --exclusively, -e Only deploy requested stacks, don't include + dependencies [boolean] - --require-approval What security-sensitive changes need manual approval + --require-approval What security-sensitive changes need manual approval [string] [choices: "never", "any-change", "broadening"] - --ci Force CI detection (deprecated) + --ci Force CI detection (deprecated) [boolean] [default: false] - --notification-arns ARNs of SNS topics that CloudFormation will notify with - stack related events [array] + --notification-arns ARNs of SNS topics that CloudFormation will notify with + stack related events [array] - --tags, -t Tags to add to the stack (KEY=VALUE) [array] + --tags, -t Tags to add to the stack (KEY=VALUE) [array] - --execute Whether to execute ChangeSet (--no-execute will NOT - execute the ChangeSet) [boolean] [default: true] + --execute Whether to execute ChangeSet (--no-execute will NOT + execute the ChangeSet) [boolean] [default: true] - --force, -f Always deploy stack even if templates are identical + --force, -f Always deploy stack even if templates are identical [boolean] [default: false] - --parameters Additional parameters passed to CloudFormation at deploy - time (STACK:KEY=VALUE) [array] [default: {}] + --parameters Additional parameters passed to CloudFormation at + deploy time (STACK:KEY=VALUE) [array] [default: {}] + + --outputs-file, -O Path to file where stack outputs will be written as + JSON [string] - --outputs-file, -O Path to file where stack outputs will be written as JSON - [string] + --previous-parameters Use previous values for existing parameters (you must + specify all parameters on every deployment if this is + disabled) [boolean] [default: true] ``` If your app has a single stack, you don't have to specify the stack name\. From 0e8a8411a8e454f5497a57e0061945c4ad9d794c Mon Sep 17 00:00:00 2001 From: ali-tayebi <4958087+ali-tayebi@users.noreply.github.com> Date: Fri, 15 May 2020 11:25:27 +1000 Subject: [PATCH 157/655] Improves C# example to CDK app --- doc_source/constructs.md | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index dd685404..502e9009 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -125,12 +125,27 @@ public class HelloCdkStack extends Stack { using Amazon.CDK; using Amazon.CDK.AWS.S3; -public HelloCdkStack(Construct scope, string id, IStackProps props) : base(scope, id, props) +namespace HelloCdkApp { - new Bucket(this, "MyFirstBucket", new BucketProps { - Versioned = true - }); + internal static class Program + { + public static void Main(string[] args) + { + var app = new App(); + new HelloCdkStack(app, "HelloCdkStack"); + app.Synth(); + } + } + + public class HelloCdkStack : Stack + { + public HelloCdkStack(Construct scope, string id, IStackProps props= null) : base(scope, id, props) + { + new Bucket(this, "MyFirstBucket", new BucketProps { Versioned = true }); + } + } } + ``` ------ @@ -200,7 +215,7 @@ public class HelloCdkStack extends Stack { ``` public class HelloCdkStack : Stack { - public HelloCdkStack(App scope, string id, StackProps props) : base(scope, id, props) + public HelloCdkStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) { //... } @@ -823,4 +838,4 @@ var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketP images.topic.AddSubscription(new SqsSubscription(queue)); ``` ------- \ No newline at end of file +------ From 8f15ad44e1b9c05e74f2c93ed50946317f5efd0a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 15 May 2020 15:05:17 +0000 Subject: [PATCH 158/655] add info about reusing parameters --- doc_source/parameters.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/doc_source/parameters.md b/doc_source/parameters.md index 41c0d172..13699ee7 100644 --- a/doc_source/parameters.md +++ b/doc_source/parameters.md @@ -203,4 +203,6 @@ If you are deploying multiple stacks, you can specify a different value of each ``` cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket --parameters YourStack:uploadBucketName=UpBucket -``` \ No newline at end of file +``` + +By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the \-\-no\-previous\-parameters flag to require all parameters to be specified\. \ No newline at end of file From 93bf094ab1bbaf7c4846560c4e006d209c966bea Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 15 May 2020 22:42:28 +0000 Subject: [PATCH 159/655] update events section to make it more general (it doesn't actually mean CWE/EventBridge) --- doc_source/resources.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index fe214f1d..fcdef06d 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1041,9 +1041,9 @@ fleet.Connections.AllowToDefaultPort(rdsDatabase, "Fleet can access database"); ------ -## Amazon CloudWatch Events +## Event handling -Some resources can act as event sources\. Use the `addEventNotification` method \(Python: `add_event_notification`\) to register an event target to a particular event type emitted by the resource\. In addition to this, `addXxxNotification` methods offer a simplified way to register a handler for a common event type\. +Some resources can act as event sources\. Use the `addEventNotification` method \(Python: `add_event_notification`\) to register an event target to a particular event type emitted by the resource\. In addition to this, `addXxxNotification` methods offer a simple way to register a handler for common event types\. The following example shows how to trigger a Lambda function when an object is added to an Amazon S3 bucket\. From 4a4672aed5524819cdcdacc82dbd01e294bb0384 Mon Sep 17 00:00:00 2001 From: Kevin Rich Date: Sun, 17 May 2020 10:31:16 -0700 Subject: [PATCH 160/655] Update how to create a metric for C# The method to add Dimensions as shown in the current version result in a compile error in C#. I have tested this change with success --- doc_source/how_to_set_cw_alarm.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index 72f9fb64..654e8310 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -122,9 +122,9 @@ var metric = new Metric(this, "Metric", new MetricProps { Namespace = "MyNamespace", MetricName = "MyMetric", - Dimensions = new Dictionary + Dimensions = new Dictionary { - ["MyDimension"]: "MyDimensionValue" + { "MyDimension", "MyDimensionValue" } } }); ``` @@ -202,4 +202,4 @@ new Alarm(this, "Alarm", new AlarmProps { }); ``` ------- \ No newline at end of file +------ From 1d72ab43f2f6d287e07abf640c3da987dd4f11f1 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 18 May 2020 22:54:28 +0000 Subject: [PATCH 161/655] quote wildcard argument to cdk --- doc_source/codepipeline_example.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index ce803e09..e8f25f8a 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -1180,5 +1180,5 @@ Try making a change, such as to your `LambdaStack` AWS CDK code or to your Lambd To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done with this exercise\. ``` -cdk destroy * +cdk destroy '*' ``` \ No newline at end of file From 70a426a0da82c54e101d53b7412ffcd1859727dc Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 20 May 2020 23:49:06 +0000 Subject: [PATCH 162/655] fix some problem wtih code in this example --- doc_source/codepipeline_example.md | 69 +++++++++++++++--------------- 1 file changed, 35 insertions(+), 34 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index e8f25f8a..3f842ca1 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -6,6 +6,9 @@ The AWS CDK enables you to easily create applications running in the AWS Cloud\. The following example shows how to deploy an AWS Lambda function in a pipeline\. In this example, your AWS CDK code and your Lambda code are in the same project\. The Lambda code is in the `Lambda` directory\. +**Note** +The Lambda function itself is assumed to be written in TypeScript regardless of the language you're using for your AWS CDK app\. + To set up a project like this from scratch, follow these instructions\. ------ @@ -53,6 +56,7 @@ pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_ mkdir pipeline cd pipeline cdk init --language java +mkdir Lambda ``` You can import the resulting Maven project into your Java IDE\. @@ -76,6 +80,7 @@ s3 mkdir pipeline cd pipeline cdk init --language csharp +mkdir Lambda ``` You can open the file `src/Pipeline.sln` in Visual Studio\. @@ -84,18 +89,14 @@ Choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solut ``` Amazon.CDK.AWS.CodeDeploy -Amazon.CDK.AWS.Lambda Amazon.CDK.AWS.CodeBuild Amazon.CDK.AWS.CodeCommit Amazon.CDK.AWS.CodePipeline Amazon.CDK.AWS.CodePipeline.Actions +Amazon.CDK.AWS.Lambda Amazon.CDK.AWS.S3 ``` -**Tip** -If you don't see these packages in the **Browse** tab of the **Manage Packages for Solution** page, make sure the **Include prerelease** checkbox is ticked\. -For a better experience, also add the `Amazon.Jsii.Analyzers` package to provide compile\-time checks for missing required properties\. - ------ ## Lambda stack @@ -108,7 +109,7 @@ This class includes the `lambdaCode` \(Python: `lambda_code`\) property, which i The example also uses the CodeDeploy support for blue\-green deployments to Lambda, and the deployment increases the traffic to the new version in 10\-percent increments every minute\. As blue\-green deployment can only operate on aliases, not on the function directly, we create an alias for our function, named `Prod`\. -The alias uses a Lambda version, which is named after the date when the code executed\. This ensures that every invocation of the AWS CDK code publishes a new version of the function\. +The alias uses a Lambda version obtained using the function's `currentVersion` property\. This ensures that every invocation of the AWS CDK code publishes a new version of the function\. If the Lambda function needs any other resources when executing, such as an Amazon S3 bucket, Amazon DynamoDB table, or Amazon API Gateway, declare those resources here\. @@ -136,7 +137,7 @@ export class LambdaStack extends Stack { runtime: lambda.Runtime.NODEJS_10_X, }); - const version = func.addVersion(new Date().toISOString()); + const version = func.latestVersion; const alias = new lambda.Alias(this, 'LambdaAlias', { aliasName: 'Prod', version, @@ -173,7 +174,7 @@ class LambdaStack extends Stack { runtime: lambda.Runtime.NODEJS_10_X }); - const version = func.addVersion(new Date().toISOString()); + const version = func.latestVersion; const alias = new lambda.Alias(this, 'LambdaAlias', { aliasName: 'Prod', version @@ -197,8 +198,6 @@ File: `pipeline/lambda_stack.py` ``` from aws_cdk import core, aws_codedeploy as codedeploy, aws_lambda as lambda_ -from datetime import datetime - class LambdaStack(core.Stack): def __init__(self, app: core.App, id: str, **kwargs): super().__init__(app, id, **kwargs) @@ -211,7 +210,7 @@ class LambdaStack(core.Stack): runtime=lambda_.Runtime.NODEJS_10_X, ) - version = func.add_version(datetime.now().isoformat()) + version = func.latest_version alias = lambda_.Alias(self, "LambdaAlias", alias_name="Prod", version=version) @@ -225,13 +224,11 @@ class LambdaStack(core.Stack): ------ #### [ Java ] -File: src/main/java/com/myorg/LambdaStack\.java +File: `src/main/java/com/myorg/LambdaStack.java` ``` package com.myorg; -import java.time.Instant; - import software.amazon.awscdk.core.App; import software.amazon.awscdk.core.Stack; import software.amazon.awscdk.core.StackProps; @@ -269,7 +266,7 @@ public class LambdaStack extends Stack { .handler("index.handler") .runtime(Runtime.NODEJS_10_X).build(); - Version version = func.addVersion(Instant.now().toString()); + Version version = func.getCurrentVersion(); Alias alias = Alias.Builder.create(this, "LambdaAlias") .aliasName("LambdaAlias") .version(version).build(); @@ -284,7 +281,7 @@ public class LambdaStack extends Stack { ------ #### [ C\# ] -File: `src/pipeline/LambdaStack.cs` +File: `src/Pipeline/LambdaStack.cs` ``` using System; @@ -298,7 +295,7 @@ namespace Pipeline { public readonly CfnParametersCode lambdaCode; - public LambdaStack(App app, string id, StackProps props=null) : base(app, id, props) + public LambdaStack(App app, string id, StackProps props = null) : base(app, id, props) { lambdaCode = Code.FromCfnParameters(); @@ -309,7 +306,7 @@ namespace Pipeline Runtime = Runtime.NODEJS_10_X }); - var version = func.AddVersion(DateTime.UtcNow.ToString("s")); + var version = func.LatestVersion; var alias = new Alias(this, "LambdaAlias", new AliasProps { AliasName = "Prod", @@ -703,7 +700,7 @@ class PipelineStack(core.Stack): ------ #### [ Java ] -File: src/main/java/com/myorg/PipelineStack\.java +File: `src/main/java/com/myorg/PipelineStack.java` ``` package com.myorg; @@ -722,6 +719,7 @@ import software.amazon.awscdk.services.codebuild.LinuxBuildImage; import software.amazon.awscdk.services.codebuild.PipelineProject; import software.amazon.awscdk.services.codecommit.Repository; +import software.amazon.awscdk.services.codecommit.IRepository; import software.amazon.awscdk.services.codepipeline.Artifact; import software.amazon.awscdk.services.codepipeline.StageProps; @@ -810,8 +808,8 @@ public class PipelineStack extends Stack { .project(lambdaBuild) .input(sourceOutput) .outputs(Arrays.asList(lambdaBuildOutput)).build(), - CodeBuildAction.Buildercreate() - .actionName("Lambda_Build") + CodeBuildAction.Builder.create() + .actionName("CDK_Build") .project(cdkBuild) .input(sourceOutput) .outputs(Arrays.asList(cdkBuildOutput)) @@ -826,7 +824,8 @@ public class PipelineStack extends Stack { .adminPermissions(true) .parameterOverrides(lambdaCode.assign(lambdaBuildOutput.getS3Location())) .extraInputs(Arrays.asList(lambdaBuildOutput)) - .build()) + .stackName("LambdaDeploymentStack") + .build())) .build())) .build(); } @@ -836,7 +835,7 @@ public class PipelineStack extends Stack { ------ #### [ C\# ] -File: src/pipeline/PipelineStack\.cs +File: `src/Pipeline/PipelineStack.cs` ``` using Amazon.CDK; @@ -856,9 +855,9 @@ namespace Pipeline public class PipelineStack : Stack { - public PipelineStack(App app, string id, PipelineStackProps props=null) + public PipelineStack(App app, string id, PipelineStackProps props = null) { - var code = Repository.FromRepositoryName(this, "ImportedRepo", + var code = Repository.FromRepositoryName(this, "ImportedRepo", "NameOfYourCodeCommitRepository"); var cdkBuild = new PipelineProject(this, "CDKBuild", new PipelineProjectProps @@ -868,23 +867,23 @@ namespace Pipeline ["version"] = "0.2", ["phases"] = new Dictionary { - ["install"] = new Dictionary + ["install"] = new Dictionary { ["commands"] = "npm install" }, ["build"] = new Dictionary { - ["commands"] = new List { + ["commands"] = new string[] { "npm run build", "npm run cdk synth -- o dist" } } }, - ["artifacts"] = new Dictionary + ["artifacts"] = new Dictionary { ["base-directory"] = "dist" }, - ["files"] = new List + ["files"] = new string[] { "LambdaStack.template.json" } @@ -904,7 +903,7 @@ namespace Pipeline { ["install"] = new Dictionary { - ["commands"] = new List + ["commands"] = new string[] { "cd lambda", "npm install" @@ -918,7 +917,7 @@ namespace Pipeline ["artifacts"] = new Dictionary { ["base-directory"] = "lambda", - ["files"] = new List + ["files"] = new string[] { "index.js", "node_modules/**/*" @@ -937,7 +936,7 @@ namespace Pipeline new Amazon.CDK.AWS.CodePipeline.Pipeline(this, "Pipeline", new PipelineProps { - Stages = new [] + Stages = new[] { new StageProps { @@ -1073,7 +1072,7 @@ app.synth() ------ #### [ Java ] -File: src/main/java/com/myorg/PipelineApp\.java +File: `src/main/java/com/myorg/PipelineApp.java` ``` package com.myorg; @@ -1095,6 +1094,8 @@ public class PipelineApp { ------ #### [ C\# ] +File: `src/Pipeline/Program.cs` + ``` using Amazon.CDK; @@ -1111,7 +1112,7 @@ namespace Pipeline { LambdaCode = lambdaStack.lambdaCode }); - + app.Synth(); } } From d32033f3fbac3733f675052ec2767cacb30bd3b6 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 20 May 2020 23:50:00 +0000 Subject: [PATCH 163/655] add info on how to write objects and arrays --- doc_source/work-with-cdk-csharp.md | 4 ++++ doc_source/work-with-cdk-java.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 0b66e76c..b5c82a6b 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -132,6 +132,10 @@ When calling the parent class's initializer or overridden method, you can genera Keep in mind that future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues using your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion for your construct's users\. You can avoid this potential problem by naming your properties so they clearly belong to your construct \(e\.g\. `BobEncryption` rather than just `encryption`, assuming you're Bob\)\. If there are many new properties, bundle them into an appropriately\-named class \(`BobBucketPoperties`?\) and pass them as a single property\. +### Generic structures + +In some places, the AWS CDK uses JavaScript arrays or untyped objects or as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In C\#, objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` in C\#\. + ### Missing values In C\#, missing values in AWS CDK objects such as props are represented by `null`\. The null\-conditional member access operator `?.` and the null coalescing operator `??` are convenient for working with these values\. diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 6de2ec11..e0c1b849 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -103,6 +103,10 @@ Bucket bucket = Bucket.Builder.create(this, "MyBucket") When deriving your own construct from an existing construct, you may want to accept additional properties\. We recommend that you follow these builder patterns\. However, this isn't as simple as subclassing a construct class\. You must provide the moving parts of the two new `Builder` classes yourself\. Given this fact, you may prefer to simply have your construct accept additional arguments\. In this case, provide additional constructors when an argument is optional\. +### Generic structures + +In some places, the AWS CDK uses JavaScript arrays or untyped objects or as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Java, objects are represented as `java.util.HashMap`\. In cases where the values are all strings, you can use `HashMap`\. JavaScript arrays are represented as `Object[]` or `String[]` in Java\. + ### Missing values In Java, missing values in AWS CDK objects such as props are represented by `null`\. You must explicitly test any value that could be `null` to make sure it contains a value before doing anything with it\. Java does not have "syntactic sugar" to help handle null values as some other languages do\. You may find Apache ObjectUtil's [defaultIfNull](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#defaultIfNull-T-T-) and [firstNonNull](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#firstNonNull-T...-) useful in some situations\. Alternatively, write your own static helper methods to make it easier to handle potentially null values and make your code more readable\. From f4945a083d36d68b61c35566e803b7dfcfd8cc0e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 22 May 2020 03:41:46 +0000 Subject: [PATCH 164/655] update cdk help --- doc_source/tools.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/doc_source/tools.md b/doc_source/tools.md index 6ee323cd..863d7682 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -186,6 +186,9 @@ Options: --bootstrap-kms-key-id AWS KMS master key ID used for the SSE-KMS encryption [string] + --qualifier Unique string to distinguish + multiple bootstrap stacks [string] + --tags, -t Tags to add for the stack (KEY=VALUE) [array] [default: []] From 8e42ed5a739ebe8e1ac1245576ae1edd4bc2b3e4 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 22 May 2020 03:41:59 +0000 Subject: [PATCH 165/655] add more info about grants --- doc_source/permissions.md | 90 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 89 insertions(+), 1 deletion(-) diff --git a/doc_source/permissions.md b/doc_source/permissions.md index 440c002c..f22ecde3 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -30,7 +30,95 @@ The first argument of a **grant** method is always of type [IGrantable](https:// Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other entities that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. -Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly \(`bucket.grantRead(lambda)`, or `grant_read` in Python\) instead of granting access to their role\. +Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly \(`bucket.grantRead(lambda)`, or `grant_read` in Python\) instead of granting access to their role\. For example, if `bucket` is an Amazon S3 bucket, and `function` is a Lambda function, the code below grants the function read access to the bucket\. + +------ +#### [ TypeScript ] + +``` +bucket.grantRead(function); +``` + +------ +#### [ JavaScript ] + +``` +bucket.grantRead(function); +``` + +------ +#### [ Python ] + +``` +bucket.grant_read(function) +``` + +------ +#### [ Java ] + +``` +bucket.grantRead(function); +``` + +------ +#### [ C\# ] + +``` +bucket.GrantRead(function); +``` + +------ + + Sometimes permissions must be applied while your stack is being deployed\. One such case is when you grant a AWS CloudFormation custom resource access to some other resource\. The custom resource will be invoked during deployment, so it must have the specified permissions at deployment time\. Another case is when a service verifies that the role you pass to it has the right policies applied \(a number of AWS services do this to make sure you didn't forget to set the policies\)\. In those cases, the deployment may fail if the permissions are applied too late\. + + To force the grant's permissions to be applied before another resource is created, you can add a dependency on the grant itself, as shown here\. Though the return value of grant methods is commonly discarded, every grant method in fact returns an `iam.Grant` object\. + +------ +#### [ TypeScript ] + +``` +const grant = bucket.grantRead(lambda); +const custom = new CustomResource(...); +custom.node.addDependency(grant); +``` + +------ +#### [ JavaScript ] + +``` +const grant = bucket.grantRead(lambda); +const custom = new CustomResource(...); +custom.node.addDependency(grant); +``` + +------ +#### [ Python ] + +``` +grant = bucket.grant_read(function) +custom = CustomResource(...) +custom.node.add_dependency(grant) +``` + +------ +#### [ Java ] + +``` +Grant grant = bucket.grantRead(function); +CustomResource custom = new CustomResource(...); +custom.node.addDependency(grant); +``` + +------ +#### [ C\# ] + +``` +var grant = bucket.GrantRead(function); +var custom = new CustomResource(...); +custom.node.AddDependency(grant); +``` + +------ ## Roles From 1098daa647df855400eeeb1e3b0b8dd759a9c319 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 22 May 2020 22:05:57 +0000 Subject: [PATCH 166/655] clean up some wording and code formatting --- doc_source/constructs.md | 5 ++--- doc_source/environments.md | 15 ++++----------- doc_source/how_to_set_cw_alarm.md | 2 +- 3 files changed, 7 insertions(+), 15 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 502e9009..aa74d332 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -139,13 +139,12 @@ namespace HelloCdkApp public class HelloCdkStack : Stack { - public HelloCdkStack(Construct scope, string id, IStackProps props= null) : base(scope, id, props) + public HelloCdkStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) { new Bucket(this, "MyFirstBucket", new BucketProps { Versioned = true }); } } } - ``` ------ @@ -838,4 +837,4 @@ var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketP images.topic.AddSubscription(new SqsSubscription(queue)); ``` ------- +------ \ No newline at end of file diff --git a/doc_source/environments.md b/doc_source/environments.md index 635eda35..353e789f 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -103,10 +103,10 @@ The following code fragment shows how to access the account and region passed fr ------ #### [ TypeScript ] -Access environment variables via the `process` object\. +Access environment variables via Node's `process` object\. **Note** -TypeScript users must install the DefinitelyTyped NodeJS module with NPM to be able to use `process`\. `cdk init` now installs this module for you, but if you are working with a project created before it was added, or didn't set up your project using `cdk init`, install it manually\. + You need the DefinitelyTyped module to use `process` in TypeScript\. `cdk init` installs this module for you, but if you are working with a project created before it was added, or didn't set up your project using `cdk init`, install it manually\. ``` npm install @types/node @@ -123,14 +123,7 @@ new MyDevStack(app, 'dev', { ------ #### [ JavaScript ] -Access environment variables via the `process` object\. - -**Note** -TypeScript users must install the DefinitelyTyped NodeJS module with NPM to be able to use `process`\. `cdk init` now installs this module for you, but if you are working with a project created before it was added, or didn't set up your project using `cdk init`, install it manually\. - -``` -npm install @types/node -``` +Access environment variables via Node's `process` object\. ``` new MyDevStack(app, 'dev', { @@ -143,7 +136,7 @@ new MyDevStack(app, 'dev', { ------ #### [ Python ] -Use the `os` module's `environ` dictonary to access environment variables\. +Use the `os` module's `environ` dictionary to access environment variables\. ``` import os diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index 654e8310..a3a6b825 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -202,4 +202,4 @@ new Alarm(this, "Alarm", new AlarmProps { }); ``` ------- +------ \ No newline at end of file From 6a6df9ef4b8a18bfb9af780bf5972ffa0fc97861 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 23 May 2020 00:10:02 +0000 Subject: [PATCH 167/655] improve pipeline example --- doc_source/codepipeline_example.md | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 3f842ca1..112f1d0d 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -4,10 +4,10 @@ This example creates a code pipeline using the AWS CDK\. The AWS CDK enables you to easily create applications running in the AWS Cloud\. But creating the application is just the start of the journey\. You also want to make changes to it, test those changes, and finally deploy them to your stack\. The AWS CDK enables this workflow by using the **Code\*** suite of AWS tools: AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline\. Together, they allow you to build what's called a [deployment pipeline](https://aws.amazon.com/getting-started/tutorials/continuous-deployment-pipeline/) for your application\. -The following example shows how to deploy an AWS Lambda function in a pipeline\. In this example, your AWS CDK code and your Lambda code are in the same project\. The Lambda code is in the `Lambda` directory\. +The following example shows how to deploy an AWS Lambda function in a pipeline\. Two stacks are created: one to deploy your Lambda code, and one to define a pipeline to deploy the first stack whenever your Lambda code changes\. Your Lambda code is intended to be in a AWS CodeCommit repository, although you can work through this example without any Lambda code \(the pipeline will fail, but the stack that defines it will deploy\)\. **Note** -The Lambda function itself is assumed to be written in TypeScript regardless of the language you're using for your AWS CDK app\. +The Lambda function itself is assumed to be written in TypeScript regardless of the language you're using for your AWS CDK app\. To use this example to deploy a Lambda function written in a different language, you'll need to modify the pipeline\. To set up a project like this from scratch, follow these instructions\. @@ -18,7 +18,6 @@ To set up a project like this from scratch, follow these instructions\. mkdir pipeline cd pipeline cdk init --language typescript -mkdir Lambda npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 ``` @@ -30,7 +29,6 @@ npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/a mkdir pipeline cd pipeline cdk init ‐-language javascript -mkdir Lambda npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 ``` @@ -44,7 +42,6 @@ cd pipeline cdk init --language python source .env/bin/activate pip install -r requirements.txt -mkdir Lambda pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_s3 ``` @@ -56,7 +53,6 @@ pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_ mkdir pipeline cd pipeline cdk init --language java -mkdir Lambda ``` You can import the resulting Maven project into your Java IDE\. @@ -80,7 +76,6 @@ s3 mkdir pipeline cd pipeline cdk init --language csharp -mkdir Lambda ``` You can open the file `src/Pipeline.sln` in Visual Studio\. @@ -1121,7 +1116,7 @@ namespace Pipeline ------ -## Creating the pipeline +## Deploying the pipeline The final steps are building the code and deploying the pipeline\. @@ -1170,15 +1165,18 @@ cdk deploy PipelineDeployingLambdaStack The name, **PipelineDeployingLambdaStack**, is the name we used when we instantiated `PipelineStack`\. +**Note** +Don't deploy *LambdaStack*\. This stack is meant to be deployed by the pipeline\. + After the deployment finishes, you should have a three\-stage pipeline that looks something like the following\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/pipeline.jpg) -Try making a change, such as to your `LambdaStack` AWS CDK code or to your Lambda function code, and push it to the repository\. The pipeline should pick up your change, build it, and deploy it automatically, without any human intervention\. +Try making a change to your Lambda function code and push it to the repository\. The pipeline should pick up your change, build it, and deploy it automatically, without any human intervention\. ## Cleaning up -To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done with this exercise\. +To avoid unexpected AWS charges, destroy your AWS CDK stacks after you're done with this exercise\. ``` cdk destroy '*' From 1735903806a152afa188ca458e23c2cd2ced7302 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 23 May 2020 01:09:38 +0000 Subject: [PATCH 168/655] tweaks to code and fix name (s3_not) --- doc_source/resources.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index fcdef06d..5d9699ef 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1077,7 +1077,7 @@ import aws_cdk.aws_s3_notifications as s3_nots handler = lambda_.Function(self, "Handler", ...) bucket = s3.Bucket(self, "Bucket") -bucket.add_object_created_notification(s3_not.LambdaDestination(handler)) +bucket.add_object_created_notification(s3_nots.LambdaDestination(handler)) ``` ------ @@ -1099,11 +1099,11 @@ bucket.addObjectCreatedNotification(new LambdaDestination(handler)); ``` using lambda = Amazon.CDK.AWS.Lambda; using s3 = Amazon.CDK.AWS.S3; -using s3_not = Amazon.CDK.AWS.S3.Notifications; +using s3Nots = Amazon.CDK.AWS.S3.Notifications; var handler = new lambda.Function(this, "Handler", new lambda.FunctionProps { .. }); var bucket = new s3.Bucket(this, "Bucket"); -bucket.AddObjectCreatedNotification(new s3_not.LambdaDestination(handler)); +bucket.AddObjectCreatedNotification(new s3Nots.LambdaDestination(handler)); ``` ------ From c3a3f795eaaff1f2c313f31980040966dd224b40 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 23 May 2020 20:26:02 +0000 Subject: [PATCH 169/655] remove redundant text --- doc_source/permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/permissions.md b/doc_source/permissions.md index f22ecde3..6c0073d2 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -30,7 +30,7 @@ The first argument of a **grant** method is always of type [IGrantable](https:// Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other entities that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. -Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly \(`bucket.grantRead(lambda)`, or `grant_read` in Python\) instead of granting access to their role\. For example, if `bucket` is an Amazon S3 bucket, and `function` is a Lambda function, the code below grants the function read access to the bucket\. +Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly instead of granting access to their role\. For example, if `bucket` is an Amazon S3 bucket, and `function` is a Lambda function, the code below grants the function read access to the bucket\. ------ #### [ TypeScript ] From e064d633a027be9a96359f7a2a51e0f3e2d0e411 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 26 May 2020 18:21:38 +0000 Subject: [PATCH 170/655] info about where Lambda code must go --- doc_source/codepipeline_example.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 112f1d0d..754d13f3 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -6,8 +6,10 @@ The AWS CDK enables you to easily create applications running in the AWS Cloud\. The following example shows how to deploy an AWS Lambda function in a pipeline\. Two stacks are created: one to deploy your Lambda code, and one to define a pipeline to deploy the first stack whenever your Lambda code changes\. Your Lambda code is intended to be in a AWS CodeCommit repository, although you can work through this example without any Lambda code \(the pipeline will fail, but the stack that defines it will deploy\)\. +The Lambda code must be in a directory named `Lambda` in the named AWS CodeCommit repository\. The AWS CDK code does not need to be in a repository\. + **Note** -The Lambda function itself is assumed to be written in TypeScript regardless of the language you're using for your AWS CDK app\. To use this example to deploy a Lambda function written in a different language, you'll need to modify the pipeline\. +The Lambda function is assumed to be written in TypeScript regardless of the language you're using for your AWS CDK app\. To use this example to deploy a Lambda function written in anotehr language, you'll need to modify the pipeline\. This is outside the scope of this example\. To set up a project like this from scratch, follow these instructions\. From 5d96c84b6fb70c550e3c5f30d807224b19678f85 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 28 May 2020 14:45:02 +0000 Subject: [PATCH 171/655] fix typo --- doc_source/codepipeline_example.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 754d13f3..209630b0 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -9,7 +9,7 @@ The following example shows how to deploy an AWS Lambda function in a pipeline\. The Lambda code must be in a directory named `Lambda` in the named AWS CodeCommit repository\. The AWS CDK code does not need to be in a repository\. **Note** -The Lambda function is assumed to be written in TypeScript regardless of the language you're using for your AWS CDK app\. To use this example to deploy a Lambda function written in anotehr language, you'll need to modify the pipeline\. This is outside the scope of this example\. +The Lambda function is assumed to be written in TypeScript regardless of the language you're using for your AWS CDK app\. To use this example to deploy a Lambda function written in another language, you'll need to modify the pipeline\. This is outside the scope of this example\. To set up a project like this from scratch, follow these instructions\. From 2df07e7d9cc67f75925c1c08e9779d8aabb589ea Mon Sep 17 00:00:00 2001 From: H G <47661750+HaileyGu@users.noreply.github.com> Date: Sun, 31 May 2020 00:49:04 +0200 Subject: [PATCH 172/655] fix wrong date and order of document history --- doc_source/doc-history.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 3995d4e0..713a8716 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -11,10 +11,10 @@ The table below represents significant milestones\. We fix errors and improve co | Change | Description | Date | | --- |--- |--- | +| [Version 1\.21\.0](#doc-history) | Add "Working with the CDK" articles for the five supported languages\. Various other improvements and fixes\. | February 4, 2020 | | [Version 1\.18\.0](#doc-history) | Add Java code snippets throughout\. Designate Java and C\# bindings stable\. | November 25, 2019 | | [Version 1\.17\.0](#doc-history) | Add C\# code snippets throughout\. | November 19, 2019 | | [Version 1\.16\.0](#doc-history) | Add Python code snippets throughout\. Add Troubleshooting and Testing topics\. | November 14, 2019 | | [Version 1\.8\.0](#doc-history) | Updates to reflect improvements to ECS Patterns module\. | September 17, 2019 | | [Version 1\.3\.0](#doc-history) | Update tagging topic to use new API\. | August 13, 2019 | | [Version 1\.0\.0](#doc-history) | The AWS CDK Developer Guide is released\. | July 11, 2019 | -| [Version 1\.21\.0](#doc-history) | Add "Working with the CDK" articles for the five supported languages\. Various other improvements and fixes\. | February 4, 2019 | \ No newline at end of file From 01b36dcf73e5aba35cbd1a0959a45e18403b3774 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 5 Jun 2020 20:42:17 +0000 Subject: [PATCH 173/655] update doc history, serverless example, other tweaks --- doc_source/context.md | 2 +- doc_source/doc-history.md | 31 +++++++++++++++++-------------- doc_source/index.md | 2 +- doc_source/serverless_example.md | 20 ++++++++++++++++++++ 4 files changed, 39 insertions(+), 16 deletions(-) diff --git a/doc_source/context.md b/doc_source/context.md index 6acb498d..802ad2ef 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -8,7 +8,7 @@ Context values are made available to your AWS CDK app in six different ways: + Automatically from the current AWS account\. + Through the \-\-context option to the cdk command\. + In the project's `cdk.context.json` file\. -+ In the `context` key of the project's `cdk.json` file\. ++ In the project's `cdk.json` file\. + In the `context` key of your `~/cdk.json` file\. + In your AWS CDK app using the `construct.node.setContext` method\. diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 713a8716..e4ef6d74 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -1,20 +1,23 @@ -# Document history for the AWS CDK Developer Guide +# AWS CDK Developer Guide history -This document reflects the following release of the AWS Cloud Development Kit \(AWS CDK\)\. -+ **API version: 1\.18\.0** -+ **Latest documentation update:** November 25, 2019 - -See [Releases](https://github.com/awslabs/aws-cdk/releases) for a list of the AWS CDK releases\. +See [Releases](https://github.com/awslabs/aws-cdk/releases) for information on AWS CDK releases\. The AWS CDK is updated approximately once a week\. Maintenance versions may be released between weekly releases to address critical issues in the weekly release\. Each release includes a matched AWS CDK Toolkit \(CDK CLI\), AWS Construct Library, and API Reference\. **Note** -The table below represents significant milestones\. We fix errors and improve content on an ongoing basis\. +The table below represents significant documentation milestones\. We fix errors and improve content on an ongoing basis\. | Change | Description | Date | | --- |--- |--- | -| [Version 1\.21\.0](#doc-history) | Add "Working with the CDK" articles for the five supported languages\. Various other improvements and fixes\. | February 4, 2020 | -| [Version 1\.18\.0](#doc-history) | Add Java code snippets throughout\. Designate Java and C\# bindings stable\. | November 25, 2019 | -| [Version 1\.17\.0](#doc-history) | Add C\# code snippets throughout\. | November 19, 2019 | -| [Version 1\.16\.0](#doc-history) | Add Python code snippets throughout\. Add Troubleshooting and Testing topics\. | November 14, 2019 | -| [Version 1\.8\.0](#doc-history) | Updates to reflect improvements to ECS Patterns module\. | September 17, 2019 | -| [Version 1\.3\.0](#doc-history) | Update tagging topic to use new API\. | August 13, 2019 | -| [Version 1\.0\.0](#doc-history) | The AWS CDK Developer Guide is released\. | July 11, 2019 | +| [CDK Toolkit versioning](#doc-history) | Add information about cloud assembly versioning and compatibility of the CDK Toolkit \(CLI\) with the AWS Construct Library | April 22, 2020 | +| [Translating from TypeScript](#doc-history) | Updated "CDK in Other Languages" topic to also include JavaScript, Java, and C\# and renamed it "Translating from TypeScript\." | April 10, 2020 | +| [Parameters topc](#doc-history) | Add Concepts topic on using parameters with the AWS CDK\. | April 8, 2020 | +| [JavaScript code snippets](#doc-history) | Reinstate JavaScript code snippets throughout \(automated translation via Babel\)\. | April 3, 2020 | +| [JavaScript code snippets](#doc-history) | Reinstate JavaScript code snippets throughout \(automated translation via Babel\) | April 3, 2020 | +| [Working with the CDK](#doc-history) | Add "Working with the CDK" articles for the five supported languages\. Various other improvements and fixes\. | February 4, 2020 | +| [Java code snippets](#doc-history) | Add Java code snippets throughout\. Designate Java and C\# bindings stable\. | November 25, 2019 | +| [C\# code snippets](#doc-history) | Add C\# code snippets throughout\. | November 19, 2019 | +| [Python code snippets0](#doc-history) | Add Python code snippets throughout\. Add Troubleshooting and Testing topics\. | November 14, 2019 | +| [Troubleshooting topic](#doc-history) | Add Troubleshooting topic to AWS CDK Developer Guide\. | October 30, 2019 | +| [Improve Environments topic](#doc-history) | Add Troubleshooting topic to AWS CDK Developer Guide\. | October 10, 2019 | +| [ECS Patterns improvements](#doc-history) | Updates to reflect improvements to ECS Patterns module\. | September 17, 2019 | +| [New tagging API](#doc-history) | Update tagging topic to use new API\. | August 13, 2019 | +| [Ceneral availability](#doc-history) | The AWS CDK Developer Guide is released\. | July 11, 2019 | \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index ea888e5d..060aff29 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -63,4 +63,4 @@ Amazon's trademarks and trade dress may not be used in + [Infrastructure security for the AWS Cloud Development Kit (AWS CDK)](infrastructure-security.md) + [Troubleshooting common AWS CDK issues](troubleshooting.md) + [OpenPGP keys for the AWS CDK and JSII](pgp-keys.md) -+ [Document history for the AWS CDK Developer Guide](doc-history.md) \ No newline at end of file ++ [AWS CDK Developer Guide history](doc-history.md) \ No newline at end of file diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index e2d05852..3e45a4c5 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -179,6 +179,16 @@ mkdir resources Create the following JavaScript file, `widgets.js`, in the `resources` directory\. ``` +/* +This code uses callbacks to handle asynchronous function responses. +It currently demonstrates using an async-await pattern. +AWS supports both the async-await and promises patterns. +For more information, see the following: +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises +https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html +https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html +*/ const AWS = require('aws-sdk'); const S3 = new AWS.S3(); @@ -777,6 +787,16 @@ The next step is to create Lambda functions to create, show, and delete individu Replace the existing `exports.main` function in `widgets.js` \(in `resources`\) with the following code\. ``` +/* +This code uses callbacks to handle asynchronous function responses. +It currently demonstrates using an async-await pattern. +AWS supports both the async-await and promises patterns. +For more information, see the following: +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises +https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html +https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html +*/ exports.main = async function(event, context) { try { var method = event.httpMethod; From d1b0669d88371e8288846abe9da77c075f8999b5 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 11 Jun 2020 01:24:33 +0000 Subject: [PATCH 174/655] fix typos --- doc_source/doc-history.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index e4ef6d74..6e20d4f5 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -9,15 +9,15 @@ The table below represents significant documentation milestones\. We fix errors | --- |--- |--- | | [CDK Toolkit versioning](#doc-history) | Add information about cloud assembly versioning and compatibility of the CDK Toolkit \(CLI\) with the AWS Construct Library | April 22, 2020 | | [Translating from TypeScript](#doc-history) | Updated "CDK in Other Languages" topic to also include JavaScript, Java, and C\# and renamed it "Translating from TypeScript\." | April 10, 2020 | -| [Parameters topc](#doc-history) | Add Concepts topic on using parameters with the AWS CDK\. | April 8, 2020 | +| [Parameters topic](#doc-history) | Add Concepts topic on using parameters with the AWS CDK\. | April 8, 2020 | | [JavaScript code snippets](#doc-history) | Reinstate JavaScript code snippets throughout \(automated translation via Babel\)\. | April 3, 2020 | | [JavaScript code snippets](#doc-history) | Reinstate JavaScript code snippets throughout \(automated translation via Babel\) | April 3, 2020 | | [Working with the CDK](#doc-history) | Add "Working with the CDK" articles for the five supported languages\. Various other improvements and fixes\. | February 4, 2020 | | [Java code snippets](#doc-history) | Add Java code snippets throughout\. Designate Java and C\# bindings stable\. | November 25, 2019 | | [C\# code snippets](#doc-history) | Add C\# code snippets throughout\. | November 19, 2019 | -| [Python code snippets0](#doc-history) | Add Python code snippets throughout\. Add Troubleshooting and Testing topics\. | November 14, 2019 | +| [Python code snippets](#doc-history) | Add Python code snippets throughout\. Add Troubleshooting and Testing topics\. | November 14, 2019 | | [Troubleshooting topic](#doc-history) | Add Troubleshooting topic to AWS CDK Developer Guide\. | October 30, 2019 | | [Improve Environments topic](#doc-history) | Add Troubleshooting topic to AWS CDK Developer Guide\. | October 10, 2019 | | [ECS Patterns improvements](#doc-history) | Updates to reflect improvements to ECS Patterns module\. | September 17, 2019 | | [New tagging API](#doc-history) | Update tagging topic to use new API\. | August 13, 2019 | -| [Ceneral availability](#doc-history) | The AWS CDK Developer Guide is released\. | July 11, 2019 | \ No newline at end of file +| [General availability](#doc-history) | The AWS CDK Developer Guide is released\. | July 11, 2019 | \ No newline at end of file From 90b3b6d566a6918c9e04c0c83f7f5e76bf1e281e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 11 Jun 2020 22:25:44 +0000 Subject: [PATCH 175/655] update stability index for AWS Construct Library modules --- doc_source/doc-history.md | 1 + doc_source/reference.md | 46 ++++++++++++++++----------------------- 2 files changed, 20 insertions(+), 27 deletions(-) diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 6e20d4f5..337ddf31 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -7,6 +7,7 @@ The table below represents significant documentation milestones\. We fix errors | Change | Description | Date | | --- |--- |--- | +| [Update stability index](#doc-history) | Incorporate the latest definitions of the stability levels for AWS Construct Library modules\. | June 11, 2020 | | [CDK Toolkit versioning](#doc-history) | Add information about cloud assembly versioning and compatibility of the CDK Toolkit \(CLI\) with the AWS Construct Library | April 22, 2020 | | [Translating from TypeScript](#doc-history) | Updated "CDK in Other Languages" topic to also include JavaScript, Java, and C\# and renamed it "Translating from TypeScript\." | April 10, 2020 | | [Parameters topic](#doc-history) | Add Concepts topic on using parameters with the AWS CDK\. | April 8, 2020 | diff --git a/doc_source/reference.md b/doc_source/reference.md index d43d16db..da727a4c 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -6,10 +6,10 @@ Each library contains information about how to use the library\. For example, th ## Versioning -Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and generally adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version and be expected to continue to build and run, producing the same output\. **Note** -This compatibility promise does not apply to APIs designated as experimental\. See [AWS CDK stability index](#aws_construct_lib_stability) for more details\. +This compatibility promise does not apply to APIs under active development, which are designated as experimental\. See [AWS CDK stability index](#aws_construct_lib_stability) for more details\. ### AWS CDK Toolkit \(CLI\) compatibility @@ -29,41 +29,33 @@ For more details on the cloud assembly schema, see [Cloud Assembly Versioning](h ### AWS CDK stability index -Certain APIs do not adhere to the semantic versioning model\. There are three levels of stability in the AWS Construct Library, which define the level of semantic versioning that applies to each module\. +The modules in the AWS Construct Library move through various stages as they are developed from concept to mature API\. Different stages imply different promises for API stability in subsequent versions of the AWS CDK\. -Stable -The API is subject to the semantic versioning model\. We will not introduce non\-backward\-compatible changes or remove the API in a subsequent patch or feature release\. +Stage 0: CFN resources +All construct library modules start in stage 0 when they are auto\-generated from the AWS CloudFormation resource specification\. The goal of stage 0 is to make new AWS CloudFormation resources/properties available to CDK customers as quickly as possible\. We create tracking documents that to capture the data required to decide when L2 resources to add in the future\. +AWS CloudFormation resources themselves are considered stable APIs, regardless of whether other constructs in the module are under active development\. -CloudFormation Only -These APIs are automatically built from the AWS CloudFormation resource specification and are subject only to changes introduced by AWS CloudFormation\. +Stage 1: Experimental +The goal of the experimental stage is to retain the freedom to make breaking changes to APIs while we design and build a module During this stage, the primary use cases and the set of L2 constructs required to support them are incrementally identified, implemented, and validated\. +Development of L2 constructs is community\-oriented and transparent\. For large and/or complex changes, we author a Request for Comments \(RFC\) that outlines our intended design and publish it for feedback\. We also use pull requests to conduct API design reviews\. +At this stage, individual APIs may be in flux, and breaking changes may occur from release to release if we deem these necessary to support customer use cases\. -Experimental -The API is still under active development and subject to non\-backward\-compatible changes or removal in any future version\. Such changes are announced in the AWS CDK release notes under *BREAKING CHANGES*\. We recommend that you do not use this API in production environments\. Experimental APIs are not subject to the semantic versioning model\. +Stage 2: Developer preview \(DP\) +At the developer preview stage, our aim is to deliver a release candidate with a stable API with which to conduct user acceptance testing\. When the API passes acceptance, it is deemed suitable for general availability\. +We make breaking changes at this stage only when required to address unforeseen customer use cases or issues\. Since breaking changes are still possible, the package itself retains the "experimental" label while in developer preview\. -Deprecated -The API may emit warnings\. We do not guarantee backward compatibility\. +Stage 3: General availability \(GA\) +The module is generally available with a backwards compatible guarantee across minor versions\. We will only make backward\-compatible changes to the API, so that your existing apps will continue to work until the next major AWS CDK release\. +In some cases, we may use [feature flags](featureflags.md) to optionally enable new behavior while retaining the previous behavior to support existing apps\. -Experimental and stable modules receive the same level of support from AWS\. The only difference is that we might change experimental APIs within a major version\. Although we don't recommend using experimental APIs in production, we vet them the same way as we vet stable APIs before we include them in a release\. - -### Identifying the support level of an API - -Each module in the [API Reference](https://docs.aws.amazon.com/cdk/api/latest) starts with a section outlining the module's stability index\. The libraries that include only AWS CloudFormation resources, and no hand\-curated constructs, are labeled with the maturity indicator **CloudFormation\-only**\. - -The module level gives an indication of the stability of the majority of the APIs included in the module, however, individual APIs within the module can be annotated with different stability levels\. - - -| Stability | TypeScript | JavaScript | Python | C\#/\.NET | Java | -| --- |--- |--- |--- |--- |--- | -| Experimental | @experimental | @stability Experimental | @experimental | Stability: Experimental | Stability: Experimental | -| Stable | @stable | @stability Stable | @stable | Stability: Stable | Stability: Stable | -| Deprecated | @deprecated | @Deprecated | @deprecated | \[Obsolete\] | Stability: Deprecated | +For more information on these stages, see [AWS Construct Library Module Lifecycle](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0107-construct-library-module-lifecycle.md)\. ### Language binding stability -In addition to modules of the AWS CDK Construct Library, language support is also subject to a stability indication\. Although the API described in all the languages is the same, the way that API is expressed varies by language and may change as the language support evolves\. For this reason, language bindings are deemed experimental for a time until they are considered ready for production use\. +From time to time, we may add support to the AWS CDK for additional programming languages\. Although the API described in all the languages is the same, the way that API is expressed varies by language and may change as the language support evolves\. For this reason, language bindings are deemed experimental for a time until they are considered ready for production use\. Currently, all supported languages are considered stable\. -| Language | stability | +| Language | Stability | | --- |--- | | TypeScript | Stable | | JavaScript | Stable | From f06d8a0a058711f51709c61ec0dee5742dbf6104 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 12 Jun 2020 18:53:16 +0000 Subject: [PATCH 176/655] fix typos --- doc_source/multiple_languages.md | 2 +- doc_source/reference.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 39e610d0..a425c7f6 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -68,7 +68,7 @@ bucket = Bucket(...) Java's imports work differently from TypeScript's\. Each import statement imports either a single class name from a given package, or all classes defined in that package \(using `*`\)\. After importing, classes may be accessed using either the class name by itself or \(in case of name conflicts\) the *qualified* class name including its package\. -Packages are named like `software.amazon.awscdk.services.xxx` for AWS Construct Library packages \(the core module is `software.amazon.awscdk.core`\)\. The Maven group ID is for AWS CDK packages `software.amazon.awscdk`\. +Packages are named like `software.amazon.awscdk.services.xxx` for AWS Construct Library packages \(the core module is `software.amazon.awscdk.core`\)\. The Maven group ID for AWS CDK packages is `software.amazon.awscdk`\. ``` // Make all Amazon S3 construct library classes available diff --git a/doc_source/reference.md b/doc_source/reference.md index da727a4c..441a4e26 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -32,11 +32,11 @@ For more details on the cloud assembly schema, see [Cloud Assembly Versioning](h The modules in the AWS Construct Library move through various stages as they are developed from concept to mature API\. Different stages imply different promises for API stability in subsequent versions of the AWS CDK\. Stage 0: CFN resources -All construct library modules start in stage 0 when they are auto\-generated from the AWS CloudFormation resource specification\. The goal of stage 0 is to make new AWS CloudFormation resources/properties available to CDK customers as quickly as possible\. We create tracking documents that to capture the data required to decide when L2 resources to add in the future\. +All construct library modules start in stage 0 when they are auto\-generated from the AWS CloudFormation resource specification\. The goal of stage 0 is to make new AWS CloudFormation resources/properties available to CDK customers as quickly as possible\. We create tracking documents to capture the data required to decide when L2 resources to add in the future\. AWS CloudFormation resources themselves are considered stable APIs, regardless of whether other constructs in the module are under active development\. Stage 1: Experimental -The goal of the experimental stage is to retain the freedom to make breaking changes to APIs while we design and build a module During this stage, the primary use cases and the set of L2 constructs required to support them are incrementally identified, implemented, and validated\. +The goal of the experimental stage is to retain the freedom to make breaking changes to APIs while we design and build a module\. During this stage, the primary use cases and the set of L2 constructs required to support them are incrementally identified, implemented, and validated\. Development of L2 constructs is community\-oriented and transparent\. For large and/or complex changes, we author a Request for Comments \(RFC\) that outlines our intended design and publish it for feedback\. We also use pull requests to conduct API design reviews\. At this stage, individual APIs may be in flux, and breaking changes may occur from release to release if we deem these necessary to support customer use cases\. @@ -45,7 +45,7 @@ At the developer preview stage, our aim is to deliver a release candidate with a We make breaking changes at this stage only when required to address unforeseen customer use cases or issues\. Since breaking changes are still possible, the package itself retains the "experimental" label while in developer preview\. Stage 3: General availability \(GA\) -The module is generally available with a backwards compatible guarantee across minor versions\. We will only make backward\-compatible changes to the API, so that your existing apps will continue to work until the next major AWS CDK release\. +The module is generally available with a backwards\-compatible guarantee across minor versions\. We will only make backward\-compatible changes to the API, so that your existing apps will continue to work until the next major AWS CDK release\. In some cases, we may use [feature flags](featureflags.md) to optionally enable new behavior while retaining the previous behavior to support existing apps\. For more information on these stages, see [AWS Construct Library Module Lifecycle](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0107-construct-library-module-lifecycle.md)\. From 5920aa0b7915319ea26cc5386bdd38ce3c7596a9 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 12 Jun 2020 21:46:54 +0000 Subject: [PATCH 177/655] change API name (RedirectTarget -> WebsiteRedirect) --- doc_source/multiple_languages.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index a425c7f6..5156dbcc 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -134,9 +134,9 @@ const bucket = new s3.Bucket(this, 'MyBucket', { versioned: true, }); -// Instantiate Bucket with redirectTarget, which has its own sub-properties +// Instantiate Bucket with websiteRedirect, which has its own sub-properties const bucket = new s3.Bucket(this, 'MyBucket', { - redirectTarget: {host: 'aws.amazon.com'}}); + websiteRedirect: {host: 'aws.amazon.com'}}); ``` ------ @@ -157,8 +157,8 @@ bucket = s3.Bucket(self, "MyBucket") # Instantiate Bucket with bucket_name and versioned properties bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=true) -# Instantiate Bucket with redirect_target, which has its own sub-properties -bucket = s3.Bucket(self, "MyBucket", redirect_target=s3.RedirectTarget( +# Instantiate Bucket with website_redirect, which has its own sub-properties +bucket = s3.Bucket(self, "MyBucket", website_redirect=s3.WebsiteRedirect( host_name="aws.amazon.com")) ``` @@ -180,9 +180,9 @@ Bucket bucket = Bucket.Builder.create(self, "MyBucket") .bucketName("my-bucket").versioned(true) .build(); -# Instantiate Bucket with redirectTarget, which has its own sub-properties +# Instantiate Bucket with websiteRedirect, which has its own sub-properties Bucket bucket = Bucket.Builder.create(self, "MyBucket") - .redirectTarget(new RedirectTarget.Builder() + .websiteRedirect(new websiteRedirect.Builder() .hostName("aws.amazon.com").build()) .build(); ``` @@ -205,9 +205,9 @@ var bucket = Bucket(self, "MyBucket", new BucketProps { BucketName = "my-bucket", Versioned = true}); -// Instantiate Bucket with RedirectTarget, which has its own sub-properties +// Instantiate Bucket with WebsiteRedirect, which has its own sub-properties var bucket = Bucket(self, "MyBucket", new BucketProps { - RedirectTarget = new RedirectTarget { + WebsiteRedirect = new WebsiteRedirect { HostName = "aws.amazon.com" }}); ``` From dff1c6585057388753e5f847d71c1f8e5d9a73ce Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 12 Jun 2020 21:49:41 +0000 Subject: [PATCH 178/655] AWS Solutions Konstruk -> Constructs --- doc_source/tools.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/tools.md b/doc_source/tools.md index 863d7682..482693cf 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -344,7 +344,7 @@ To gain insight into how the AWS CDK is used, the versions of libraries used by By default, the AWS CDK reports the name and version of the following NPM modules that are loaded at synthesis time: + AWS CDK core module + AWS Construct Library modules -+ AWS Solutions Konstruk module ++ AWS Solutions Constructs module The `AWS::CDK::Metadata` resource looks like the following\. @@ -352,7 +352,7 @@ The `AWS::CDK::Metadata` resource looks like the following\. CDKMetadata: Type: "AWS::CDK::Metadata" Properties: - Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,@aws-solutions-konstruk/aws-apigateway-lambda=0.8.0" + Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,@aws-solutions-consturcts/aws-apigateway-lambda=0.8.0" ``` ### Opting out from version reporting From 5cf6d306bbee37e1adbb3e86abb75a8af210b7fe Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 12 Jun 2020 23:06:17 +0000 Subject: [PATCH 179/655] remove many references to manual building (CDK does this automatically when you run the app) --- doc_source/codepipeline_example.md | 41 +--- doc_source/ecs_example.md | 88 +------ doc_source/getting_started.md | 126 ---------- doc_source/serverless_example.md | 216 +----------------- .../stack_how_to_create_multiple_stacks.md | 43 +--- doc_source/testing.md | 3 +- doc_source/tools.md | 3 +- doc_source/work-with-cdk-csharp.md | 8 +- doc_source/work-with-cdk-java.md | 11 +- doc_source/work-with-cdk-javascript.md | 2 +- doc_source/work-with-cdk-python.md | 2 +- doc_source/work-with-cdk-typescript.md | 6 +- 12 files changed, 19 insertions(+), 530 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 209630b0..c5d55cf4 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -1120,46 +1120,7 @@ namespace Pipeline ## Deploying the pipeline -The final steps are building the code and deploying the pipeline\. - ------- -#### [ TypeScript ] - -``` -npm run build -``` - ------- -#### [ JavaScript ] - -No build step is necessary\. - ------- -#### [ Python ] - -No build step is necessary\. - ------- -#### [ Java ] - -``` -mvn compile -``` - -**Note** -Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. - ------- -#### [ C\# ] - -``` -dotnet build src -``` - -**Note** -Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. - ------- +The final steps is to deploy the pipeline\. ``` cdk deploy PipelineDeployingLambdaStack diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index d2e4d567..5846733a 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -84,54 +84,12 @@ You may now open `src/MyEcsConstruct.sln` in Visual Studio\./ ------ -Build and run the app and confirm that it creates an empty stack\. - ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] +Run the app and confirm that it creates an empty stack\. ``` cdk synth ``` ------- -#### [ Python ] - -``` -cdk synth -``` - ------- -#### [ Java ] - -``` -mvn compile -cdk synth -``` - -**Note** -Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. - ------- -#### [ C\# ] - -``` -dotnet build src -cdk synth -``` - -**Note** -Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. - ------- - You should see a stack like the following, where *CDK\-VERSION* is the version of the CDK and *NODE\-VERSION* is the version of Node\.js\. \(Your output may differ slightly from what's shown here\.\) ``` @@ -384,54 +342,12 @@ Replace the comment at the end of the constructor with the following code\. ------ -Save it and make sure it builds and creates a stack\. - ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] +Save it and make sure it runs and creates a stack\. ``` cdk synth ``` ------- -#### [ Python ] - -``` -cdk synth -``` - ------- -#### [ Java ] - -``` -mvn compile -cdk synth -``` - -**Note** -Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. - ------- -#### [ C\# ] - -``` -dotnet build src -cdk synth -``` - -**Note** -Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. - ------- - The stack is hundreds of lines, so we don't show it here\. The stack should contain one default instance, a private subnet and a public subnet for the three Availability Zones, and a security group\. Deploy the stack\. diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 2b1414ab..e4eae13f 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -451,48 +451,6 @@ cdk init --language csharp ### Compiling the app -Compile your program, as follows\. - ------- -#### [ TypeScript ] - -``` -npm run build -``` - ------- -#### [ JavaScript ] - -Nothing to compile\. - ------- -#### [ Python ] - -Nothing to compile\. - ------- -#### [ Java ] - -``` -mvn compile -``` - -or press Control\-B in Eclipse - -**Tip** -You can suppress the **\[INFO\]** messages in the build log by adding the **\-q** option to your `mvn` commands\. \(Don"t forget the one in `cdk.json`\.\) - ------- -#### [ C\# ] - -``` -dotnet build src -``` - -or press F6 in Visual Studio - ------- - ### Listing the stacks in the app List the stacks in the app\. @@ -684,48 +642,6 @@ Notice a few things: + `MyFirstBucket` is the **id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. To specify a physical name for your bucket, set the [bucketName](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#bucketname) property \(`bucket_name` in Python\) when you define your bucket\. + Because the bucket's [versioned](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. -Compile your program, as follows\. - ------- -#### [ TypeScript ] - -``` -npm run build -``` - ------- -#### [ JavaScript ] - -Nothing to compile\. - ------- -#### [ Python ] - -Nothing to compile\. - ------- -#### [ Java ] - -``` -mvn compile -``` - -or press Control\-B in Eclipse - -**Tip** -You can suppress the **\[INFO\]** messages in the build log by adding the **\-q** option to your `mvn` commands\. \(Don"t forget the one in `cdk.json`\.\) - ------- -#### [ C\# ] - -``` -dotnet build src -``` - -or press F6 in Visual Studio - ------- - ### Synthesizing an AWS CloudFormation template Synthesize an AWS CloudFormation template for the app, as follows\. If you get an error like "\-\-app is required\.\.\.", it's because you are running the command from a subdirectory of your project directory\. Navigate to the project directory and try again\. @@ -838,48 +754,6 @@ new Bucket(this, "MyFirstBucket", new BucketProps ------ -Compile your program, as follows\. - ------- -#### [ TypeScript ] - -``` -npm run build -``` - ------- -#### [ JavaScript ] - -Nothing to compile\. - ------- -#### [ Python ] - -Nothing to compile\. - ------- -#### [ Java ] - -``` -mvn compile -``` - -or press Control\-B in Eclipse - -**Tip** -You can suppress the **\[INFO\]** messages in the build log by adding the **\-q** option to your `mvn` commands\. \(Don"t forget the one in `cdk.json`\.\) - ------- -#### [ C\# ] - -``` -dotnet build src -``` - -or press F6 in Visual Studio - ------- - ### Preparing for deployment Before you deploy the updated app, evaluate the difference between the AWS CDK app and the deployed app\. diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 3e45a4c5..9b8a0dea 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -108,54 +108,12 @@ The important files in the blank project are as follows\. \(We will also be addi ------ -Build the app and note that it synthesizes an empty stack\. - ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] - -``` -cdk synth -``` - ------- -#### [ Python ] - -``` -cdk synth -``` - ------- -#### [ Java ] +Run the app and note that it synthesizes an empty stack\. ``` -mvn compile cdk synth ``` -**Note** -Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. - ------- -#### [ C\# ] - -``` -dotnet build src -cdk synth -``` - -**Note** -Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. - ------- - You should see output like the following, where *CDK\-VERSION* is the version of the AWS CDK\. ``` @@ -231,52 +189,10 @@ exports.main = async function(event, context) { Save it and be sure the project still results in an empty stack\. We haven't yet wired the Lambda function to the AWS CDK app, so the Lambda asset doesn't appear in the output\. ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] - -``` -cdk synth -``` - ------- -#### [ Python ] - -``` -cdk synth -``` - ------- -#### [ Java ] - -``` -mvn compile -cdk synth -``` - -**Note** -Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. - ------- -#### [ C\# ] - ``` -dotnet build src cdk synth ``` -**Note** -Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. - ------- - ## Creating a widget service Add the API Gateway, Lambda, and Amazon S3 packages to the app\. @@ -565,52 +481,10 @@ namespace MyWidgetService Save the app and make sure it still synthesizes an empty stack\. ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] - ``` cdk synth ``` ------- -#### [ Python ] - -``` -cdk synth -``` - ------- -#### [ Java ] - -``` -mvn compile -cdk synth -``` - -**Note** -Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. - ------- -#### [ C\# ] - -``` -dotnet build src -cdk synth -``` - -**Note** -Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. - ------- - ## Add the service to the app To add the widget service to our AWS CDK app, we'll need to modify the source file that defines the stack to instantiate the service construct\. @@ -690,54 +564,12 @@ new WidgetService(this, "Widgets"); ------ -Be sure the app builds and synthesizes a stack \(we won't show the stack here: it's over 250 lines\)\. - ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] - -``` -cdk synth -``` - ------- -#### [ Python ] - -``` -cdk synth -``` - ------- -#### [ Java ] +Be sure the app runs and synthesizes a stack \(we won't show the stack here: it's over 250 lines\)\. ``` -mvn compile cdk synth ``` -**Note** -Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. - ------- -#### [ C\# ] - -``` -dotnet build src -cdk synth -``` - -**Note** -Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. - ------- - ## Deploy and test the app Before you can deploy your first AWS CDK app containing a lambda function, you must bootstrap your AWS environment\. This creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see the **bootstrap** section of the [AWS CDK tools](tools.md) \(if you've already bootstrapped, you'll get a warning and nothing will change\)\. @@ -1012,54 +844,12 @@ File: `src/MyWidgetService/WidgetService.cs` ------ -Save, build, and deploy the app\. - ------- -#### [ TypeScript ] - -``` -npm run build -cdk deploy -``` - ------- -#### [ JavaScript ] +Save and deploy the app\. ``` cdk deploy ``` ------- -#### [ Python ] - -``` -cdk deploy -``` - ------- -#### [ Java ] - -``` -mvn compile -cdk deploy -``` - -**Note** -Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. - ------- -#### [ C\# ] - -``` -dotnet build src -cdk deploy -``` - -**Note** -Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. - ------- - We can now store, show, or delete an individual widget\. Use the following commands to list the widgets, create the widget **example**, list all of the widgets, show the contents of **example** \(it should show today's date\), delete **example**, and then show the list of widgets again\. ``` diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index 382206ec..0b4eca19 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -587,48 +587,7 @@ namespace Multistack ## Synthesize and deploy the stack -Now you can deploy stacks from the app\. First, build the project, if necessary\. - ------- -#### [ TypeScript ] - -``` -npm run build -``` - ------- -#### [ JavaScript ] - -No build step is necessary\. - ------- -#### [ Python ] - -No build step is necessary\. - ------- -#### [ Java ] - -``` -mvn compile -``` - -**Note** -Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. - ------- -#### [ C\# ] - -``` -dotnet build src -``` - -**Note** -Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. - ------- - -Next, synthesize a AWS CloudFormation template for `MyEastCdkStack`—the stack in `us-east-1`\. This is the stack with the encrypted S3 bucket\. +Now you can deploy stacks from the app\. First, synthesize a AWS CloudFormation template for `MyEastCdkStack`—the stack in `us-east-1`\. This is the stack with the encrypted S3 bucket\. ``` $ cdk synth MyEastCdkStack diff --git a/doc_source/testing.md b/doc_source/testing.md index 44b18391..a3068ce2 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -100,8 +100,7 @@ test('dlq creates an alarm', () => { To build the project and run the test, issue these commands\. ``` -npm run build -npm test +npm run build && npm test ``` The output from Jest indicates that it has run the test and recorded a snapshot\. diff --git a/doc_source/tools.md b/doc_source/tools.md index 482693cf..a98ca1f0 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -414,10 +414,9 @@ This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda fu return "This is a Lambda Function defined through CDK" ``` -1. Compile your AWS CDK app and create a AWS CloudFormation template +1. Run your AWS CDK app and create a AWS CloudFormation template ``` - npm run build cdk synth --no-staging > template.yaml ``` diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index b5c82a6b..0a0d1a9a 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -134,7 +134,7 @@ Keep in mind that future releases of the AWS CDK may coincidentally add a new pr ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects or as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In C\#, objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` in C\#\. +In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In C\#, objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` in C\#\. ### Missing values @@ -150,9 +150,7 @@ string MimeType = props?.MimeType ?? "text/plain"; ## Building, synthesizing, and deploying -Before running, build \(compile\) the app by pressing F6 in Visual Studio or by issuing `dotnet build src` from the command line, where `src` is the directory in your project directory that contains the Visual Studio Solution \(`.sln`\) file\. - -The build step reports any syntax or type errors in your code\. Once you can build your application without errors, you're ready to synthesize or deploy\. +The AWS CDK automatically compiles your app before running it\. However, it can be useful to build your app manually to check for errors and run tests\. You can do this by pressing F6 in Visual Studio or by issuing `dotnet build src` from the command line, where `src` is the directory in your project directory that contains the Visual Studio Solution \(`.sln`\) file\. The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. @@ -161,6 +159,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. +You don't need to explicitly buiild your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index e0c1b849..decb0085 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -73,7 +73,7 @@ If you are not using an IDE, or just want full control over the versions of your The version specifier `[1.0,2.0)` in this example indicates that the latest version between 1\.0 \(inclusive\) and 2\.0 \(exclusive\) will be installed\. Since the AWS CDK uses semantic versioning for stable AWS Construct Library modules, \(see [Versioning](reference.md#versioning)\), this ensures that only newer versions without breaking API changes will be installed\. -Maven automatically downloads a version of your dependencies that will match the requirements in `pom.xml`, if necessary, the next time you build your project\. +Maven automatically downloads a version of your dependencies that will match the requirements in `pom.xml`, if necessary, the next time your project is built\. ## AWS CDK idioms in Java @@ -113,12 +113,7 @@ In Java, missing values in AWS CDK objects such as props are represented by `nul ## Building, synthesizing, and deploying -Before running, build \(compile\) the app in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn compile` at a command prompt while in your project's root directory\. - -The build step reports any syntax or type errors in your code\. Once you can build your application without errors, you're ready to synthesize or deploy\. - -**Note** -Every time you change your application code, re\-compile \(e\.g\. `mvn compile` or `mvn test`\) before using the `cdk` command\. Otherwise, the `cdk` command uses the previously compiled version of your application code\. +The AWS CDK automatically compiles your app before running it\. However, it can be useful to build your app manually to check for errors and run tests\. You can do this in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn compile` at a command prompt while in your project's root directory\. Run any tests you've written by running `mvn test` at a command prompt\. @@ -129,6 +124,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. +You don't need to explicitly buiild your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index a21bba54..bc0dd4d7 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -88,7 +88,7 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. +You don't need to explicitly buiild your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 384e8786..a2fb06d1 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -152,6 +152,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. +You don't need to explicitly buiild your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index 791df1d7..6ded6078 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -79,9 +79,7 @@ Generally, you should be in the project's root directory when building and runni Node\.js cannot run TypeScript directly; instead, your application is converted to JavaScript using the TypeScript compiler, `tsc`\. The resulting JavaScript code is then executed\. -To compile your TypeScript app, issue `npm run build`\. You may also issue `npm run watch` to enter watch mode, in which the TypeScript compiler automatically rebuilds your app whenever you save changes to a source file\. - -The build step reports any syntax or type errors in your code\. Once you can build your application without errors, you're ready to synthesize or deploy\. +The AWS CDK automatically does this whenever it needs to run your app\. However, it can be useful to compile manually to check for errors and to run tests\. To compile your TypeScript app manually, issue `npm run build`\. You may also issue `npm run watch` to enter watch mode, in which the TypeScript compiler automatically rebuilds your app whenever you save changes to a source file\. The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. @@ -90,6 +88,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you\. +You don't need to explicitly buiild your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file From 0fba783dfed1a9ff9580aed8fffcac66585eff9f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 13 Jun 2020 00:24:06 +0000 Subject: [PATCH 180/655] have reader replace entire file to make sure imports are correct --- doc_source/serverless_example.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 9b8a0dea..8b986b52 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -616,9 +616,14 @@ Because we haven't stored any widgets yet, the output should be similar to the f The next step is to create Lambda functions to create, show, and delete individual widgets\. -Replace the existing `exports.main` function in `widgets.js` \(in `resources`\) with the following code\. +Replace the code in `widgets.js` \(in `resources`\) with the following\. ``` +const AWS = require('aws-sdk'); +const S3 = new AWS.S3(); + +const bucketName = process.env.BUCKET; + /* This code uses callbacks to handle asynchronous function responses. It currently demonstrates using an async-await pattern. From c4a7b33dd8efe7b99749cad65a7708378ee5f7e4 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 13 Jun 2020 01:06:02 +0000 Subject: [PATCH 181/655] fix Java code to not intsantiate two buckets --- doc_source/constructs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index aa74d332..c538bc3a 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -553,7 +553,7 @@ class NotifyingBucket(core.Construct): #### [ Java ] ``` -public class NotifyingBucket extends Bucket { +public class NotifyingBucket extends Construct { public NotifyingBucket(final Construct scope, final String id) { this(scope, id, null, null); From 63454e1d1d053a1038b3b3009b3201debacb56b7 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 18 Jun 2020 03:00:09 +0000 Subject: [PATCH 182/655] revamp Getting Started --- doc_source/doc-history.md | 3 +- doc_source/getting_started.md | 803 +++++----------------------------- doc_source/hello_world.md | 518 ++++++++++++++++++++++ doc_source/index.md | 1 + 4 files changed, 624 insertions(+), 701 deletions(-) create mode 100644 doc_source/hello_world.md diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 337ddf31..fb77344a 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -1,12 +1,13 @@ # AWS CDK Developer Guide history -See [Releases](https://github.com/awslabs/aws-cdk/releases) for information on AWS CDK releases\. The AWS CDK is updated approximately once a week\. Maintenance versions may be released between weekly releases to address critical issues in the weekly release\. Each release includes a matched AWS CDK Toolkit \(CDK CLI\), AWS Construct Library, and API Reference\. +See [Releases](https://github.com/awslabs/aws-cdk/releases) for information on AWS CDK releases\. The AWS CDK is updated approximately once a week\. Maintenance versions may be released between weekly releases to address critical issues\. Each release includes a matched AWS CDK Toolkit \(CDK CLI\), AWS Construct Library, and API Reference\. **Note** The table below represents significant documentation milestones\. We fix errors and improve content on an ongoing basis\. | Change | Description | Date | | --- |--- |--- | +| [Improve Getting Started](#doc-history) | Remove extraneous material from Getting Started, use a more conversational tone, incorporate current best practices\. Break out Hello World into its own topic\. | June 17, 2020 | | [Update stability index](#doc-history) | Incorporate the latest definitions of the stability levels for AWS Construct Library modules\. | June 11, 2020 | | [CDK Toolkit versioning](#doc-history) | Add information about cloud assembly versioning and compatibility of the CDK Toolkit \(CLI\) with the AWS Construct Library | April 22, 2020 | | [Translating from TypeScript](#doc-history) | Updated "CDK in Other Languages" topic to also include JavaScript, Java, and C\# and renamed it "Translating from TypeScript\." | April 10, 2020 | diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index e4eae13f..2cfe8204 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -1,807 +1,210 @@ # Getting started with the AWS CDK -This topic describes how to install and configure the AWS CDK and create your first AWS CDK app\. +This topic introduces you to important AWS CDK concepts, describes how to install and configure the AWS CDK, and walks you through creating your first AWS CDK app\. -**Note** -Want to dig deeper? Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour of a real\-world project\. - -**Tip** -The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the AWS Toolkit](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. - -## Prerequisites - -All CDK developers need to install [Node\.js](https://nodejs.org/en/download) >= 10\.3\.0, even those working in languages other than TypeScript or JavaScript\. The AWS CDK Toolkit \(`cdk` command\-line tool\) and the AWS Construct Library are developed in TypeScript and run on Node\.js\. The bindings for other supported languages use this backend and toolset\. - -You must provide your credentials and an AWS Region to use the AWS CDK CLI, as described in [Specifying your credentials and Region](#getting_started_credentials)\. - -Other prerequisites depend on your development language, as follows\. - ------- -#### [ TypeScript ] - -TypeScript >= 2\.7 +## Your background ------- -#### [ JavaScript ] +The AWS Cloud Development Kit \(AWS CDK\) lets you define your cloud infrastructure as code in one of five supported programming languages\. It is intended for moderately to highly experienced AWS users\. -No additional prerequisites +Ideally, you already have experience with popular AWS services, particularly [AWS Identity and Access Management](https://aws.amazon.com/iam/) \(IAM\)\. You might already have AWS credentials on your workstation for use with an AWS SDK or the AWS CLI and experience working with AWS resources programmatically\. ------- -#### [ Python ] -+ Python >= 3\.6 +Familiarity with [AWS CloudFormation](https://aws.amazon.com/cloudformation/) is also useful, as the output of an AWS CDK program is a AWS CloudFormation template\. ------- -#### [ Java ] -+ Maven >= 3\.5 and Java >= 8 -+ A Java IDE is preferred \(the examples in this guide may refer to Eclipse\)\. `cdk init` creates a Maven project, which most IDEs can import\. Some IDEs may need to be configured to use Java 8 \(also known as 1\.8\)\. -+ Set the `JAVA_HOME` environment variable to the path to where you have installed the JDK on your machine +Finally, you should be proficient in the programming language you intend to use with the AWS CDK\. ------- -#### [ C\# ] - -\.NET standard 2\.1 compatible implementation: -+ \.NET Core >= 3\.1 -+ \.NET Framework >= 4\.6\.1, or -+ Mono >= 5\.4 - -Visual Studio 2019 \(any edition\) recommended\. +## Key concepts ------- - -## Installing the AWS CDK - -Install the AWS CDK using the following command\. - -``` -npm install -g aws-cdk -``` - -Run the following command to verify correct installation and print the version number of the AWS CDK\. - -``` -cdk --version -``` - -## Updating your language dependencies - -If you get an error message that your language framework is out of date, use one of the following commands to update the components that the AWS CDK needs to support the language\. - ------- -#### [ TypeScript ] - -``` -npx npm-check-updates -u -``` - ------- -#### [ JavaScript ] - -``` -npx npm-check-updates -u -``` - ------- -#### [ Python ] - -``` -pip install --upgrade aws-cdk.core -``` - -You might have to issue this command multiple times to update all dependencies\. - ------- -#### [ Java ] - -``` -mvn versions:use-latest-versions -``` - ------- -#### [ C\# ] - -``` -nuget update -``` - -Or **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio - ------- - -## Using the env property to specify account and Region - -You can use the `env` property on a stack to specify the account and region used when deploying a stack, as shown in the following example, where *REGION* is the region and *ACCOUNT* is the account ID\. - ------- -#### [ TypeScript ] - -``` -new MyStack(app, 'MyStack', { - env: { - region: 'REGION', - account: 'ACCOUNT' - } -}); -``` - ------- -#### [ JavaScript ] - -``` -new MyStack(app, 'MyStack', { - env: { - region: 'REGION', - account: 'ACCOUNT' - } -}); -``` +The AWS CDK is designed around a handful of important concepts\. We will introduce a few of these here briefly\. Follow the links to learn more, or see the Concepts topics in this guide's Table of Contents\. ------- -#### [ Python ] +An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, Python, Java, or C\# that uses the AWS CDK to define AWS infrastructure\. An app defines one or more [stacks](stacks.md)\. Stacks \(equivalent to AWS CloudFormation stacks\) contains [constructs](constructs.md), each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on\. -``` -MyStack(app, "MyStack", env=core.Environment( - region="REGION", - account="ACCOUNT")) -``` +Constructs \(as well as stacks and apps\) are represented as types in your programming language of choice\. You instantiate constructs within a stack to declare them to AWS, and connect them to each other using well\-defined interfaces\. ------- -#### [ Java ] +The AWS CDK includes the AWS CDK Toolkit \(also called the CLI\), a command\-line tool for working with your AWS CDK apps and stacks\. Among other functions, the Toolkit provides the ability to convert one or more AWS CDK stacks to AWS CloudFormation templates and related assets \(a process called *synthesis*\) and to deploy your stacks to an AWS account\. -``` -new MyStack(app, "MyStack", StackProps.builder().env( - Environment.builder() - .account("ACCOUNT") - .region("REGION") - .build()).build()); -``` +The AWS CDK includes a library of AWS constructs called the AWS Construct Library\. Each AWS service has at least one corresponding module in the library containing the constructs that represent that service's resources\. ------- -#### [ C\# ] +Constructs come in three fundamental flavors: ++ **AWS CloudFormation\-only** or L1 \(short for "level 1"\)\. These constructs correspond directly to resource types defined by AWS CloudFormation\. In fact, these constructs are automatically generated from the AWS CloudFormation specification, so when a new AWS service is launched, the AWS CDK supports it as soon as AWS CloudFormation does\. AWS CloudFormation resources always have names that begin with `Cfn`\. For example, in the Amazon S3 module, `CfnBucket` is the L1 module for an Amazon S3 bucket\. ++ **Curated** or L2\. These constructs are carefully developed by the AWS CDK team to address specific use cases and simplify infrastructure development\. For the most part, they encapsulate L1 modules, providing sensible defaults and best\-practice security policies\. L2 modules may also define supporting resources needed by the primary resource\. For example, in the Amazon S3 module, `Bucket` is the L2 module for an Amazon S3 bucket\. Some services have more than one L2 module in the Construct Library for organizational purposes\. ++ **Patterns** or L3\. Patterns declare multiple resources to create entire AWS architectures for particular use cases\. All the plumbing is already hooked up, and configuration is boiled down to a few important parameters\. In the AWS Construct Library, patterns are in separate modules from L1 and L2 constructs\. -``` -new MyStack(app, "MyStack", new StackProps -{ - Env = new Amazon.CDK.Environment - { - Account = "ACCOUNT", - Region = "REGION" - } -}); -``` +The AWS CDK's core module \(usually imported into code as `cdk`\) contains constructs used by the AWS CDK itself as well as base classes for constructs, apps, resources, and other AWS CDK objects\. ------- +## Supported programming languages -**Note** -The AWS CDK team recommends that you explicitly set your account and region using the `env` property on a stack when you deploy stacks to production\. +The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) -Since you can create any number of stacks in any of your accounts in any region that supports all of the stack's resources, the AWS CDK team recommends that you create your production stacks in one AWS CDK app, and deploy them as necessary\. For example, if you own three accounts, with account IDs *ONE*, *TWO*, and *THREE* and want to be able to deploy each one in **us\-west\-2** and **us\-east\-1**, you might declare them as: +To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. We have taken pains to make AWS CDK app development in each language follow that language's usual conventions\. For example, note how the names of methods, classes, and so on are adapted to each language in the snippets below ------ #### [ TypeScript ] ``` -new MyStack(app, 'Stack-One-W', { env: { account: 'ONE', region: 'us-west-2' }}); -new MyStack(app, 'Stack-One-E', { env: { account: 'ONE', region: 'us-east-1' }}); -new MyStack(app, 'Stack-Two-W', { env: { account: 'TWO', region: 'us-west-2' }}); -new MyStack(app, 'Stack-Two-E', { env: { account: 'TWO', region: 'us-east-1' }}); -new MyStack(app, 'Stack-Three-W', { env: { account: 'THREE', region: 'us-west-2' }}); -new MyStack(app, 'Stack-Three-E', { env: { account: 'THREE', region: 'us-east-1' }}); +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket', + versioned: true, + websiteRedirect: {host: 'aws.amazon.com'}}); ``` ------ #### [ JavaScript ] ``` -new MyStack(app, 'Stack-One-W', { env: { account: 'ONE', region: 'us-west-2' }}); -new MyStack(app, 'Stack-One-E', { env: { account: 'ONE', region: 'us-east-1' }}); -new MyStack(app, 'Stack-Two-W', { env: { account: 'TWO', region: 'us-west-2' }}); -new MyStack(app, 'Stack-Two-E', { env: { account: 'TWO', region: 'us-east-1' }}); -new MyStack(app, 'Stack-Three-W', { env: { account: 'THREE', region: 'us-west-2' }}); -new MyStack(app, 'Stack-Three-E', { env: { account: 'THREE', region: 'us-east-1' }}); +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket', + versioned: true, + websiteRedirect: {host: 'aws.amazon.com'}}); ``` ------ #### [ Python ] ``` -MyStack(app, "Stack-One-W", env=core.Environment(account="ONE", region="us-west-2")) -MyStack(app, "Stack-One-E", env=core.Environment(account="ONE", region="us-east-1")) -MyStack(app, "Stack-Two-W", env=core.Environment(account="TWO", region="us-west-2")) -MyStack(app, "Stack-Two-E", env=core.Environment(account="TWO", region="us-east-1")) -MyStack(app, "Stack-Three-W", env=core.Environment(account="THREE", region="us-west-2")) -MyStack(app, "Stack-Three-E", env=core.Environment(account="THREE", region="us-east-1")) +bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=true, + website_redirect=s3.WebsiteRedirect(host_name="aws.amazon.com")) ``` ------ #### [ Java ] ``` -public class MyApp { - - private static App app; - - // Helper method to declare MyStacks in specific accounts/regions - private static MyStack makeMyStack(final String name, final String account, - final String region) { - - return new MyStack(app, name, StackProps.builder() - .env(Environment.builder() - .account(account) - .region(region) - .build()) - .build()); - } - - public static void main(final String argv[]) { - app = new App(); - - makeMyStack("Stack-One-W", "ONE", "us-west-2"); - makeMyStack("Stack-One-E", "ONE", "us-east-1"); - makeMyStack("Stack-Two-W", "TWO", "us-west-2"); - makeMyStack("Stack-Two-E", "TWO", "us-east-1"); - makeMyStack("Stack-Three-W", "THREE", "us-west-2"); - makeMyStack("Stack-Three-E", "THREE", "us-east-1"); - - app.synth(); - } -} +Bucket bucket = Bucket.Builder.create(self, "MyBucket") + .bucketName("my-bucket") + .versioned(true) + .websiteRedirect(new websiteRedirect.Builder() + .hostName("aws.amazon.com").build()) + .build(); ``` ------ #### [ C\# ] ``` -// Helper func to declare MyStacks in specific accounts/regions -Stack makeMyStack(string name, string account, string region) -{ - return new MyStack(app, name, new StackProps - { - Env = new Amazon.CDK.Environment - { - Account = account, - Region = region - } - }); -} - -makeMyStack("Stack-One-W", account: "ONE", region: "us-west-2"); -makeMyStack("Stack-One-E", account: "ONE", region: "us-east-1"); -makeMyStack("Stack-Two-W", account: "TWO", region: "us-west-2"); -makeMyStack("Stack-Two-E", account: "TWO", region: "us-east-1"); -makeMyStack("Stack-Three-W", account: "THREE", region: "us-west-2"); -makeMyStack("Stack-Three-E", account: "THREE", region: "us-east-1"); +var bucket = Bucket(self, "MyBucket", new BucketProps { + BucketName = "my-bucket", + Versioned = true, + WebsiteRedirect = new WebsiteRedirect { + HostName = "aws.amazon.com" + }}); ``` ------ -And deploy the stack for account *TWO* in **us\-east\-1** with: - -``` -cdk deploy Stack-Two-E -``` - **Note** -If the existing credentials do not have permission to create resources within the account you specify, the AWS CDK returns an AWS CloudFormation error when you attempt to deploy the stack\. - -## Specifying your credentials and Region - -You must specify your credentials and an AWS Region to use the AWS CDK CLI\. The CDK looks for credentials and region in the following order: -+ Using the \-\-profile option to cdk commands\. -+ Using environment variables\. -+ Using the default profile as set by the AWS Command Line Interface \(AWS CLI\)\. - -### Using the \-\-profile option to specify credentials and Region - -Use the \-\-profile *PROFILE* option to a cdk command to use a specific profile when executing the command\. - -For example, if the `~/.aws/config` \(Linux or Mac\) or `%USERPROFILE%\.aws\config` \(Windows\) file contains the following profile: - -``` -[profile test] -aws_access_key_id=AKIAI44QH8DHBEXAMPLE -aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY -region=us-west-2 -``` - -You can deploy your app using the **test** profile with the following command\. - -``` -cdk deploy --profile test -``` - -**Note** -The profile must contain the access key, secret access key, and region\. - -See [Named Profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) in the AWS CLI documentation for details\. - -### Using environment variables to specify credentials and a Region - -Use environment variables to specify your credentials and region\. -+ `AWS_ACCESS_KEY_ID` – Specifies your access key\. -+ `AWS_SECRET_ACCESS_KEY` – Specifies your secret access key\. -+ `AWS_DEFAULT_REGION` – Specifies your default Region\. - -For example, to set the region to `us-east-2` on Linux or macOS: - -``` -export AWS_DEFAULT_REGION=us-east-2 -``` - -To do the same on Windows: - -``` -set AWS_DEFAULT_REGION=us-east-2 -``` - -See [Environment Variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-environment.html) in the *AWS Command Line Interface User Guide* for details\. - -### Using the AWS CLI to specify credentials and a Region - -Use the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide) aws configure command to specify your default credentials and a region\. - -## Hello World tutorial - -The typical workflow for creating a new app is: - -1. Create the app directory\. - -1. Initialize the app\. - -1. Add code to the app\. - -1. Compile the app, if necessary\. - -1. Deploy the resources defined in the app\. - -1. Test the app\. - -1. If there are any issues, loop through modify, compile \(if necessary\), deploy, and test again\. - -And of course, keep your code under version control\. - -This tutorial walks you through how to create and deploy a simple AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. The app contains one resource, an Amazon S3 bucket\. - -### Creating the app directory - -Create a directory for your app with an empty Git repository\. - -``` -mkdir hello-cdk -cd hello-cdk -``` - -**Note** - Be sure to use the name `hello-cdk` for your project directory\. The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, you'll need to change some of the code in this article\. - -### Initializing the app - -To initialize your new AWS CDK app, you use the `cdk init` command\. - -``` -cdk init --language LANGUAGE [TEMPLATE] -``` - -Where: -+ *LANGUAGE* is one of the supported programming languages: **csharp** \(C\#\), **java** \(Java\), **javascript** \(JavaScript\), **python** \(Python\), or **typescript** \(TypeScript\) -+ *TEMPLATE* is an optional template\. If the desired template is *app*, the default, you may omit it\. - -The following table describes the templates available with the supported languages\. - -| | | -| --- |--- | -| app \(default\) | Creates an empty AWS CDK app\. | -| sample\-app | Creates an AWS CDK app with a stack containing an Amazon SQS queue and an Amazon SNS topic\. | - -For Hello World, you can just use the default template\. - ------- -#### [ TypeScript ] - -``` -cdk init --language typescript -``` - ------- -#### [ JavaScript ] - -``` -cdk init ‐-language javascript -``` - ------- -#### [ Python ] - -``` -cdk init --language python -``` - -Once the init command finishes, your prompt should show **\(\.env\)**, indicating you are running under virtualenv\. If not, activate the virtual environment by issuing the command below\. - -``` -source .env/bin/activate -``` - -Once you've got your virtualenv running, run the following command to install the required dependencies\. - -``` -pip install -r requirements.txt -``` - -Change the instantiation of **HelloCdkStack** in `app.py` to the following\. - -``` -HelloCdkStack(app, "HelloCdkStack") -``` - ------- -#### [ Java ] - -``` -cdk init --language java -``` - ------- -#### [ C\# ] - -``` -cdk init --language csharp -``` - ------- - -### Compiling the app - -### Listing the stacks in the app - -List the stacks in the app\. - -``` -cdk ls -``` - -The result is just the name of the stack\. - -``` -HelloCdkStack -``` - -### Adding an Amazon S3 bucket - -At this point, what can you do with this app? Nothing, because the stack is empty, so there's nothing to deploy\. Let's define an Amazon S3 bucket\. - -Install the `@aws-cdk/aws-s3` package\. - ------- -#### [ TypeScript ] - -``` -npm install @aws-cdk/aws-s3 -``` - ------- -#### [ JavaScript ] - -``` -npm install @aws-cdk/aws-s3 -``` - ------- -#### [ Python ] - -``` -pip install aws-cdk.aws-s3 -``` - -You might have to execute this command multiple times to resolve dependencies\. - ------- -#### [ Java ] - -If necessary, add the following to `pom.xml`, where *CDK\-VERSION* is the version of the AWS CDK\. - -``` - - software.amazon.awscdk - s3 - CDK-VERSION - -``` - ------- -#### [ C\# ] - -Run the following command in the `src/HelloCdk` directory\. - -``` -dotnet add package Amazon.CDK.AWS.S3 -``` - -Or **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio, then locate and install the `Amazon.CDK.AWS.S3` package - ------- - -Next, define an Amazon S3 bucket in the stack\. Amazon S3 buckets are represented by the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) class\. - ------- -#### [ TypeScript ] +These code snippets are intended for illustration only\. They are incomplete and won't run as they are\. -In `lib/hello-cdk-stack.ts`: +The AWS Construct Library is distributed using each language's standard package management tools, including NPM, PyPi, Maven, and NuGet\. There's even a version of the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) for each language\. -``` -import * as core from '@aws-cdk/core'; -import * as s3 from '@aws-cdk/aws-s3'; - -export class HelloCdkStack extends core.Stack { - constructor(scope: core.App, id: string, props?: core.StackProps) { - super(scope, id, props); - - new s3.Bucket(this, 'MyFirstBucket', { - versioned: true - }); - } -} -``` +To help you use the AWS CDK in your favorite language, this Guide includes topics that explain how to use the AWS CDK in all supported languages\. ++ [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) ++ [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) ++ [Working with the AWS CDK in Python](work-with-cdk-python.md) ++ [Working with the AWS CDK in Java](work-with-cdk-java.md) ++ [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) ------- -#### [ JavaScript ] +Furthermore, since TypeScript was the first language supported by the AWS CDK, much AWS CDK example code is written in TypeScript\. For this reason, this Guide also includes a topic specifically to show how to adapt TypeScript AWS CDK code for use with the other supported languages\. See [Translating TypeScript AWS CDK code to other languages ](multiple_languages.md)\. -In `lib/hello-cdk-stack.js`: - -``` -const core = require('@aws-cdk/core'); -const s3 = require('@aws-cdk/aws-s3'); - -class HelloCdkStack extends core.Stack { - constructor(scope, id, props) { - super(scope, id, props); +## Prerequisites - new s3.Bucket(this, 'MyFirstBucket', { - versioned: true - }); - } -} +With the concepts out of the way, here's what you need to have on your workstation before you install the AWS CDK and start developing\. -module.exports = { HelloCdkStack } -``` +All CDK developers need to [install Node\.js](https://nodejs.org/en/download/) 10\.3\.0 or later, even those working in languages other than TypeScript or JavaScript\. The AWS CDK Toolkit \(cdk command\-line tool\) and the AWS Construct Library are developed in TypeScript and run on Node\.js\. The bindings for other supported languages use this back end and tool set\. We suggest the latest LTS version\. ------- -#### [ Python ] +**Important** +Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK -Replace the first import statement in `hello_cdk_stack.py` in the `hello_cdk` directory with the following code\. +You must provide your credentials and an AWS Region to use AWS CDK, if you have not already done so\. -``` -from aws_cdk import ( - aws_s3 as s3, - core -) -``` +**Important** +We strongly recommend against using your AWS root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. -Replace the comment with the following code\. +If you have the AWS CLI installed, the easiest way to satisfy this requirement is to install the AWS CLI and issue the following command: ``` -bucket = s3.Bucket(self, - "MyFirstBucket", - versioned=True,) +aws configure ``` ------- -#### [ Java ] +Provide your AWS access key ID, secret access key, and default region when prompted\. -In `src/main/java/com/myorg/HelloStack.java`: +You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(Linux or Mac\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. ++ In `~/.aws/config` or `%USERPROFILE%\.aws\config` -``` -package com.myorg; - -import software.amazon.awscdk.core.Construct; -import software.amazon.awscdk.core.Stack; -import software.amazon.awscdk.core.StackProps; -import software.amazon.awscdk.services.s3.Bucket; + ``` + [default] + region=us-west-2 + ``` ++ In `~/.aws/credentials` or `%USERPROFILE%\.aws\credentials` -public class HelloStack extends Stack { - public HelloStack(final Construct scope, final String id) { - this(scope, id, null); - } + ``` + [default] + aws_access_key_id=AKIAI44QH8DHBEXAMPLE + aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY + ``` - public HelloStack(final Construct scope, final String id, final StackProps props) { - super(scope, id, props); +Finally, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. - Bucket.Builder.create(this, "MyFirstBucket") - .versioned(true).build(); - } -} -``` - ------- -#### [ C\# ] - -Update `HelloStack.cs` to include a Amazon S3 bucket with versioning enabled\. - -``` -using Amazon.CDK; -using Amazon.CDK.AWS.S3; - -namespace HelloCdk -{ - public class HelloStack : Stack - { - public HelloStack(Construct scope, string id, IStackProps props) : base(scope, id, props) - { - new Bucket(this, "MyFirstBucket", new BucketProps - { - Versioned = true - }); - } - } -} -``` - ------- - -Notice a few things: -+ [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) is a construct\. This means its initialization signature has `scope`, `id`, and `props` and it is a child of the stack\. -+ `MyFirstBucket` is the **id** of the bucket construct, not the physical name of the Amazon S3 bucket\. The logical ID is used to uniquely identify resources in your stack across deployments\. To specify a physical name for your bucket, set the [bucketName](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#bucketname) property \(`bucket_name` in Python\) when you define your bucket\. -+ Because the bucket's [versioned](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html#versioned) property is `true`, [versioning](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) is enabled on the bucket\. - -### Synthesizing an AWS CloudFormation template - -Synthesize an AWS CloudFormation template for the app, as follows\. If you get an error like "\-\-app is required\.\.\.", it's because you are running the command from a subdirectory of your project directory\. Navigate to the project directory and try again\. - -``` -cdk synth -``` - -This command executes the AWS CDK app and synthesizes an AWS CloudFormation template for the `HelloCdkStack` stack\. You should see something similar to the following, where *VERSION* is the version of the AWS CDK\. - -``` -Resources: - MyFirstBucketB8884501: - Type: AWS::S3::Bucket - Properties: - VersioningConfiguration: - Status: Enabled - Metadata: - aws:cdk:path: HelloCdkStack/MyFirstBucket/Resource - CDKMetadata: - Type: AWS::CDK::Metadata - Properties: - Modules: "@aws-cdk/aws-codepipeline-api=VERSION,@aws-cdk/aws-events=VERSION,@aws-c\ - dk/aws-iam=VERSION,@aws-cdk/aws-kms=VERSION,@aws-cdk/aws-s3=VERSION,@aws-c\ - dk/aws-s3-notifications=VERSION,@aws-cdk/cdk=VERSION,@aws-cdk/cx-api=VERSION\ - .0,hello-cdk=0.1.0" -``` - -You can see that the stack contains an `AWS::S3::Bucket` resource with the versioning configuration we want\. - -**Note** -The AWS CDK CLI automatically adds the **AWS::CDK::Metadata** resource to your template\. The AWS CDK uses metadata to gain insight into how the AWS CDK is used\. One possible benefit is that the CDK team could notify users if a construct is going to be deprecated\. For details, including how to [opt out](tools.md#version_reporting_opt_out) of version reporting, see [Version reporting](tools.md#version_reporting) \. - -### Deploying the stack - -Deploy the stack, as follows\. - -``` -cdk deploy -``` - -The deploy command synthesizes an AWS CloudFormation template from the app's stack, and then invokes AWS CloudFormation to deploy it in your AWS account\. If your code would change your infrastructure's security posture, the command displays information about those changes and requires you to confirm them before your stack is deployed\. The command displays information as it completes various steps in the process\. - -### Modifying the app - -Configure the bucket to use AWS Key Management Service \(AWS KMS\) managed encryption\. +Other prerequisites depend on your development language and are as follows\. ------ #### [ TypeScript ] - -Update `lib/hello-cdk-stack.ts` - -``` -new s3.Bucket(this, 'MyFirstBucket', { - versioned: true, - encryption: s3.BucketEncryption.KMS_MANAGED -}); -``` ++ TypeScript 2\.7 or later ------ #### [ JavaScript ] -Update `lib/hello-cdk-stack.js`\. - -``` -new s3.Bucket(this, 'MyFirstBucket', { - versioned: true, - encryption: s3.BucketEncryption.KMS_MANAGED -}); -``` +No additional requirements ------ #### [ Python ] - -``` -bucket = s3.Bucket(self, - "MyFirstBucket", - versioned=True, - encryption=s3.BucketEncryption.KMS_MANAGED,) -``` ++ Python 3\.6 or later including `pip` and `virtualenv` ------ #### [ Java ] ++ Java Development Kit \(JDK\) 8 \(a\.k\.a\. 1\.8\) or later ++ Apache Maven 3\.5 or later -Update `src/main/java/com/myorg/HelloStack.java`\. - -``` -import software.amazon.awscdk.services.s3.BucketEncryption; -``` - -``` -Bucket.Builder.create(this, "MyFirstBucket") - .versioned(true) - .encryption(BucketEncryption.KMS_MANAGED) - .build(); -``` +Java IDE recommended \(we use Eclipse in some examples in this Developer Guide\)\. IDE must be able to import Maven projects\. Check to make sure your project is set to use Java 1\.8\. Set the JAVA\_HOME environment variable to the path where you have installed the JDK\. ------ #### [ C\# ] -Update `HelloStack.cs`\. +A \.NET Standard 2\.1\-compatible implementation is required, such as\. ++ \.NET Core 3\.1 or later ++ \.NET Framework 4\.6\.1 or later ++ Mono 5\.4 or later -``` -new Bucket(this, "MyFirstBucket", new BucketProps -{ - Versioned = true, - Encryption = BucketEncryption.KMS_MANAGED -}); -``` +Visual Studio 2019 \(any edition\) recommended\. ------ -### Preparing for deployment +## Install the AWS CDK -Before you deploy the updated app, evaluate the difference between the AWS CDK app and the deployed app\. +Install the AWS CDK Toolkit globally using the following Node Package Manager command\. ``` -cdk diff -``` - -The AWS CDK CLI queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares the result with the template synthesized from the app\. The Resources section of the output should look like the following\. - -``` -Stack HelloCdkStack -Resources -[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 - |- [+] BucketEncryption - |- {"ServerSideEncryptionConfiguration":[{"ServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms"}}]} +npm install -g aws-cdk ``` -As you can see, the diff indicates that the `ServerSideEncryptionConfiguration` property of the bucket is now set to enable server\-side encryption\. - -You can also see that the bucket isn't going to be replaced, but will be updated instead \(**Updating MyFirstBucket\.\.\.**\)\. - -Deploy the changes\. +Run the following command to verify correct installation and print the version number of the AWS CDK\. ``` -cdk deploy -``` - -Enter y to approve the changes and deploy the updated stack\. The AWS CDK CLI updates the bucket configuration to enable server\-side AWS KMS encryption for the bucket\. The final output is the ARN of the stack, where *REGION* is your default region, *ACCOUNT\-ID* is your account ID, and *ID* is a unique identifier for the bucket or stack\. - +cdk --version ``` -HelloCdkStack: deploying... -HelloCdkStack: creating CloudFormation changeset... - 0/2 | 10:55:30 AM | UPDATE_IN_PROGRESS | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketID) - 1/2 | 10:55:50 AM | UPDATE_COMPLETE | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketID) -HelloCdkStack +## AWS CDK tools -Stack ARN: -arn:aws:cloudformation:REGION:ACCOUNT-ID:stack/HelloCdkStack/ID -``` +We've already been using the AWS CDK Toolkit, also known as the Command Line Interface \(CLI\)\. It's the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CDK templates it generates\. It also has deployment, diff, deletion, and troubleshooting capabilities\. For more information, see cdk \-\-help or [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. -### Destroying the app's resources +The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open\-source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the plug\-in](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. -Destroy the app's resources to avoid incurring any costs from the resources created in this tutorial, as follows\. +## Next steps -``` -cdk destroy -``` +Where do you go now that you've dipped your toes in the AWS CDK? ++ Come on in; the water's fine\! Build [your first AWS CDK app](hello_world.md)\. ++ Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. ++ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite API services\. ++ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. ++ Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -Enter y to approve the changes and delete any stack resources\. In some cases this command fails, such as when a resource isn't empty and must be empty before it can be destroyed\. See [Delete Stack Fails](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#troubleshooting-errors-delete-stack-fails) in the *AWS CloudFormation User Guide* for details\. \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md new file mode 100644 index 00000000..0930eaee --- /dev/null +++ b/doc_source/hello_world.md @@ -0,0 +1,518 @@ +# Your first AWS CDK app + +You're read [Getting started with the AWS CDK](getting_started.md)? Great\! Now let's see how it feels to work with the AWS CDK\. + +The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps to synthesize your stack to an AWS CloudFormation template and deploy it\. + +1. Create the app from a template provided by the AWS CDK + +1. Add code to the app to create resources within stacks + +1. Build the app \(optional; the AWS CDK Toolkit will do it for you if you forget\) + +1. Synthesize one or more stacks in the app to create an AWS CloudFormation template + +1. Deploy one or more stacks to your AWS account + +The build step catches syntax and type errors\. The synthesis step catches logical errors in defining your AWS resources\. The deployment may find permission issues\. As always, you go back to the code, find the problem, fix it, then build, synthesize and deploy again\. + +**Note** +Don't forget to keep your AWS CDK code under version control\! + +This tutorial walks you through creating and deploying a simple AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. The app contains one stack, which contains one resource: an Amazon S3 bucket\. + +We'll also show what happens when you make a change and re\-deploy, and how to clean up when you're done\. + +## Create the app + +Each AWS CDK app should be in its own directory, with its own local module dependencies\. Create a new directory for your app\. Starting in your home directory, or another directory if you prefer, issue the following commands\. + +``` +mkdir hello-cdk +cd hello-cdk +``` + +**Note** +Be sure to use the name `hello-cdk` for your project directory, *exactly as shown here\.* The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, some of the code in this tutorial won't work\. + +Now initialize the app using the cdk init command, specifying the desired template \("app"\) and programming language\. + +``` +cdk init TEMPLATE --language LANGUAGE +``` + +That is: + +------ +#### [ TypeScript ] + +``` +cdk init app --language typescript +``` + +------ +#### [ JavaScript ] + +``` +cdk init app --language javascript +``` + +------ +#### [ Python ] + +``` +cdk init app --language python +``` + +After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install its dependencies\. + +``` +source env/bin/activate +pip install -r requirements.txt +``` + +------ +#### [ Java ] + +``` +cdk init app --language java +``` + +If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set ta use Java 8 \(1\.8\)\. + +------ +#### [ C\# ] + +``` +cdk init app --language csharp +``` + +If you are using Visual Studio, open the solution file, `src\HelloCdk.sln`\. + +------ + +**Tip** +If you don't specify a template, the default is "app," which is the one we wanted anyway, so technically you can leave it out and save four keystrokes\. + +Each project you create using cdk init is also a Git repository\. We'll ignore that for now, but it's there when you need it\. + +## List the stacks in the app + +Just to verify everything is working correctly, list the stacks in your app\. + +``` +cdk ls +``` + +If you don't see `HelloCdk`, make sure you named your app's directory `hello-cdk`\. If you didn't, go back to [Create the app](#hello_world_tutorial_create_app) and try again\. + +## Add an Amazon S3 bucket + +At this point, your app doesn't do anything useful because the stack doesn't define any resources\. Let's define an Amazon S3 bucket\. + +Install the Amazon S3 package from the AWS Construct Library\. + +------ +#### [ TypeScript ] + +``` +npm install @aws-cdk/aws-s3 +``` + +------ +#### [ JavaScript ] + +``` +npm install @aws-cdk/aws-s3 +``` + +------ +#### [ Python ] + +``` +pip install aws-cdk.aws-s3 +``` + +------ +#### [ Java ] + +If necessary, add the following to `pom.xml`, where *CDK\-VERSION* is the version of the AWS CDK\. + +``` + + software.amazon.awscdk + s3 + CDK-VERSION + +``` + +------ +#### [ C\# ] + +Run the following command in the `src/HelloCdk` directory\. + +``` +dotnet add package Amazon.CDK.AWS.S3 +``` + +Or **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio, then locate and install the `Amazon.CDK.AWS.S3` package + +------ + +Next, define an Amazon S3 bucket in the stack using an L2 construct, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) class\. + +------ +#### [ TypeScript ] + +In `lib/hello-cdk-stack.ts`: + +``` +import * as core from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; + +export class HelloCdkStack extends core.Stack { + constructor(scope: core.App, id: string, props?: core.StackProps) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} +``` + +------ +#### [ JavaScript ] + +In `lib/hello-cdk-stack.js`: + +``` +const core = require('@aws-cdk/core'); +const s3 = require('@aws-cdk/aws-s3'); + +class HelloCdkStack extends core.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} + +module.exports = { HelloCdkStack } +``` + +------ +#### [ Python ] + +Replace the first import statement in `hello_cdk_stack.py` in the `hello_cdk` directory with the following code\. + +``` +from aws_cdk import ( + aws_s3 as s3, + core +) +``` + +Replace the comment with the following code\. + +``` +bucket = s3.Bucket(self, + "MyFirstBucket", + versioned=True,) +``` + +------ +#### [ Java ] + +In `src/main/java/com/myorg/HelloStack.java`: + +``` +package com.myorg; + +import software.amazon.awscdk.core.*; +import software.amazon.awscdk.services.s3.Bucket; + +public class HelloStack extends Stack { + public HelloStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public HelloStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + Bucket.Builder.create(this, "MyFirstBucket") + .versioned(true).build(); + } +} +``` + +------ +#### [ C\# ] + +Update `HelloStack.cs` to look like this\. + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +namespace HelloCdk +{ + public class HelloStack : Stack + { + public HelloStack(Construct scope, string id, IStackProps props) : base(scope, id, props) + { + new Bucket(this, "MyFirstBucket", new BucketProps + { + Versioned = true + }); + } + } +} +``` + +------ + +`Bucket` is the first construct we've seen, so let's take a closer look\. Like all constructs, the `Bucket` class takes three parameters\. ++ **scope:** Tells the bucket that the stack is its parent: it is defined within the scope of the stack\. You can define constructs inside of constructs, creating a hierarchy \(tree\)\. ++ **Id:** The logical ID of the Bucket within your AWS CDK app\. This \(plus a hash based on the bucket's location within the stack\) uniquely identifies the bucket across deployments so the AWS CDK can update it if you change how it's defined in your app\. Buckets can also have a name, which is separate from this ID \(it's the `bucketName` property\)\. ++ **props:** A bundle of values that define properties of the bucket\. Here we've defined only one property: `versioned`, which enables versioning for the files in the bucket\. + +All constructs take these same three arguments, so it's easy to stay oriented as you learn about new ones\. And as you might expect, you can subclass any construct to extend it to suit your needs, or just to change its defaults\. + +**Tip** +If all a construct's props are optional, you can omit the third parameter entirely\. + +It's interesting to take note of how praps are represented in the different supported languages\. ++ In TypeScript and JavaScript, `props` is a single argument and you pass in an object containing the desired properties\. ++ In Python, props are represented as keyword arguments\. ++ In Java, a Builder is provided to pass the props\. \(Two, actually; one for `BucketProps`, and a second for `Bucket` to let you build the construct and its props object in one step\. This code uses the latter\.\) ++ In C\#, you instantiate a `BucketProps` object using an object initializer and pass it as the third parameter\. + +## Build the app + +Normally, after making any changes to your code, you'd build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you\. But you can still build manually to catch syntax and type errors\. For reference, here's how\. + +------ +#### [ TypeScript ] + +``` +npm run build +``` + +------ +#### [ JavaScript ] + +No build step is necessary\. + +------ +#### [ Python ] + +No build step is necessary\. + +------ +#### [ Java ] + +``` +mvn compile +``` + +**Note** +Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. + +------ +#### [ C\# ] + +``` +dotnet build src +``` + +**Note** +Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. + +------ + +## Synthesize an AWS CloudFormation template + +Synthesize an AWS CloudFormation template for the app, as follows\. + +``` +cdk synth +``` + +If your app contained more than one stack, you'd need to specify which stack\(s\) to synthesize\. But since it only contains one, the Toolkit knows you must mean that one\. + +**Tip** +If you received an error like `--app is required...`, it's probably because you are running the command from a subdirectory\. Navigate to the main app directory and try again\. + +The cdk synth command executes your app, which causes the resources defined in it to be translated to an AWS CloudFormation template\. The output of `cdk synth` is a YAML\-format AWS CloudFormation template, which looks something like this\. Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for an `AWS::S3::Bucket` + +``` +Resources: + MyFirstBucketB8884501: + Type: AWS::S3::Bucket + Properties: + VersioningConfiguration: + Status: Enabled + UpdateReplacePolicy: Retain + DeletionPolicy: Retain + Metadata: + aws:cdk:path: HelloCdkStack/MyFirstBucket/Resource + CDKMetadata: + Type: AWS::CDK::Metadata + Properties: + Modules: aws-cdk=1.45.0,@aws-cdk/aws-events=1.45.0,@aws-cdk/aws-iam=1.45.0,@aws-cdk/aws-kms=1.45.0,@aws-cdk/aws-s3=1.45.0,@aws-cdk/cdk-assets-schema=1.45.0,@aws-cdk/cloud-assembly-schema=1.45.0,@aws-cdk/core=1.45.0,@aws-cdk/cx-api=1.45.0,@aws-cdk/region-info=1.45.0,jsii-runtime=node.js/v12.16.3 +``` + +**Note** +Every generated template contains a `AWS::CDK::Metadata` resource by default\. The AWS CDK team uses this metadata to gain insight into how the AWS CDK is used, so we can continue to improve it\. For details, including how to opt out of version reporting, see [Version reporting](tools.md#version_reporting)\. + +The output of `cdk synth` is a perfectly valid AWS CloudFormation template\. You could take it and deploy it using the AWS CloudFormation console\. But the AWS CDK Toolkit also has that feature built\-in\. + +## Deploying the stack + +To deploy the stack using AWS CloudFormation, issue: + +``` +cdk deploy +``` + +As with `cdk synth`, you don't need to specify the name of the stack since there's only one in the app\. + +It is optional \(though good practice\) to synthesize before deploying\. The AWS CDK synthesizes your stack before each deployment\. + +If your code changes have security implications, you'll see a summary of these, and be asked to confirm them before deployment proceeds\. + +`cdk deploy` displays progress information as your stack is deployed\. When it's done, the command prompt reappears\. You can go to the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home) and see that it now lists `HelloStack`\. You'll also find `MyFirstBucket` in the Amazon S3 console\. + +You've deployed your first stack using the AWS CDK—congratulations\! But that's not all there is to the AWS CDK\. + +## Modifying the app + +The AWS CDK can update your deployed resources after you modify your app\. Let's make a little change to our bucket\. We want to be able to delete the bucket automatically when we delete the stack, so we'll change the RemovalPolicy\. + +------ +#### [ TypeScript ] + +Update `lib/hello-cdk-stack.ts` + +``` +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true, + removalPolicy: core.RemovalPolicy.DESTROY + +}); +``` + +------ +#### [ JavaScript ] + +Update `lib/hello-cdk-stack.js`\. + +``` +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true, + removalPolicy: core.RemovalPolicy.DESTROY +}); +``` + +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, + "MyFirstBucket", + versioned=True, + removal_policy=core.RemovalPolicy.DESTROY) +``` + +------ +#### [ Java ] + +Update `src/main/java/com/myorg/HelloStack.java`\. + +``` +import software.amazon.awscdk.services.s3.BucketEncryption; +``` + +``` +Bucket.Builder.create(this, "MyFirstBucket") + .versioned(true) + .removalPolicy(RemovalPolicy.DESTROY) + .build(); +``` + +------ +#### [ C\# ] + +Update `HelloStack.cs`\. + +``` +new Bucket(this, "MyFirstBucket", new BucketProps +{ + Versioned = true, + RemovalPolicy = RemovalPolicy.DESTROY +}); +``` + +------ + +Now we'll use the `cdk diff` command to see the differences between what's already been deployed, and the code we just changed\. + +``` +cdk diff +``` + +The AWS CDK Toolkit queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares it with the template it synthesized from your app\. The Resources section of the output should look like the following\. + +``` +[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 + ├─ [~] DeletionPolicy + │ ├─ [-] Retain + │ └─ [+] Delete + └─ [~] UpdateReplacePolicy + ├─ [-] Retain + └─ [+] Delete +``` + +As you can see, the diff indicates that the `DeletionPolicy` property of the bucket is now set to `DESTROY`, enabling the bucket to be deleted when its stack is deleted\. The `UpdateReplacePolicy `is also changed\. + +Don't be confused by the difference in name\. The AWS CDK calls it `RemovalPolicy` because its meaning is slightly different from AWS CloudFormation's `DeletionPolicy`: the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it\. See [Removal policies](resources.md#resources_removal) for further details\. + +You can also see that the bucket isn't going to be replaced, but will be updated instead\. + +Now let's deploy\. + +``` +cdk deploy +``` + +Enter y to approve the changes and deploy the updated stack\. The Toolkit updates the bucket configuration as you requested\. + +``` +HelloCdkStack: deploying... +HelloCdkStack: creating CloudFormation changeset... + 0/2 | 10:55:30 AM | UPDATE_IN_PROGRESS | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketID) + 1/2 | 10:55:50 AM | UPDATE_COMPLETE | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketID) + +HelloCdkStack + +Stack ARN: +arn:aws:cloudformation:REGION:ACCOUNT-ID:stack/HelloCdkStack/ID +``` + +## Destroying the app's resources + +Now that you're done with the quick tour, destroy your app's resources to avoid incurring any costs from the bucket you created, as follows\. + +``` +cdk destroy +``` + +Enter y to approve the changes and delete any stack resources\. + +**Note** +This wouldn't have worked if we hadn't changed tho bucket's `RemovalPolicy` just a minute ago\! + +If cdk destroy fails, it probably means you put something in your Amazon S3 bucket\. AWS CloudFormation won't delete buckets with files in them\. Delete the files and try again\. \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index 060aff29..10d87a78 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -16,6 +16,7 @@ Amazon's trademarks and trade dress may not be used in ## Contents + [What is the AWS CDK?](home.md) + [Getting started with the AWS CDK](getting_started.md) ++ [Your first AWS CDK app](hello_world.md) + [Working with the AWS CDK](work-with.md) + [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) + [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) From 1a175e0a97aa0110fd3c3948098f0e4f6a5be132 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 18 Jun 2020 04:40:57 +0000 Subject: [PATCH 183/655] fix some typos --- doc_source/getting_started.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 2cfe8204..8d3b4112 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -1,6 +1,6 @@ # Getting started with the AWS CDK -This topic introduces you to important AWS CDK concepts, describes how to install and configure the AWS CDK, and walks you through creating your first AWS CDK app\. +This topic introduces you to important AWS CDK concepts and describes how to install and configure the AWS CDK\. When you're done, you'll be ready to create [your first AWS CDK app\.](hello_world.md)\. ## Your background @@ -16,7 +16,7 @@ Finally, you should be proficient in the programming language you intend to use The AWS CDK is designed around a handful of important concepts\. We will introduce a few of these here briefly\. Follow the links to learn more, or see the Concepts topics in this guide's Table of Contents\. -An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, Python, Java, or C\# that uses the AWS CDK to define AWS infrastructure\. An app defines one or more [stacks](stacks.md)\. Stacks \(equivalent to AWS CloudFormation stacks\) contains [constructs](constructs.md), each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on\. +An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, Python, Java, or C\# that uses the AWS CDK to define AWS infrastructure\. An app defines one or more [stacks](stacks.md)\. Stacks \(equivalent to AWS CloudFormation stacks\) contain [constructs](constructs.md), each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on\. Constructs \(as well as stacks and apps\) are represented as types in your programming language of choice\. You instantiate constructs within a stack to declare them to AWS, and connect them to each other using well\-defined interfaces\. @@ -112,7 +112,7 @@ With the concepts out of the way, here's what you need to have on your workstati All CDK developers need to [install Node\.js](https://nodejs.org/en/download/) 10\.3\.0 or later, even those working in languages other than TypeScript or JavaScript\. The AWS CDK Toolkit \(cdk command\-line tool\) and the AWS Construct Library are developed in TypeScript and run on Node\.js\. The bindings for other supported languages use this back end and tool set\. We suggest the latest LTS version\. **Important** -Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK +Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK\. You must provide your credentials and an AWS Region to use AWS CDK, if you have not already done so\. From 95c0f2358ff9c27fdc851e0b9c9f628bdc2aa0ff Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 18 Jun 2020 15:50:20 +0000 Subject: [PATCH 184/655] fix typos and other tweaks --- doc_source/hello_world.md | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 0930eaee..3a1bc88f 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -1,6 +1,6 @@ # Your first AWS CDK app -You're read [Getting started with the AWS CDK](getting_started.md)? Great\! Now let's see how it feels to work with the AWS CDK\. +You're read [Getting started with the AWS CDK](getting_started.md)? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. In this process you'll learn about the structure of a AWS CDK project, how to access the AWS Construct Library, and how to use the AWS CDK Toolkit command\-line tool\.\. The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps to synthesize your stack to an AWS CloudFormation template and deploy it\. @@ -32,7 +32,7 @@ mkdir hello-cdk cd hello-cdk ``` -**Note** +**Important** Be sure to use the name `hello-cdk` for your project directory, *exactly as shown here\.* The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, some of the code in this tutorial won't work\. Now initialize the app using the cdk init command, specifying the desired template \("app"\) and programming language\. @@ -292,7 +292,7 @@ It's interesting to take note of how praps are represented in the different supp ## Build the app -Normally, after making any changes to your code, you'd build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you\. But you can still build manually to catch syntax and type errors\. For reference, here's how\. +Normally, after making any changes to your code, you'd build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you so you can't forget\. But you can still build manually to catch syntax and type errors\. For reference, here's how\. ------ #### [ TypeScript ] @@ -346,7 +346,7 @@ If your app contained more than one stack, you'd need to specify which stack\(s\ **Tip** If you received an error like `--app is required...`, it's probably because you are running the command from a subdirectory\. Navigate to the main app directory and try again\. -The cdk synth command executes your app, which causes the resources defined in it to be translated to an AWS CloudFormation template\. The output of `cdk synth` is a YAML\-format AWS CloudFormation template, which looks something like this\. Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for an `AWS::S3::Bucket` +The `cdk synth` command executes your app, which causes the resources defined in it to be translated to an AWS CloudFormation template\. The output of `cdk synth` is a YAML\-format AWS CloudFormation template, which looks something like this\. Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for an `AWS::S3::Bucket`\. ``` Resources: @@ -362,7 +362,7 @@ Resources: CDKMetadata: Type: AWS::CDK::Metadata Properties: - Modules: aws-cdk=1.45.0,@aws-cdk/aws-events=1.45.0,@aws-cdk/aws-iam=1.45.0,@aws-cdk/aws-kms=1.45.0,@aws-cdk/aws-s3=1.45.0,@aws-cdk/cdk-assets-schema=1.45.0,@aws-cdk/cloud-assembly-schema=1.45.0,@aws-cdk/core=1.45.0,@aws-cdk/cx-api=1.45.0,@aws-cdk/region-info=1.45.0,jsii-runtime=node.js/v12.16.3 + Modules: aws-cdk=1.XX.X,@aws-cdk/aws-events=1.XX.X,@aws-cdk/aws-iam=1.XX.X,@aws-cdk/aws-kms=1.XX.X,@aws-cdk/aws-s3=1.XX.X,@aws-cdk/cdk-assets-schema=1.XX.X,@aws-cdk/cloud-assembly-schema=1.XX.X,@aws-cdk/core=1.XX.X,@aws-cdk/cx-api=1.XX.X,@aws-cdk/region-info=1.XX.X,jsii-runtime=node.js/vXX.XX.X ``` **Note** @@ -476,7 +476,7 @@ The AWS CDK Toolkit queries your AWS account for the current AWS CloudFormation └─ [+] Delete ``` -As you can see, the diff indicates that the `DeletionPolicy` property of the bucket is now set to `DESTROY`, enabling the bucket to be deleted when its stack is deleted\. The `UpdateReplacePolicy `is also changed\. +As you can see, the diff indicates that the `DeletionPolicy` property of the bucket is now set to `Delete`, enabling the bucket to be deleted when its stack is deleted\. The `UpdateReplacePolicy `is also changed\. Don't be confused by the difference in name\. The AWS CDK calls it `RemovalPolicy` because its meaning is slightly different from AWS CloudFormation's `DeletionPolicy`: the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it\. See [Removal policies](resources.md#resources_removal) for further details\. @@ -493,13 +493,14 @@ Enter y to approve the changes and deploy the updated stack\. The Toolkit update ``` HelloCdkStack: deploying... HelloCdkStack: creating CloudFormation changeset... - 0/2 | 10:55:30 AM | UPDATE_IN_PROGRESS | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketID) - 1/2 | 10:55:50 AM | UPDATE_COMPLETE | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketID) + 1/1 | 8:39:43 AM | UPDATE_COMPLETE | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketB8884501) + 1/1 | 8:39:44 AM | UPDATE_COMPLETE_CLEA | AWS::CloudFormation::Stack | HelloCdkStack + 2/1 | 8:39:45 AM | UPDATE_COMPLETE | AWS::CloudFormation::Stack | HelloCdkStack -HelloCdkStack + ✅ HelloCdkStack Stack ARN: -arn:aws:cloudformation:REGION:ACCOUNT-ID:stack/HelloCdkStack/ID +arn:aws:cloudformation:REDION:ACCOUNT:stack/HelloCdkStack/ID ``` ## Destroying the app's resources @@ -515,4 +516,14 @@ Enter y to approve the changes and delete any stack resources\. **Note** This wouldn't have worked if we hadn't changed tho bucket's `RemovalPolicy` just a minute ago\! -If cdk destroy fails, it probably means you put something in your Amazon S3 bucket\. AWS CloudFormation won't delete buckets with files in them\. Delete the files and try again\. \ No newline at end of file +If cdk destroy fails, it probably means you put something in your Amazon S3 bucket\. AWS CloudFormation won't delete buckets with files in them\. Delete the files and try again\. + +## Next steps + +Where do you go now that you've dipped your toes in the AWS CDK? ++ Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. ++ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite API services\. ++ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. ++ Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. + +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file From e7ac75fa7fe9c0171cdca34c147b57c9a541c746 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 18 Jun 2020 16:04:14 +0000 Subject: [PATCH 185/655] tweaks --- doc_source/getting_started.md | 2 +- doc_source/index.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 8d3b4112..9d6f1152 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -35,7 +35,7 @@ The AWS CDK's core module \(usually imported into code as `cdk`\) contains const The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) -To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. We have taken pains to make AWS CDK app development in each language follow that language's usual conventions\. For example, note how the names of methods, classes, and so on are adapted to each language in the snippets below +To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. We have taken pains to make AWS CDK app development in each language follow that language's usual conventions, so writing AWS CDK apps feels natural, not like writing TypeScript in Python \(for example\)\. Take a look: ------ #### [ TypeScript ] diff --git a/doc_source/index.md b/doc_source/index.md index 10d87a78..1a877707 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -16,7 +16,7 @@ Amazon's trademarks and trade dress may not be used in ## Contents + [What is the AWS CDK?](home.md) + [Getting started with the AWS CDK](getting_started.md) -+ [Your first AWS CDK app](hello_world.md) + + [Your first AWS CDK app](hello_world.md) + [Working with the AWS CDK](work-with.md) + [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) + [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) From 3cd772287875c728ac5e1e67b5c3999d10826fc5 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 18 Jun 2020 16:28:46 +0000 Subject: [PATCH 186/655] geting started tweaks; remove duplicate entry from history --- doc_source/doc-history.md | 1 - doc_source/getting_started.md | 14 ++++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index fb77344a..01d2ede8 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -13,7 +13,6 @@ The table below represents significant documentation milestones\. We fix errors | [Translating from TypeScript](#doc-history) | Updated "CDK in Other Languages" topic to also include JavaScript, Java, and C\# and renamed it "Translating from TypeScript\." | April 10, 2020 | | [Parameters topic](#doc-history) | Add Concepts topic on using parameters with the AWS CDK\. | April 8, 2020 | | [JavaScript code snippets](#doc-history) | Reinstate JavaScript code snippets throughout \(automated translation via Babel\)\. | April 3, 2020 | -| [JavaScript code snippets](#doc-history) | Reinstate JavaScript code snippets throughout \(automated translation via Babel\) | April 3, 2020 | | [Working with the CDK](#doc-history) | Add "Working with the CDK" articles for the five supported languages\. Various other improvements and fixes\. | February 4, 2020 | | [Java code snippets](#doc-history) | Add Java code snippets throughout\. Designate Java and C\# bindings stable\. | November 25, 2019 | | [C\# code snippets](#doc-history) | Add C\# code snippets throughout\. | November 19, 2019 | diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 9d6f1152..22f7263d 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -25,8 +25,12 @@ The AWS CDK includes the AWS CDK Toolkit \(also called the CLI\), a command\-lin The AWS CDK includes a library of AWS constructs called the AWS Construct Library\. Each AWS service has at least one corresponding module in the library containing the constructs that represent that service's resources\. Constructs come in three fundamental flavors: -+ **AWS CloudFormation\-only** or L1 \(short for "level 1"\)\. These constructs correspond directly to resource types defined by AWS CloudFormation\. In fact, these constructs are automatically generated from the AWS CloudFormation specification, so when a new AWS service is launched, the AWS CDK supports it as soon as AWS CloudFormation does\. AWS CloudFormation resources always have names that begin with `Cfn`\. For example, in the Amazon S3 module, `CfnBucket` is the L1 module for an Amazon S3 bucket\. -+ **Curated** or L2\. These constructs are carefully developed by the AWS CDK team to address specific use cases and simplify infrastructure development\. For the most part, they encapsulate L1 modules, providing sensible defaults and best\-practice security policies\. L2 modules may also define supporting resources needed by the primary resource\. For example, in the Amazon S3 module, `Bucket` is the L2 module for an Amazon S3 bucket\. Some services have more than one L2 module in the Construct Library for organizational purposes\. ++ **AWS CloudFormation\-only** or L1 \(short for "level 1"\)\. These constructs correspond directly to resource types defined by AWS CloudFormation\. In fact, these constructs are automatically generated from the AWS CloudFormation specification, so when a new AWS service is launched, the AWS CDK supports it as soon as AWS CloudFormation does\. + + AWS CloudFormation resources always have names that begin with `Cfn`\. For example, in the Amazon S3 module, `CfnBucket` is the L1 module for an Amazon S3 bucket\. ++ **Curated** or L2\. These constructs are carefully developed by the AWS CDK team to address specific use cases and simplify infrastructure development\. For the most part, they encapsulate L1 modules, providing sensible defaults and best\-practice security policies\. For example, in the Amazon S3 module, `Bucket` is the L2 module for an Amazon S3 bucket\. + + L2 modules may also define supporting resources needed by the primary resource\. Some services have more than one L2 module in the Construct Library for organizational purposes\. + **Patterns** or L3\. Patterns declare multiple resources to create entire AWS architectures for particular use cases\. All the plumbing is already hooked up, and configuration is boiled down to a few important parameters\. In the AWS Construct Library, patterns are in separate modules from L1 and L2 constructs\. The AWS CDK's core module \(usually imported into code as `cdk`\) contains constructs used by the AWS CDK itself as well as base classes for constructs, apps, resources, and other AWS CDK objects\. @@ -35,7 +39,9 @@ The AWS CDK's core module \(usually imported into code as `cdk`\) contains const The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) -To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. We have taken pains to make AWS CDK app development in each language follow that language's usual conventions, so writing AWS CDK apps feels natural, not like writing TypeScript in Python \(for example\)\. Take a look: +To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. + +We have taken pains to make AWS CDK app development in each language follow that language's usual conventions, so writing AWS CDK apps feels natural, not like writing TypeScript in Python \(for example\)\. Take a look: ------ #### [ TypeScript ] @@ -148,7 +154,7 @@ Other prerequisites depend on your development language and are as follows\. ------ #### [ TypeScript ] -+ TypeScript 2\.7 or later ++ TypeScript 2\.7 or later \(`npm -g install typescript`\) ------ #### [ JavaScript ] From 6bb917eff09003db9712bffe48cfca71a71e8bc0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 19 Jun 2020 16:08:30 +0000 Subject: [PATCH 187/655] tweaks --- doc_source/doc-history.md | 2 +- doc_source/getting_started.md | 2 +- doc_source/hello_world.md | 14 ++++++++------ doc_source/work-with-cdk-java.md | 4 ++-- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 01d2ede8..f1515aa8 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -1,6 +1,6 @@ # AWS CDK Developer Guide history -See [Releases](https://github.com/awslabs/aws-cdk/releases) for information on AWS CDK releases\. The AWS CDK is updated approximately once a week\. Maintenance versions may be released between weekly releases to address critical issues\. Each release includes a matched AWS CDK Toolkit \(CDK CLI\), AWS Construct Library, and API Reference\. +See [Releases](https://github.com/awslabs/aws-cdk/releases) for information on AWS CDK releases\. The AWS CDK is updated approximately once a week\. Maintenance versions may be released between weekly releases to address critical issues\. Each release includes a matched AWS CDK Toolkit \(CDK CLI\), AWS Construct Library, and API Reference\. Updates to this Guide generally do not synchronize with AWS CDK releases\. **Note** The table below represents significant documentation milestones\. We fix errors and improve content on an ongoing basis\. diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 22f7263d..50aacdc6 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -33,7 +33,7 @@ Constructs come in three fundamental flavors: L2 modules may also define supporting resources needed by the primary resource\. Some services have more than one L2 module in the Construct Library for organizational purposes\. + **Patterns** or L3\. Patterns declare multiple resources to create entire AWS architectures for particular use cases\. All the plumbing is already hooked up, and configuration is boiled down to a few important parameters\. In the AWS Construct Library, patterns are in separate modules from L1 and L2 constructs\. -The AWS CDK's core module \(usually imported into code as `cdk`\) contains constructs used by the AWS CDK itself as well as base classes for constructs, apps, resources, and other AWS CDK objects\. +The AWS CDK's core module \(usually imported into code as `core` or `cdk`\) contains constructs used by the AWS CDK itself as well as base classes for constructs, apps, resources, and other AWS CDK objects\. ## Supported programming languages diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 3a1bc88f..44e5df4d 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -67,7 +67,7 @@ cdk init app --language python After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install its dependencies\. ``` -source env/bin/activate +source .env/bin/activate pip install -r requirements.txt ``` @@ -136,16 +136,18 @@ pip install aws-cdk.aws-s3 ------ #### [ Java ] -If necessary, add the following to `pom.xml`, where *CDK\-VERSION* is the version of the AWS CDK\. +If necessary, add the following to the `` container of `pom.xml`, where *CDK\-VERSION* is the version of the AWS CDK\. ``` - software.amazon.awscdk - s3 - CDK-VERSION + software.amazon.awscdk + s3 + [1.0,2.0) ``` +If you are using a Java IDE, it should have a simpler way to add this dependency to your project\. For example, in Eclipse, you can use the **Dependencies** tab of the POM editor\. See [Using a Java IDE](work-with-cdk-java.md#java-maven-ide-gui) for further instructions\. + ------ #### [ C\# ] @@ -390,7 +392,7 @@ You've deployed your first stack using the AWS CDK—congratulations\! But that' ## Modifying the app -The AWS CDK can update your deployed resources after you modify your app\. Let's make a little change to our bucket\. We want to be able to delete the bucket automatically when we delete the stack, so we'll change the RemovalPolicy\. +The AWS CDK can update your deployed resources after you modify your app\. Let's make a little change to our bucket\. We want to be able to delete the bucket automatically when we delete the stack, so we'll change the `RemovalPolicy`\. ------ #### [ TypeScript ] diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index decb0085..58f36826 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -51,7 +51,7 @@ If you're using an IDE, its Maven integration is probably the simplest way to in 1. In the search results, find the desired package \(e\.g\. `s3`\) and double\-click it\. \(You may also expand the package and choose a specific version, if you don't want the latest\.\) -1. Repeat step 5 for each additional AWS Construct Library package you want to install\. +1. Repeat steps 3\-5 for each additional AWS Construct Library package you want to install\. You can periodically issue the following command to update your dependencies to the latest version\. Maven updates the version specification in `pom.xml` with the latest version of each specified package available in the Maven Central Repository\. @@ -67,7 +67,7 @@ If you are not using an IDE, or just want full control over the versions of your software.amazon.awscdk s3 - [1.0,2.0) + [1.0,2.0) ``` From a46cbae10721d471540f92551a0ee8d476d5944e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 19 Jun 2020 20:02:31 +0000 Subject: [PATCH 188/655] typo --- doc_source/hello_world.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 44e5df4d..7705e09e 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -94,7 +94,7 @@ If you are using Visual Studio, open the solution file, `src\HelloCdk.sln`\. **Tip** If you don't specify a template, the default is "app," which is the one we wanted anyway, so technically you can leave it out and save four keystrokes\. -Each project you create using cdk init is also a Git repository\. We'll ignore that for now, but it's there when you need it\. +If you have Git installed, ach project you create using cdk init is also initialized as a Git repository\. We'll ignore that for now, but it's there when you need it\. ## List the stacks in the app @@ -286,7 +286,7 @@ All constructs take these same three arguments, so it's easy to stay oriented as **Tip** If all a construct's props are optional, you can omit the third parameter entirely\. -It's interesting to take note of how praps are represented in the different supported languages\. +It's interesting to take note of how props are represented in the different supported languages\. + In TypeScript and JavaScript, `props` is a single argument and you pass in an object containing the desired properties\. + In Python, props are represented as keyword arguments\. + In Java, a Builder is provided to pass the props\. \(Two, actually; one for `BucketProps`, and a second for `Bucket` to let you build the construct and its props object in one step\. This code uses the latter\.\) From 879e413d019a7c8b330b69d5218301290d5c5fe3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 19 Jun 2020 20:14:11 +0000 Subject: [PATCH 189/655] tweaks --- doc_source/getting_started.md | 2 +- doc_source/hello_world.md | 6 ++++-- doc_source/multiple_languages.md | 1 + 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 50aacdc6..bff88393 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -209,7 +209,7 @@ The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode Where do you go now that you've dipped your toes in the AWS CDK? + Come on in; the water's fine\! Build [your first AWS CDK app](hello_world.md)\. + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. -+ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite API services\. ++ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite AWS services\. + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 7705e09e..1b746556 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -348,7 +348,7 @@ If your app contained more than one stack, you'd need to specify which stack\(s\ **Tip** If you received an error like `--app is required...`, it's probably because you are running the command from a subdirectory\. Navigate to the main app directory and try again\. -The `cdk synth` command executes your app, which causes the resources defined in it to be translated to an AWS CloudFormation template\. The output of `cdk synth` is a YAML\-format AWS CloudFormation template, which looks something like this\. Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for an `AWS::S3::Bucket`\. +The `cdk synth` command executes your app, which causes the resources defined in it to be translated to an AWS CloudFormation template\. The output of `cdk synth` is a YAML\-format AWS CloudFormation template, which looks something like this\. ``` Resources: @@ -367,6 +367,8 @@ Resources: Modules: aws-cdk=1.XX.X,@aws-cdk/aws-events=1.XX.X,@aws-cdk/aws-iam=1.XX.X,@aws-cdk/aws-kms=1.XX.X,@aws-cdk/aws-s3=1.XX.X,@aws-cdk/cdk-assets-schema=1.XX.X,@aws-cdk/cloud-assembly-schema=1.XX.X,@aws-cdk/core=1.XX.X,@aws-cdk/cx-api=1.XX.X,@aws-cdk/region-info=1.XX.X,jsii-runtime=node.js/vXX.XX.X ``` +Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for an `AWS::S3::Bucket` and see how the versioning configuration was translated\. + **Note** Every generated template contains a `AWS::CDK::Metadata` resource by default\. The AWS CDK team uses this metadata to gain insight into how the AWS CDK is used, so we can continue to improve it\. For details, including how to opt out of version reporting, see [Version reporting](tools.md#version_reporting)\. @@ -524,7 +526,7 @@ If cdk destroy fails, it probably means you put something in your Amazon S3 buck Where do you go now that you've dipped your toes in the AWS CDK? + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. -+ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite API services\. ++ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite AWS services\. + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 5156dbcc..9fa456dd 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -295,6 +295,7 @@ Python doesn't have an interface feature\. However, for the AWS CDK you can indi ``` from aws_cdk.core import IAspect, IConstruct +import jsii @jsii.implements(IAspect) class MyAspect(): From a5de5e82b29f98ef172a9c2b3825cb44fd3f2300 Mon Sep 17 00:00:00 2001 From: Ara Gevorkian <4725661+aragevorkian@users.noreply.github.com> Date: Mon, 22 Jun 2020 09:49:00 -0700 Subject: [PATCH 190/655] Fix typo in work-with-cdk-csharp.md --- doc_source/work-with-cdk-csharp.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 0a0d1a9a..1c403660 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -159,6 +159,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly buiild your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. +You don't need to explicitly build your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. From ab72bd28f82bf598cdd2fe4183b59b60b424d689 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 23 Jun 2020 00:06:05 +0000 Subject: [PATCH 191/655] typo --- doc_source/work-with-cdk-csharp.md | 2 +- doc_source/work-with-cdk-java.md | 2 +- doc_source/work-with-cdk-javascript.md | 2 +- doc_source/work-with-cdk-python.md | 2 +- doc_source/work-with-cdk-typescript.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 1c403660..884d9e36 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -161,4 +161,4 @@ You can specify the names of multiple stacks to be synthesized or deployed in a **Tip** You don't need to explicitly build your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 58f36826..20654c62 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -124,6 +124,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly buiild your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. +You don't need to explicitly build your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index bc0dd4d7..0a8618b1 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -88,7 +88,7 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly buiild your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. +You don't need to explicitly build your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index a2fb06d1..be826139 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -152,6 +152,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly buiild your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. +You don't need to explicitly build your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index 6ded6078..bf22cde0 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -88,6 +88,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly buiild your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. +You don't need to explicitly build your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file From c090a5f00532effa4745262ed8ca180e05e4d025 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 23 Jun 2020 02:51:22 +0000 Subject: [PATCH 192/655] tweaks --- doc_source/testing.md | 1 - doc_source/work-with-cdk-csharp.md | 2 +- doc_source/work-with-cdk-java.md | 2 +- doc_source/work-with-cdk-javascript.md | 2 +- doc_source/work-with-cdk-python.md | 2 +- doc_source/work-with-cdk-typescript.md | 2 +- 6 files changed, 5 insertions(+), 6 deletions(-) diff --git a/doc_source/testing.md b/doc_source/testing.md index a3068ce2..31d67f3b 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -134,7 +134,6 @@ Object { To make sure the test works, change the construct so that it generates different AWS CloudFormation output, then build and test again\. For example, add a `period` property of 1 minute to override the default of 5 minutes\. The boldface line below shows the code that needs to be added to `index.ts`\. ``` -this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { alarmDescription: 'There are messages in the Dead Letter Queue', evaluationPeriods: 1, diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 884d9e36..8b148092 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -159,6 +159,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly build your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 20654c62..f6311273 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -124,6 +124,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly build your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 0a8618b1..623339b3 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -88,7 +88,7 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly build your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index be826139..7448dc48 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -152,6 +152,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly build your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index bf22cde0..33a3a93e 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -88,6 +88,6 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. **Tip** -You don't need to explicitly build your app or synthesize stacks before deploying them; `cdk deploy` performs these steps for you\. +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file From 0367ede402ce56a703700a38e5c71d8a1d7448dc Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 24 Jun 2020 15:14:18 +0000 Subject: [PATCH 193/655] fix some missing props arguments in super() calls --- doc_source/constructs.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index c538bc3a..21b9922b 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -509,7 +509,7 @@ export interface NotifyingBucketProps { export class NotifyingBucket extends Construct { constructor(scope: Construct, id: string, props: NotifyingBucketProps = {}) { - super(scope, id); + super(scope, id, props); const bucket = new s3.Bucket(this, 'bucket'); const topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(new s3notify.SnsDestination(topic), @@ -524,7 +524,7 @@ export class NotifyingBucket extends Construct { ``` class NotifyingBucket extends Construct { constructor(scope, id, props = {}) { - super(scope, id); + super(scope, id, props); const bucket = new s3.Bucket(this, 'bucket'); const topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(new s3notify.SnsDestination(topic), @@ -542,7 +542,7 @@ module.exports = { NotifyingBucket } class NotifyingBucket(core.Construct): def __init__(self, scope: core.Construct, id: str, *, prefix=None, **kwargs): - super().__init__(scope, id) + super().__init__(scope, id, **kwargs) bucket = s3.Bucket(self, "bucket") topic = sns.Topic(self, "topic") bucket.add_object_created_notification(s3notify.SnsDestination(topic), @@ -568,7 +568,7 @@ public class NotifyingBucket extends Construct { } public NotifyingBucket(final Construct scope, final String id, final BucketProps props, final String prefix) { - super(scope, id); + super(scope, id, props); Bucket bucket = new Bucket(this, "bucket"); Topic topic = new Topic(this, "topic"); @@ -590,7 +590,7 @@ public class NotifyingBucketProps : BucketProps public class NotifyingBucket : Construct { - public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id) + public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id, props) { var bucket = new Bucket(this, "bucket"); var topic = new Topic(this, "topic"); @@ -695,7 +695,7 @@ export class NotifyingBucket extends Construct { public readonly topic: sns.Topic; constructor(scope: Construct, id: string, props: NotifyingBucketProps) { - super(scope, id); + super(scope, id, props); const bucket = new s3.Bucket(this, 'bucket'); this.topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(this.topic, { prefix: props.prefix }); @@ -710,7 +710,7 @@ export class NotifyingBucket extends Construct { class NotifyingBucket extends Construct { constructor(scope, id, props) { - super(scope, id); + super(scope, id, props); const bucket = new s3.Bucket(this, 'bucket'); this.topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(this.topic, { prefix: props.prefix }); @@ -774,7 +774,7 @@ public class NotifyingBucket : Construct { public readonly Topic topic; - public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id) + public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id, props) { var bucket = new Bucket(this, "bucket"); topic = new Topic(this, "topic"); @@ -795,7 +795,7 @@ Now, consumers can subscribe to the topic, for example: ``` const queue = new sqs.Queue(this, 'NewImagesQueue'); -const images = new NotifyingBucket(this, 'Images'); +const images = new NotifyingBucket(this, '/images'); images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); ``` @@ -804,7 +804,7 @@ images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); ``` const queue = new sqs.Queue(this, 'NewImagesQueue'); -const images = new NotifyingBucket(this, 'Images'); +const images = new NotifyingBucket(this, '/images'); images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); ``` From 5b1139facc10d47ca5e8eff8928d4144ab2e0dc4 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 25 Jun 2020 14:44:42 +0000 Subject: [PATCH 194/655] typos --- doc_source/hello_world.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 1b746556..fd00eb8f 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -94,7 +94,7 @@ If you are using Visual Studio, open the solution file, `src\HelloCdk.sln`\. **Tip** If you don't specify a template, the default is "app," which is the one we wanted anyway, so technically you can leave it out and save four keystrokes\. -If you have Git installed, ach project you create using cdk init is also initialized as a Git repository\. We'll ignore that for now, but it's there when you need it\. +If you have Git installed, each project you create using cdk init is also initialized as a Git repository\. We'll ignore that for now, but it's there when you need it\. ## List the stacks in the app @@ -405,7 +405,6 @@ Update `lib/hello-cdk-stack.ts` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, removalPolicy: core.RemovalPolicy.DESTROY - }); ``` @@ -504,7 +503,7 @@ HelloCdkStack: creating CloudFormation changeset... ✅ HelloCdkStack Stack ARN: -arn:aws:cloudformation:REDION:ACCOUNT:stack/HelloCdkStack/ID +arn:aws:cloudformation:REGION:ACCOUNT:stack/HelloCdkStack/ID ``` ## Destroying the app's resources From 70c6572c1621760ed340a86c35c318688dd5df26 Mon Sep 17 00:00:00 2001 From: 13agupta <32616412+13agupta@users.noreply.github.com> Date: Thu, 25 Jun 2020 17:36:58 -0400 Subject: [PATCH 195/655] Change "errror" to "error" --- doc_source/work-with-cdk-python.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 7448dc48..c0f150dc 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -141,7 +141,7 @@ In our experience, the type errors Python programmers make tend to fall into the + Passing a single value where a construct expects a container \(Python list or dictionary\) or vice versa\. + Passing a value of a type associated with a Level 1 \(`CfnXxxxxx`\) construct to a higher\-level construct, or vice versa\. -The AWS CDK Python modules do include type annotations\. If you are not using an IDE that supports these, such as [PyCharm](https://www.jetbrains.com/pycharm/), you might want to call the [MyPy](http://mypy-lang.org/) type validator as a step in your build process\. There are also runtime type checkers that can improve errror messages for type\-related errors\. +The AWS CDK Python modules do include type annotations\. If you are not using an IDE that supports these, such as [PyCharm](https://www.jetbrains.com/pycharm/), you might want to call the [MyPy](http://mypy-lang.org/) type validator as a step in your build process\. There are also runtime type checkers that can improve error messages for type\-related errors\. ## Synthesizing and deploying @@ -154,4 +154,4 @@ You can specify the names of multiple stacks to be synthesized or deployed in a **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. From 911f4e5b76f39cec7052d4a87f869d35f30a0b88 Mon Sep 17 00:00:00 2001 From: Tuan Ardouin Date: Fri, 26 Jun 2020 12:45:28 +0200 Subject: [PATCH 196/655] Minor typo Minor typo --- doc_source/hello_world.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index fd00eb8f..231abfe7 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -1,6 +1,6 @@ # Your first AWS CDK app -You're read [Getting started with the AWS CDK](getting_started.md)? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. In this process you'll learn about the structure of a AWS CDK project, how to access the AWS Construct Library, and how to use the AWS CDK Toolkit command\-line tool\.\. +You've read [Getting started with the AWS CDK](getting_started.md)? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. In this process you'll learn about the structure of a AWS CDK project, how to access the AWS Construct Library, and how to use the AWS CDK Toolkit command\-line tool\.\. The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps to synthesize your stack to an AWS CloudFormation template and deploy it\. @@ -529,4 +529,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? From 17013a7a82fb226320c35c5dfc858cf8f07b15c4 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 26 Jun 2020 15:52:41 +0000 Subject: [PATCH 197/655] typo --- doc_source/hello_world.md | 2 +- doc_source/resources.md | 2 +- doc_source/work-with-cdk-python.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 231abfe7..745e052a 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -529,4 +529,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/doc_source/resources.md b/doc_source/resources.md index 5d9699ef..4a5bc02e 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -32,7 +32,7 @@ new sqs.Queue(this, 'MyQueue', { ``` import aws_cdk.aws_sqs as sqs -sqs_Queue(self, "MyQueue", encryption=sqs.QueueEncryption.KMS_MANAGED) +sqs.Queue(self, "MyQueue", encryption=sqs.QueueEncryption.KMS_MANAGED) ``` ------ diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index c0f150dc..2b3006c1 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -154,4 +154,4 @@ You can specify the names of multiple stacks to be synthesized or deployed in a **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file From 35fe3a81d11df0edaa5fa5a91d75b772fd48d929 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 2 Jul 2020 15:32:25 +0000 Subject: [PATCH 198/655] substantial improvements to CodePipeline example --- doc_source/codepipeline_example.md | 468 ++++++++++++++++++----------- doc_source/examples.md | 2 +- doc_source/index.md | 2 +- 3 files changed, 302 insertions(+), 170 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index c5d55cf4..9342787e 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -1,114 +1,219 @@ -# Creating a code pipeline using the AWS CDK +# Creating a pipeline using the AWS CDK -This example creates a code pipeline using the AWS CDK\. +The AWS CDK lets you easily define applications in the AWS Cloud using your programming language of choice\. But creating an application is just the start of the journey\. You also want to make changes to it and deploy them\. You can do this through the **Code** suite of tools: AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline\. Together, they allow you to build what's called a [deployment pipeline](https://aws.amazon.com/getting-started/tutorials/continuous-deployment-pipeline/) for your application\. This example shows how to deploy an AWS Lambda function using such a pipeline\. -The AWS CDK enables you to easily create applications running in the AWS Cloud\. But creating the application is just the start of the journey\. You also want to make changes to it, test those changes, and finally deploy them to your stack\. The AWS CDK enables this workflow by using the **Code\*** suite of AWS tools: AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline\. Together, they allow you to build what's called a [deployment pipeline](https://aws.amazon.com/getting-started/tutorials/continuous-deployment-pipeline/) for your application\. +## How it works -The following example shows how to deploy an AWS Lambda function in a pipeline\. Two stacks are created: one to deploy your Lambda code, and one to define a pipeline to deploy the first stack whenever your Lambda code changes\. Your Lambda code is intended to be in a AWS CodeCommit repository, although you can work through this example without any Lambda code \(the pipeline will fail, but the stack that defines it will deploy\)\. +Our application contains two AWS CDK stacks\. The first stack, `PipelineStack`, defines the pipeline itself\. The second, `LambdaStack`, is used to deploy the Lambda function\. -The Lambda code must be in a directory named `Lambda` in the named AWS CodeCommit repository\. The AWS CDK code does not need to be in a repository\. +The key to this example is that you deploy `PipelineStack` from your own workstation, but `LambdaStack` is deployed by the pipeline; you never deploy it yourself\. +Since the `LambdaStack` is deployed by the pipeline, it must be available to the pipeline \(along with the Lambda code\)\. Therefore, this app and the Lambda function are stored in a CodeCommit repository\. + +The `PipelineStack` contains the definitions of the pipeline, which includes build steps for both the Lambda function and the `LambdaStack`\. + +## Prerequisites + +Beyond having the AWS CDK set up and configured, your workstation needs to be able to push to AWS CodeCommit using Git, which means you need some way of identifying yourself to CodeCommit\. The easiest way to do this is to configure Git credentials for an IAM user, as described in [Setup for HTTPS users using Git credentials](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html)\. + +You can also use the `git-remote-codecommit` Git add\-on or other methods of connecting and authenticating [supported by CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up.html)\. + +Also, make sure you have issued `cdk bootstrap`, as the Amazon S3 bucket in the bootstrap stack is required to deploy a Lambda function with the AWS CDK\. + +## Setting up the project + +To set up a new AWS CDK project in CodeCommit; + +1. [Create a new CodeCommit repository](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html) named `pipeline` using the CodeCommit console or the AWS CLI\. + + if you already have a CodeCommit repository named `pipeline`, you can use another name\. Just make sure you clone it to a directory named pipeline on your local system\. + +1. Clone this new repository to your local computer in a directory named pipeline\. If you are authenticating with an IAM user with Git credentials, copy the HTTPS URL from the CodeCommit console\. \(Other authentication methods require a different URL\.\) + + ``` + git clone CODECOMMIT-REPO-URL pipeline + ``` + + Enter your credentials if prompted for them\. **Note** -The Lambda function is assumed to be written in TypeScript regardless of the language you're using for your AWS CDK app\. To use this example to deploy a Lambda function written in another language, you'll need to modify the pipeline\. This is outside the scope of this example\. +During cloning, Git will warn you that you appear have cloned an empty repository; this is normal and expected\. -To set up a project like this from scratch, follow these instructions\. +1. Change to the pipeline directory and initialize it as a new CDK project, then install the AWS Construct Libraries we'll use in our app\. ------ #### [ TypeScript ] -``` -mkdir pipeline -cd pipeline -cdk init --language typescript -npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline -npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 -``` + ``` + cd pipeline + cdk init --language typescript + npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline + npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 + ``` ------ #### [ JavaScript ] -``` -mkdir pipeline -cd pipeline -cdk init ‐-language javascript -npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline -npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 -``` + ``` + cd pipeline + cdk init ‐-language javascript + npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline + npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 + ``` ------ #### [ Python ] -``` -mkdir pipeline -cd pipeline -cdk init --language python -source .env/bin/activate -pip install -r requirements.txt -pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline -pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_s3 -``` + A couple of commands differ between Windows and Linux or Mac OS\. + + **Linux or Mac OS X** + + ``` + cd pipeline + cdk init --language python + source .env/bin/activate + pip install -r requirements.txt + pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline + pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_s3 + pip freeze | grep -v '-e git' > requirements.txt + ``` + + **Windows** + + ``` + cd pipeline + cdk init --language python + .env\Scripts\activate.bat + pip install -r requirements.txt + pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline + pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_s3 + pip freeze | find /V "-e git" > requirements.txt + ``` ------ #### [ Java ] -``` -mkdir pipeline -cd pipeline -cdk init --language java -``` + ``` + cd pipeline + cdk init --language java + ``` -You can import the resulting Maven project into your Java IDE\. + You can import the resulting Maven project into your Java IDE\. -Using the Maven integration in your IDE \(for example, in Eclipse, right\-click the project and choose **Maven** > **Add Dependency**\), add the following packages in the group `software.amazon.awscdk`\. + Using the Maven integration in your IDE \(for example, in Eclipse, right\-click the project and choose **Maven** > **Add Dependency**\), add the following packages in the group `software.amazon.awscdk`\. -``` -lambda -codedeploy -codebuild -codecommit -codepipeline -codepipeline-actions -s3 -``` + ``` + lambda + codedeploy + codebuild + codecommit + codepipeline + codepipeline-actions + s3 + ``` + + Alternatively, add `` elements like the following to `pom.xml`\. You can copy the existing dependency for the AWS CDK core module and modify it\. For example, a dependency for the AWS Lambda module looks like this\. + + ``` + + software.amazon.awscdk + lambda + ${cdk.version} + + ``` ------ #### [ C\# ] -``` -mkdir pipeline -cd pipeline -cdk init --language csharp -``` + ``` + cd pipeline + cdk init --language csharp + ``` -You can open the file `src/Pipeline.sln` in Visual Studio\. + You can open the file `src/Pipeline.sln` in Visual Studio\. -Choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio and add the following packages\. + Choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio and add the following packages\. -``` -Amazon.CDK.AWS.CodeDeploy -Amazon.CDK.AWS.CodeBuild -Amazon.CDK.AWS.CodeCommit -Amazon.CDK.AWS.CodePipeline -Amazon.CDK.AWS.CodePipeline.Actions -Amazon.CDK.AWS.Lambda -Amazon.CDK.AWS.S3 -``` + ``` + Amazon.CDK.AWS.CodeDeploy + Amazon.CDK.AWS.CodeBuild + Amazon.CDK.AWS.CodeCommit + Amazon.CDK.AWS.CodePipeline + Amazon.CDK.AWS.CodePipeline.Actions + Amazon.CDK.AWS.Lambda + Amazon.CDK.AWS.S3 + ``` + +------ + +1. If a directory named `test` exists, delete it\. We won't be using it in this example, and some of the code in the tests will cause errors because of other changes we'll be making\. ------ +#### [ Linux or Mac OS X ] + + ``` + rm -rf test + ``` + +------ +#### [ Windows ] + + ``` + cd test + del /f /q /s *.* + cd .. + rmdir test + ``` + +------ + +1. Stage all the files in the directory, commit them to your local repository, and push to CodeCommit\. + + ``` + git add --all + git commit -m "initial commit" + git push + ``` + +## Add Lambda code + +1. Create a directory for your AWS Lambda code\. + + ``` + mkdir lambda + ``` -## Lambda stack +1. Place your AWS Lambda function in the new directory\. Our CDK app expects a Lambda function written in TypeScript, with a main file of `index.ts` and a main function named `main()`, regardless of what language the rest of the app is written in\. The function will be built \(transpiled to JavaScript\) by the TypeScript compiler as part of the pipeline\. Some changes will be needed in the Lambda build process if your function is written in another language\. -The first step is to define the AWS CloudFormation stack that will create the Lambda function\. This is the stack that we'll deploy in our pipeline\. + If you don't have a function handy to play with, this one will do: -We'll create a new file to hold this stack\. + ``` + // index.ts + const GREETING = "Hello, AWS!"; + export async function handler(event: any, context: any) { + console.log(GREETING); + return GREETING; + } + ``` -This class includes the `lambdaCode` \(Python: `lambda_code`\) property, which is an instance of the `CfnParametersCode` class\. This property represents the code that is supplied later by the pipeline\. Because the pipeline needs access to the object, we expose it as a public property of our class\. +1. Commit your changes and push\. -The example also uses the CodeDeploy support for blue\-green deployments to Lambda, and the deployment increases the traffic to the new version in 10\-percent increments every minute\. As blue\-green deployment can only operate on aliases, not on the function directly, we create an alias for our function, named `Prod`\. + ``` + git add --all/index.ts + git commit -m "add lambda function" + git push + ``` + +## Define Lambda stack + +Let's define the AWS CloudFormation stack that will create the Lambda function, the stack that we'll deploy in our pipeline\. We'll create a new file to hold this stack\. + +We need some way to get a reference to the Lambda function we'll be deploying\. This code is built by the pipeline, and the pipeline passes us a reference to it as AWS CloudFormation parameters\. We get it using the `fromCfnParameters()` method and store it as an attribute named `lambdaCode`, where it can be picked up by the deployment stage of the pipeline\. + +The example also uses the CodeDeploy support for blue\-green deployments to Lambda, transferring traffic to the new version in 10\-percent increments every minute\. As blue\-green deployment can only operate on aliases, not on the function directly, we create an alias for our function, named `Prod`\. The alias uses a Lambda version obtained using the function's `currentVersion` property\. This ensures that every invocation of the AWS CDK code publishes a new version of the function\. -If the Lambda function needs any other resources when executing, such as an Amazon S3 bucket, Amazon DynamoDB table, or Amazon API Gateway, declare those resources here\. +If the Lambda function needs any other resources when executing, such as an Amazon S3 bucket, Amazon DynamoDB table, or Amazon API Gateway, you'd declare those resources here\. ------ #### [ TypeScript ] @@ -134,10 +239,9 @@ export class LambdaStack extends Stack { runtime: lambda.Runtime.NODEJS_10_X, }); - const version = func.latestVersion; const alias = new lambda.Alias(this, 'LambdaAlias', { aliasName: 'Prod', - version, + version: func.latestVersion, }); new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', { @@ -171,10 +275,9 @@ class LambdaStack extends Stack { runtime: lambda.Runtime.NODEJS_10_X }); - const version = func.latestVersion; const alias = new lambda.Alias(this, 'LambdaAlias', { aliasName: 'Prod', - version + version: func.latestVersion }); new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', { @@ -207,9 +310,8 @@ class LambdaStack(core.Stack): runtime=lambda_.Runtime.NODEJS_10_X, ) - version = func.latest_version - alias = lambda_.Alias(self, "LambdaAlias", - alias_name="Prod", version=version) + alias = lambda_.Alias(self, "LambdaAlias", alias_name="Prod", + version=func.latest_version) codedeploy.LambdaDeploymentGroup(self, "DeploymentGroup", alias=alias, @@ -230,14 +332,9 @@ import software.amazon.awscdk.core.App; import software.amazon.awscdk.core.Stack; import software.amazon.awscdk.core.StackProps; -import software.amazon.awscdk.services.codedeploy.LambdaDeploymentConfig; -import software.amazon.awscdk.services.codedeploy.LambdaDeploymentGroup; - -import software.amazon.awscdk.services.lambda.Alias; -import software.amazon.awscdk.services.lambda.CfnParametersCode; -import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.codedeploy.*; +import software.amazon.awscdk.services.lambda.*; import software.amazon.awscdk.services.lambda.Runtime; -import software.amazon.awscdk.services.lambda.Version; public class LambdaStack extends Stack { @@ -281,7 +378,6 @@ public class LambdaStack extends Stack { File: `src/Pipeline/LambdaStack.cs` ``` -using System; using Amazon.CDK; using Amazon.CDK.AWS.CodeDeploy; using Amazon.CDK.AWS.Lambda; @@ -292,7 +388,8 @@ namespace Pipeline { public readonly CfnParametersCode lambdaCode; - public LambdaStack(App app, string id, StackProps props = null) : base(app, id, props) + public LambdaStack(Construct scope, string id, StackProps props = null) : + base(scope, id, props) { lambdaCode = Code.FromCfnParameters(); @@ -322,21 +419,24 @@ namespace Pipeline ------ -## Pipeline stack +## Define pipeline stack + +Our second stack, `PipelineStack`, contains the code that defines our pipeline\. -The second class, `PipelineStack`, is the stack that contains our pipeline\. +First it needs a reference to the Lambda code it's deploying\. For that, we define a new props interface for it, `PipelineStackProps`\. This extends the standard `StackProps` and is how clients of this class \(including ourselves\) pass the Lambda code that the class needs\. -First it needs a reference to the Lambda code it's deploying\. For that, we define a new props interface for it, `PipelineStackProps`\. \(This isn't necessary in Python, where properties are instead passed as keyword arguments\.\) This extends the standard `StackProps` and is how clients of this class \(including ourselves\) pass the Lambda code that the class needs\. +The name of the CodeCommit repo hosting our source code is also passed in the stack's props\. The `Repository.fromRepositoryName` method is a standard AWS CDK idiom for referencing a resource, such as a CodeCommit repository, that lives outside the AWS CDK code\. -Then comes the Git repository used to store the source code\. In the example, it's hosted by CodeCommit\. The `Repository.fromRepositoryName` method \(Python: `from_repository_name`\) is a standard AWS CDK idiom for referencing a resource, such as a CodeCommit repository, that lives outside the AWS CDK code\. Replace *NameOfYourCodeCommitRepository* with the name of your repository\. +The pipeline has two CodeBuild projects\. The first project synthesizes the AWS CloudFormation template to deploy the Lambda function from the AWS CDK code\. To do that, it installs the AWS CDK Toolkit using `npm`, then any dependencies, and then issues cdk synth command to produce AWS CloudFormation templates in the target directory `dist`\. The `dist/LambdaStack.template.json` file is this step's output\. -The example has two CodeBuild projects\. The first project obtains the AWS CloudFormation template from the AWS CDK code\. To do that, it calls the standard install and build targets for Node\.js, and then calls the cdk synth command\. This produces AWS CloudFormation templates in the target directory `dist`\. Finally, it uses the `dist/LambdaStack.template.json` file as its output\. +The second project builds the Lambda code\. It begins by changing the current directory to `lambda`, which is where the Lambda code lives\. It then installs any dependencies and the TypeScript compiler, then builds the code\. The output is the contents of the `node_modules` directory, plus the `index.js` file\. The Lambda runtime will call the `handler\(\)` function in this file to handle requests\. -The second project does a similar thing, except for the Lambda code\. Because of that, it starts by changing the current directory to `lambda`, which is where we said the Lambda code lives in the repository\. It then invokes the same install and build Node\.js targets as before\. The output is the contents of the node\_modules directory, plus the `index.js` file\. Because `index.handler` is the entry point to the Lambda code, `index.js` must exist, and must export a `handler` function\. This function is called by the Lambda runtime to handle requests\. If your Lambda code uses more files than just `index.js`, add them here\. +**Tip** +This is where you'll need some changes if you use a Lambda function written in a language other than TypeScript\. -Finally, we create our pipeline\. It has a source Action targeting the CodeCommit repository, two build Actions using the previously defined projects, and finally a deploy Action that uses AWS CloudFormation\. It takes the template generated by the AWS CDK build Project \(stored in the `LambdaStack.template.json` file, same as the build specified\), and then uses the Lambda code that was passed in its props to reference the output of the build of our Lambda function\. The deployed Lambda function uses the output of that build as its code\. We have to make sure that the Lambda build output is an input to the AWS CloudFormation action though, and that's why we pass it in the `extraInputs` property \(Python: `extra_inputs`\)\. +Finally, we define our pipeline\. It has a source Action targeting the CodeCommit repository, two build Actions using the previously defined projects, and finally a deploy Action that uses AWS CloudFormation\. It takes the template generated by the AWS CDK build Project \(stored in the `LambdaStack.template.json` file\), passes it to AWS CloudFormation for deployment\. To make the Lambda build output is an input to the AWS CloudFormation action, we pass it in the `extraInputs` property\. -We also change the name of the stack that will be deployed, from `LambdaStack` to `LambdaDeploymentStack`\. The name change isn't required\. We could have left it the same\. +We also change the name of the stack that will be deployed, from `LambdaStack` to `LambdaDeploymentStack`\. This isn't required; it's just an example of how you'd do this if you wanted\. ------ #### [ TypeScript ] @@ -354,6 +454,7 @@ import { App, Stack, StackProps } from '@aws-cdk/core'; export interface PipelineStackProps extends StackProps { readonly lambdaCode: lambda.CfnParametersCode; + readonly repoName: string } export class PipelineStack extends Stack { @@ -361,7 +462,7 @@ export class PipelineStack extends Stack { super(app, id, props); const code = codecommit.Repository.fromRepositoryName(this, 'ImportedRepo', - 'NameOfYourCodeCommitRepository'); + props.repoName); const cdkBuild = new codebuild.PipelineProject(this, 'CdkBuild', { buildSpec: codebuild.BuildSpec.fromObject({ @@ -486,7 +587,7 @@ class PipelineStack extends Stack { super(app, id, props); const code = codecommit.Repository.fromRepositoryName(this, 'ImportedRepo', - 'NameOfYourCodeCommitRepository'); + props.repoName); const cdkBuild = new codebuild.PipelineProject(this, 'CdkBuild', { buildSpec: codebuild.BuildSpec.fromObject({ @@ -496,10 +597,7 @@ class PipelineStack extends Stack { commands: 'npm install' }, build: { - commands: [ - 'npm run build', - 'npm run cdk synth -- -o dist' - ] + commands: 'npm run cdk synth -- -o dist' } }, artifacts: { @@ -513,6 +611,7 @@ class PipelineStack extends Stack { buildImage: codebuild.LinuxBuildImage.STANDARD_2_0 } }); + const lambdaBuild = new codebuild.PipelineProject(this, 'LambdaBuild', { buildSpec: codebuild.BuildSpec.fromObject({ version: '0.2', @@ -520,11 +619,12 @@ class PipelineStack extends Stack { install: { commands: [ 'cd lambda', - 'npm install' + 'npm install', + 'npm install typescript' ] }, build: { - commands: 'npm run build' + commands: 'npx tsc index.ts' } }, artifacts: { @@ -609,22 +709,25 @@ from aws_cdk import (core, aws_codebuild as codebuild, class PipelineStack(core.Stack): - def __init__(self, scope: core.Construct, id: str, *, - lambda_code: lambda_.CfnParametersCode = None, **kwargs) -> None: + def __init__(self, scope: core.Construct, id: str, *, repo_name: str=None, + lambda_code: lambda_.CfnParametersCode=None, **kwargs) -> None: super().__init__(scope, id, **kwargs) code = codecommit.Repository.from_repository_name(self, "ImportedRepo", - "NameOfYourCodeCommitRepository"); + repo_name) cdk_build = codebuild.PipelineProject(self, "CdkBuild", build_spec=codebuild.BuildSpec.from_object(dict( version="0.2", phases=dict( install=dict( - commands="npm install"), + commands=[ + "npm install aws-cdk", + "npm update", + "python -m pip install -r requirements.txt" + ]), build=dict(commands=[ - "npm run build", - "npm run cdk synth -- -o dist"])), + "npx cdk synth -o dist"])), artifacts={ "base-directory": "dist", "files": [ @@ -639,9 +742,11 @@ class PipelineStack(core.Stack): install=dict( commands=[ "cd lambda", - "npm install"]), + "npm install", + "npm install typescript"]), build=dict( - commands="npm run build")), + commands=[ + "npx tsc index.ts"])), artifacts={ "base-directory": "lambda", "files": [ @@ -706,51 +811,39 @@ import java.util.Arrays; import java.util.List; import java.util.HashMap; -import software.amazon.awscdk.core.App; -import software.amazon.awscdk.core.Stack; -import software.amazon.awscdk.core.StackProps; - -import software.amazon.awscdk.services.codebuild.BuildEnvironment; -import software.amazon.awscdk.services.codebuild.BuildSpec; -import software.amazon.awscdk.services.codebuild.LinuxBuildImage; -import software.amazon.awscdk.services.codebuild.PipelineProject; - -import software.amazon.awscdk.services.codecommit.Repository; -import software.amazon.awscdk.services.codecommit.IRepository; - -import software.amazon.awscdk.services.codepipeline.Artifact; +import software.amazon.awscdk.core.*; +import software.amazon.awscdk.services.codebuild.*; +import software.amazon.awscdk.services.codecommit.*; +import software.amazon.awscdk.services.codepipeline.*; import software.amazon.awscdk.services.codepipeline.StageProps; -import software.amazon.awscdk.services.codepipeline.Pipeline; - -import software.amazon.awscdk.services.codepipeline.actions.CloudFormationCreateUpdateStackAction; -import software.amazon.awscdk.services.codepipeline.actions.CodeBuildAction; -import software.amazon.awscdk.services.codepipeline.actions.CodeCommitSourceAction; - -import software.amazon.awscdk.services.lambda.CfnParametersCode; +import software.amazon.awscdk.services.codepipeline.actions.*; +import software.amazon.awscdk.services.lambda.*; public class PipelineStack extends Stack { - // alternate constructor for calls without props. lambdaCode is required. - public PipelineStack(final App scope, final String id, final CfnParametersCode lambdaCode) { - this(scope, id, null, lambdaCode); + // alternate constructor for calls without props. + // lambdaCode and repoName are both required. + public PipelineStack(final App scope, final String id, + final CfnParametersCode lambdaCode, final String repoName) { + this(scope, id, null, lambdaCode, repoName); } @SuppressWarnings("serial") - public PipelineStack(final App scope, final String id, final StackProps props, final CfnParametersCode lambdaCode) { + public PipelineStack(final App scope, final String id, final StackProps props, + final CfnParametersCode lambdaCode, final String repoName) { super(scope, id, props); - IRepository code = Repository.fromRepositoryName(this, "ImportedRepo", - "NameOfYourCodeCommitRepository"); + IRepository code = Repository.fromRepositoryName(this, "ImportedRepo", repoName); PipelineProject cdkBuild = PipelineProject.Builder.create(this, "CDKBuild") .buildSpec(BuildSpec.fromObject(new HashMap() {{ put("version", "0.2"); put("phases", new HashMap() {{ put("install", new HashMap() {{ - put("commands", "npm install"); + put("commands", "npm install aws-cdk"); }}); put("build", new HashMap() {{ - put("commands", Arrays.asList("npm run build", - "npm run cdk synth -- o dist")); + put("commands", Arrays.asList("mvn compile -q -DskipTests", + "npx cdk synth -o dist")); }}); }}); put("artifacts", new HashMap() {{ @@ -767,10 +860,11 @@ public class PipelineStack extends Stack { put("version", "0.2"); put("phases", new HashMap() {{ put("install", new HashMap>() {{ - put("commands", Arrays.asList("cd lambda", "npm install")); + put("commands", Arrays.asList("cd lambda", "npm install", + "npm install typescript")); }}); put("build", new HashMap>() {{ - put("commands", Arrays.asList("npm run build")); + put("commands", Arrays.asList("npx tsc index.ts")); }}); }}); put("artifacts", new HashMap() {{ @@ -848,14 +942,15 @@ namespace Pipeline public class PipelineStackProps : StackProps { public CfnParametersCode LambdaCode { get; set; } + public string RepoName { get; set; } } public class PipelineStack : Stack { - public PipelineStack(App app, string id, PipelineStackProps props = null) + public PipelineStack(Construct scope, string id, PipelineStackProps props = null) : + base(scope, id, props) { - var code = Repository.FromRepositoryName(this, "ImportedRepo", - "NameOfYourCodeCommitRepository"); + var code = Repository.FromRepositoryName(this, "ImportedRepo", props.RepoName); var cdkBuild = new PipelineProject(this, "CDKBuild", new PipelineProjectProps { @@ -866,14 +961,11 @@ namespace Pipeline { ["install"] = new Dictionary { - ["commands"] = "npm install" + ["commands"] = "npm install aws-cdk" }, ["build"] = new Dictionary { - ["commands"] = new string[] { - "npm run build", - "npm run cdk synth -- o dist" - } + ["commands"] = "npx cdk synth -o dist" } }, ["artifacts"] = new Dictionary @@ -887,7 +979,7 @@ namespace Pipeline }), Environment = new BuildEnvironment { - BuildImage = LinuxBuildImage.STANDARD_2_0 + BuildImage = WindowsBuildImage.WINDOWS_BASE_2_0 } }); @@ -903,12 +995,13 @@ namespace Pipeline ["commands"] = new string[] { "cd lambda", - "npm install" + "npm install", + "npm install typescript" } }, ["build"] = new Dictionary { - ["commands"] = "npm run build" + ["commands"] = "npx tsc index.ts" } }, ["artifacts"] = new Dictionary @@ -935,7 +1028,7 @@ namespace Pipeline { Stages = new[] { - new StageProps + new Amazon.CDK.AWS.CodePipeline.StageProps { StageName = "Source", Actions = new [] @@ -948,7 +1041,7 @@ namespace Pipeline }) } }, - new StageProps + new Amazon.CDK.AWS.CodePipeline.StageProps { StageName = "Build", Actions = new [] @@ -969,7 +1062,7 @@ namespace Pipeline }) } }, - new StageProps + new Amazon.CDK.AWS.CodePipeline.StageProps { StageName = "Deploy", Actions = new [] @@ -995,9 +1088,12 @@ namespace Pipeline ## Main program -Finally, we have our main AWS CDK entry point file, which contains our app\. +Finally, we have our main AWS CDK application file\. + +**Note** +If you didn't name your new CodeCommit repository `pipeline`, here's where you'd change it\. Just edit the value of `CODECOMMIT_REPO_NAME`\. -This code is straightforward: it first instantiates the `LambdaStack` class as `LambdaStack`, which is what the AWS CDK build in the pipeline expects\. Then it instantiates the `PipelineStack` class, passing the required Lambda code from the `LambdaStack` object\. +This code is straightforward: it first instantiates the `LambdaStack` class as `LambdaStack`, which is what the AWS CDK build in the pipeline expects\. Then it instantiates the `PipelineStack` class, passing the Lambda code from the `LambdaStack` object\. ------ #### [ TypeScript ] @@ -1007,6 +1103,8 @@ File: `bin/pipeline.ts` ``` #!/usr/bin/env node +const CODECOMMIT_REPO_NAME = "pipeline"; + import { App } from '@aws-cdk/core'; import { LambdaStack } from '../lib/lambda-stack'; import { PipelineStack } from '../lib/pipeline-stack'; @@ -1016,6 +1114,7 @@ const app = new App(); const lambdaStack = new LambdaStack(app, 'LambdaStack'); new PipelineStack(app, 'PipelineDeployingLambdaStack', { lambdaCode: lambdaStack.lambdaCode, + repoName: CODECOMMIT_REPO_NAME }); app.synth(); @@ -1029,6 +1128,8 @@ File: `bin/pipeline.js` ``` #!/usr/bin/env node +const CODECOMMIT_REPO_NAME = "pipeline"; + const { App } = require('@aws-cdk/core'); const { LambdaStack } = require('../lib/lambda-stack'); const { PipelineStack } = require('../lib/pipeline-stack'); @@ -1037,7 +1138,8 @@ const app = new App(); const lambdaStack = new LambdaStack(app, 'LambdaStack'); new PipelineStack(app, 'PipelineDeployingLambdaStack', { - lambdaCode: lambdaStack.lambdaCode + lambdaCode: lambdaStack.lambdaCode, + repoName: CODECOMMIT_REPO_NAME }); app.synth(); @@ -1051,6 +1153,8 @@ File: `app.py` ``` #!/usr/bin/env python3 +CODECOMMIT_REPO_NAME = "pipeline" + from aws_cdk import core from pipeline.pipeline_stack import PipelineStack @@ -1061,7 +1165,8 @@ app = core.App() lambda_stack = LambdaStack(app, "LambdaStack") PipelineStack(app, "PipelineDeployingLambdaStack", - lambda_code=lambda_stack.lambda_code) + lambda_code=lambda_stack.lambda_code, + repo_name=CODECOMMIT_REPO_NAME) app.synth() ``` @@ -1074,14 +1179,17 @@ File: `src/main/java/com/myorg/PipelineApp.java` ``` package com.myorg; -import software.amazon.awscdk.core.App; +import software.amazon.awscdk.core.*; public class PipelineApp { - public static void main(final String argv[]) { + static final String CODECOMMIT_REPO_NAME = "pipeline"; + + public static void main(final String[] argv) { App app = new App(); LambdaStack lambdaStack = new LambdaStack(app, "LambdaStack"); - new PipelineStack(app, "PipelineStack", lambdaStack.getLambdaCode()); + new PipelineStack(app, "PipelineStack", + lambdaStack.getLambdaCode(), CODECOMMIT_REPO_NAME); app.synth(); } @@ -1100,6 +1208,8 @@ namespace Pipeline { class Program { + const string CODECOMMIT_REPO_NAME = "pipeline"; + static void Main(string[] args) { var app = new App(); @@ -1107,7 +1217,8 @@ namespace Pipeline var lambdaStack = new LambdaStack(app, "LambdaStack"); new PipelineStack(app, "PipelineDeployingLambdaStack", new PipelineStackProps { - LambdaCode = lambdaStack.lambdaCode + LambdaCode = lambdaStack.lambdaCode, + RepoName = CODECOMMIT_REPO_NAME }); app.Synth(); @@ -1118,29 +1229,50 @@ namespace Pipeline ------ +Now check this code in to Git and push it to AWS CodeCommit\. + +``` +git add --all +git commit -m "add CDK app" +git push +``` + ## Deploying the pipeline -The final steps is to deploy the pipeline\. +Now we can deploy the pipeline\. ``` cdk deploy PipelineDeployingLambdaStack ``` -The name, **PipelineDeployingLambdaStack**, is the name we used when we instantiated `PipelineStack`\. +The name, `PipelineDeployingLambdaStack`, is the name we used when we instantiated `PipelineStack`\. -**Note** -Don't deploy *LambdaStack*\. This stack is meant to be deployed by the pipeline\. +**Tip** +Rather than typing that whole name out, this is a good place to use a wildcard\! Put quotes around the name pattern to prevent the shell from tyring to expand it\. + +``` +cdk deploy "Pipe*" +``` + +You'll be asked to approve your stack's security changes\. Type **y** to accept them and continue with deployment\. + +Don't deploy `LambdaStack`\. This stack is deployed by the pipeline, and it won't deploy without values provided by the pipeline\. After the deployment finishes, you should have a three\-stage pipeline that looks something like the following\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/pipeline.jpg) -Try making a change to your Lambda function code and push it to the repository\. The pipeline should pick up your change, build it, and deploy it automatically, without any human intervention\. +Try making a change to your Lambda function code and push it to the repository\. The pipeline should pick up your change, build it, and deploy it automatically, without any other action from you\. ## Cleaning up To avoid unexpected AWS charges, destroy your AWS CDK stacks after you're done with this exercise\. +Delete the `LambdaStack` first, then the `PipelineDeployingLambdaStack`\. The IAM role needed to delete `LambdaStack` is provided by `PipelineDeployingLambdaStack`, so if you delete it first, you no longer have permission to destroy `LambdaStack`\. + ``` -cdk destroy '*' -``` \ No newline at end of file +cdk destroy LambdaStack +cdk destroy PipelineDeployingLambdaStack +``` + +Finally, delete your AWS CodeCommit repository from the AWS Console\. \ No newline at end of file diff --git a/doc_source/examples.md b/doc_source/examples.md index 513edae3..40557422 100644 --- a/doc_source/examples.md +++ b/doc_source/examples.md @@ -3,4 +3,4 @@ This topic contains the following examples: + [Creating a serverless application using the AWS CDK](serverless_example.md) Creates a serverless application using Lambda, API Gateway, and Amazon S3\. + [Creating an AWS Fargate service using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. -+ [Creating a code pipeline using the AWS CDK](codepipeline_example.md) Creates a CI/CD pipeline\. \ No newline at end of file ++ [Creating a pipeline using the AWS CDK](codepipeline_example.md) Creates a CI/CD pipeline\. \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index 1a877707..c994ccd2 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -44,7 +44,7 @@ Amazon's trademarks and trade dress may not be used in + [Examples](examples.md) + [Creating a serverless application using the AWS CDK](serverless_example.md) + [Creating an AWS Fargate service using the AWS CDK](ecs_example.md) - + [Creating a code pipeline using the AWS CDK](codepipeline_example.md) + + [Creating a pipeline using the AWS CDK](codepipeline_example.md) + [AWS CDK examples](about_examples.md) + [AWS CDK how-tos](how_tos.md) + [Get a value from an environment variable](get_env_var.md) From e617e2fda4917e0f7ac57512ec391ac988bdce23 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 2 Jul 2020 18:35:39 +0000 Subject: [PATCH 199/655] typo --- doc_source/codepipeline_example.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 9342787e..0e4dd2ea 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -36,7 +36,7 @@ To set up a new AWS CDK project in CodeCommit; Enter your credentials if prompted for them\. **Note** -During cloning, Git will warn you that you appear have cloned an empty repository; this is normal and expected\. +During cloning, Git will warn you that you appear to have cloned an empty repository; this is normal and expected\. 1. Change to the pipeline directory and initialize it as a new CDK project, then install the AWS Construct Libraries we'll use in our app\. From c6af5d01da41dab6ba3c78d316cbd9c345973b64 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 6 Jul 2020 02:11:25 +0000 Subject: [PATCH 200/655] fix Java and C# Deploy step --- doc_source/codepipeline_example.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 0e4dd2ea..0fc8969d 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -848,8 +848,8 @@ public class PipelineStack extends Stack { }}); put("artifacts", new HashMap() {{ put("base-directory", "dist"); + put("files", Arrays.asList("LambdaStack.template.json")); }}); - put("files", Arrays.asList("LambdaStack.template.json")); }})) .environment(BuildEnvironment.builder().buildImage( LinuxBuildImage.STANDARD_2_0).build()) @@ -970,11 +970,11 @@ namespace Pipeline }, ["artifacts"] = new Dictionary { - ["base-directory"] = "dist" - }, - ["files"] = new string[] - { - "LambdaStack.template.json" + ["base-directory"] = "dist", + ["files"] = new string[] + { + "LambdaStack.template.json" + } } }), Environment = new BuildEnvironment From 495f70a30a346bee71954214e2ed323962bc97e0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 6 Jul 2020 02:36:10 +0000 Subject: [PATCH 201/655] update teardown instructions --- doc_source/codepipeline_example.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 0fc8969d..4ee57944 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -1268,7 +1268,9 @@ Try making a change to your Lambda function code and push it to the repository\. To avoid unexpected AWS charges, destroy your AWS CDK stacks after you're done with this exercise\. -Delete the `LambdaStack` first, then the `PipelineDeployingLambdaStack`\. The IAM role needed to delete `LambdaStack` is provided by `PipelineDeployingLambdaStack`, so if you delete it first, you no longer have permission to destroy `LambdaStack`\. +Delete the `LambdaStack` first using the AWS CloudFormation console\. The IAM role needed to delete `LambdaStack` is provided by `PipelineDeployingLambdaStack`, so if you delete it first, you no longer have permission to destroy `LambdaStack`\. + +Then you may delete the `PipelineDeployingLambdaStack`\. ``` cdk destroy LambdaStack From 1f68929eadee31917def4bf7528ce43868740da1 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 6 Jul 2020 02:40:45 +0000 Subject: [PATCH 202/655] fix git add for lambda --- doc_source/codepipeline_example.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 4ee57944..e861daa7 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -198,7 +198,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi 1. Commit your changes and push\. ``` - git add --all/index.ts + git add --all git commit -m "add lambda function" git push ``` From 4817dbfd33c583621d745766c7cd8d397ebee0e9 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 6 Jul 2020 15:32:05 +0000 Subject: [PATCH 203/655] various tweaks and fixes --- doc_source/codepipeline_example.md | 1 + doc_source/getting_started.md | 2 +- doc_source/hello_world.md | 26 ++++++++++++++++---------- doc_source/permissions.md | 2 +- 4 files changed, 19 insertions(+), 12 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index e861daa7..14044bbd 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -1242,6 +1242,7 @@ git push Now we can deploy the pipeline\. ``` +npm run build cdk deploy PipelineDeployingLambdaStack ``` diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index bff88393..46809dfb 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -87,7 +87,7 @@ Bucket bucket = Bucket.Builder.create(self, "MyBucket") #### [ C\# ] ``` -var bucket = Bucket(self, "MyBucket", new BucketProps { +var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-bucket", Versioned = true, WebsiteRedirect = new WebsiteRedirect { diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 745e052a..ff24b117 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -228,7 +228,7 @@ bucket = s3.Bucket(self, ------ #### [ Java ] -In `src/main/java/com/myorg/HelloStack.java`: +In `src/main/java/com/myorg/HelloCdkStack.java`: ``` package com.myorg; @@ -236,12 +236,12 @@ package com.myorg; import software.amazon.awscdk.core.*; import software.amazon.awscdk.services.s3.Bucket; -public class HelloStack extends Stack { - public HelloStack(final Construct scope, final String id) { +public class HelloCdkStack extends Stack { + public HelloCdkStack(final Construct scope, final String id) { this(scope, id, null); } - public HelloStack(final Construct scope, final String id, final StackProps props) { + public HelloCdkStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); Bucket.Builder.create(this, "MyFirstBucket") @@ -253,7 +253,7 @@ public class HelloStack extends Stack { ------ #### [ C\# ] -Update `HelloStack.cs` to look like this\. +Update `HelloCdkStack.cs` to look like this\. ``` using Amazon.CDK; @@ -261,9 +261,9 @@ using Amazon.CDK.AWS.S3; namespace HelloCdk { - public class HelloStack : Stack + public class HelloCdkStack : Stack { - public HelloStack(Construct scope, string id, IStackProps props) : base(scope, id, props) + public HelloCdkStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) { new Bucket(this, "MyFirstBucket", new BucketProps { @@ -340,6 +340,7 @@ Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. Synthesize an AWS CloudFormation template for the app, as follows\. ``` +npm run build cdk synth ``` @@ -379,6 +380,7 @@ The output of `cdk synth` is a perfectly valid AWS CloudFormation template\. You To deploy the stack using AWS CloudFormation, issue: ``` +npm run build cdk deploy ``` @@ -388,7 +390,7 @@ It is optional \(though good practice\) to synthesize before deploying\. The AWS If your code changes have security implications, you'll see a summary of these, and be asked to confirm them before deployment proceeds\. -`cdk deploy` displays progress information as your stack is deployed\. When it's done, the command prompt reappears\. You can go to the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home) and see that it now lists `HelloStack`\. You'll also find `MyFirstBucket` in the Amazon S3 console\. +`cdk deploy` displays progress information as your stack is deployed\. When it's done, the command prompt reappears\. You can go to the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home) and see that it now lists `HelloSCdktack`\. You'll also find `MyFirstBucket` in the Amazon S3 console\. You've deployed your first stack using the AWS CDK—congratulations\! But that's not all there is to the AWS CDK\. @@ -423,6 +425,8 @@ new s3.Bucket(this, 'MyFirstBucket', { ------ #### [ Python ] +Update `hello_cdk/hello_cdk_stack.py` + ``` bucket = s3.Bucket(self, "MyFirstBucket", @@ -433,7 +437,7 @@ bucket = s3.Bucket(self, ------ #### [ Java ] -Update `src/main/java/com/myorg/HelloStack.java`\. +Update `src/main/java/com/myorg/HelloCdkStack.java`\. ``` import software.amazon.awscdk.services.s3.BucketEncryption; @@ -449,7 +453,7 @@ Bucket.Builder.create(this, "MyFirstBucket") ------ #### [ C\# ] -Update `HelloStack.cs`\. +Update `HelloCdkStack.cs`\. ``` new Bucket(this, "MyFirstBucket", new BucketProps @@ -464,6 +468,7 @@ new Bucket(this, "MyFirstBucket", new BucketProps Now we'll use the `cdk diff` command to see the differences between what's already been deployed, and the code we just changed\. ``` +npm run build cdk diff ``` @@ -488,6 +493,7 @@ You can also see that the bucket isn't going to be replaced, but will be updated Now let's deploy\. ``` +npm run build cdk deploy ``` diff --git a/doc_source/permissions.md b/doc_source/permissions.md index 6c0073d2..ee6e638e 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -387,7 +387,7 @@ project.addToRolePolicy(new iam.PolicyStatement({ project = codebuild.Project.from_project_name(self, 'Project', 'ProjectName') # project is imported, so project.role is undefined, and this call has no effect -project.add_to_role_policy(new iam.PolicyStatement( +project.add_to_role_policy(iam.PolicyStatement( effect=iam.Effect.ALLOW, # ... and so on defining the policy ) ``` From 40c48a569b4920f8e16645eb00ac7cdb52eaf009 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 6 Jul 2020 19:06:32 +0000 Subject: [PATCH 204/655] fixes --- doc_source/doc-history.md | 1 + doc_source/hello_world.md | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index f1515aa8..a1582a8d 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -7,6 +7,7 @@ The table below represents significant documentation milestones\. We fix errors | Change | Description | Date | | --- |--- |--- | +| [Improve CodePipeline example](#doc-history) | Update pipeline stack to build in proper language and add more material dealing with the CodeCommit repository\. | July 6, 2020 | | [Improve Getting Started](#doc-history) | Remove extraneous material from Getting Started, use a more conversational tone, incorporate current best practices\. Break out Hello World into its own topic\. | June 17, 2020 | | [Update stability index](#doc-history) | Incorporate the latest definitions of the stability levels for AWS Construct Library modules\. | June 11, 2020 | | [CDK Toolkit versioning](#doc-history) | Add information about cloud assembly versioning and compatibility of the CDK Toolkit \(CLI\) with the AWS Construct Library | April 22, 2020 | diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index ff24b117..ba5a0641 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -406,7 +406,7 @@ Update `lib/hello-cdk-stack.ts` ``` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, - removalPolicy: core.RemovalPolicy.DESTROY + removalPolicy: cdk.RemovalPolicy.DESTROY }); ``` @@ -418,7 +418,7 @@ Update `lib/hello-cdk-stack.js`\. ``` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, - removalPolicy: core.RemovalPolicy.DESTROY + removalPolicy: cdk.RemovalPolicy.DESTROY }); ``` From d53ee403b40e0fc87b520becb9697ab05d011f66 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 6 Jul 2020 21:24:54 +0000 Subject: [PATCH 205/655] update Java dependency info, expand generic object section --- doc_source/hello_world.md | 2 +- doc_source/work-with-cdk-java.md | 63 +++++++++++++++----------------- 2 files changed, 31 insertions(+), 34 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index ba5a0641..1fd957c1 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -146,7 +146,7 @@ If necessary, add the following to the `` container of `pom.xml`, ``` -If you are using a Java IDE, it should have a simpler way to add this dependency to your project\. For example, in Eclipse, you can use the **Dependencies** tab of the POM editor\. See [Using a Java IDE](work-with-cdk-java.md#java-maven-ide-gui) for further instructions\. +If you are using a Java IDE, it should have a simpler way to add this dependency to your project\. For example, in Eclipse, you can use the **Dependencies** tab of the POM editor\. See [Managing AWS construct library modules](work-with-cdk-java.md#java-managemodules) for further instructions\. ------ #### [ C\# ] diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index f6311273..4884dce1 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -30,50 +30,31 @@ If you are using an IDE, you can now open or import the project\. In Eclipse, fo ## Managing AWS construct library modules -Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk` and named for their service\. For example, the Maven artifact ID for Amazon S3 is `s3`\. Its Java package name, for use in import statements, is `software.amazon.awscdk.services.s3`\. +Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk` and named for their service\. For example, the Maven artifact ID for Amazon S3 is `s3`\. Its Java package name, for use in import statements, is `software.amazon.awscdk.services.s3`\. [Search the Maven Central Repository](https://search.maven.org/search?q=software.amazon.awscdk) to find the names of all AWS Construct Module libraries\. **Note** All AWS Construct Library modules used in your project must be the same version\. -### Using a Java IDE - -If you're using an IDE, its Maven integration is probably the simplest way to install AWS Construct Library packages\. For example, in Eclipse: - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/eclipse-maven.png) - -1. Open your project's `pom.xml` file in the Eclipse editor\. - -1. Switch to the editor's **Dependencies** page\. - -1. Click the **Add** button next to the **Dependencies** list\. - -1. Enter the AWS CDK Maven group ID, `software.amazon.awscdk`, in the search field\. - -1. In the search results, find the desired package \(e\.g\. `s3`\) and double\-click it\. \(You may also expand the package and choose a specific version, if you don't want the latest\.\) - -1. Repeat steps 3\-5 for each additional AWS Construct Library package you want to install\. - -You can periodically issue the following command to update your dependencies to the latest version\. Maven updates the version specification in `pom.xml` with the latest version of each specified package available in the Maven Central Repository\. - -``` -mvn versions:use-latest-versions -``` - -### Setting dependencies manually - -If you are not using an IDE, or just want full control over the versions of your dependencies, you can specify the modules that your application depends on by editing `pom.xml` and adding a new `` element in the `` container\. For example, the following `` element specifies the Amazon S3 construct library module: +Specify the modules that your application depends on by editing `pom.xml` and adding a new `` element in the `` container\. For example, the following `` element specifies the Amazon S3 construct library module: ``` software.amazon.awscdk s3 - [1.0,2.0) + ${cdk.version} ``` -The version specifier `[1.0,2.0)` in this example indicates that the latest version between 1\.0 \(inclusive\) and 2\.0 \(exclusive\) will be installed\. Since the AWS CDK uses semantic versioning for stable AWS Construct Library modules, \(see [Versioning](reference.md#versioning)\), this ensures that only newer versions without breaking API changes will be installed\. +**Tip** +If you use a Java IDE, it probably has features for managing Maven dependencies\. We recommend always editing `pom.xml` directly, however, unless you are absolutely sure the IDE's functionality matches what you'd do by hand\. + +The default `pom.xml` defines the variable `cdk.version` to be the version of the AWS CDK that created the project\. You can easily update the version by updating the value of this variable\. -Maven automatically downloads a version of your dependencies that will match the requirements in `pom.xml`, if necessary, the next time your project is built\. +``` +1.XX.Y +``` + +This value can be any valid Maven version specifier\. For example, `[1.XX.Y,2.0)` indicates that any version between the current version 1\.XX\.Y \(inclusive\) and 2\.0 \(exclusive\), may be installed\. However, to avoid mismatched versions, we recommend using a fixed version like 1\.XX and updating it when moving a new AWS CDK release\. ## AWS CDK idioms in Java @@ -105,7 +86,23 @@ When deriving your own construct from an existing construct, you may want to acc ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects or as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Java, objects are represented as `java.util.HashMap`\. In cases where the values are all strings, you can use `HashMap`\. JavaScript arrays are represented as `Object[]` or `String[]` in Java\. +In some places, the AWS CDK uses JavaScript arrays or untyped objects or as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Java, objects are represented as `java.util.HashMap`\. In cases where the values are all strings, you can use `HashMap`\. It is convenient to use double braces to define `HashMap`s\. + +``` +new HashMap() {{ + put("base-directory", "dist"); + put("files", "LambdaStack.template.json"); +}}; +``` + +**Note** +The double\-brace notation \(which technically declares an anonymous inner class\) is sometimes considered an anti\-pattern\. However, its disadvantages are not very relevant to this use case, and it is a reasonably compact way to write what would be object or dictionary literals in other languages\. + +JavaScript arrays are represented as `Object[]` or `String[]` arrays in Java\. The method `Arrays.asList` is convenient for defining short arrays\. + +``` +String[] cmds = Arrays.asList("cd lambda", "npm install", "npm install typescript") +``` ### Missing values @@ -113,7 +110,7 @@ In Java, missing values in AWS CDK objects such as props are represented by `nul ## Building, synthesizing, and deploying -The AWS CDK automatically compiles your app before running it\. However, it can be useful to build your app manually to check for errors and run tests\. You can do this in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn compile` at a command prompt while in your project's root directory\. + Build your app to check for errors and to run tests\. You can do this in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn compile` at a command prompt while in your project's root directory\. Run any tests you've written by running `mvn test` at a command prompt\. From 6faa52a56c2fc4ab7570d473e1134433dc62be1f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 7 Jul 2020 01:16:45 +0000 Subject: [PATCH 206/655] add info about L1 constructs --- doc_source/constructs.md | 143 ++++++++++++++++++++++++++++++- doc_source/work-with-cdk-java.md | 4 +- 2 files changed, 141 insertions(+), 6 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 21b9922b..7a483cea 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -10,9 +10,9 @@ The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html)` class represents an Amazon DynamoDB table\. -There are different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources*\. These constructs represent all of the AWS resources that are available in AWS CloudFormation\. CFN Resources are generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) on a regular basis\. They are named **Cfn***Xyz*, where *Xyz* represents the name of the resource\. For example, [s3\.CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) CFN Resource\. When you use CFN resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying resource model\. +There are different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "level 1"\)\. These constructs directly represent all of the AWS resources that are available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [s3\.CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) CFN Resource\. When you use CFN resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. -The next level of constructs also represent AWS resources, but with a higher\-level, intent\-based API\. They provide the same functionality, but handle much of the details, boilerplate, and glue logic required by CFN constructs\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#add-wbr-lifecycle-wbr-rulerule), which adds a lifecycle rule to the bucket\. +The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#add-wbr-lifecycle-wbr-rulerule), which adds a lifecycle rule to the bucket\. Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs-patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. @@ -223,9 +223,144 @@ public class HelloCdkStack : Stack ------ -## Using constructs +## Using L1 constructs -Once you have defined a stack, you can populate it with resources\. The following example imports the [Amazon S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) module and uses it to define a new Amazon S3 bucket by creating an instance of the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class within the current scope \(`this` or, in Python, `self`\) which, in our case is the `HelloCdkStack` instance\. + L1 constructs are exactly the resources defined by AWS CloudFormation—no more, no less\. You must provide the resource's required configuration yourself\. Here, for example, is how to create an Amazon S3 bucket using the `CfnBucket` class\. \(You'll see a similar definition using the `Bucket` class in the next section\.\) + +------ +#### [ TypeScript ] + +``` +const bucket = new s3.CfnBucket(this, "MyBucket", { + bucketName: "MyBucket" +}); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = new s3.CfnBucket(this, "MyBucket", { + bucketName: "MyBucket" +}); +``` + +------ +#### [ Python ] + +``` +bucket = s3.CfnBucket(self, "MyBucket", bucket_name="MyBucket") +``` + +------ +#### [ Java ] + +``` +CfnBucket bucket = new CfnBucket.Builder().bucketName("MyBucket").build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps +{ + BucketName= "MyBucket" +}); +``` + +------ + +In Python, Java, and C\#, L1 construct properties that aren't simple Booleans, strings, numbers, or containers are represented by types defined as inner classes of the L1 construct\. For example, the optional property `corsConfiguration` of a `CfnBucket` requires a wrapper of type `Cfn.CorsConfigurationProperty`\. Here we are defining `corsConfiguration` on a `CfnBucket` instance\. + +------ +#### [ TypeScript ] + +``` +const bucket = new s3.CfnBucket(this, "MyBucket", { + bucketName: "MyBucket", + corsConfiguration: { + corsRules: [{ + allowedOrigins: ["*"], + allowedMethods: ["*"] + }] + } +}); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = new s3.CfnBucket(this, "MyBucket", { + bucketName: "MyBucket", + corsConfiguration: { + corsRules: [{ + allowedOrigins: ["*"], + allowedMethods: ["*"] + }] + } +}); +``` + +------ +#### [ Python ] + +``` +bucket = CfnBucket(self, "MyBucket", bucket_name="MyBucket", + cors_configuration=CfnBucket.CorsConfigurationProperty( + cors_rules=[CfnBucket.CorsRuleProperty( + allowed_origins=["*"], + allowed_methods=["GET"] + )] + ) +) +``` + +------ +#### [ Java ] + +``` +CfnBucket bucket = CfnBucket.Builder.create(this, "MyBucket") + .bucketName("MyBucket") + .corsConfiguration(new CfnBucket.CorsConfigurationProperty.Builder() + .corsRules(Arrays.asList(new CfnBucket.CorsRuleProperty.Builder() + .allowedOrigins(Arrays.asList("*")) + .allowedMethods(Arrays.asList("GET")) + .build())) + .build()) + .build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps +{ + BucketName = "MyBucket", + CorsConfiguration = new CfnBucket.CorsConfigurationProperty + { + CorsRules = new object[] { + new CfnBucket.CorsRuleProperty + { + AllowedOrigins = new string[] { "*" }, + AllowedMethods = new string[] { "GET" }, + } + } + } +}); +``` + +------ + +**Important** +You can't use L2 property types with L1 constructs, or vice versa\. When working with L1 constructs, always use the type defined inside the L1 construct you're using\. Do not use types from other L1 constructs \(there are some that have the same name, but they are not the same type\)\. +Some of our language\-specific API references currently have errors in the paths to L1 property types, or don't document these classes at all\. We hope to fix this soon\. In the meantime, just remember that these types are always inner classes of the L1 construct they are used with\. + +## Using L2 constructs + +Once you have defined a stack, you can populate it with resources by instantiating constructs\. The following example imports the [Amazon S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) module and uses it to define a new Amazon S3 bucket by creating an instance of the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class within the current scope \(`this` or, in Python, `self`\) which, in our case is the `HelloCdkStack` instance\. ------ #### [ TypeScript ] diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 4884dce1..a33a3547 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -86,7 +86,7 @@ When deriving your own construct from an existing construct, you may want to acc ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects or as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Java, objects are represented as `java.util.HashMap`\. In cases where the values are all strings, you can use `HashMap`\. It is convenient to use double braces to define `HashMap`s\. +In some places, the AWS CDK uses JavaScript arrays or untyped objects or as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Java, objects are represented as `java.util.Map`\. In cases where the values are all strings, you can use `Map`\. It is convenient to use double braces to define `HashMap`s\. ``` new HashMap() {{ @@ -98,7 +98,7 @@ new HashMap() {{ **Note** The double\-brace notation \(which technically declares an anonymous inner class\) is sometimes considered an anti\-pattern\. However, its disadvantages are not very relevant to this use case, and it is a reasonably compact way to write what would be object or dictionary literals in other languages\. -JavaScript arrays are represented as `Object[]` or `String[]` arrays in Java\. The method `Arrays.asList` is convenient for defining short arrays\. +JavaScript arrays are represented as `List` or `List` in Java\. The method `java.util.Arrays.asList` is convenient for defining short `ArrayList`s\. ``` String[] cmds = Arrays.asList("cd lambda", "npm install", "npm install typescript") From d2e0091de628548b58d9597cd802215241b2670d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 7 Jul 2020 03:21:13 +0000 Subject: [PATCH 207/655] re-add build steps since Java doesn't do it automatically yet --- doc_source/ecs_example.md | 72 +++++++++ doc_source/hello_world.md | 216 ++++++++++++++++++++++--- doc_source/serverless_example.md | 180 +++++++++++++++++++++ doc_source/work-with-cdk-csharp.md | 9 +- doc_source/work-with-cdk-java.md | 9 +- doc_source/work-with-cdk-javascript.md | 9 +- doc_source/work-with-cdk-python.md | 9 +- doc_source/work-with-cdk-typescript.md | 9 +- 8 files changed, 486 insertions(+), 27 deletions(-) diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 5846733a..24c9ec26 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -86,10 +86,46 @@ You may now open `src/MyEcsConstruct.sln` in Visual Studio\./ Run the app and confirm that it creates an empty stack\. +------ +#### [ TypeScript ] + +``` +npm run build +cdk synth +``` + +------ +#### [ JavaScript ] + +``` +cdk synth +``` + +------ +#### [ Python ] + ``` cdk synth ``` +------ +#### [ Java ] + +``` +mvn compile +cdk synth +``` + +------ +#### [ C\# ] + +``` +dotnet build src +cdk synth +``` + +------ + You should see a stack like the following, where *CDK\-VERSION* is the version of the CDK and *NODE\-VERSION* is the version of Node\.js\. \(Your output may differ slightly from what's shown here\.\) ``` @@ -344,10 +380,46 @@ Replace the comment at the end of the constructor with the following code\. Save it and make sure it runs and creates a stack\. +------ +#### [ TypeScript ] + +``` +npm run build +cdk synth +``` + +------ +#### [ JavaScript ] + +``` +cdk synth +``` + +------ +#### [ Python ] + ``` cdk synth ``` +------ +#### [ Java ] + +``` +mvn compile +cdk synth +``` + +------ +#### [ C\# ] + +``` +dotnet build src +cdk synth +``` + +------ + The stack is hundreds of lines, so we don't show it here\. The stack should contain one default instance, a private subnet and a public subnet for the three Availability Zones, and a security group\. Deploy the stack\. diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 1fd957c1..9266ea41 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -96,14 +96,89 @@ If you don't specify a template, the default is "app," which is the one we wante If you have Git installed, each project you create using cdk init is also initialized as a Git repository\. We'll ignore that for now, but it's there when you need it\. +## Build the app + +Here's how to build \(compile\) your code to find syntax and type errors\. Try it now, if you like\. It should work perfectly because you haven't yet made any changes to the template code\. + +------ +#### [ TypeScript ] + +``` +npm run build +``` + +------ +#### [ JavaScript ] + +No build step is necessary\. + +------ +#### [ Python ] + +No build step is necessary\. + +------ +#### [ Java ] + +``` +mvn compile +``` + +------ +#### [ C\# ] + +``` +dotnet build src +``` + +------ + +Don't worry about memorizing this command; in this tutorial, we'll provide it when it's needed\. + ## List the stacks in the app Just to verify everything is working correctly, list the stacks in your app\. +------ +#### [ TypeScript ] + ``` +npm run build cdk ls ``` +------ +#### [ JavaScript ] + +``` +cdk ls +``` + +------ +#### [ Python ] + +``` +cdk ls +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk ls +``` + +------ +#### [ C\# ] + +``` +dotnet build src +cdk ls +``` + +------ + If you don't see `HelloCdk`, make sure you named your app's directory `hello-cdk`\. If you didn't, go back to [Create the app](#hello_world_tutorial_create_app) and try again\. ## Add an Amazon S3 bucket @@ -142,11 +217,11 @@ If necessary, add the following to the `` container of `pom.xml`, software.amazon.awscdk s3 - [1.0,2.0) + $(cdk.version) ``` -If you are using a Java IDE, it should have a simpler way to add this dependency to your project\. For example, in Eclipse, you can use the **Dependencies** tab of the POM editor\. See [Managing AWS construct library modules](work-with-cdk-java.md#java-managemodules) for further instructions\. +If you are using a Java IDE, it probably has a simpler way to add this dependency to your project\. Resist temptation and edit `pom.xml` by hand\. ------ #### [ C\# ] @@ -292,58 +367,50 @@ It's interesting to take note of how props are represented in the different supp + In Java, a Builder is provided to pass the props\. \(Two, actually; one for `BucketProps`, and a second for `Bucket` to let you build the construct and its props object in one step\. This code uses the latter\.\) + In C\#, you instantiate a `BucketProps` object using an object initializer and pass it as the third parameter\. -## Build the app +## Synthesize an AWS CloudFormation template -Normally, after making any changes to your code, you'd build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you so you can't forget\. But you can still build manually to catch syntax and type errors\. For reference, here's how\. +Synthesize an AWS CloudFormation template for the app, as follows\. ------ #### [ TypeScript ] ``` npm run build +cdk synth ``` ------ #### [ JavaScript ] -No build step is necessary\. +``` +cdk synth +``` ------ #### [ Python ] -No build step is necessary\. +``` +cdk synth +``` ------ #### [ Java ] ``` mvn compile +cdk synth ``` -**Note** -Instead of issuing `mvn compile`, you can instead press Control\-B in Eclipse\. - ------ #### [ C\# ] ``` dotnet build src +cdk synth ``` -**Note** -Instead of issuing `dotnet build`, you can instead press F6 in Visual Studio\. - ------ -## Synthesize an AWS CloudFormation template - -Synthesize an AWS CloudFormation template for the app, as follows\. - -``` -npm run build -cdk synth -``` - If your app contained more than one stack, you'd need to specify which stack\(s\) to synthesize\. But since it only contains one, the Toolkit knows you must mean that one\. **Tip** @@ -373,17 +440,52 @@ Even if you aren't very familiar with AWS CloudFormation, you should be able to **Note** Every generated template contains a `AWS::CDK::Metadata` resource by default\. The AWS CDK team uses this metadata to gain insight into how the AWS CDK is used, so we can continue to improve it\. For details, including how to opt out of version reporting, see [Version reporting](tools.md#version_reporting)\. -The output of `cdk synth` is a perfectly valid AWS CloudFormation template\. You could take it and deploy it using the AWS CloudFormation console\. But the AWS CDK Toolkit also has that feature built\-in\. +The `cdk synth` generates a perfectly valid AWS CloudFormation template\. You could take it and deploy it using the AWS CloudFormation console\. But the AWS CDK Toolkit also has that feature built\-in\. ## Deploying the stack To deploy the stack using AWS CloudFormation, issue: +------ +#### [ TypeScript ] + ``` npm run build cdk deploy ``` +------ +#### [ JavaScript ] + +``` +cdk deploy +``` + +------ +#### [ Python ] + +``` +cdk deploy +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk deploy +``` + +------ +#### [ C\# ] + +``` +dotnet build src +cdk deploy +``` + +------ + As with `cdk synth`, you don't need to specify the name of the stack since there's only one in the app\. It is optional \(though good practice\) to synthesize before deploying\. The AWS CDK synthesizes your stack before each deployment\. @@ -467,11 +569,46 @@ new Bucket(this, "MyFirstBucket", new BucketProps Now we'll use the `cdk diff` command to see the differences between what's already been deployed, and the code we just changed\. +------ +#### [ TypeScript ] + ``` npm run build cdk diff ``` +------ +#### [ JavaScript ] + +``` +cdk diff +``` + +------ +#### [ Python ] + +``` +cdk diff +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk diff +``` + +------ +#### [ C\# ] + +``` +dotnet build src +cdk diff +``` + +------ + The AWS CDK Toolkit queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares it with the template it synthesized from your app\. The Resources section of the output should look like the following\. ``` @@ -492,11 +629,46 @@ You can also see that the bucket isn't going to be replaced, but will be updated Now let's deploy\. +------ +#### [ TypeScript ] + ``` npm run build cdk deploy ``` +------ +#### [ JavaScript ] + +``` +cdk deploy +``` + +------ +#### [ Python ] + +``` +cdk deploy +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk deploy +``` + +------ +#### [ C\# ] + +``` +dotnet build src +cdk deploy +``` + +------ + Enter y to approve the changes and deploy the updated stack\. The Toolkit updates the bucket configuration as you requested\. ``` diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 8b986b52..865b5d80 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -110,10 +110,46 @@ The important files in the blank project are as follows\. \(We will also be addi Run the app and note that it synthesizes an empty stack\. +------ +#### [ TypeScript ] + +``` +npm run build +cdk synth +``` + +------ +#### [ JavaScript ] + +``` +cdk synth +``` + +------ +#### [ Python ] + +``` +cdk synth +``` + +------ +#### [ Java ] + ``` +mvn compile cdk synth ``` +------ +#### [ C\# ] + +``` +dotnet build src +cdk synth +``` + +------ + You should see output like the following, where *CDK\-VERSION* is the version of the AWS CDK\. ``` @@ -189,10 +225,46 @@ exports.main = async function(event, context) { Save it and be sure the project still results in an empty stack\. We haven't yet wired the Lambda function to the AWS CDK app, so the Lambda asset doesn't appear in the output\. +------ +#### [ TypeScript ] + ``` +npm run build cdk synth ``` +------ +#### [ JavaScript ] + +``` +cdk synth +``` + +------ +#### [ Python ] + +``` +cdk synth +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk synth +``` + +------ +#### [ C\# ] + +``` +dotnet build src +cdk synth +``` + +------ + ## Creating a widget service Add the API Gateway, Lambda, and Amazon S3 packages to the app\. @@ -481,10 +553,46 @@ namespace MyWidgetService Save the app and make sure it still synthesizes an empty stack\. +------ +#### [ TypeScript ] + +``` +npm run build +cdk synth +``` + +------ +#### [ JavaScript ] + +``` +cdk synth +``` + +------ +#### [ Python ] + ``` cdk synth ``` +------ +#### [ Java ] + +``` +mvn compile +cdk synth +``` + +------ +#### [ C\# ] + +``` +dotnet build src +cdk synth +``` + +------ + ## Add the service to the app To add the widget service to our AWS CDK app, we'll need to modify the source file that defines the stack to instantiate the service construct\. @@ -566,10 +674,46 @@ new WidgetService(this, "Widgets"); Be sure the app runs and synthesizes a stack \(we won't show the stack here: it's over 250 lines\)\. +------ +#### [ TypeScript ] + +``` +npm run build +cdk synth +``` + +------ +#### [ JavaScript ] + +``` +cdk synth +``` + +------ +#### [ Python ] + +``` +cdk synth +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk synth +``` + +------ +#### [ C\# ] + ``` +dotnet build src cdk synth ``` +------ + ## Deploy and test the app Before you can deploy your first AWS CDK app containing a lambda function, you must bootstrap your AWS environment\. This creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see the **bootstrap** section of the [AWS CDK tools](tools.md) \(if you've already bootstrapped, you'll get a warning and nothing will change\)\. @@ -851,10 +995,46 @@ File: `src/MyWidgetService/WidgetService.cs` Save and deploy the app\. +------ +#### [ TypeScript ] + ``` +npm run build cdk deploy ``` +------ +#### [ JavaScript ] + +``` +cdk deploy +``` + +------ +#### [ Python ] + +``` +cdk deploy +``` + +------ +#### [ Java ] + +``` +mvn compile +cdk deploy +``` + +------ +#### [ C\# ] + +``` +dotnet build src +cdk deploy +``` + +------ + We can now store, show, or delete an individual widget\. Use the following commands to list the widgets, create the widget **example**, list all of the widgets, show the contents of **example** \(it should show today's date\), delete **example**, and then show the list of widgets again\. ``` diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 8b148092..fcf6fafd 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -156,7 +156,14 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. -You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to specify partial names\. When using wildcards, place quotes around the partial name to avoid having the shell try to expand them to filenames before they are passed to the CDK Toolkit\. + +``` +cdk sytnh "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. +``` **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index a33a3547..9efd3f24 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -118,7 +118,14 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. -You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to specify partial names\. When using wildcards, place quotes around the partial name to avoid having the shell try to expand them to filenames before they are passed to the CDK Toolkit\. + +``` +cdk sytnh "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. +``` **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 623339b3..00809246 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -85,7 +85,14 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. -You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to specify partial names\. When using wildcards, place quotes around the partial name to avoid having the shell try to expand them to filenames before they are passed to the CDK Toolkit\. + +``` +cdk sytnh "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. +``` **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 2b3006c1..6a1e013c 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -149,7 +149,14 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. -You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to specify partial names\. When using wildcards, place quotes around the partial name to avoid having the shell try to expand them to filenames before they are passed to the CDK Toolkit\. + +``` +cdk sytnh "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. +``` **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index 33a3a93e..ee4703c4 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -85,7 +85,14 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. -You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to specify partial names\. When using wildcards, place quotes around the partial name to avoid having the shell try to expand them to filenames before they are passed to the CDK Toolkit\. + +``` +cdk sytnh "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. +``` **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. From 611eeead703824220fb6ec2272786ace28ce71e7 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 7 Jul 2020 03:25:11 +0000 Subject: [PATCH 208/655] tweak --- doc_source/hello_world.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 9266ea41..7f1dfeec 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -211,7 +211,7 @@ pip install aws-cdk.aws-s3 ------ #### [ Java ] -If necessary, add the following to the `` container of `pom.xml`, where *CDK\-VERSION* is the version of the AWS CDK\. +Add the following to the `` container of `pom.xml`\. ``` From e22fde52bc8eee7ba308c1b28a4eb8b287268791 Mon Sep 17 00:00:00 2001 From: Steve Gordon Date: Tue, 7 Jul 2020 07:28:52 +0100 Subject: [PATCH 209/655] Fix typo in code sample --- doc_source/work-with-cdk-csharp.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index fcf6fafd..8b0641d9 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -161,11 +161,11 @@ You can specify the names of multiple stacks to be synthesized or deployed in a You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to specify partial names\. When using wildcards, place quotes around the partial name to avoid having the shell try to expand them to filenames before they are passed to the CDK Toolkit\. ``` -cdk sytnh "Stack?" # Stack1, StackA, etc. +cdk synth "Stack?" # Stack1, StackA, etc. cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. ``` **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. From adc2fdd4d7d187ebb12aabafc06103fd85490a5f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 7 Jul 2020 15:12:04 +0000 Subject: [PATCH 210/655] tweaks --- doc_source/constructs.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 7a483cea..f257a637 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -225,7 +225,9 @@ public class HelloCdkStack : Stack ## Using L1 constructs - L1 constructs are exactly the resources defined by AWS CloudFormation—no more, no less\. You must provide the resource's required configuration yourself\. Here, for example, is how to create an Amazon S3 bucket using the `CfnBucket` class\. \(You'll see a similar definition using the `Bucket` class in the next section\.\) +Once you have defined a stack, you can populate it with resources by instantiating constructs\. First, we'll do it with an L1 construct\. + +L1 constructs are exactly the resources defined by AWS CloudFormation—no more, no less\. You must provide the resource's required configuration yourself\. Here, for example, is how to create an Amazon S3 bucket using the `CfnBucket` class\. \(You'll see a similar definition using the `Bucket` class in the next section\.\) ------ #### [ TypeScript ] @@ -355,12 +357,12 @@ var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps ------ **Important** -You can't use L2 property types with L1 constructs, or vice versa\. When working with L1 constructs, always use the type defined inside the L1 construct you're using\. Do not use types from other L1 constructs \(there are some that have the same name, but they are not the same type\)\. -Some of our language\-specific API references currently have errors in the paths to L1 property types, or don't document these classes at all\. We hope to fix this soon\. In the meantime, just remember that these types are always inner classes of the L1 construct they are used with\. +You can't use L2 property types with L1 constructs, or vice versa\. When working with L1 constructs, always use the types defined inside the L1 construct you're using\. Do not use types from other L1 constructs \(some may have the same name, but they are not the same type\)\. +Some of our language\-specific API references currently have errors in the paths to L1 property types, or don't document these classes at all\. We hope to fix this soon\. In the meantime, just remember that such types are always inner classes of the L1 construct they are used with\. ## Using L2 constructs -Once you have defined a stack, you can populate it with resources by instantiating constructs\. The following example imports the [Amazon S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) module and uses it to define a new Amazon S3 bucket by creating an instance of the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class within the current scope \(`this` or, in Python, `self`\) which, in our case is the `HelloCdkStack` instance\. +The following example defines an Amazon S3 bucket by creating an instance of the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class, an L2 construct\. ------ #### [ TypeScript ] From ddf6f76dfe720ab929be89f5c601b380a283478a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 7 Jul 2020 15:46:07 +0000 Subject: [PATCH 211/655] update shared content --- doc_source/work-with-cdk-csharp.md | 11 ++++++++--- doc_source/work-with-cdk-java.md | 11 ++++++++--- doc_source/work-with-cdk-javascript.md | 11 ++++++++--- doc_source/work-with-cdk-python.md | 11 ++++++++--- doc_source/work-with-cdk-typescript.md | 11 ++++++++--- 5 files changed, 40 insertions(+), 15 deletions(-) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index fcf6fafd..c2cecb41 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -156,12 +156,17 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. -You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. -You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to specify partial names\. When using wildcards, place quotes around the partial name to avoid having the shell try to expand them to filenames before they are passed to the CDK Toolkit\. +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes; otherwise, the shell may try to expand \("glob"\) it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` -cdk sytnh "Stack?" # Stack1, StackA, etc. +cdk synth "Stack?" # Stack1, StackA, etc. cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. ``` diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 9efd3f24..a32a319a 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -118,12 +118,17 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. -You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. -You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to specify partial names\. When using wildcards, place quotes around the partial name to avoid having the shell try to expand them to filenames before they are passed to the CDK Toolkit\. +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes; otherwise, the shell may try to expand \("glob"\) it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` -cdk sytnh "Stack?" # Stack1, StackA, etc. +cdk synth "Stack?" # Stack1, StackA, etc. cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. ``` diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 00809246..74408a10 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -85,12 +85,17 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. -You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. -You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to specify partial names\. When using wildcards, place quotes around the partial name to avoid having the shell try to expand them to filenames before they are passed to the CDK Toolkit\. +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes; otherwise, the shell may try to expand \("glob"\) it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` -cdk sytnh "Stack?" # Stack1, StackA, etc. +cdk synth "Stack?" # Stack1, StackA, etc. cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. ``` diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 6a1e013c..d541b83a 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -149,12 +149,17 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. -You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. -You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to specify partial names\. When using wildcards, place quotes around the partial name to avoid having the shell try to expand them to filenames before they are passed to the CDK Toolkit\. +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes; otherwise, the shell may try to expand \("glob"\) it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` -cdk sytnh "Stack?" # Stack1, StackA, etc. +cdk synth "Stack?" # Stack1, StackA, etc. cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. ``` diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index ee4703c4..f9f8dce0 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -85,12 +85,17 @@ The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. -You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, its name is assumed and you do not need to specify it\. +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. -You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to specify partial names\. When using wildcards, place quotes around the partial name to avoid having the shell try to expand them to filenames before they are passed to the CDK Toolkit\. +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes; otherwise, the shell may try to expand \("glob"\) it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` -cdk sytnh "Stack?" # Stack1, StackA, etc. +cdk synth "Stack?" # Stack1, StackA, etc. cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. ``` From 36ffe5dbe789820aab42af322e864324ebdaf95c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 8 Jul 2020 23:16:33 +0000 Subject: [PATCH 212/655] fixes --- doc_source/about_examples.md | 2 +- doc_source/hello_world.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/about_examples.md b/doc_source/about_examples.md index 4ebced7b..ccf624e9 100644 --- a/doc_source/about_examples.md +++ b/doc_source/about_examples.md @@ -2,4 +2,4 @@ For more examples of AWS CDK stacks and apps in your favorite supported programming language, see: + The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repository on GitHub -+ The [AWS Code Sample Catalog](https://docs.aws.amazon.com/code-samples/latest/catalog/welcome.html)\. \ No newline at end of file ++ The [AWS Code Example Repository](https://github.com/awsdocs/aws-doc-sdk-examples)\. \ No newline at end of file diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 7f1dfeec..a072e598 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -508,7 +508,7 @@ Update `lib/hello-cdk-stack.ts` ``` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, - removalPolicy: cdk.RemovalPolicy.DESTROY + removalPolicy: core.RemovalPolicy.DESTROY }); ``` @@ -520,7 +520,7 @@ Update `lib/hello-cdk-stack.js`\. ``` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, - removalPolicy: cdk.RemovalPolicy.DESTROY + removalPolicy: core.RemovalPolicy.DESTROY }); ``` From 60b19607aeeee9c0e42ff30c7fdea7d257064903 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 8 Jul 2020 23:27:18 +0000 Subject: [PATCH 213/655] cdk, not cli --- doc_source/reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/reference.md b/doc_source/reference.md index 441a4e26..ba78d3c6 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -13,7 +13,7 @@ This compatibility promise does not apply to APIs under active development, whic ### AWS CDK Toolkit \(CLI\) compatibility -The AWS CDK Toolkit \(that is, the `cli` command line command\) is *always* compatible with construct libraries of a semantically *lower* or *equal* version number\. It is, therefore, always safe to upgrade the AWS CDK Toolkit within the same major version\. +The AWS CDK Toolkit \(that is, the `cdk` command line command\) is *always* compatible with construct libraries of a semantically *lower* or *equal* version number\. It is, therefore, always safe to upgrade the AWS CDK Toolkit within the same major version\. The AWS CDK Toolkit may be, but is *not always*, compatible with construct libraries of a semantically *higher* version, depending on whether the same cloud assembly schema version is employed by the two components\. The AWS CDK framework generates a cloud assembly during synthesis; the AWS CDK Toolkit consumes it for deployment\. The schema that defines the format of the cloud assembly is strictly specified and versioned\. AWS construct libraries using a given cloud assembly schema version are compatible with AWS CDK toolkit versions using that schema version or later, which may include releases of the AWS CDK Toolkit *older than* a given construct library release\. From 2d105edcde2828610216076e163fb94ad433844a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Jul 2020 03:29:26 +0000 Subject: [PATCH 214/655] revamp Tools topic and CLI doc in particular --- doc_source/assets.md | 2 +- doc_source/cli.md | 356 +++++++++++++++++++ doc_source/environments.md | 2 +- doc_source/getting_started.md | 2 +- doc_source/hello_world.md | 2 +- doc_source/index.md | 3 + doc_source/parameters.md | 2 +- doc_source/sam.md | 74 ++++ doc_source/tools.md | 450 +------------------------ doc_source/vscode.md | 3 + doc_source/work-with-cdk-csharp.md | 2 +- doc_source/work-with-cdk-java.md | 2 +- doc_source/work-with-cdk-javascript.md | 2 +- doc_source/work-with-cdk-python.md | 2 +- doc_source/work-with-cdk-typescript.md | 2 +- 15 files changed, 451 insertions(+), 455 deletions(-) create mode 100644 doc_source/cli.md create mode 100644 doc_source/sam.md create mode 100644 doc_source/vscode.md diff --git a/doc_source/assets.md b/doc_source/assets.md index 19c668ec..bc677522 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -868,7 +868,7 @@ In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.am ## AWS CloudFormation resource metadata **Note** -This section is relevant only for construct authors\. In certain situations, tools need to know that a certain CFN resource is using a local asset\. For example, you can use the AWS SAM CLI to invoke Lambda functions locally for debugging purposes\. See [SAM CLI](tools.md#sam) for details\. +This section is relevant only for construct authors\. In certain situations, tools need to know that a certain CFN resource is using a local asset\. For example, you can use the AWS SAM CLI to invoke Lambda functions locally for debugging purposes\. See [SAM CLI](sam.md) for details\. To enable such use cases, external tools consult a set of metadata entries on AWS CloudFormation resources: + `aws:asset:path` – Points to the local path of the asset\. diff --git a/doc_source/cli.md b/doc_source/cli.md new file mode 100644 index 00000000..868abfe9 --- /dev/null +++ b/doc_source/cli.md @@ -0,0 +1,356 @@ +# AWS CDK Toolkit \(`cdk` command\) + +The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting with your AWS CDK app\. It executes the your AWS CDK app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. It also provides other features that are useful for creating and working with AWS CDK projects\. This topic contains information on common use cases of the CDK Toolkit\. + +## Toolkit commands + +All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(`list`, `synthesize`, `deploy`, etc\.\)\. Some subcommands have a shorter version \(`ls`, `synth`, etc\.\) that is equivalent\. Options and arguments follow the subcommand in any order\. The available commands are summarized here\. + + +| Command | Function | +| --- | --- | +| cdk list \(ls\) | Lists the stacks in the app | +| cdk synthesize \(synth\) | Synthesizes and prints the CloudFormation template for the specified stack\(s\) | +| cdk bootstrap | Deploys the CDK Toolkit stack, required to deploy stacks containing assets | +| cdk deploy | Deploys the specified stack\(s\) | +| cdk destroy | Destroys the specified stack\(s\) | +| cdk diff | Compares the specified stack with the deployed stack or a local CloudFormation template | +| cdk metadata | Displays metadata about the specified stack | +| cdk init | Creates a new CDK project in the current directory from a specified template | +| cdk context | Manages cached context values | +| cdk docs \(doc\) | Opens the CDK API reference in your browser | +| cdk doctor | Checks your CDK project for potential problems | + +## Built\-in help + +The AWS CDK Toolkit has integrated help\. You can see general help about the utility and a list of the provided subcommands by issuing: + +``` +cdk --help +``` + +To see help for a particular subcommand, for example `deploy`, specify it before the `--help` flag\. + +``` +cdk deploy --help +``` + +Issue `cdk version` to display the version of the AWS CDK Toolkit\. Provide this information when requesting support\. + +## Version reporting + +To gain insight into how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. + +By default, the AWS CDK reports the name and version of the following NPM modules that are loaded at synthesis time: ++ AWS CDK core module ++ AWS Construct Library modules ++ AWS Solutions Constructs module + +The `AWS::CDK::Metadata` resource looks something like the following\. + +``` +CDKMetadata: + Type: "AWS::CDK::Metadata" + Properties: + Modules: "@aws-cdk/core=X.YY.Z,@aws-cdk/s3=X.YY.Z,@aws-solutions-consturcts/aws-apigateway-lambda=X.YY.Z" +``` + +To opt out of version reporting, use one of the following methods: ++ Use the cdk command with the \-\-no\-version\-reporting argument to opt out for a single command\. + + ``` + cdk --no-version-reporting synth + ``` + + Remember, the AWS CDK Toolkit synthesizes fresh templates before deploying, so you should also add `--no-version-reporting` to `cdk deploy` commands\. ++ Set versionReporting to **false** in `./cdk.json` or `~/.cdk.json`\. This opts out unless you opt in by specifying `--version-reporting` on an individual command\. + + ``` + { + "app": "...", + "versionReporting": false + } + ``` + +## Specifying the environment + + In AWS CDK terms, the [Environment](environments.md) consists of a region and AWS credentials valid in that region\. The CDK Toolkit needs credentials in order to query your AWS account and to deploy CloudFormation templates\. + +**Important** +We strongly recommend against using your AWS root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. + +If you have the AWS CLI installed, the easiest way to satisfy this requirement is to install the AWS CLI and issue the following command: + +``` +aws configure +``` + +Provide your AWS access key ID, secret access key, and default region when prompted\. + +You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(Linux or Mac\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. ++ In `~/.aws/config` or `%USERPROFILE%\.aws\config` + + ``` + [default] + region=us-west-2 + ``` ++ In `~/.aws/credentials` or `%USERPROFILE%\.aws\credentials` + + ``` + [default] + aws_access_key_id=AKIAI44QH8DHBEXAMPLE + aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY + ``` + +Besides specifying AWS credentials and a region under the `[default]` section, you can also put them in a `[profile NAME]` section, where *NAME* is the name of the profile\. You can add any number of named profiles, with or without a `[default]` section\. Be sure to add the same profile sections to both the configuration and credentials files\. + +**Tip** +Don't name a profile `default`\. That's just confusing\. + +Use the `--profile` flag to choose a set of credentials and default region from these configuration files for a given command\. + +``` +cdk deploy --profile test PipelineStack +``` + +Instead of the configuration file, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. + +You may optionally use the `--role-arn` \(or `-r`\) option to specify the ARN of an IAM role that should be used for deployment\. This role must be assumable by the AWS account being used\. + +## Specifying the app command + +Many features of the CDK Toolkit require one or more AWS CloudFormation templates be synthesized, which in turn requires running your application\. Since the AWS CDK supports programs written in a variety of languages, it uses a configuration option to specify the exact command necessary to run your app\. This option can be specified in two ways\. + +First, and most commonly, it can be specified using the `app` key inside the file `cdk.json`, which is in the main directory of your AWS CDK project\. The CDK Toolkit provides an appropriate command when creating a new project with `cdk init`\. Here is the `cdk.json` from a fresh TypeScript project, for instance\. + +``` +{ + "app": "npx ts-node bin/hello-cdk.ts" +} +``` + +The CDK Toolkit looks for `cdk.json` in the current working directory when attempting to run your app, so you might keep a shell open in your project's main directory for issuing CDK Toolkit commands\. + +The CDK Toolkit also looks for the app key in `~/.cdk.json` \(that is, in your home directory\) if it can't find it in `./cdk.json`\. Adding the app command here can be useful if you usually work with CDK code in the same language, as it does not require you to be in the app's main directory when you run a `cdk` command\. + +If you are in some other directory, or if you want to run your app via a command other than the one in `cdk.json`, you can use the `--app` \(or `-a`\) option to specify it\. + +``` +cdk --app "npx ts-node bin/hello-cdk.ts" ls +``` + +## Specifying stacks + +Many CDK Toolkit commands \(for example, `cdk deploy`\) work on stacks defined in your app\. If your app contains only one stack, the CDK Toolkit assumes you mean that one if you don't specify a stack explicitly\. + +Otherwise, you must specify the stack or stacks you want to work with\. You can do this by specifying the desired stacks by name individually on the command line\. + +``` +cdk synth PipelineStack LambdaStack +``` + +You may also use wildcards to specify names that match a pattern\. ++ ? matches any single character ++ \* matches any number of characters + +When using wildcards, enclose the pattern in quotes\. If you don't, your shell may try to expand the pattern to the names of files in the current directory\. At best, this won't do what you expect; at worst, you could deploy stacks you didn't intend to\. + +``` +cdk synth "*Stack" # PipelineStack, LambdaStack, etc. +cdk synth "Stack?" # StackA, StackB, Stack1, etc. +cdk synth "*" # All stacks in the app +``` + +**Note** +The CDK Toolkit does not guarantee that stacks are processed in the specified order\. If for some reason the order of the stacks is important, use multiple `cdk` commands\. + +## Bootstrapping your AWS environment + +Stacks that contain [Assets](assets.md) or large AWS Lambda functions require special dedicated AWS CDK resources to be provisioned\. Currently, this is only an Amazon S3 bucket\. The `cdk bootstrap` command creates the necessary resources for you\. You only need to bootstrap if you are deploying a stack that requires these dedicated resources\. + +**Important** +Each region to which you deploy such a stack must be bootstrapped separately\. + +You may incur charges for what the AWS CDK stores in the bucket\. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK\. From time to time, then, you might want to clear out the bucket from the Amazon S3 console\. + +You can use the `--bootstrap-bucket-name` option of `cdk bootstrap` to specify the name of the bootstrap bucket, if the default \(`StagingBucket`\) is not suitable for some reason\. You can use the `--toolkit-stack-name` option if the standard name of the stack itself \(`CDKToolkit`\) is not suitable\. + +## Creating a new app + +To create a new app, create a directory for it, then, inside the directory, issue `cdk init`\. + +``` +mkdir my-cdk-app +cd my-cdk-app +cdk init TEMPLATE --language LANGUAGE +``` + +The supported languages \(*LANGUAGE*\) are: + + +| Code | Language | +| --- | --- | +| typescript | TypeScript | +| javascript | JavaScript | +| python | Python | +| java | Java | +| csharp | C\# | + +*TEMPLATE* is an optional template\. If the desired template is *app*, the default, you may omit it\. The available templates are: + +| | | +| --- |--- | +| app \(default\) | Creates an empty AWS CDK app\. | +| sample\-app | Creates an AWS CDK app with a stack containing an Amazon SQS queue and an Amazon SNS topic\. | + +The templates use the name of the project folder to generate names for files and classes inside your new app\. + +## Synthesizing stacks + +The `cdk synthesize` command \(almost always abbreviated `synth`\) synthesizes a stack defined in your app into a CloudFormation template\. + +``` +cdk synth # if app contains only one stack +cdk synth MyStack +cdk synth Stack1 Stack2 +cdk synth "*" # all stacks in app +``` + +**Note** +The CDK Toolkit actually runs your app and synthesizes fresh templates before most operations \(e\.g\. when deploying or comparing stacks\)\. These templates are stored by default in the cdk\.out directory\. The `cdk synth` command simply prints the generated templates for the specified stack\(s\)\. + +See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. + +**Specifying context values** +Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. + +``` +# specify a single context value +cdk synth –context key=value MyStack + +# specify multiple context values (any number) +cdk synth --context key1=value1 --context key2=value2 MyStack +``` + +When deploying multiple stacks, the specified context values are passed to all of them\. If you wish, you may specify different values for each stack by prefixing the stack name to the context value\. + +``` +# different context values for each stack +cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 +``` + +**Specifying display format** +By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. + +``` +cdk synth –json MyStack +``` + +**Specifying output directory** +Add the \-\-output \(\-o\) option to write the synthesized templates to a directory other than cdk\.out\. + +``` +cdk synth –output=~/templates +``` + +## Deploying stacks + +The `cdk deploy` subcommand deploys the specified stack\(s\) to your AWS account\. + +``` +cdk deploy # if app contains only one stack +cdk deploy MyStack +cdk deploy Stack1 Stack2 +cdk deploy "*" # all stacks in app +``` + +**Note** +The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates before deploying anything\. Therefore, most command line options you can use with `cdk synth` \(for example, `--context`\) can also be used with `cdk deploy`\. + +See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. + +**Specifying AWS CloudFormation parameters** +The AWS CDK Toolkit supports specifying parameters at deployment\. You may provide these on the command line following the `--parameters` flag\. + +``` +cdk deploy MyStack --parameters uploadBucketName=UploadBucket +``` + +To define multiple parameters, use multiple `--parameters` flags\. + +``` +cdk deploy MyStack --parameters uploadBucketName=UpBucket --parameters downloadBucketName=DownBucket +``` + +If you are deploying multiple stacks, you can specify a different value of each parameter for each stack by prefixing the name of the parameter with the stack name and a colon\. Otherwise, the same value is passed to all stacks\. + +``` +cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket --parameters YourStack:uploadBucketName=UpBucket +``` + +By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. + +**Specifying outputs file** +If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. + +``` +cdk deploy –output-file outputs.json MyStack +``` + +## Security\-related changes + +To protect you against unintended changes that affect your security posture, the AWS CDK Toolkit prompts you to approve security\-related changes before deploying them\. + +You can change the level of change that requires approval by specifying: + +``` +cdk deploy --require-approval LEVEL +``` + +*LEVEL* can be one of the following: + + +| Term | Meaning | +| --- | --- | +| never | Approval is never required | +| any\-change | Requires approval on any IAM or security\-group\-related change | +| broadening \(default\) | Requires approval when IAM statements or traffic rules are added; removals don't require approval | + +The setting can also be configured in the `cdk.json` file\. + +``` +{ + "app": "...", + "requireApproval": "never" +} +``` + +## Comparing stacks + +The `cdk diff` command compares the current version of a stack defined in your app with the already\-deployed version, or with a saved AWS CloudFormation template, and displays a list of differences\. + +``` +[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 + ├─ [~] DeletionPolicy + │ ├─ [-] Retain + │ └─ [+] Delete + └─ [~] UpdateReplacePolicy + ├─ [-] Retain + └─ [+] Delete +``` + +To compare your app's stack\(s\) with the existing deployment: + +``` +cdk diff MyStack +``` + +To compare your app's stack\(s\) with a saved CloudFormation template: + +``` +cdk diff --template ~/stacks/MyStack.old MyStack +``` + +## Help us help you + +Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you\. Please click **Provide feedback** below and let us know\! Providing your e\-mail address is optional, but very helpful in case we have further questions\. \(We'll keep it to ourselves\.\) \ No newline at end of file diff --git a/doc_source/environments.md b/doc_source/environments.md index 353e789f..f7d193af 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -7,7 +7,7 @@ If you don't specify an environment when you define a stack, the stack is said t **Note** In an environment\-agnostic stack, any constructs that use availability zones will see two of them\. This allows the stack to be deployed to almost any region, since nearly all regions have at least two availability zones\. The only exception is Osaka \(`ap-northeast-3`\), which has one\. -When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Toolkit \(`cdk`\)](tools.md#cli) for details\. +When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Toolkit \(`cdk` command\)](cli.md) for details\. For production stacks, we recommend that you explicitly specify the environment for each stack in your app using the `env` property\. The following example specifies different environments for its two different stacks\. diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 46809dfb..ad76ec5f 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -200,7 +200,7 @@ cdk --version ## AWS CDK tools -We've already been using the AWS CDK Toolkit, also known as the Command Line Interface \(CLI\)\. It's the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CDK templates it generates\. It also has deployment, diff, deletion, and troubleshooting capabilities\. For more information, see cdk \-\-help or [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. +We've already been using the AWS CDK Toolkit, also known as the Command Line Interface \(CLI\)\. It's the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CDK templates it generates\. It also has deployment, diff, deletion, and troubleshooting capabilities\. For more information, see cdk \-\-help or [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open\-source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the plug\-in](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index a072e598..2c0fa575 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -438,7 +438,7 @@ Resources: Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for an `AWS::S3::Bucket` and see how the versioning configuration was translated\. **Note** -Every generated template contains a `AWS::CDK::Metadata` resource by default\. The AWS CDK team uses this metadata to gain insight into how the AWS CDK is used, so we can continue to improve it\. For details, including how to opt out of version reporting, see [Version reporting](tools.md#version_reporting)\. +Every generated template contains a `AWS::CDK::Metadata` resource by default\. The AWS CDK team uses this metadata to gain insight into how the AWS CDK is used, so we can continue to improve it\. For details, including how to opt out of version reporting, see [Version reporting](cli.md#version_reporting)\. The `cdk synth` generates a perfectly valid AWS CloudFormation template\. You could take it and deploy it using the AWS CloudFormation console\. But the AWS CDK Toolkit also has that feature built\-in\. diff --git a/doc_source/index.md b/doc_source/index.md index c994ccd2..8108b295 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -56,6 +56,9 @@ Amazon's trademarks and trade dress may not be used in + [Set a CloudWatch alarm](how_to_set_cw_alarm.md) + [Get a value from a context variable](get_context_var.md) + [AWS CDK tools](tools.md) + + [AWS CDK Toolkit (cdk command)](cli.md) + + [AWS Toolkit for Visual Studio code](vscode.md) + + [SAM CLI](sam.md) + [Testing constructs](testing.md) + [Security for the AWS Cloud Development Kit (AWS CDK)](security.md) + [Identity and access management for the AWS Cloud Development Kit (AWS CDK)](security-iam.md) diff --git a/doc_source/parameters.md b/doc_source/parameters.md index 13699ee7..b4e572d6 100644 --- a/doc_source/parameters.md +++ b/doc_source/parameters.md @@ -205,4 +205,4 @@ If you are deploying multiple stacks, you can specify a different value of each cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket --parameters YourStack:uploadBucketName=UpBucket ``` -By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the \-\-no\-previous\-parameters flag to require all parameters to be specified\. \ No newline at end of file +By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the `--no-previous-parameters flag` to require all parameters to be specified\. \ No newline at end of file diff --git a/doc_source/sam.md b/doc_source/sam.md new file mode 100644 index 00000000..cefecfdb --- /dev/null +++ b/doc_source/sam.md @@ -0,0 +1,74 @@ +# SAM CLI + +This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. + +1. The first step is to create a AWS CDK application and add the Lambda package\. + + ``` + mkdir cdk-sam-example + cd cdk-sam-example + cdk init app --language typescript + npm install @aws-cdk/aws-lambda + ``` + +1. Add a Lambda reference to `lib/cdk-sam-example-stack.ts`: + + ``` + import * as lambda from '@aws-cdk/aws-lambda'; + ``` + +1. Replace the comment in `lib/cdk-sam-example-stack.ts` with the following Lambda function: + + ``` + new lambda.Function(this, 'MyFunction', { + runtime: lambda.Runtime.PYTHON_3_7, + handler: 'app.lambda_handler', + code: lambda.Code.asset('./my_function'), + }); + ``` + +1. Create the directory `my_function` + + ``` + mkdir my_function + ``` + +1. Create the file `app.py` in `my_function` with the following content: + + ``` + def lambda_handler(event, context): + return "This is a Lambda Function defined through CDK" + ``` + +1. Run your AWS CDK app and create a AWS CloudFormation template + + ``` + cdk synth --no-staging > template.yaml + ``` + +1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: + + ``` + Type: AWS::Lambda::Function + ``` + +1. Run the function by executing: + + ``` + sam local invoke MyFunction12345678 --no-event + ``` + + The output should look something like the following\. + + ``` + 2019-04-01 12:22:41 Found credentials in shared credentials file: ~/.aws/credentials + 2019-04-01 12:22:41 Invoking app.lambda_handler (python3.7) + + Fetching lambci/lambda:python3.7 Docker container image...... + 2019-04-01 12:22:43 Mounting D:\cdk-sam-example\.cdk.staging\a57f59883918e662ab3c46b964d2faa5 as /var/task:ro,delegated inside runtime container + START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST + END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 + REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB + + "This is a Lambda Function defined through CDK" + ``` \ No newline at end of file diff --git a/doc_source/tools.md b/doc_source/tools.md index a98ca1f0..956d5738 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -1,448 +1,8 @@ # AWS CDK tools -This section contains information about AWS CDK tools\. +This section contains information about the AWS CDK tools listed below\. -## AWS Toolkit for Visual Studio code - -The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the AWS Toolkit](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. - -## AWS CDK Toolkit \(`cdk`\) - -The AWS CDK Toolkit, the CLI cdk, is the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. - -There are two ways to tell cdk what command to use to run your AWS CDK app\. The first way is to include an explicit \-\-app option whenever you use a cdk command\. - -``` -cdk --app "npx ts-node bin/hello-cdk.ts" ls -``` - -The second way is to add the following entry to the `cdk.json` file \(if you use the cdk init command, the command does this for you\)\. - -``` -{ - "app": "npx ts-node bin/hello-cdk.ts" -} -``` - -You can also use npx cdk instead of just cdk\. npx cdk looks for a locally\-installed copy of the AWS CDK CLI in the current project before falling back to a global installation\. - -Here are the actions you can take on your AWS CDK app \(this is the output of the cdk \-\-help command\)\. - -``` -Usage: cdk -a COMMAND - -Commands: - - cdk list [STACKS..] Lists all stacks in the app [aliases: ls] - - cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation - template for this stack [aliases: synth] - - cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS - environment - - cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your - AWS account - - cdk destroy [STACKS..] Destroy the stack(s) named STACKS - - cdk diff [STACKS..] Compares the specified stack with the deployed - stack or a local template file, and returns - with status 1 if any difference is found - - cdk metadata [STACK] Returns all metadata associated with this - stack - - cdk init [TEMPLATE] Create a new, empty CDK project from a - template. Invoked without TEMPLATE, the app - template will be used. - - cdk context Manage cached context values - - cdk docs Opens the reference documentation in a browser - [aliases: doc] - - cdk doctor Check your set-up for potential problems - -Options: - - --app, -a REQUIRED: command-line for executing your app or a cloud - assembly directory (e.g. "node bin/my-app.js") [string] - - --context, -c Add contextual string parameter (KEY=VALUE) [array] - - --plugin, -p Name or path of a node package that extend the CDK - features. Can be specified multiple times [array] - - --trace Print trace for stack warnings [boolean] - - --strict Do not construct stacks with warnings [boolean] - - --ignore-errors Ignores synthesis errors, which will likely produce an - invalid output [boolean] [default: false] - - --json, -j Use JSON output instead of YAML when templates are - printed to STDOUT [boolean] [default: false] - - --verbose, -v Show debug logs [boolean] [default: false] - - --profile Use the indicated AWS profile as the default environment - [string] - - --proxy Use the indicated proxy. Will read from HTTPS_PROXY - environment variable if not specified. [string] - - --ca-bundle-path Path to CA certificate to use when validating HTTPS - requests. Will read from AWS_CA_BUNDLE environment - variable if not specified. [string] - - --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: - guess EC2 instance status. [boolean] - - --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized - templates (enabled by default) [boolean] - - --path-metadata Include "aws:cdk:path" CloudFormation metadata for each - resource (enabled by default) [boolean] [default: true] - - --asset-metadata Include "aws:asset:*" CloudFormation metadata for - resources that user assets (enabled by default) - [boolean] [default: true] - - --role-arn, -r ARN of Role to use when invoking CloudFormation [string] - - --toolkit-stack-name The name of the CDK toolkit stack [string] - - --staging Copy assets to the output directory (use --no-staging to - disable, needed for local debugging the source files - with SAM CLI) [boolean] [default: true] - - --output, -o Emits the synthesized cloud assembly into a directory - (default: cdk.out) [string] - - --no-color Removes colors and other style from console output - [boolean] [default: false] - - --fail Fail with exit code 1 in case of diff - [boolean] [default: false] - - --version Show version number [boolean] - - -h, --help Show help [boolean] - -If your app has a single stack, there is no need to specify the stack name - -If one of cdk.json or ~/.cdk.json exists, options specified there will be used -as defaults. Settings in cdk.json take precedence. -``` - -If a `cdk.json` or `~/.cdk.json` file exists, options specified there are used as defaults\. Settings in `cdk.json` take precedence\. - -### AWS CDK toolkit commands - -The AWS CDK CLI supports several distinct commands\. Help for each \(including only the command\-line options specific to the particular command\) follows\. Commands with no command\-specific options are not listed\. All commands additionally accept the options listed above\. - -#### `cdk list` \(`ls`\) - -``` -cdk list [STACKS..] - -Lists all stacks in the app - -Options: - - --long, -l Display environment information for each stack - [boolean] [default: false] -``` - -#### `cdk synthesize` \(`synth`\) - -``` -cdk synthesize [STACKS..] - -Synthesizes and prints the CloudFormation template for this stack - -Options: - - --exclusively, -e Only synthesize requested stacks, don't include - dependencies [boolean] -``` - -If your app has a single stack, you don't have to specify the stack name\. - -#### `cdk bootstrap` - -``` -cdk bootstrap [ENVIRONMENTS..] - -Deploys the CDK toolkit stack into an AWS environment - -Options: - - --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket; - --toolkit-bucket-name bucket will be created and must not - exist [string] - - --bootstrap-kms-key-id AWS KMS master key ID used for the - SSE-KMS encryption [string] - - --qualifier Unique string to distinguish - multiple bootstrap stacks [string] - - --tags, -t Tags to add for the stack - (KEY=VALUE) [array] [default: []] - - --execute Whether to execute ChangeSet - (--no-execute will NOT execute the - ChangeSet) [boolean] [default: true] - - --force, -f Always bootstrap even if it would - downgrade template version - [boolean] [default: false] -``` - -#### `cdk deploy` - -``` -cdk deploy [STACKS..] - -Deploys the stack(s) named STACKS into your AWS account - -Options: - - --build-exclude, -E Do not rebuild asset with the given ID. Can be - specified multiple times. [array] [default: []] - - --exclusively, -e Only deploy requested stacks, don't include - dependencies [boolean] - - --require-approval What security-sensitive changes need manual approval - [string] [choices: "never", "any-change", "broadening"] - - --ci Force CI detection (deprecated) - [boolean] [default: false] - - --notification-arns ARNs of SNS topics that CloudFormation will notify with - stack related events [array] - - --tags, -t Tags to add to the stack (KEY=VALUE) [array] - - --execute Whether to execute ChangeSet (--no-execute will NOT - execute the ChangeSet) [boolean] [default: true] - - --force, -f Always deploy stack even if templates are identical - [boolean] [default: false] - - --parameters Additional parameters passed to CloudFormation at - deploy time (STACK:KEY=VALUE) [array] [default: {}] - - --outputs-file, -O Path to file where stack outputs will be written as - JSON [string] - - --previous-parameters Use previous values for existing parameters (you must - specify all parameters on every deployment if this is - disabled) [boolean] [default: true] -``` - -If your app has a single stack, you don't have to specify the stack name\. - -#### `cdk destroy` - -``` -cdk destroy [STACKS..] - -Destroy the stack(s) named STACKS - -Options: - - --exclusively, -e Only destroy requested stacks, don't include dependees - [boolean] - - --force, -f Do not ask for confirmation before destroying the stacks - [boolean] -``` - -If your app has a single stack, you don't have to specify the stack name\. - -#### `cdk init` - -``` -cdk init [TEMPLATE] - -Create a new, empty CDK project from a template. Invoked without TEMPLATE, the -app template will be used. - -Options: - - --language, -l The language to be used for the new project (default can - be configured in ~/.cdk.json) - [string] [choices: "csharp", "fsharp", "java", "javascript", "python", - "typescript"] - - --list List the available templates [boolean] - - --generate-only If true, only generates project files, without executing - additional operations such as setting up a git repo, - installing dependencies or compiling the project - [boolean] [default: false] -``` - -#### `cdk context` - -``` -cdk context - -Manage cached context values - -Options: - - --reset, -e The context key (or its index) to reset [string] - - --clear Clear all context [boolean] -``` - -### Bootstrapping your AWS environment - -Before you can use the AWS CDK you must bootstrap your AWS environment to create the infrastructure that the AWS CDK CLI needs to deploy your AWS CDK app\. Currently the bootstrap command creates only an Amazon S3 bucket\. - -You incur any charges for what the AWS CDK stores in the bucket\. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK\. You can get rid of the bucket by deleting the **CDKToolkit** stack from your AWS account\. - -### Security\-related changes - -To protect you against unintended changes that affect your security posture, the AWS CDK toolkit prompts you to approve security\-related changes before deploying them\. - -You change the level of changes that requires approval by specifying: - -``` -cdk deploy --require-approval LEVEL -``` - -Where *LEVEL* can be one of the following: - -never -Approval is never required\. - -any\-change -Requires approval on any IAM or security\-group related change\. - -broadening -\(default\) Requires approval when IAM statements or traffic rules are added\. Removals don't require approval\. - -The setting can also be configured in the `cdk.json` file\. - -``` -{ - "app": "...", - "requireApproval": "never" -} -``` - -### Version reporting - -To gain insight into how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. - -By default, the AWS CDK reports the name and version of the following NPM modules that are loaded at synthesis time: -+ AWS CDK core module -+ AWS Construct Library modules -+ AWS Solutions Constructs module - -The `AWS::CDK::Metadata` resource looks like the following\. - -``` -CDKMetadata: - Type: "AWS::CDK::Metadata" - Properties: - Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,@aws-solutions-consturcts/aws-apigateway-lambda=0.8.0" -``` - -### Opting out from version reporting - -To opt out of version reporting, use one of the following methods: -+ Use the cdk command with the \-\-no\-version\-reporting argument\. - - ``` - cdk --no-version-reporting synth - ``` -+ Set versionReporting to **false** in `./cdk.json` or `~/.cdk.json`\. - - ``` - { - "app": "...", - "versionReporting": false - } - ``` - -## SAM CLI - -This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. - -1. The first step is to create a AWS CDK application and add the Lambda package\. - - ``` - mkdir cdk-sam-example - cd cdk-sam-example - cdk init app --language typescript - npm install @aws-cdk/aws-lambda - ``` - -1. Add a Lambda reference to `lib/cdk-sam-example-stack.ts`: - - ``` - import * as lambda from '@aws-cdk/aws-lambda'; - ``` - -1. Replace the comment in `lib/cdk-sam-example-stack.ts` with the following Lambda function: - - ``` - new lambda.Function(this, 'MyFunction', { - runtime: lambda.Runtime.PYTHON_3_7, - handler: 'app.lambda_handler', - code: lambda.Code.asset('./my_function'), - }); - ``` - -1. Create the directory `my_function` - - ``` - mkdir my_function - ``` - -1. Create the file `app.py` in `my_function` with the following content: - - ``` - def lambda_handler(event, context): - return "This is a Lambda Function defined through CDK" - ``` - -1. Run your AWS CDK app and create a AWS CloudFormation template - - ``` - cdk synth --no-staging > template.yaml - ``` - -1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: - - ``` - Type: AWS::Lambda::Function - ``` - -1. Run the function by executing: - - ``` - sam local invoke MyFunction12345678 --no-event - ``` - - The output should look something like the following\. - - ``` - 2019-04-01 12:22:41 Found credentials in shared credentials file: ~/.aws/credentials - 2019-04-01 12:22:41 Invoking app.lambda_handler (python3.7) - - Fetching lambci/lambda:python3.7 Docker container image...... - 2019-04-01 12:22:43 Mounting D:\cdk-sam-example\.cdk.staging\a57f59883918e662ab3c46b964d2faa5 as /var/task:ro,delegated inside runtime container - START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST - END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 - REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB - - "This is a Lambda Function defined through CDK" - ``` \ No newline at end of file +**Topics** ++ [AWS CDK Toolkit \(`cdk` command\)](cli.md) ++ [AWS Toolkit for Visual Studio code](vscode.md) ++ [SAM CLI](sam.md) \ No newline at end of file diff --git a/doc_source/vscode.md b/doc_source/vscode.md new file mode 100644 index 00000000..bb084990 --- /dev/null +++ b/doc_source/vscode.md @@ -0,0 +1,3 @@ +# AWS Toolkit for Visual Studio code + +The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the AWS Toolkit](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index c2cecb41..1c945283 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -173,4 +173,4 @@ cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index a32a319a..2f838d44 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -135,4 +135,4 @@ cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 74408a10..b801213f 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -102,7 +102,7 @@ cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. ## Using TypeScript examples with JavaScript diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index d541b83a..f204c8c3 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -166,4 +166,4 @@ cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index f9f8dce0..d0e679fb 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -102,4 +102,4 @@ cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk`\)](tools.md#cli)\. \ No newline at end of file +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file From 5dc8877840751fc474d53cbfff69f3be61850c63 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Jul 2020 03:59:44 +0000 Subject: [PATCH 215/655] tweaks and typos --- doc_source/cli.md | 2 +- doc_source/index.md | 2 +- doc_source/tools.md | 2 +- doc_source/vscode.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 868abfe9..9780df52 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -1,6 +1,6 @@ # AWS CDK Toolkit \(`cdk` command\) -The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting with your AWS CDK app\. It executes the your AWS CDK app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. It also provides other features that are useful for creating and working with AWS CDK projects\. This topic contains information on common use cases of the CDK Toolkit\. +The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting with your AWS CDK app\. It executes your AWS CDK app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. It also provides other features that are useful for creating and working with AWS CDK projects\. This topic contains information on common use cases of the CDK Toolkit\. ## Toolkit commands diff --git a/doc_source/index.md b/doc_source/index.md index 8108b295..b5ba1275 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -57,7 +57,7 @@ Amazon's trademarks and trade dress may not be used in + [Get a value from a context variable](get_context_var.md) + [AWS CDK tools](tools.md) + [AWS CDK Toolkit (cdk command)](cli.md) - + [AWS Toolkit for Visual Studio code](vscode.md) + + [AWS Toolkit for Visual Studio Code](vscode.md) + [SAM CLI](sam.md) + [Testing constructs](testing.md) + [Security for the AWS Cloud Development Kit (AWS CDK)](security.md) diff --git a/doc_source/tools.md b/doc_source/tools.md index 956d5738..d0df8f1a 100644 --- a/doc_source/tools.md +++ b/doc_source/tools.md @@ -4,5 +4,5 @@ This section contains information about the AWS CDK tools listed below\. **Topics** + [AWS CDK Toolkit \(`cdk` command\)](cli.md) -+ [AWS Toolkit for Visual Studio code](vscode.md) ++ [AWS Toolkit for Visual Studio Code](vscode.md) + [SAM CLI](sam.md) \ No newline at end of file diff --git a/doc_source/vscode.md b/doc_source/vscode.md index bb084990..3c089740 100644 --- a/doc_source/vscode.md +++ b/doc_source/vscode.md @@ -1,3 +1,3 @@ -# AWS Toolkit for Visual Studio code +# AWS Toolkit for Visual Studio Code The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the AWS Toolkit](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. \ No newline at end of file From e69d6ffdc7ec7e859eddd4dcd46aa2f5fafc2950 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Jul 2020 04:19:00 +0000 Subject: [PATCH 216/655] tweak --- doc_source/cli.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 9780df52..5dfac4c8 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -74,7 +74,7 @@ To opt out of version reporting, use one of the following methods: ## Specifying the environment - In AWS CDK terms, the [Environment](environments.md) consists of a region and AWS credentials valid in that region\. The CDK Toolkit needs credentials in order to query your AWS account and to deploy CloudFormation templates\. + In AWS CDK terms, the [environment](environments.md) consists of a region and AWS credentials valid in that region\. The CDK Toolkit needs credentials in order to query your AWS account and to deploy CloudFormation templates\. **Important** We strongly recommend against using your AWS root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. @@ -166,7 +166,7 @@ The CDK Toolkit does not guarantee that stacks are processed in the specified or ## Bootstrapping your AWS environment -Stacks that contain [Assets](assets.md) or large AWS Lambda functions require special dedicated AWS CDK resources to be provisioned\. Currently, this is only an Amazon S3 bucket\. The `cdk bootstrap` command creates the necessary resources for you\. You only need to bootstrap if you are deploying a stack that requires these dedicated resources\. +Stacks that contain [assets](assets.md) or large AWS Lambda functions require special dedicated AWS CDK resources to be provisioned\. Currently, this is only an Amazon S3 bucket\. The `cdk bootstrap` command creates the necessary resources for you\. You only need to bootstrap if you are deploying a stack that requires these dedicated resources\. **Important** Each region to which you deploy such a stack must be bootstrapped separately\. From 7d3719cd44220313cfcb61a25212a8356cd3c915 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Jul 2020 05:19:10 +0000 Subject: [PATCH 217/655] tweaks to tables --- doc_source/cli.md | 62 ++++++++++++++++++++++++++--------------------- 1 file changed, 34 insertions(+), 28 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 5dfac4c8..c8f16d3f 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -9,17 +9,17 @@ All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(` | Command | Function | | --- | --- | -| cdk list \(ls\) | Lists the stacks in the app | -| cdk synthesize \(synth\) | Synthesizes and prints the CloudFormation template for the specified stack\(s\) | -| cdk bootstrap | Deploys the CDK Toolkit stack, required to deploy stacks containing assets | -| cdk deploy | Deploys the specified stack\(s\) | -| cdk destroy | Destroys the specified stack\(s\) | -| cdk diff | Compares the specified stack with the deployed stack or a local CloudFormation template | -| cdk metadata | Displays metadata about the specified stack | -| cdk init | Creates a new CDK project in the current directory from a specified template | -| cdk context | Manages cached context values | -| cdk docs \(doc\) | Opens the CDK API reference in your browser | -| cdk doctor | Checks your CDK project for potential problems | +| `cdk list` \(`ls`\) | Lists the stacks in the app | +| `cdk synthesize` \(`synth`\) | Synthesizes and prints the CloudFormation template for the specified stack\(s\) | +| `cdk bootstrap` | Deploys the CDK Toolkit stack, required to deploy stacks containing assets | +| `cdk deploy` | Deploys the specified stack\(s\) | +| `cdk destroy` | Destroys the specified stack\(s\) | +| `cdk diff` | Compares the specified stack with the deployed stack or a local CloudFormation template | +| `cdk metadata` | Displays metadata about the specified stack | +| `cdk init` | Creates a new CDK project in the current directory from a specified template | +| `cdk context` | Manages cached context values | +| `cdk docs` \(`doc`\) | Opens the CDK API reference in your browser | +| `cdk doctor` | Checks your CDK project for potential problems | ## Built\-in help @@ -190,18 +190,19 @@ The supported languages \(*LANGUAGE*\) are: | Code | Language | | --- | --- | -| typescript | TypeScript | -| javascript | JavaScript | -| python | Python | -| java | Java | -| csharp | C\# | +| `typescript` | TypeScript | +| `javascript` | JavaScript | +| `python` | Python | +| `java` | Java | +| `csharp` | C\# | *TEMPLATE* is an optional template\. If the desired template is *app*, the default, you may omit it\. The available templates are: -| | | -| --- |--- | -| app \(default\) | Creates an empty AWS CDK app\. | -| sample\-app | Creates an AWS CDK app with a stack containing an Amazon SQS queue and an Amazon SNS topic\. | + +| Template | Description | +| --- | --- | +| `app` \(default\) | Creates an empty AWS CDK app\. | +| `sample-app` | Creates an AWS CDK app with a stack containing an Amazon SQS queue and an Amazon SNS topic\. | The templates use the name of the project folder to generate names for files and classes inside your new app\. @@ -221,7 +222,8 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -**Specifying context values** +### Specifying context values + Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. ``` @@ -239,14 +241,16 @@ When deploying multiple stacks, the specified context values are passed to all o cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -**Specifying display format** +### Specifying display format + By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. ``` cdk synth –json MyStack ``` -**Specifying output directory** +### Specifying output directory + Add the \-\-output \(\-o\) option to write the synthesized templates to a directory other than cdk\.out\. ``` @@ -269,7 +273,8 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -**Specifying AWS CloudFormation parameters** +### Specifying AWS CloudFormation parameters + The AWS CDK Toolkit supports specifying parameters at deployment\. You may provide these on the command line following the `--parameters` flag\. ``` @@ -290,7 +295,8 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -**Specifying outputs file** +### Specifying outputs file + If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. ``` @@ -312,9 +318,9 @@ cdk deploy --require-approval LEVEL | Term | Meaning | | --- | --- | -| never | Approval is never required | -| any\-change | Requires approval on any IAM or security\-group\-related change | -| broadening \(default\) | Requires approval when IAM statements or traffic rules are added; removals don't require approval | +| `never` | Approval is never required | +| `any-change` | Requires approval on any IAM or security\-group\-related change | +| `broadening` \(default\) | Requires approval when IAM statements or traffic rules are added; removals don't require approval | The setting can also be configured in the `cdk.json` file\. From 571d00270b768d771403db3d695773bcdbde8b64 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Jul 2020 14:17:05 +0000 Subject: [PATCH 218/655] tweaks --- doc_source/cli.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index c8f16d3f..7761928f 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -218,7 +218,7 @@ cdk synth "*" # all stacks in app ``` **Note** -The CDK Toolkit actually runs your app and synthesizes fresh templates before most operations \(e\.g\. when deploying or comparing stacks\)\. These templates are stored by default in the cdk\.out directory\. The `cdk synth` command simply prints the generated templates for the specified stack\(s\)\. +The CDK Toolkit actually runs your app and synthesizes fresh templates before most operations \(e\.g\. when deploying or comparing stacks\)\. These templates are stored by default in the `cdk.out` directory\. The `cdk synth` command simply prints the generated templates for the specified stack\(s\)\. See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. @@ -275,7 +275,7 @@ See `cdk deploy --help` for all available options\. A few of the most\-frequentl ### Specifying AWS CloudFormation parameters -The AWS CDK Toolkit supports specifying parameters at deployment\. You may provide these on the command line following the `--parameters` flag\. +The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. ``` cdk deploy MyStack --parameters uploadBucketName=UploadBucket From d7d430f851b4085238f99f5aa302505a6b6dd49b Mon Sep 17 00:00:00 2001 From: ayachnes2 <65786110+ayachnes2@users.noreply.github.com> Date: Thu, 9 Jul 2020 10:37:28 -0400 Subject: [PATCH 219/655] POM S3 dependency has a syntax error The S3 POM dependency for Java has parentheses around `cdk.version` which obviously errors when you try to run `mvn compile`. I fixed the issue by adding curly braces `{`, `}` to `cdk.version`. --- doc_source/hello_world.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 2c0fa575..36aae32a 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -217,7 +217,7 @@ Add the following to the `` container of `pom.xml`\. software.amazon.awscdk s3 - $(cdk.version) + ${cdk.version} ``` @@ -707,4 +707,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? From ad2ee84ecb37f8e7161a0ff5e646c25a29b1faca Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Jul 2020 15:03:57 +0000 Subject: [PATCH 220/655] add install, reference, beef up bootstrapping --- doc_source/cli.md | 324 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 318 insertions(+), 6 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 7761928f..54b15053 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -2,6 +2,13 @@ The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting with your AWS CDK app\. It executes your AWS CDK app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. It also provides other features that are useful for creating and working with AWS CDK projects\. This topic contains information on common use cases of the CDK Toolkit\. +The AWS CDK Toolkit is installed with the Node Package Manager: + +``` +npm install aws-cdk # install latest version +npm install aws-cdk@X.YY.Z # install specific version +``` + ## Toolkit commands All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(`list`, `synthesize`, `deploy`, etc\.\)\. Some subcommands have a shorter version \(`ls`, `synth`, etc\.\) that is equivalent\. Options and arguments follow the subcommand in any order\. The available commands are summarized here\. @@ -21,6 +28,8 @@ All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(` | `cdk docs` \(`doc`\) | Opens the CDK API reference in your browser | | `cdk doctor` | Checks your CDK project for potential problems | +For the options available for each command, see [Toolkit reference](#cli-ref) or [Built\-in help](#cli-help)\. + ## Built\-in help The AWS CDK Toolkit has integrated help\. You can see general help about the utility and a list of the provided subcommands by issuing: @@ -168,8 +177,21 @@ The CDK Toolkit does not guarantee that stacks are processed in the specified or Stacks that contain [assets](assets.md) or large AWS Lambda functions require special dedicated AWS CDK resources to be provisioned\. Currently, this is only an Amazon S3 bucket\. The `cdk bootstrap` command creates the necessary resources for you\. You only need to bootstrap if you are deploying a stack that requires these dedicated resources\. +``` +cdk bootstrap # bootstraps default account/region +cdk bootstrap --profile test # bootstraps test environment +``` + +You may also bootstrap a specific environment\. Credentials must be configured \(e\.g\. in `~/.aws/credentials`\) for the specified account and region\. You may specify a profile that contains the required credentials\. + +``` +cdk bootstrap ACCOUNT-NUMBER/REGION # e.g. +cdk bootstrap 1111111111/us-east-1 +aws bootstrap --profile test 1111111111/us-east-1 +``` + **Important** -Each region to which you deploy such a stack must be bootstrapped separately\. +Each environment \(account/region combination\) to which you deploy such a stack must be bootstrapped separately\. You may incur charges for what the AWS CDK stores in the bucket\. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK\. From time to time, then, you might want to clear out the bucket from the Amazon S3 console\. @@ -222,7 +244,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -241,7 +263,7 @@ When deploying multiple stacks, the specified context values are passed to all o cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -249,7 +271,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth –json MyStack ``` -### Specifying output directory +### Specifying output directory Add the \-\-output \(\-o\) option to write the synthesized templates to a directory other than cdk\.out\. @@ -273,7 +295,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -295,7 +317,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. @@ -357,6 +379,296 @@ To compare your app's stack\(s\) with a saved CloudFormation template: cdk diff --template ~/stacks/MyStack.old MyStack ``` +## Toolkit reference + +This section provides a reference for the AWS CDK Toolkit derived from its help, first a general reference with the options available with all commands, then \(in collapsible sections\) specific references with options available only with specific subcommands\. + +``` +Usage: cdk -a COMMAND + +Commands: + + cdk list [STACKS..] Lists all stacks in the app [aliases: ls] + + cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation + template for this stack [aliases: synth] + + cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS + environment + + cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your + AWS account + + cdk destroy [STACKS..] Destroy the stack(s) named STACKS + + cdk diff [STACKS..] Compares the specified stack with the deployed + stack or a local template file, and returns + with status 1 if any difference is found + + cdk metadata [STACK] Returns all metadata associated with this + stack + + cdk init [TEMPLATE] Create a new, empty CDK project from a + template. Invoked without TEMPLATE, the app + template will be used. + + cdk context Manage cached context values + + cdk docs Opens the reference documentation in a browser + [aliases: doc] + + cdk doctor Check your set-up for potential problems + +Options: + + --app, -a REQUIRED: command-line for executing your app or a cloud + assembly directory (e.g. "node bin/my-app.js") [string] + + --context, -c Add contextual string parameter (KEY=VALUE) [array] + + --plugin, -p Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] + + --trace Print trace for stack warnings [boolean] + + --strict Do not construct stacks with warnings [boolean] + + --ignore-errors Ignores synthesis errors, which will likely produce an + invalid output [boolean] [default: false] + + --json, -j Use JSON output instead of YAML when templates are + printed to STDOUT [boolean] [default: false] + + --verbose, -v Show debug logs (specify multiple times to increase + verbosity) [count] [default: false] + + --profile Use the indicated AWS profile as the default environment + [string] + + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified. [string] + + --ca-bundle-path Path to CA certificate to use when validating HTTPS + requests. Will read from AWS_CA_BUNDLE environment + variable if not specified. [string] + + --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: + guess EC2 instance status. [boolean] + + --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized + templates (enabled by default) [boolean] + + --path-metadata Include "aws:cdk:path" CloudFormation metadata for each + resource (enabled by default) [boolean] [default: true] + + --asset-metadata Include "aws:asset:*" CloudFormation metadata for + resources that user assets (enabled by default) + [boolean] [default: true] + + --role-arn, -r ARN of Role to use when invoking CloudFormation [string] + + --toolkit-stack-name The name of the CDK toolkit stack [string] + + --staging Copy assets to the output directory (use --no-staging to + disable, needed for local debugging the source files + with SAM CLI) [boolean] [default: true] + + --output, -o Emits the synthesized cloud assembly into a directory + (default: cdk.out) [string] + + --no-color Removes colors and other style from console output + [boolean] [default: false] + + --fail Fail with exit code 1 in case of diff + [boolean] [default: false] + + --version Show version number [boolean] + + -h, --help Show help [boolean] + +If your app has a single stack, there is no need to specify the stack name + +If one of cdk.json or ~/.cdk.json exists, options specified there will be used +as defaults. Settings in cdk.json take precedence. +``` + +### `cdk list` \(`ls`\) + +``` +cdk list [STACKS..] + +Lists all stacks in the app + +Options: + + --long, -l Display environment information for each stack + [boolean] [default: false] +``` + +### `cdk synthesize` \(`synth`\) + +``` +cdk synthesize [STACKS..] + +Synthesizes and prints the CloudFormation template for this stack + +Options: + + --exclusively, -e Only synthesize requested stacks, don't include + dependencies [boolean] +``` + +### `cdk bootstrap` + +``` +cdk bootstrap [ENVIRONMENTS..] + +Deploys the CDK toolkit stack into an AWS environment + +Options: + + --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket; + --toolkit-bucket-name bucket will be created and must not + exist [string] + + --bootstrap-kms-key-id AWS KMS master key ID used for the + SSE-KMS encryption [string] + + --qualifier Unique string to distinguish + multiple bootstrap stacks [string] + + --public-access-block-configuration Block public access configuration + on CDK toolkit bucket (enabled by + default) [boolean] [default: true] + + --tags, -t Tags to add for the stack + (KEY=VALUE) [array] [default: []] + + --execute Whether to execute ChangeSet + (--no-execute will NOT execute the + ChangeSet) [boolean] [default: true] + + --force, -f Always bootstrap even if it would + downgrade template version + [boolean] [default: false] +``` + +### `cdk deploy` + +``` +cdk deploy [STACKS..] + +Deploys the stack(s) named STACKS into your AWS account + +Options: + + --build-exclude, -E Do not rebuild asset with the given ID. Can be + specified multiple times. [array] [default: []] + + --exclusively, -e Only deploy requested stacks, don't include + dependencies [boolean] + + --require-approval What security-sensitive changes need manual approval + [string] [choices: "never", "any-change", "broadening"] + + --ci Force CI detection (deprecated) + [boolean] [default: false] + + --notification-arns ARNs of SNS topics that CloudFormation will notify with + stack related events [array] + + --tags, -t Tags to add to the stack (KEY=VALUE) [array] + + --execute Whether to execute ChangeSet (--no-execute will NOT + execute the ChangeSet) [boolean] [default: true] + + --force, -f Always deploy stack even if templates are identical + [boolean] [default: false] + + --parameters Additional parameters passed to CloudFormation at + deploy time (STACK:KEY=VALUE) [array] [default: {}] + + --outputs-file, -O Path to file where stack outputs will be written as + JSON [string] + + --previous-parameters Use previous values for existing parameters (you must + specify all parameters on every deployment if this is + disabled) [boolean] [default: true] +``` + +### `cdk destroy` + +``` +cdk destroy [STACKS..] + +Destroy the stack(s) named STACKS + +Options: + + --exclusively, -e Only destroy requested stacks, don't include dependees + [boolean] + + --force, -f Do not ask for confirmation before destroying the stacks + [boolean] +``` + +### `cdk diff` + +``` +cdk diff [STACKS..] + +Compares the specified stack with the deployed stack or a local template file, +and returns with status 1 if any difference is found + +Options: + + --exclusively, -e Only diff requested stacks, don't include dependencies + [boolean] + + --context-lines Number of context lines to include in arbitrary JSON + diff rendering [number] [default: 3] + + --template The path to the CloudFormation template to compare with + [string] +``` + +### `cdk init` + +``` +cdk init [TEMPLATE] + +Create a new, empty CDK project from a template. Invoked without TEMPLATE, the +app template will be used. + +Options: + + --language, -l The language to be used for the new project (default can + be configured in ~/.cdk.json) + [string] [choices: "csharp", "fsharp", "java", "javascript", "python", + "typescript"] + + --list List the available templates [boolean] + + --generate-only If true, only generates project files, without executing + additional operations such as setting up a git repo, + installing dependencies or compiling the project + [boolean] [default: false] +``` + +### `cdk context` + +``` +cdk context + +Manage cached context values + +Options: + + --reset, -e The context key (or its index) to reset [string] + + --clear Clear all context [boolean] +``` + ## Help us help you Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you\. Please click **Provide feedback** below and let us know\! Providing your e\-mail address is optional, but very helpful in case we have further questions\. \(We'll keep it to ourselves\.\) \ No newline at end of file From 936caf16f9414e55cfb6156e50798c8cc900debb Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Jul 2020 15:16:42 +0000 Subject: [PATCH 221/655] add more feedback solicitation --- doc_source/codepipeline_example.md | 6 +++++- doc_source/getting_started.md | 6 +++++- doc_source/hello_world.md | 6 +++++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 14044bbd..a1123ba8 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -1278,4 +1278,8 @@ cdk destroy LambdaStack cdk destroy PipelineDeployingLambdaStack ``` -Finally, delete your AWS CodeCommit repository from the AWS Console\. \ No newline at end of file +Finally, delete your AWS CodeCommit repository from the AWS Console\. + +## Help us help you + +Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you\. Please click **Provide feedback** below and let us know\! Providing your e\-mail address is optional, but very helpful in case we have further questions\. \(We'll keep it to ourselves\.\) \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index ad76ec5f..1a63b546 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -213,4 +213,8 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? + +## Help us help you + +Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you\. Please click **Provide feedback** below and let us know\! Providing your e\-mail address is optional, but very helpful in case we have further questions\. \(We'll keep it to ourselves\.\) \ No newline at end of file diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 2c0fa575..54d08fef 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -707,4 +707,8 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? + +## Help us help you + +Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you\. Please click **Provide feedback** below and let us know\! Providing your e\-mail address is optional, but very helpful in case we have further questions\. \(We'll keep it to ourselves\.\) \ No newline at end of file From 6997b70c4a28e9d73fbec48c2fd9c7c7c16261f4 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Jul 2020 15:30:32 +0000 Subject: [PATCH 222/655] update doc history --- doc_source/doc-history.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index a1582a8d..e35d93c4 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -7,6 +7,7 @@ The table below represents significant documentation milestones\. We fix errors | Change | Description | Date | | --- |--- |--- | +| [Improve CDK Toolkit topic](#doc-history) | Include more information and examples around performing common tasks with the CLI \(and the relevant flags\) rather than just including a copy of the help\. | July 9, 2020 | | [Improve CodePipeline example](#doc-history) | Update pipeline stack to build in proper language and add more material dealing with the CodeCommit repository\. | July 6, 2020 | | [Improve Getting Started](#doc-history) | Remove extraneous material from Getting Started, use a more conversational tone, incorporate current best practices\. Break out Hello World into its own topic\. | June 17, 2020 | | [Update stability index](#doc-history) | Incorporate the latest definitions of the stability levels for AWS Construct Library modules\. | June 11, 2020 | From 31388c6659168769c7a8918deb2cb28138cb92f2 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Jul 2020 15:39:21 +0000 Subject: [PATCH 223/655] add note about local/global install --- doc_source/cli.md | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 54b15053..3c9ffde5 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -2,13 +2,16 @@ The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting with your AWS CDK app\. It executes your AWS CDK app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. It also provides other features that are useful for creating and working with AWS CDK projects\. This topic contains information on common use cases of the CDK Toolkit\. -The AWS CDK Toolkit is installed with the Node Package Manager: +The AWS CDK Toolkit is installed with the Node Package Manager\. In most cases, we recommend intalling it globally\. ``` -npm install aws-cdk # install latest version -npm install aws-cdk@X.YY.Z # install specific version +npm install -g aws-cdk # install latest version +npm install -g aws-cdk@X.YY.Z # install specific version ``` +**Tip** +If you regularly work with multiple versions of the AWS CDK, you may want to install a matching version of the AWS CDK Toolkit in indivdidual CDK projects\. To do this, omit `-g` from the `npm install` command\. Then use `npx cdk` to invoke it; this will run the local version if one exists, falling back to a global version if not\. + ## Toolkit commands All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(`list`, `synthesize`, `deploy`, etc\.\)\. Some subcommands have a shorter version \(`ls`, `synth`, etc\.\) that is equivalent\. Options and arguments follow the subcommand in any order\. The available commands are summarized here\. @@ -244,7 +247,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -263,7 +266,7 @@ When deploying multiple stacks, the specified context values are passed to all o cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -271,7 +274,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth –json MyStack ``` -### Specifying output directory +### Specifying output directory Add the \-\-output \(\-o\) option to write the synthesized templates to a directory other than cdk\.out\. @@ -295,7 +298,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -317,7 +320,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. @@ -492,7 +495,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -505,7 +508,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -518,7 +521,7 @@ Options: dependencies [boolean] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -553,7 +556,7 @@ Options: [boolean] [default: false] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -596,7 +599,7 @@ Options: disabled) [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -612,7 +615,7 @@ Options: [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -632,7 +635,7 @@ Options: [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -655,7 +658,7 @@ Options: [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context From 917836d8fe8a14a93a886e184dcf43655f5a21d6 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Jul 2020 17:16:15 +0000 Subject: [PATCH 224/655] typos --- doc_source/cli.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 3c9ffde5..945f0acb 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -2,7 +2,7 @@ The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting with your AWS CDK app\. It executes your AWS CDK app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. It also provides other features that are useful for creating and working with AWS CDK projects\. This topic contains information on common use cases of the CDK Toolkit\. -The AWS CDK Toolkit is installed with the Node Package Manager\. In most cases, we recommend intalling it globally\. +The AWS CDK Toolkit is installed with the Node Package Manager\. In most cases, we recommend installing it globally\. ``` npm install -g aws-cdk # install latest version @@ -10,7 +10,7 @@ npm install -g aws-cdk@X.YY.Z # install specific version ``` **Tip** -If you regularly work with multiple versions of the AWS CDK, you may want to install a matching version of the AWS CDK Toolkit in indivdidual CDK projects\. To do this, omit `-g` from the `npm install` command\. Then use `npx cdk` to invoke it; this will run the local version if one exists, falling back to a global version if not\. +If you regularly work with multiple versions of the AWS CDK, you may want to install a matching version of the AWS CDK Toolkit in individual CDK projects\. To do this, omit `-g` from the `npm install` command\. Then use `npx cdk` to invoke it; this will run the local version if one exists, falling back to a global version if not\. ## Toolkit commands From ad61185260dc3eb3006795e805fb3302bf725563 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Jul 2020 21:07:23 +0000 Subject: [PATCH 225/655] add info about --context flag to Context topic --- doc_source/cli.md | 4 ++-- doc_source/context.md | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 945f0acb..324e6a30 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -1,6 +1,6 @@ # AWS CDK Toolkit \(`cdk` command\) -The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting with your AWS CDK app\. It executes your AWS CDK app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. It also provides other features that are useful for creating and working with AWS CDK projects\. This topic contains information on common use cases of the CDK Toolkit\. +The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting with your AWS CDK app\. It executes your app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. It also provides other features useful for creating and working with AWS CDK projects\. This topic contains information on common use cases of the CDK Toolkit\. The AWS CDK Toolkit is installed with the Node Package Manager\. In most cases, we recommend installing it globally\. @@ -259,7 +259,7 @@ cdk synth –context key=value MyStack cdk synth --context key1=value1 --context key2=value2 MyStack ``` -When deploying multiple stacks, the specified context values are passed to all of them\. If you wish, you may specify different values for each stack by prefixing the stack name to the context value\. +When deploying multiple stacks, the specified context values are normally passed to all of them\. If you wish, you may specify different values for each stack by prefixing the stack name to the context value\. ``` # different context values for each stack diff --git a/doc_source/context.md b/doc_source/context.md index 802ad2ef..cb9ba3e3 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -89,6 +89,25 @@ $ cdk context --clear Only context values stored in `cdk.context.json` can be reset or cleared\. The AWS CDK does not touch other context files\. To protect a context value from being reset using these commands, then, you might copy the value to `cdk.json`\. +## AWS CDK Toolkit `--context` flag + +Use the `--context` \(`-c` for short\) option to pass runtime context values to your CDK app during synthesis or deployment\. + +``` +# specify a single context value +cdk synth –context key=value MyStack + +# specify multiple context values (any number) +cdk synth --context key1=value1 --context key2=value2 MyStack +``` + +When deploying multiple stacks, the specified context values are normally passed to all of them\. If you wish, you may specify different values for each stack by prefixing the stack name to the context value\. + +``` +# different context values for each stack +cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 +``` + ## Example Below is an example of importing an existing Amazon VPC using AWS CDK context\. From f411d0b8a1080649c7fd365b9abee7707896ea22 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 11 Jul 2020 01:25:55 +0000 Subject: [PATCH 226/655] fix links --- doc_source/hello_world.md | 2 +- doc_source/home.md | 2 +- doc_source/serverless_example.md | 2 +- doc_source/work-with-cdk-csharp.md | 2 +- doc_source/work-with-cdk-java.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 83005ea2..5775f22e 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -711,4 +711,4 @@ The AWS CDK is an open\-source project\. Want to [contribute](https://github.com ## Help us help you -Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you\. Please click **Provide feedback** below and let us know\! Providing your e\-mail address is optional, but very helpful in case we have further questions\. \(We'll keep it to ourselves\.\) +Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you\. Please click **Provide feedback** below and let us know\! Providing your e\-mail address is optional, but very helpful in case we have further questions\. \(We'll keep it to ourselves\.\) \ No newline at end of file diff --git a/doc_source/home.md b/doc_source/home.md index 58635997..9d1ed98a 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -212,7 +212,7 @@ Other advantages of the AWS CDK include: Code snippets and longer examples are available in the AWS CDK's supported programming languages: TypeScript, JavaScript, Python, Java, and C\#\. See [AWS CDK examples](about_examples.md) for a list of the examples\. -The [AWS CDK tools](tools.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. +The [AWS CDK Toolkit](cli.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. The [AWS Construct Library](constructs.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to create resources for an Amazon or AWS service\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 865b5d80..71ac189e 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -716,7 +716,7 @@ cdk synth ## Deploy and test the app -Before you can deploy your first AWS CDK app containing a lambda function, you must bootstrap your AWS environment\. This creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see the **bootstrap** section of the [AWS CDK tools](tools.md) \(if you've already bootstrapped, you'll get a warning and nothing will change\)\. +Before you can deploy your first AWS CDK app containing a lambda function, you must bootstrap your AWS environment\. This creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see [Bootstrapping your AWS environment](cli.md#cli-bootstrap)\. If you've already bootstrapped, you'll get a warning and nothing will change\. ``` cdk bootstrap diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index d3f7d53d..1c945283 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -173,4 +173,4 @@ cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 2f838d44..28ffc470 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -48,7 +48,7 @@ Specify the modules that your application depends on by editing `pom.xml` and ad **Tip** If you use a Java IDE, it probably has features for managing Maven dependencies\. We recommend always editing `pom.xml` directly, however, unless you are absolutely sure the IDE's functionality matches what you'd do by hand\. -The default `pom.xml` defines the variable `cdk.version` to be the version of the AWS CDK that created the project\. You can easily update the version by updating the value of this variable\. +The default `pom.xml` defines the variable `cdk.version` to be the version of the AWS CDK that created the project\. You can easily update the version required by updating the value of this variable, while keeping all module versions in sync\. ``` 1.XX.Y From c1f6f78ad591c1ab2439b5117ce38d6344554ec7 Mon Sep 17 00:00:00 2001 From: minchao Date: Sat, 11 Jul 2020 16:41:35 +0800 Subject: [PATCH 227/655] fix typo --- doc_source/context.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/context.md b/doc_source/context.md index cb9ba3e3..71b5e4f0 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -95,7 +95,7 @@ Use the `--context` \(`-c` for short\) option to pass runtime context values to ``` # specify a single context value -cdk synth –context key=value MyStack +cdk synth -–context key=value MyStack # specify multiple context values (any number) cdk synth --context key1=value1 --context key2=value2 MyStack From 9b1e2ddbcf0d179696027b6a96834235768a6c70 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 11 Jul 2020 23:26:35 +0000 Subject: [PATCH 228/655] refix --- doc_source/context.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/context.md b/doc_source/context.md index 71b5e4f0..c04c1ba3 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -95,7 +95,7 @@ Use the `--context` \(`-c` for short\) option to pass runtime context values to ``` # specify a single context value -cdk synth -–context key=value MyStack +cdk synth --context key=value MyStack # specify multiple context values (any number) cdk synth --context key1=value1 --context key2=value2 MyStack From f777b3234d6f8d79529dc59a52925fab4069fe8e Mon Sep 17 00:00:00 2001 From: Steven Demurjian Jr Date: Mon, 13 Jul 2020 22:33:22 -0400 Subject: [PATCH 229/655] Construct constructor does not accept "props" argument --- doc_source/constructs.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index f257a637..21524962 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -847,7 +847,7 @@ export class NotifyingBucket extends Construct { class NotifyingBucket extends Construct { constructor(scope, id, props) { - super(scope, id, props); + super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); this.topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(this.topic, { prefix: props.prefix }); @@ -974,4 +974,4 @@ var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketP images.topic.AddSubscription(new SqsSubscription(queue)); ``` ------- \ No newline at end of file +------ From 9cde87367c79e825919475d1a3ca2c0fff1db497 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 14 Jul 2020 16:00:58 +0000 Subject: [PATCH 230/655] super call to Construct constructor shouldn't pass props because Construct doesn't take them --- doc_source/constructs.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 21524962..99fe72bf 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -646,7 +646,7 @@ export interface NotifyingBucketProps { export class NotifyingBucket extends Construct { constructor(scope: Construct, id: string, props: NotifyingBucketProps = {}) { - super(scope, id, props); + super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); const topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(new s3notify.SnsDestination(topic), @@ -661,7 +661,7 @@ export class NotifyingBucket extends Construct { ``` class NotifyingBucket extends Construct { constructor(scope, id, props = {}) { - super(scope, id, props); + super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); const topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(new s3notify.SnsDestination(topic), @@ -678,8 +678,8 @@ module.exports = { NotifyingBucket } ``` class NotifyingBucket(core.Construct): - def __init__(self, scope: core.Construct, id: str, *, prefix=None, **kwargs): - super().__init__(scope, id, **kwargs) + def __init__(self, scope: core.Construct, id: str, *, prefix=None): + super().__init__(scope, id) bucket = s3.Bucket(self, "bucket") topic = sns.Topic(self, "topic") bucket.add_object_created_notification(s3notify.SnsDestination(topic), @@ -705,7 +705,7 @@ public class NotifyingBucket extends Construct { } public NotifyingBucket(final Construct scope, final String id, final BucketProps props, final String prefix) { - super(scope, id, props); + super(scope, id); Bucket bucket = new Bucket(this, "bucket"); Topic topic = new Topic(this, "topic"); @@ -727,7 +727,7 @@ public class NotifyingBucketProps : BucketProps public class NotifyingBucket : Construct { - public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id, props) + public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id) { var bucket = new Bucket(this, "bucket"); var topic = new Topic(this, "topic"); @@ -847,7 +847,7 @@ export class NotifyingBucket extends Construct { class NotifyingBucket extends Construct { constructor(scope, id, props) { - super(scope, id); + super(scope, id, props); const bucket = new s3.Bucket(this, 'bucket'); this.topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(this.topic, { prefix: props.prefix }); @@ -974,4 +974,4 @@ var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketP images.topic.AddSubscription(new SqsSubscription(queue)); ``` ------- +------ \ No newline at end of file From cdcf76c3dc726bd75934eaba7fe5142fa8fa0c56 Mon Sep 17 00:00:00 2001 From: Brian Gibson Date: Tue, 14 Jul 2020 15:35:15 -0400 Subject: [PATCH 231/655] Updates environments.md Windows example scripts Address issue #239 --- doc_source/environments.md | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index f7d193af..98145e30 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -316,10 +316,8 @@ cdk deploy "$@" @echo off rem cdk-deploy-to.bat set CDK_DEPLOY_ACCOUNT=%1 -shift -set CDK_DEPLOY_REGION=%1 -shift -cdk deploy %* +set CDK_DEPLOY_REGION=%2 +cdk deploy %3 ``` ------ @@ -341,7 +339,7 @@ bash cdk-deploy-to.sh 123457689 us-east-1 "$@" ``` @echo off rem cdk-deploy-to-test.bat -cdk-deploy-to 135792469 us-east-1 %* +cdk-deploy-to 135792469 us-east-1 %1 ``` ------ @@ -364,10 +362,10 @@ bash cdk-deploy-to.sh 246813579 eu-west-1 "$@" ``` @echo off rem cdk-deploy-to-prod.bat -cdk-deploy-to 135792469 us-west-1 %* || goto :eof -cdk-deploy-to 245813579 eu-west-1 %* +cdk-deploy-to 135792469 us-west-1 %1 || goto :eof +cdk-deploy-to 245813579 eu-west-1 %1 ``` ------ -Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. \ No newline at end of file +Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. From e179a0b2f295a4073782c1acfe55761f6bc7700d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 15 Jul 2020 02:03:52 +0000 Subject: [PATCH 232/655] profile HUHU to HTML only (thereby removing it from Markdown) --- doc_source/cli.md | 6 +----- doc_source/codepipeline_example.md | 6 +----- doc_source/getting_started.md | 6 +----- doc_source/hello_world.md | 6 +----- 4 files changed, 4 insertions(+), 20 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 324e6a30..ea9ba151 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -670,8 +670,4 @@ Options: --reset, -e The context key (or its index) to reset [string] --clear Clear all context [boolean] -``` - -## Help us help you - -Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you\. Please click **Provide feedback** below and let us know\! Providing your e\-mail address is optional, but very helpful in case we have further questions\. \(We'll keep it to ourselves\.\) \ No newline at end of file +``` \ No newline at end of file diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index a1123ba8..14044bbd 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -1278,8 +1278,4 @@ cdk destroy LambdaStack cdk destroy PipelineDeployingLambdaStack ``` -Finally, delete your AWS CodeCommit repository from the AWS Console\. - -## Help us help you - -Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you\. Please click **Provide feedback** below and let us know\! Providing your e\-mail address is optional, but very helpful in case we have further questions\. \(We'll keep it to ourselves\.\) \ No newline at end of file +Finally, delete your AWS CodeCommit repository from the AWS Console\. \ No newline at end of file diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 1a63b546..ad76ec5f 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -213,8 +213,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? - -## Help us help you - -Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you\. Please click **Provide feedback** below and let us know\! Providing your e\-mail address is optional, but very helpful in case we have further questions\. \(We'll keep it to ourselves\.\) \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 5775f22e..582417b2 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -707,8 +707,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? - -## Help us help you - -Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you\. Please click **Provide feedback** below and let us know\! Providing your e\-mail address is optional, but very helpful in case we have further questions\. \(We'll keep it to ourselves\.\) \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file From ca529653e178ca7b13c64b0454adbf0eb239e7fd Mon Sep 17 00:00:00 2001 From: Brady Sullivan Date: Sat, 18 Jul 2020 14:22:23 -0700 Subject: [PATCH 233/655] Correct the example output show when listing stacks After app creation, 'cdk ls' should output "HelloCdkStack" not just "HelloCdk". --- doc_source/hello_world.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 582417b2..b630b4b3 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -179,7 +179,7 @@ cdk ls ------ -If you don't see `HelloCdk`, make sure you named your app's directory `hello-cdk`\. If you didn't, go back to [Create the app](#hello_world_tutorial_create_app) and try again\. +If you don't see `HelloCdkStack`, make sure you named your app's directory `hello-cdk`\. If you didn't, go back to [Create the app](#hello_world_tutorial_create_app) and try again\. ## Add an Amazon S3 bucket @@ -707,4 +707,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? From 176c39e8e24612a9bd99dab2b34034ef4cef6bf0 Mon Sep 17 00:00:00 2001 From: bhushanchirmade Date: Sat, 18 Jul 2020 19:18:55 -0500 Subject: [PATCH 234/655] Corrected URL There were 2 places where URL was not formed correctly. * Instead of execute-api it was only execute word * Instead of dot(.) after execute-api, it was dash(-) --- doc_source/serverless_example.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 71ac189e..23132502 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -737,7 +737,7 @@ https://GUID.execute-api-REGION.amazonaws.com/prod/ Test your app by getting the list of widgets \(currently empty\) by navigating to this URL in a browser, or use the following command\. ``` -curl -X GET 'https://GUID.execute-REGION.amazonaws.com/prod' +curl -X GET 'https://GUID.execute-api.REGION.amazonaws.com/prod' ``` You can also test the app by: @@ -1038,12 +1038,12 @@ cdk deploy We can now store, show, or delete an individual widget\. Use the following commands to list the widgets, create the widget **example**, list all of the widgets, show the contents of **example** \(it should show today's date\), delete **example**, and then show the list of widgets again\. ``` -curl -X GET 'https://GUID.execute-api-REGION.amazonaws.com/prod' -curl -X POST 'https://GUID.execute-api-REGION.amazonaws.com/prod/example' -curl -X GET 'https://GUID.execute-api-REGION.amazonaws.com/prod' -curl -X GET 'https://GUID.execute-api-REGION.amazonaws.com/prod/example' -curl -X DELETE 'https://GUID.execute-api-REGION.amazonaws.com/prod/example' -curl -X GET 'https://GUID.execute-api-REGION.amazonaws.com/prod' +curl -X GET 'https://GUID.execute-api.REGION.amazonaws.com/prod' +curl -X POST 'https://GUID.execute-api.REGION.amazonaws.com/prod/example' +curl -X GET 'https://GUID.execute-api.REGION.amazonaws.com/prod' +curl -X GET 'https://GUID.execute-api.REGION.amazonaws.com/prod/example' +curl -X DELETE 'https://GUID.execute-api.REGION.amazonaws.com/prod/example' +curl -X GET 'https://GUID.execute-api.REGION.amazonaws.com/prod' ``` You can also use the API Gateway console to test these functions\. Set the **name** value to the name of a widget, such as **example**\. @@ -1054,4 +1054,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` \ No newline at end of file +``` From 193072c283a49252ffba4ab6cec8ed123767fd48 Mon Sep 17 00:00:00 2001 From: Yerzhan <19510938+tashbenbetov@users.noreply.github.com> Date: Tue, 21 Jul 2020 12:41:38 +0300 Subject: [PATCH 235/655] Update getting_started.md Erase unnecessary symbols. --- doc_source/getting_started.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index ad76ec5f..ac1c1415 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -1,6 +1,6 @@ # Getting started with the AWS CDK -This topic introduces you to important AWS CDK concepts and describes how to install and configure the AWS CDK\. When you're done, you'll be ready to create [your first AWS CDK app\.](hello_world.md)\. +This topic introduces you to important AWS CDK concepts and describes how to install and configure the AWS CDK\. When you're done, you'll be ready to create [your first AWS CDK app](hello_world.md)\. ## Your background @@ -109,7 +109,7 @@ To help you use the AWS CDK in your favorite language, this Guide includes topic + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) -Furthermore, since TypeScript was the first language supported by the AWS CDK, much AWS CDK example code is written in TypeScript\. For this reason, this Guide also includes a topic specifically to show how to adapt TypeScript AWS CDK code for use with the other supported languages\. See [Translating TypeScript AWS CDK code to other languages ](multiple_languages.md)\. +Furthermore, since TypeScript was the first language supported by the AWS CDK, much AWS CDK example code is written in TypeScript\. For this reason, this Guide also includes a topic specifically to show how to adapt TypeScript AWS CDK code for use with the other supported languages\. See [Translating TypeScript AWS CDK code to other languages](multiple_languages.md)\. ## Prerequisites @@ -213,4 +213,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? From 7bb70b20c58181403abb76b0bad9e3e79c98914c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 21 Jul 2020 15:20:28 +0000 Subject: [PATCH 236/655] beef up deploy-to scripts with error-checking, Windows version to pass extra args correctly --- doc_source/environments.md | 62 ++++++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 23 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index 98145e30..33b14fbc 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -294,43 +294,59 @@ new MyDevStack(app, "dev", new StackProps { Env = makeEnv() }); ------ -With your stack's environment declared this way, you can now write a short script or batch file like the following to set the variables from command line arguments, then call `cdk deploy`\. +With your stack's environment declared this way, you can now write a short script or batch file like the following to set the variables from command line arguments, then call `cdk deploy`\. Any arguments beyond the first two are passed through to `cdk deploy` and can be used to specify command\-line options or stacks\. ------ #### [ Linux/Mac OS X ] ``` -#!/bin/bash -# cdk-deploy-to.sh -export CDK_DEPLOY_ACCOUNT=$1 -shift -export CDK_DEPLOY_REGION=$1 -shift -cdk deploy "$@" +#!/usr/bin/env bash +if [[ $# -ge 2 ]]; then + export CDK_DEPLOY_ACCOUNT=$1 + export CDK_DEPLOY_REGION=$2 + shift; shift + npx cdk deploy "$@" + exit $? +else + echo 1>&2 "Provide AWS account and region as first two args." + echo 1>&2 "Addiitonal args are passed through to cdk deploy." + exit 1 +fi ``` +Save the script as `cdk-deploy-to.sh`, then execute `chmod +x cdk-deploy-to.sh` to make it executable\. + ------ #### [ Windows ] ``` -@echo off -rem cdk-deploy-to.bat -set CDK_DEPLOY_ACCOUNT=%1 -set CDK_DEPLOY_REGION=%2 -cdk deploy %3 +@findstr /B /V @ %~dpnx0 > %~dpn0.ps1 && powershell -ExecutionPolicy Bypass %~dpn0.ps1 %* +@exit /B %ERRORLEVEL% +if ($args.length -ge 2) { + $env:CDK_DEPLOY_ACCOUNT, $args = $args + $env:CDK_DEPLOY_REGION, $args = $args + npx cdk deploy $args + exit $lastExitCode +} else { + [console]::error.writeline("Provide AWS account and region as first two args.") + [console]::error.writeline("Additional args are passed through to cdk deploy.") + exit 1 +} ``` +The Windows version of the script uses PowerShell to provide the same functionality as the Linux/Mac OS X version\. It also contains instructions to allow it to be run as a batch file so it can be easily invoked from a command line\. It should be saved as `cdk-deploy-to.bat`\. The file `cdk-deploy-to.ps1` will be created when the batch file is invoked\. + ------ -Then you can write additional scripts that call that script to deploy to specific environments \(even multiple environments per script\): +Then you can write additional scripts that call the "deploy\-to" script to deploy to specific environments \(even multiple environments per script\): ------ #### [ Linux/Mac OS X ] ``` -#!/bin/bash +#!/usr/bin/env bash # cdk-deploy-to-test.sh -bash cdk-deploy-to.sh 123457689 us-east-1 "$@" +./cdk-deploy-to.sh 123457689 us-east-1 "$@" ``` ------ @@ -339,7 +355,7 @@ bash cdk-deploy-to.sh 123457689 us-east-1 "$@" ``` @echo off rem cdk-deploy-to-test.bat -cdk-deploy-to 135792469 us-east-1 %1 +cdk-deploy-to 135792469 us-east-1 %* ``` ------ @@ -350,10 +366,10 @@ When deploying to multiple environments, consider whether you want to continue d #### [ Linux/Mac OS X ] ``` -#!/bin/bash +#!/usr/bin/env bash # cdk-deploy-to-prod.sh -bash cdk-deploy-to.sh 135792468 us-west-1 "$@" || exit -bash cdk-deploy-to.sh 246813579 eu-west-1 "$@" +./cdk-deploy-to.sh 135792468 us-west-1 "$@" || exit +./cdk-deploy-to.sh 246813579 eu-west-1 "$@" ``` ------ @@ -362,10 +378,10 @@ bash cdk-deploy-to.sh 246813579 eu-west-1 "$@" ``` @echo off rem cdk-deploy-to-prod.bat -cdk-deploy-to 135792469 us-west-1 %1 || goto :eof -cdk-deploy-to 245813579 eu-west-1 %1 +cdk-deploy-to 135792469 us-west-1 %* || exit /B +cdk-deploy-to 245813579 eu-west-1 %* ``` ------ -Developers would continue to use the normal `cdk deploy` command to deploy to their own AWS environments\. +Developers could still use the normal `cdk deploy` command to deploy to their own AWS environments for development\. \ No newline at end of file From d3df56a68d2eb8d5420c30e50954ef1ba27ab345 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 21 Jul 2020 23:11:30 +0000 Subject: [PATCH 237/655] newlines (no content changes) --- doc_source/getting_started.md | 2 +- doc_source/hello_world.md | 2 +- doc_source/serverless_example.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index ac1c1415..430fc987 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -213,4 +213,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index b630b4b3..6941b2b2 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -707,4 +707,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 23132502..6e781a75 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -1054,4 +1054,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` +``` \ No newline at end of file From 2f8281b92a19d2909afe13664dd764ab8ae04a54 Mon Sep 17 00:00:00 2001 From: Yerzhan <19510938+tashbenbetov@users.noreply.github.com> Date: Wed, 22 Jul 2020 18:00:30 +0300 Subject: [PATCH 238/655] Update hello_word.md From HelloSCdktack to HelloCdkStack --- doc_source/hello_world.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 6941b2b2..c171a1a9 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -492,7 +492,7 @@ It is optional \(though good practice\) to synthesize before deploying\. The AWS If your code changes have security implications, you'll see a summary of these, and be asked to confirm them before deployment proceeds\. -`cdk deploy` displays progress information as your stack is deployed\. When it's done, the command prompt reappears\. You can go to the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home) and see that it now lists `HelloSCdktack`\. You'll also find `MyFirstBucket` in the Amazon S3 console\. +`cdk deploy` displays progress information as your stack is deployed\. When it's done, the command prompt reappears\. You can go to the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home) and see that it now lists `HelloCdkStack`\. You'll also find `MyFirstBucket` in the Amazon S3 console\. You've deployed your first stack using the AWS CDK—congratulations\! But that's not all there is to the AWS CDK\. @@ -707,4 +707,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? From aa0878e5f979b8691f3b806790b96c7bda62ae65 Mon Sep 17 00:00:00 2001 From: Daniel Neilson Date: Wed, 29 Jul 2020 17:46:24 +0000 Subject: [PATCH 239/655] Adds AWS RFDK to version reporting section The AWS RFDK is a product that is being released shortly, and we are adding tracking of its usage to the CDK's version reporting metadata. --- doc_source/cli.md | 471 +++++++++++++++++++++++----------------------- 1 file changed, 236 insertions(+), 235 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index ea9ba151..b5646d24 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -57,6 +57,7 @@ By default, the AWS CDK reports the name and version of the following NPM module + AWS CDK core module + AWS Construct Library modules + AWS Solutions Constructs module ++ AWS Render Farm Deployment Kit module The `AWS::CDK::Metadata` resource looks something like the following\. @@ -64,7 +65,7 @@ The `AWS::CDK::Metadata` resource looks something like the following\. CDKMetadata: Type: "AWS::CDK::Metadata" Properties: - Modules: "@aws-cdk/core=X.YY.Z,@aws-cdk/s3=X.YY.Z,@aws-solutions-consturcts/aws-apigateway-lambda=X.YY.Z" + Modules: "@aws-cdk/core=X.YY.Z,@aws-cdk/s3=X.YY.Z,@aws-solutions-consturcts/aws-apigateway-lambda=X.YY.Z,aws-rfdk=X.YY.Z" ``` To opt out of version reporting, use one of the following methods: @@ -387,287 +388,287 @@ cdk diff --template ~/stacks/MyStack.old MyStack This section provides a reference for the AWS CDK Toolkit derived from its help, first a general reference with the options available with all commands, then \(in collapsible sections\) specific references with options available only with specific subcommands\. ``` -Usage: cdk -a COMMAND - -Commands: - - cdk list [STACKS..] Lists all stacks in the app [aliases: ls] - - cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation - template for this stack [aliases: synth] - - cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS - environment - - cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your - AWS account - - cdk destroy [STACKS..] Destroy the stack(s) named STACKS - - cdk diff [STACKS..] Compares the specified stack with the deployed - stack or a local template file, and returns - with status 1 if any difference is found - - cdk metadata [STACK] Returns all metadata associated with this - stack - - cdk init [TEMPLATE] Create a new, empty CDK project from a - template. Invoked without TEMPLATE, the app - template will be used. - - cdk context Manage cached context values - - cdk docs Opens the reference documentation in a browser - [aliases: doc] - - cdk doctor Check your set-up for potential problems - -Options: - - --app, -a REQUIRED: command-line for executing your app or a cloud - assembly directory (e.g. "node bin/my-app.js") [string] - - --context, -c Add contextual string parameter (KEY=VALUE) [array] - - --plugin, -p Name or path of a node package that extend the CDK - features. Can be specified multiple times [array] - - --trace Print trace for stack warnings [boolean] - - --strict Do not construct stacks with warnings [boolean] - - --ignore-errors Ignores synthesis errors, which will likely produce an - invalid output [boolean] [default: false] - - --json, -j Use JSON output instead of YAML when templates are - printed to STDOUT [boolean] [default: false] - - --verbose, -v Show debug logs (specify multiple times to increase - verbosity) [count] [default: false] - - --profile Use the indicated AWS profile as the default environment - [string] - - --proxy Use the indicated proxy. Will read from HTTPS_PROXY - environment variable if not specified. [string] - - --ca-bundle-path Path to CA certificate to use when validating HTTPS - requests. Will read from AWS_CA_BUNDLE environment - variable if not specified. [string] - - --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: - guess EC2 instance status. [boolean] - - --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized - templates (enabled by default) [boolean] - - --path-metadata Include "aws:cdk:path" CloudFormation metadata for each - resource (enabled by default) [boolean] [default: true] - - --asset-metadata Include "aws:asset:*" CloudFormation metadata for - resources that user assets (enabled by default) - [boolean] [default: true] - - --role-arn, -r ARN of Role to use when invoking CloudFormation [string] - - --toolkit-stack-name The name of the CDK toolkit stack [string] - - --staging Copy assets to the output directory (use --no-staging to - disable, needed for local debugging the source files - with SAM CLI) [boolean] [default: true] - - --output, -o Emits the synthesized cloud assembly into a directory - (default: cdk.out) [string] - - --no-color Removes colors and other style from console output - [boolean] [default: false] - - --fail Fail with exit code 1 in case of diff - [boolean] [default: false] - - --version Show version number [boolean] - - -h, --help Show help [boolean] - -If your app has a single stack, there is no need to specify the stack name - -If one of cdk.json or ~/.cdk.json exists, options specified there will be used +Usage: cdk -a COMMAND + +Commands: + + cdk list [STACKS..] Lists all stacks in the app [aliases: ls] + + cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation + template for this stack [aliases: synth] + + cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS + environment + + cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your + AWS account + + cdk destroy [STACKS..] Destroy the stack(s) named STACKS + + cdk diff [STACKS..] Compares the specified stack with the deployed + stack or a local template file, and returns + with status 1 if any difference is found + + cdk metadata [STACK] Returns all metadata associated with this + stack + + cdk init [TEMPLATE] Create a new, empty CDK project from a + template. Invoked without TEMPLATE, the app + template will be used. + + cdk context Manage cached context values + + cdk docs Opens the reference documentation in a browser + [aliases: doc] + + cdk doctor Check your set-up for potential problems + +Options: + + --app, -a REQUIRED: command-line for executing your app or a cloud + assembly directory (e.g. "node bin/my-app.js") [string] + + --context, -c Add contextual string parameter (KEY=VALUE) [array] + + --plugin, -p Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] + + --trace Print trace for stack warnings [boolean] + + --strict Do not construct stacks with warnings [boolean] + + --ignore-errors Ignores synthesis errors, which will likely produce an + invalid output [boolean] [default: false] + + --json, -j Use JSON output instead of YAML when templates are + printed to STDOUT [boolean] [default: false] + + --verbose, -v Show debug logs (specify multiple times to increase + verbosity) [count] [default: false] + + --profile Use the indicated AWS profile as the default environment + [string] + + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified. [string] + + --ca-bundle-path Path to CA certificate to use when validating HTTPS + requests. Will read from AWS_CA_BUNDLE environment + variable if not specified. [string] + + --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: + guess EC2 instance status. [boolean] + + --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized + templates (enabled by default) [boolean] + + --path-metadata Include "aws:cdk:path" CloudFormation metadata for each + resource (enabled by default) [boolean] [default: true] + + --asset-metadata Include "aws:asset:*" CloudFormation metadata for + resources that user assets (enabled by default) + [boolean] [default: true] + + --role-arn, -r ARN of Role to use when invoking CloudFormation [string] + + --toolkit-stack-name The name of the CDK toolkit stack [string] + + --staging Copy assets to the output directory (use --no-staging to + disable, needed for local debugging the source files + with SAM CLI) [boolean] [default: true] + + --output, -o Emits the synthesized cloud assembly into a directory + (default: cdk.out) [string] + + --no-color Removes colors and other style from console output + [boolean] [default: false] + + --fail Fail with exit code 1 in case of diff + [boolean] [default: false] + + --version Show version number [boolean] + + -h, --help Show help [boolean] + +If your app has a single stack, there is no need to specify the stack name + +If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` ### `cdk list` \(`ls`\) ``` -cdk list [STACKS..] - -Lists all stacks in the app - -Options: - - --long, -l Display environment information for each stack +cdk list [STACKS..] + +Lists all stacks in the app + +Options: + + --long, -l Display environment information for each stack [boolean] [default: false] ``` ### `cdk synthesize` \(`synth`\) ``` -cdk synthesize [STACKS..] - -Synthesizes and prints the CloudFormation template for this stack - -Options: - - --exclusively, -e Only synthesize requested stacks, don't include +cdk synthesize [STACKS..] + +Synthesizes and prints the CloudFormation template for this stack + +Options: + + --exclusively, -e Only synthesize requested stacks, don't include dependencies [boolean] ``` ### `cdk bootstrap` ``` -cdk bootstrap [ENVIRONMENTS..] - -Deploys the CDK toolkit stack into an AWS environment - -Options: - - --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket; - --toolkit-bucket-name bucket will be created and must not - exist [string] - - --bootstrap-kms-key-id AWS KMS master key ID used for the - SSE-KMS encryption [string] - - --qualifier Unique string to distinguish - multiple bootstrap stacks [string] - - --public-access-block-configuration Block public access configuration - on CDK toolkit bucket (enabled by - default) [boolean] [default: true] - - --tags, -t Tags to add for the stack - (KEY=VALUE) [array] [default: []] - - --execute Whether to execute ChangeSet - (--no-execute will NOT execute the - ChangeSet) [boolean] [default: true] - - --force, -f Always bootstrap even if it would - downgrade template version +cdk bootstrap [ENVIRONMENTS..] + +Deploys the CDK toolkit stack into an AWS environment + +Options: + + --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket; + --toolkit-bucket-name bucket will be created and must not + exist [string] + + --bootstrap-kms-key-id AWS KMS master key ID used for the + SSE-KMS encryption [string] + + --qualifier Unique string to distinguish + multiple bootstrap stacks [string] + + --public-access-block-configuration Block public access configuration + on CDK toolkit bucket (enabled by + default) [boolean] [default: true] + + --tags, -t Tags to add for the stack + (KEY=VALUE) [array] [default: []] + + --execute Whether to execute ChangeSet + (--no-execute will NOT execute the + ChangeSet) [boolean] [default: true] + + --force, -f Always bootstrap even if it would + downgrade template version [boolean] [default: false] ``` ### `cdk deploy` ``` -cdk deploy [STACKS..] - -Deploys the stack(s) named STACKS into your AWS account - -Options: - - --build-exclude, -E Do not rebuild asset with the given ID. Can be - specified multiple times. [array] [default: []] - - --exclusively, -e Only deploy requested stacks, don't include - dependencies [boolean] - - --require-approval What security-sensitive changes need manual approval - [string] [choices: "never", "any-change", "broadening"] - - --ci Force CI detection (deprecated) - [boolean] [default: false] - - --notification-arns ARNs of SNS topics that CloudFormation will notify with - stack related events [array] - - --tags, -t Tags to add to the stack (KEY=VALUE) [array] - - --execute Whether to execute ChangeSet (--no-execute will NOT - execute the ChangeSet) [boolean] [default: true] - - --force, -f Always deploy stack even if templates are identical - [boolean] [default: false] - - --parameters Additional parameters passed to CloudFormation at - deploy time (STACK:KEY=VALUE) [array] [default: {}] - - --outputs-file, -O Path to file where stack outputs will be written as - JSON [string] - - --previous-parameters Use previous values for existing parameters (you must - specify all parameters on every deployment if this is +cdk deploy [STACKS..] + +Deploys the stack(s) named STACKS into your AWS account + +Options: + + --build-exclude, -E Do not rebuild asset with the given ID. Can be + specified multiple times. [array] [default: []] + + --exclusively, -e Only deploy requested stacks, don't include + dependencies [boolean] + + --require-approval What security-sensitive changes need manual approval + [string] [choices: "never", "any-change", "broadening"] + + --ci Force CI detection (deprecated) + [boolean] [default: false] + + --notification-arns ARNs of SNS topics that CloudFormation will notify with + stack related events [array] + + --tags, -t Tags to add to the stack (KEY=VALUE) [array] + + --execute Whether to execute ChangeSet (--no-execute will NOT + execute the ChangeSet) [boolean] [default: true] + + --force, -f Always deploy stack even if templates are identical + [boolean] [default: false] + + --parameters Additional parameters passed to CloudFormation at + deploy time (STACK:KEY=VALUE) [array] [default: {}] + + --outputs-file, -O Path to file where stack outputs will be written as + JSON [string] + + --previous-parameters Use previous values for existing parameters (you must + specify all parameters on every deployment if this is disabled) [boolean] [default: true] ``` ### `cdk destroy` ``` -cdk destroy [STACKS..] - -Destroy the stack(s) named STACKS - -Options: - - --exclusively, -e Only destroy requested stacks, don't include dependees - [boolean] - - --force, -f Do not ask for confirmation before destroying the stacks +cdk destroy [STACKS..] + +Destroy the stack(s) named STACKS + +Options: + + --exclusively, -e Only destroy requested stacks, don't include dependees + [boolean] + + --force, -f Do not ask for confirmation before destroying the stacks [boolean] ``` ### `cdk diff` ``` -cdk diff [STACKS..] - -Compares the specified stack with the deployed stack or a local template file, -and returns with status 1 if any difference is found - -Options: - - --exclusively, -e Only diff requested stacks, don't include dependencies - [boolean] - - --context-lines Number of context lines to include in arbitrary JSON - diff rendering [number] [default: 3] - - --template The path to the CloudFormation template to compare with +cdk diff [STACKS..] + +Compares the specified stack with the deployed stack or a local template file, +and returns with status 1 if any difference is found + +Options: + + --exclusively, -e Only diff requested stacks, don't include dependencies + [boolean] + + --context-lines Number of context lines to include in arbitrary JSON + diff rendering [number] [default: 3] + + --template The path to the CloudFormation template to compare with [string] ``` ### `cdk init` ``` -cdk init [TEMPLATE] - -Create a new, empty CDK project from a template. Invoked without TEMPLATE, the -app template will be used. - -Options: - - --language, -l The language to be used for the new project (default can - be configured in ~/.cdk.json) - [string] [choices: "csharp", "fsharp", "java", "javascript", "python", - "typescript"] - - --list List the available templates [boolean] - - --generate-only If true, only generates project files, without executing - additional operations such as setting up a git repo, - installing dependencies or compiling the project +cdk init [TEMPLATE] + +Create a new, empty CDK project from a template. Invoked without TEMPLATE, the +app template will be used. + +Options: + + --language, -l The language to be used for the new project (default can + be configured in ~/.cdk.json) + [string] [choices: "csharp", "fsharp", "java", "javascript", "python", + "typescript"] + + --list List the available templates [boolean] + + --generate-only If true, only generates project files, without executing + additional operations such as setting up a git repo, + installing dependencies or compiling the project [boolean] [default: false] ``` ### `cdk context` ``` -cdk context - -Manage cached context values - -Options: - - --reset, -e The context key (or its index) to reset [string] - +cdk context + +Manage cached context values + +Options: + + --reset, -e The context key (or its index) to reset [string] + --clear Clear all context [boolean] ``` \ No newline at end of file From d0b75b00ed3e57b98b49d0c4be3bd8fcad7a4fb7 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 29 Jul 2020 23:53:57 +0000 Subject: [PATCH 240/655] Add CDK Pipelines how-to --- doc_source/cdk_pipeline.md | 1772 ++++++++++++++++++++++++++++++++++++ doc_source/index.md | 1 + 2 files changed, 1773 insertions(+) create mode 100644 doc_source/cdk_pipeline.md diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md new file mode 100644 index 00000000..4121b408 --- /dev/null +++ b/doc_source/cdk_pipeline.md @@ -0,0 +1,1772 @@ +# Continuous integration and delivery \(CI/CD\) using CDK Pipelines + +[CDK Pipelines](https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html) is a construct library module for painless continuous delivery of AWS CDK applications\. Whenever you check your AWS CDK app's source code in to AWS CodeCommit, GitHub, or BitBucket, CDK Pipelines can automatically build, test, and deploy your new version\. + +CDK Pipelines are self\-updating: if you add new application stages or new stacks, the pipeline automatically reconfigures itself to deploy those new stages and/or stacks\. + +If you've looked at our [AWS CodePipeline example](codepipeline_example.md), CDK Pipelines can do everything that example does, and more, with less code\. Going forward, we anticipate widespread adoption of CDK Pipelines by AWS CDK users\. + +**Note** +CDK Pipelines is currently in developer preview, and its API is subject to change\. Breaking API changes will be announced in the AWS CDK [Release Notes](https://github.com/aws/aws-cdk/releases)\. + +## Bootstrap your AWS environments + +Before you can use CDK Pipelines, you must bootstrap the AWS environment\(s\) to which you will deploy your stacks\. An [environment](environments.md) is an account/region pair to which you want to deploy a CDK stack\. A CDK Pipeline involves at least two environments: the environment where the pipeline is provisioned, and the environment where you want to deploy the application's stacks \(or its stages, which are groups of related stacks\)\. These environments can be the same, though best practices recommend you isolate stages from each other in different AWS accounts or regions\. + +You may have already bootstrapped one or more environments so you can deploy assets and Lambda functions using the AWS CDK\. Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include additional resources, so the stack has been extended to include an additional Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. This new style of CDK Toolkit stack will eventually become the default, but at this writing, you must opt in\. The AWS CDK Toolkit will upgrade your existing bootstrap stack or create a new one, as necessary\. + +To bootstrap an environment that will provision a pipeline: + +------ +#### [ Linux/Mac OS X ] + +``` +CDK_NEW_BOOTSTRAP=1 +npx cdk bootstrap --profile ADMIN-PROFILE \ + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ + aws://ACCOUNT-ID/REGION +``` + +------ +#### [ Windows ] + +``` +set CDK_NEW_BOOTSTRAP=1 +npx cdk bootstrap --profile ADMIN-PROFILE ^ + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ + aws://ACCOUNT-ID/REGION +``` + +------ + +To bootstrap additional environments into which AWS CDK applications will be deployed by the pipeline: + +------ +#### [ Linux/Mac OS X ] + +``` +CDK_NEW_BOOTSTRAP=1 +npx cdk bootstrap --profile ADMIN-PROFILE \ + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ + --trust PIPELINE-ACCOUNT-ID \ + aws://ACCOUNT-ID/REGION +``` + +------ +#### [ Windows ] + +``` +set CDK_NEW_BOOTSTRAP=1 +npx cdk bootstrap --profile ADMIN-PROFILE ^ + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ + --trust PIPELINE-ACCOUNT-ID ^ + aws://ACCOUNT-ID/REGION +``` + +------ + +Note the following: ++ `CDK_NEW_BOOTSTRAP` is a variable that enables the bootstrapping of the new style of Toolkit stack required by the CDK Pipelines feature\. ++ *`ADMIN-PROFILE`* is a profile defined in your AWS configuration files that has credentials for the account and region being bootstrapped\. You may omit `--profile` and this value if you are using the default profile or the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to provide your AWS account credentials\. ++ `npx cdk` invokes the AWS CDK Toolkit, either the version installed in your project if any, or the global installation\. ++ `--cloudformation-execution-policies` specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The `AdministratorAccess` policy is the default; your organization may require a more constrained policy\. ++ `--trust` \(in the second example\) indicates which other accounts should have permissions to deploy AWS CDK applications into this environment\. This should be the pipeline's AWS account ID\. ++ `aws://ACCOUNT-ID/REGION` is the account and region we're bootstrapping\. It may be omitted if you are bootstrapping the profile's default region\. + +**Tip** +Use administrative credentials only to bootstrap and to provision the initial pipeline\. Drop administrative credentials as soon as possible\. + +If you are upgrading an existing bootstrapped environment, the old Amazon S3 bucket is orphaned when the new bucket is created\. Delete it manually using the Amazon S3 console\. + +## Initialize project + +Create a new, empty GitHub project and clone it to your workstation in the `cdk-pipeline` directory\. \(Our code examples in this topic use GitHub; you can also use BitBucket or AWS CodeCommit\.\) + +``` +git clone GITHUB-CLONE-URL my-pipeline +cd my-pipeline +``` + +**Note** +You may use a name other than `my-pipeline` for your app's main directory, but since the AWS CDK Toolkit bases some file and class names on the name of the main directory, you'll need to tweak these later in this topic\. + +After cloning, initialize the project as usual\. + +------ +#### [ TypeScript ] + +``` +cdk init app --language typescript +``` + +------ +#### [ JavaScript ] + +``` +cdk init app --language javascript +``` + +------ +#### [ Python ] + +``` +cdk init app --language python +``` + +After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install its dependencies\. + +``` +source .env/bin/activate +python -m pip install -r requirements.txt +``` + +------ +#### [ Java ] + +``` +cdk init app --language java +``` + +If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set ta use Java 8 \(1\.8\)\. + +------ +#### [ C\# ] + +``` +cdk init app --language csharp +``` + +If you are using Visual Studio, open the solution file in the `src` directory\. + +------ + +Install the CDK Pipelines module along with others you'll be using\. + +------ +#### [ TypeScript ] + +``` +npm install @aws-cdk/pipelines @aws-cdk/aws-codebuild +npm install @aws-cdk/aws-codepipeline @aws-cdk/aws-codepipeline-actions +``` + +------ +#### [ JavaScript ] + +``` +npm install @aws-cdk/pipelines @aws-cdk/aws-codebuild +npm install @aws-cdk/aws-codepipeline @aws-cdk/aws-codepipeline-actions +``` + +------ +#### [ Python ] + +``` +python -m pip install aws_cdk.pipelines aws_cdk.aws_codebuild +python -m pip install aws_cdk.aws_codepipeline aws_cdk.aws_codepipeline_actions +``` + +Freeze your dependencies in `requirements.txt`\. + +**Linux/Mac OS X** + +``` +python -m pip freeze | grep -v '^[-#]' > requirements.txt +``` + +**Windows** + +``` +python -m pip freeze | findstr /R /B /V "[-#]" > requirements.txt +``` + +------ +#### [ Java ] + +Edit your project's `pom.xml` and add a `` element for the `pipeline` module and a few others you'll need\. Follow the template below for each module, placing each inside the existing `` container\. + +``` + + software.amazon.awscdk + cdk-pipelines + ${cdk.version} + + + software.amazon.awscdk + codebuild + ${cdk.version} + + + software.amazon.awscdk + codepipeline + ${cdk.version} + + + software.amazon.awscdk + codepipeline-actions + ${cdk.version} + +``` + +``` +``` + +------ +#### [ C\# ] + +In Visual Studio, choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio and add the following packages\. Make sure the **Include prerelease** checkbox is marked, since the CDK Pipelines module is in developer preview\. + +``` +Amazon.CDK.Pipelines +Amazon.CDK.AWS.CodeBuild +Amazon.CDK.AWS.CodePipeline +Amazon.CDK.AWS.CodePipeline.Actions +``` + +------ + +Finally, add the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featureflags.md) to the new project's `cdk.json` file\. The file will already contain some context values; add this new one inside the `context` object\. + +``` +{ + ... + "context": { + ... + "@aws-cdk/core:newStyleStackSynthesis": "true" + } +} +``` + +In a future release of the AWS CDK, "new style" stack synthesis will become the default, but for now we need to opt in using the feature flag\. + +## Define pipelines + +The construct [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CdkPipeline.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CdkPipeline.html) is the construct that represents a CDK Pipeline\. When you instantiate `CdkPipeline` in a stack, you define the source location for the pipeline as well as the build commands\. For example, the following defines a pipeline whose source is stored in a GitHub repository, and includes a build step for a TypeScript application\. The Pipeline will be provisioned in account `111111111111` and region `eu-west-1`\. + +------ +#### [ TypeScript ] + +In `lib/my-pipeline-stack.ts` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +import { Stack, StackProps, Construct, SecretValue } from '@aws-cdk/core'; +import { CdkPipeline, SimpleSynthAction } from '@aws-cdk/pipelines'; + +import * as codepipeline from '@aws-cdk/aws-codepipeline'; +import * as codepipeline_actions from '@aws-cdk/aws-codepipeline-actions'; + +export class MyPipelineStack extends Stack { + constructor(scope: Construct, id: string, props?: StackProps) { + super(scope, id, props); + + const sourceArtifact = new codepipeline.Artifact(); + const cloudAssemblyArtifact = new codepipeline.Artifact(); + + const pipeline = new CdkPipeline(this, 'Pipeline', { + pipelineName: 'MyAppPipeline', + cloudAssemblyArtifact, + + sourceAction: new codepipeline_actions.GitHubSourceAction({ + actionName: 'GitHub', + output: sourceArtifact, + oauthToken: SecretValue.secretsManager('GITHUB_TOKEN_NAME'), + trigger: codepipeline_actions.GitHubTrigger.POLL, + // Replace these with your actual GitHub project info + owner: 'GITHUB-OWNER', + repo: 'GITHUB-REPO', + }), + + synthAction: SimpleSynthAction.standardNpmSynth({ + sourceArtifact, + cloudAssemblyArtifact, + + // Use this if you need a build step (if you're not using ts-node + // or if you have TypeScript Lambdas that need to be compiled). + buildCommand: 'npm run build', + }), + }); + } +} +``` + +In `bin/my-pipeline.ts` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +#!/usr/bin/env node +import 'source-map-support/register'; +import * as cdk from '@aws-cdk/core'; +import { MyPipelineStack } from '../lib/my-pipeline-stack'; + +const app = new cdk.App(); +new MyPipelineStack(app, 'PipelineStack', { + env: { + account: '111111111111', + region: 'eu-west-1', + } +}); + +app.synth(); +``` + +------ +#### [ JavaScript ] + +In `lib/my-pipeline-stack.js` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +const { Stack, SecretValue } = require('@aws-cdk/core'); +const { CdkPipeline, SimpleSynthAction } = require('@aws-cdk/pipelines'); + +const codepipeline = require('@aws-cdk/aws-codepipeline'); +const codepipeline_actions = require('@aws-cdk/aws-codepipeline-actions'); + +class MyPipelineStack extends Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const sourceArtifact = new codepipeline.Artifact(); + const cloudAssemblyArtifact = new codepipeline.Artifact(); + + const pipeline = new CdkPipeline(this, 'Pipeline', { + pipelineName: 'MyAppPipeline', + cloudAssemblyArtifact, + + sourceAction: new codepipeline_actions.GitHubSourceAction({ + actionName: 'GitHub', + output: sourceArtifact, + oauthToken: SecretValue.secretsManager('GITHUB_TOKEN_NAME'), + trigger: codepipeline_actions.GitHubTrigger.POLL, + // Replace these with your actual GitHub project info + owner: 'GITHUB-OWNER', + repo: 'GITHUB-REPO' + }), + + synthAction: SimpleSynthAction.standardNpmSynth({ + sourceArtifact, + cloudAssemblyArtifact, + + // Use this if you need a build step (if you're not using ts-node + // or if you have TypeScript Lambdas that need to be compiled). + buildCommand: 'npm run build' + }) + }); + } +} + +module.exports = { MyPipelineStack } +``` + +In `bin/my-pipeline.js` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +#!/usr/bin/env node + +const cdk = require('@aws-cdk/core'); +const { MyPipelineStack } = require('../lib/my-pipeline-stack'); + +const app = new cdk.App(); +new MyPipelineStack(app, 'PipelineStack', { + env: { + account: '111111111111', + region: 'eu-west-1' + } +}); + +app.synth(); +``` + +------ +#### [ Python ] + +In `my-pipeline/my-pipeline-stack.js` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +from aws_cdk.core import Stack, StackProps, Construct, SecretValue +from aws_cdk.pipelines import CdkPipeline, SimpleSynthAction + +import aws_cdk.aws_codepipeline as codepipeline +import aws_cdk.aws_codepipeline_actions as codepipeline_actions + +class MyPipelineStack(Stack): + + def __init__(self, scope: Construct, id: str, **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + source_artifact = codepipeline.Artifact() + cloud_assembly_artifact = codepipeline.Artifact() + + pipeline = CdkPipeline(self, "Pipeline", + pipeline_name="MyAppPipeline", + cloud_assembly_artifact=cloud_assembly_artifact, + source_action=codepipeline_actions.GitHubSourceAction( + action_name="GitHub", + output=source_artifact, + oauth_token=SecretValue.secrets_manager("GITHUB_TOKEN_NAME"), + trigger=codepipeline_actions.GitHubTrigger.POLL, + # Replace these with your actual GitHub project info + owner="GITHUB-OWNER", + repo="GITHUB-REPO"), + synth_action=SimpleSynthAction.standard_npm_synth( + source_artifact=source_artifact, + cloud_assembly_artifact=cloud_assembly_artifact, + # Use this if you need a build step (if you're not using ts-node + # or if you have TypeScript Lambdas that need to be compiled). + build_command="npm run build" + ) + ) +``` + +In `app.py`: + +``` +#!/usr/bin/env python3 + +from aws_cdk import core +from my_pipeline.my_pipeline_stack import MyPipelineStack + +app = core.App() +MyPipelineStack(app, "my-pipeline", + env=core.Environment(account="111111111111", region="eu-west-1")) +app.synth() +``` + +------ +#### [ Java ] + +In `src/main/java/com/myorg/MyPipelineStack.java` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +package com.myorg; + +import software.amazon.awscdk.core.Construct; +import software.amazon.awscdk.core.SecretValue; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; +import software.amazon.awscdk.pipelines.CdkPipeline; +import software.amazon.awscdk.pipelines.SimpleSynthAction; +import software.amazon.awscdk.pipelines.StandardNpmSynthOptions; +import software.amazon.awscdk.services.codepipeline.Artifact; +import software.amazon.awscdk.services.codepipeline.actions.GitHubSourceAction; +import software.amazon.awscdk.services.codepipeline.actions.GitHubTrigger; + +public class MyPipelineStack extends Stack { + public MyPipelineStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyPipelineStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + final Artifact sourceArtifact = new Artifact(); + final Artifact cloudAssemblyArtifact = new Artifact(); + + final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") + .pipelineName("MyAppPipeline") + .cloudAssemblyArtifact(cloudAssemblyArtifact) + .sourceAction(GitHubSourceAction.Builder.create() + .actionName("GitHub") + .output(sourceArtifact) + .oauthToken(SecretValue.secretsManager("GITHUB_TOKEN_NAME")) + .trigger(GitHubTrigger.POLL) + .owner("GITHUB-OWNER") + .repo("GITHUB-REPO") + .build()) + .synthAction(SimpleSynthAction.standardNpmSynth( + StandardNpmSynthOptions.builder() + .sourceArtifact(sourceArtifact) + .cloudAssemblyArtifact(cloudAssemblyArtifact) + .buildCommand("npm run build") + .build())) + .build(); + } +} +``` + +In `src/main/java/com/myorg/MyPipelineApp.java` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +package com.myorg; + +import software.amazon.awscdk.core.App; +import software.amazon.awscdk.core.Environment; + +public class MyPipelineApp { + public static void main(final String[] args) { + App app = new App(); + + MyPipelineStack.Builder.create(app, "PipelineStack") + .env(new Environment.Builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build(); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +In `src/MyPipeline/MyPipelineStack.cs` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +using Amazon.CDK; +using Amazon.CDK.Pipelines; +using Amazon.CDK.AWS.CodePipeline; +using Amazon.CDK.AWS.CodePipeline.Actions; + +namespace MyPipeline +{ + public class MyPipelineStack : Stack + { + internal MyPipelineStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) + { + var sourceArtifact = new Artifact_(); + var cloudAssemblyArtifact = new Artifact_(); + + var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps + { + PipelineName = "MyAppPipeline", + CloudAssemblyArtifact = cloudAssemblyArtifact, + SourceAction = new GitHubSourceAction(new GitHubSourceActionProps + { + ActionName = "GitHub", + Output = sourceArtifact, + OauthToken = SecretValue.SecretsManager("GITHUB TOKEN_NAME"), + Trigger = GitHubTrigger.POLL, + Owner = "GITHUB-OWNER", + Repo = "GITHUB-REPO" + }), + SynthAction = SimpleSynthAction.StandardNpmSynth(new StandardNpmSynthOptions + { + SourceArtifact = sourceArtifact, + CloudAssemblyArtifact = cloudAssemblyArtifact, + BuildCommand = "npm run build" + }) + }); + } + } +} +``` + +In `src/MyPipeline/Program.cs` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +using Amazon.CDK; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace MyPipeline +{ + sealed class Program + { + public static void Main(string[] args) + { + var app = new App(); + new MyPipelineStack(app, "MyPipelineStack", new StackProps + { + Env = new Amazon.CDK.Environment + { + Account = "111111111111", + Region = "eu-west-1" + } + }); + app.Synth(); + } + } +} +``` + +------ + +Note the following in this example: ++ The source code is stored in a GitHub repository\. ++ The GitHub access token needed to access the repo is retrieved from AWS Secrets Manager\. Provide the name of the secret where indicated\. ++ Specify the owner of the repository and the repo name where indicated\. + +You must deploy a CDK Pipeline manually once\. After that, the pipeline will keep itself up to date from the source code repository\. To perform the initial deployment: + +``` +git add --all +git commit -m "initial commit" +git push +cdk deploy +``` + +**Tip** +Now that you've done the initial deployment, you no longer need AWS administrative access\. + +## Sources and synth actions + +As we've seen in the preceding example, the basic pieces of CDK pipelines are *sources* and *synth actions*\. + +Sources are places where your code lives\. Any source from the [codepipeline\-actions](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-codepipeline-actions-readme.html) module can be used\. + +Synth actions \(`synthAction`\) define how to build and synth the project\. A synth action can be any AWS CodePipeline action that produces an artifact containing an AWS CDK Cloud Assembly \(the `cdk.out` directory created by `cdk synth`\)\. Pass the output artifact of the synth operation in the Pipeline's `cloudAssemblyArtifact` property\. + +`SimpleSynthAction` is available for synths that can be performed by running a couple of simple shell commands \(install, build, and synth\) using AWS CodeBuild\. When using these, the source repository does not require a `buildspec.yml`\. Here's an example of using `[SimpleSynthAction](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.SimpleSynthAction.html)` to run a Maven \(Java\) build followed by a `cdk synth`: + +------ +#### [ TypeScript ] + +``` +const pipeline = new CdkPipeline(this, 'Pipeline', { + // ... + synthAction: new SimpleSynthAction({ + sourceArtifact, + cloudAssemblyArtifact, + installCommand: 'npm install -g aws-cdk', + buildCommand: 'mvn package', + synthCommand: 'cdk synth', + }) +}); +``` + +------ +#### [ JavaScript ] + +``` +const pipeline = new CdkPipeline(this, 'Pipeline', { + // ... + synthAction: new SimpleSynthAction({ + sourceArtifact, + cloudAssemblyArtifact, + installCommand: 'npm install -g aws-cdk', + buildCommand: 'mvn package', + synthCommand: 'cdk synth' + }) +}); +``` + +------ +#### [ Python ] + +``` +class MyPipeline(Stack): + def __init__(self, scope: Construct, id: str, **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + pipeline = CdkPipeline(self, "Pipeline", + # ... + synth_action=SimpleSynthAction( + source_artifact=source_artifact, + cloud_assembly_artifact=cloud_assembly_artifact, + install_command="npm install -g aws-cdk", + build_command="mvn package", + synth_command="cdk synth" + )) +``` + +------ +#### [ Java ] + +``` +final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") + // ... + .synthAction(SimpleSynthAction.Builder.create() + .sourceArtifact(sourceArtifact) + .cloudAssemblyArtifact(cloudAssemblyArtifact) + .installCommand("npm install -g aws-cdk") + .buildCommand("mvn package") + .synthCommand("cdk synth") + .build()) + .build(); +``` + +------ +#### [ C\# ] + +``` +var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps +{ + SynthAction = new SimpleSynthAction(new SimpleSynthActionProps + { + SourceArtifact = sourceArtifact, + CloudAssemblyArtifact = cloudAssemblyArtifact, + InstallCommand = "npm install -g aws-cdk", + BuildCommand = "mvn package", + SynthCommand = "cdk synth" + }) +}); +``` + +------ + +A couple of convention\-based synth operations for TypeScript or JavaScript projects are available as class methods of `SimpleSynthAction`: ++ `[standardNpmSynth](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.SimpleSynthAction.html#static-standard-wbr-npm-wbr-synthoptions-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span)()` builds using NPM conventions\. Expects a `package-lock.json`, a `cdk.json`, and expects the CDK Toolkit to be a versioned dependency in `package.json`\. Does not perform a build step by default\. ++ `[standardYarnSynth](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.SimpleSynthAction.html#static-standard-wbr-yarn-wbr-synthoptions-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span)()` builds using Yarn conventions\. Expects a `yarn.lock`, a `cdk.json`, and expects the CDK Toolkit to be a versioned dependency in `package.json`\. Does not perform a build step by default\. + +If your needs are not covered by `SimpleSynthAction`, you can add a custom build/synth step by creating a custom AWS CodeBuild project and passing a corresponding `CodeBuildAction` to the pipeline\. + +## Application stages + +To define a multi\-stack AWS application that can be added to the pipeline all at once, define a subclass of `[Stage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stage.html)` \(not to be confused with `CdkStage` in the CDK Pipelines module\)\. + +The stage contains the stacks that make up your application\. If there are dependencies between the stacks, the stacks are automatically added to the pipeline in the right order\. Stacks that don't depend on each other are deployed in parallel\. You can add a dependency relationship between stacks by calling `stack1.addDependency(stack2)`\. + +Stages accept a default `env` argument, which the `Stack`s inside the `Stage` will use if no environment is specified for them\. + +An application is added to the pipeline by calling `[addApplicationStage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CdkPipeline.html#add-wbr-application-wbr-stageappstage-options-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span)()` with instances of the Stage\. A stage can be instantiated and added to the pipeline multiple times to define different stages of your DTAP or multi\-region application pipeline: + +------ +#### [ TypeScript ] + +``` +import { Construct, Stack, StackProps, Stage, StageProps } from '@aws-cdk/core'; +import * as codepipeline from '@aws-cdk/aws-codepipeline'; +import { CdkPipeline } from '@aws-cdk/pipelines'; + +export class DatabaseStack extends Stack { + // ... +} + +export class ComputeStack extends Stack { + // ... +} + +// Your application +// May consist of one or more Stacks +// +export class MyApplication extends Stage { + constructor(scope: Construct, id: string, props?: StageProps) { + super(scope, id, props); + + const dbStack = new DatabaseStack(this, 'Database'); + new ComputeStack(this, 'Compute', { + table: dbStack.table, + }); + } +} + +// Stack to hold the pipeline +// +export class MyPipelineStack extends Stack { + constructor(scope: Construct, id: string, props?: StackProps) { + super(scope, id, props); + + const sourceArtifact = new codepipeline.Artifact(); + const cloudAssemblyArtifact = new codepipeline.Artifact(); + + const pipeline = new CdkPipeline(this, 'Pipeline', { + // ...source and build information here + }); + + // Do this as many times as necessary with any account and region + // Account and region may be different from the pipeline's. + pipeline.addApplicationStage(new MyApplication(this, 'Prod', { + env: { + account: '123456789012', + region: 'eu-west-1', + } + })); + } +} +``` + +------ +#### [ JavaScript ] + +``` +const { Stack, Stage } = require('@aws-cdk/core'); +const codepipeline = require('@aws-cdk/aws-codepipeline'); +const { CdkPipeline } = require('@aws-cdk/pipelines'); + +class DatabaseStack extends Stack { + // ... +} + +class ComputeStack extends Stack { + // ... +} + +// Your application +// May consist of one or more Stacks +// +class MyApplication extends Stage { + constructor(scope, id, props) { + super(scope, id, props); + + const dbStack = new DatabaseStack(this, 'Database'); + new ComputeStack(this, 'Compute', { + table: dbStack.table + }); + } +} + +// Stack to hold the pipeline +// +class MyPipelineStack extends Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const sourceArtifact = new codepipeline.Artifact(); + const cloudAssemblyArtifact = new codepipeline.Artifact(); + + const pipeline = new CdkPipeline(this, 'Pipeline', { + // ...source and build information here + }); + + // Do this as many times as necessary with any account and region + // Account and region may be different from the pipeline's. + pipeline.addApplicationStage(new MyApplication(this, 'Prod', { + env: { + account: '123456789012', + region: 'eu-west-1' + } + })); + } +} + +module.exports = { MyApplication, MyPipelineStack, ComputeStack, DatabaseStack } +``` + +------ +#### [ Python ] + +``` +from my_pipeline.my_pipeline_stack import source_artifact +from aws_cdk.core import Construct, Stack, Stage, Environment +from aws_cdk.pipelines import CdkPipeline +import aws_cdk.aws_codepipeline as code_pipeline + +class DatabaseStack(Stack): + pass # ... + +class ComputeStack(Stack): + pass # ... + +# Your application +# May consist of one or more Stacks +# +class MyApplication(Stage): + def __init__(self, scope: Construct, id: str, **kwargs): + super().__init__(scope, id, **kwargs) + + db_stack = DatabaseStack(self, "Database") + ComputeStack(self, "Compute", table=db_stack.table) + +# Stack to hold the pipeline +# +class MyPipelineStack(Stack): + def __init__(self, scope: Construct, id: str, **kwargs): + super().__init__(scope, id, **kwargs) + + source_artifact = code_pipeline.Artifact() + cloud_assembly_artifact = code_pipeline.Artifact() + + pipeline = CdkPipeline(self, "Pipeline", + # ...source and build information here + ) + + # Do this as many times as necessary with any account and region + # Account and region may be different from the pipeline's. + pipeline.add_application_stage(MyApplication(self, 'Prod', + env=Environmentironment(account="123456789012", region="eu-west-1"))) +``` + +------ +#### [ Java ] + +``` +class DatabaseStack extends Stack { + Table table; + + public DatabaseStack(Construct scope, String id) { + super(scope, id); + // ... + } + + public Table getTable() { + return table; + } +} + +class ComputeStack extends Stack { + public ComputeStack(Construct scope, String id, Table table) { + // ... + } +} + +// Your application +// May consist of one or more Stacks +// +class MyApplication extends Stage { + public MyApplication(Construct scope, String id, StageProps props) { + super(scope, id, props); + + DatabaseStack dbStack = new DatabaseStack(this, "Database"); + new ComputeStack(this, "Compute", dbStack.getTable()); + } + +} + +// Stack to hold the pipeline +// +public class MyPipelineStack extends Stack { + public MyPipelineStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyPipelineStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + final Artifact sourceArtifact = new Artifact(); + final Artifact cloudAssemblyArtifact = new Artifact(); + + final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") + // ...source and build information here + .build(); + + // Do this as many times as necessary with any account and region + // Account and region may be different from the pipeline's. + pipeline.addApplicationStage(new MyApplication(this, "Prod", new StackProps.Builder() + .env(new Environment.Builder() + .account("123456789012") + .region("eu-west-1") + .build()) + .build())); + } +} +``` + +------ +#### [ C\# ] + +``` +public class DatabaseStack : Stack +{ + public Table Table { get; set; } + + public DatabaseStack(Construct scope, string id) : base(scope, id) + { + // ... + } + +} + +public class ComputeStack : Stack +{ + public ComputeStack(Construct scope, string id, Table table) : base(scope, id) + { + // ... + } +} + +// Your application +// May consist of one or more Stacks +// +public class MyApplication : Stage +{ + public MyApplication(Construct scope, string id, Amazon.CDK.StageProps props) : base(scope, id, props) + { + var dbStack = new DatabaseStack(this, "Database"); + new ComputeStack(this, "Compute", dbStack.Table); + } + +} + +// Stack to hold the pipeline +// +public class MyPipelineStack : Stack +{ + public MyPipelineStack(Construct scope, string id, StackProps props) : base(scope, id, props) + { + var sourceArtifact = new Artifact_(); + var cloudAssemblyArtifact = new Artifact_(); + + var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps + { + // ... source and build information here + }); + + // Do this as many times as necessary with any account and region + // Account and region may be different from the pipeline's. + pipeline.AddApplicationStage(new MyApplication(this, "Prod", new Amazon.CDK.StageProps + { + Env = new Amazon.CDK.Environment + { + Account = "123456789012", + Region = "eu-west-1" + } + })); + } +} +``` + +------ + +Every application stage added by `addApplicationStage()` leads to the addition of an individual pipeline stage, which is returned by the `addApplicationStage()` call\. This stage is represented by the [CdkStage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CdkStage.html) construct\. You can add more actions to the stage by calling its `[addActions](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CdkStage.html#add-wbr-actionsactions-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span)()` method\. For example: + +**Note** +`core.Stage` is a stage in an AWS CDK app containing stacks\. `pipelines.CdkStage` is a stage in a CDK pipeline\. + +------ +#### [ TypeScript ] + +``` +// import { ManualApprovalAction } from '@aws-cdk/aws-codepipeline-actions'; + +const testingStage = pipeline.addApplicationStage(new MyApplication(this, 'Testing', { + env: { account: '111111111111', region: 'eu-west-1' } +})); + +// Add an action -- in this case, a Manual Approval action +// (testingStage.addManualApprovalAction() is an equivalent convenience method) +testingStage.addActions(new ManualApprovalAction({ + actionName: 'ManualApproval', + runOrder: testingStage.nextSequentialRunOrder(), +})); +``` + +------ +#### [ JavaScript ] + +``` +// const { ManualApprovalAction } = require('@aws-cdk/aws-codepipeline-actions'); + +const testingStage = pipeline.addApplicationStage(new MyApplication(this, 'Testing', { + env: { account: '111111111111', region: 'eu-west-1' } +})); + +// Add an action -- in this case, a Manual Approval action +// (testingStage.addManualApprovalAction() is an equivalent convenience method) +testingStage.addActions(new ManualApprovalAction({ + actionName: 'ManualApproval', + runOrder: testingStage.nextSequentialRunOrder() +})); +``` + +------ +#### [ Python ] + +``` +# from aws_cdk.aws_codepipeline_actions import ManualApprovalAction + +testing_stage = pipeline.add_application_stage(MyApplication(self, "Testing", + env=Environment(account="111111111111", region="eu-west-1"))) + +# Add an action -- in this case, a Manual Approval action +# (testingStage.addManualApprovalAction() is an equivalent convenience method) +testing_stage.add_actions(ManualApprovalAction( + action_name="ManualApproval", + run_order=testing_stage.next_sequential_run_order() +)) +``` + +------ +#### [ Java ] + +``` +// import software.amazon.awscdk.services.codepipeline.actions.ManualApprovalAction; + +final CdkStage testingStage = pipeline.addApplicationStage(new MyApplication(this, "Testing", + new StageProps.Builder() + .env(new Environment.Builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); + +// Add an action -- in this case, a Manual Approval action +// (testingStage.addManualApprovalAction() is an equivalent convenience method) +testingStage.addActions(ManualApprovalAction.Builder.create() + .actionName("ManualApproval") + .runOrder(testingStage.nextSequentialRunOrder()) + .build()); +``` + +------ +#### [ C\# ] + +``` +// using Amazon.CDK.AWS.CodePipeline.Actions; + +var testingStage = pipeline.AddApplicationStage(new MyApplication(this, "Testing", + new Amazon.CDK.StageProps + { + Env = new Amazon.CDK.Environment + { + Account = "111111111111", + Region = "eu-west-1" + } + })); + +// Add an action -- in this case, a Manual Approval action +// (testingStage.AddManualApprovalAction() is an equivalent convenience method) +testingStage.AddActions(new ManualApprovalAction(new ManualApprovalActionProps { + ActionName = "ManualApproval", + RunOrder = testingStage.NextSequentialRunOrder() +})); +``` + +------ + +You can also add more than one application stage to a pipeline stage\. For example: + +------ +#### [ TypeScript ] + +``` +// Add two application stages to the same pipeline stage +testingStage.addApplication(new MyApplication1(this, 'MyApp1', { + env: { account: '111111111111', region: 'eu-west-1' } +})); + +testingStage.addApplication(new MyApplication2(this, 'MyApp2', { + env: { account: '111111111111', region: 'eu-west-1' } +})); +``` + +------ +#### [ JavaScript ] + +``` +// Add two application stages to the same pipeline stage +testingStage.addApplication(new MyApplication1(this, 'MyApp1', { + env: { account: '111111111111', region: 'eu-west-1' } +})); + +testingStage.addApplication(new MyApplication2(this, 'MyApp2', { + env: { account: '111111111111', region: 'eu-west-1' } +})); +``` + +------ +#### [ Python ] + +``` +# Add two application stages to the same pipeline stage +testing_stage.add_application(MyApplication1(this, 'MyApp1', + env=Environment(account="111111111111", region="eu-west-1"))) + +testing_stage.add_application(MyApplication2(this, 'MyApp2', + env=Environment(account="111111111111", region="eu-west-1"))) +``` + +------ +#### [ Java ] + +``` +// Add two application stages to the same pipeline stage +testingStage.addApplication(new MyApplication1(this, "MyApp1", new StageProps.Builder() + .env(new Environment.Builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); + +testingStage.addApplication(new MyApplication2(this, "MyApp2", new StageProps.Builder() + .env(new Environment.Builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); +``` + +------ +#### [ C\# ] + +``` +// Add two application stages to the same pipeline stage + +testingStage.AddApplication(new MyApplication1(this, "MyApp1", new Amazon.CDK.StageProps +{ + Env = new Amazon.CDK.Environment + { + Account = "111111111111", + Region = "eu-west-1" + } +})); + +testingStage.AddApplication(new MyApplication2(this, "MyApp1", new Amazon.CDK.StageProps +{ + Env = new Amazon.CDK.Environment + { + Account = "111111111111", + Region = "eu-west-1" + } +})); +``` + +------ + +## Testing deployments + +You can add any type of AWS CodePipeline action to a CDK Pipeline to validate the deployments you are performing\. Using the CDK Pipeline library's `[ShellScriptAction](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.ShellScriptAction.html)`, you can try to access a just\-deployed Amazon API Gateway backed by a Lambda function, for example, or issue an AWS CLI command to check some setting of a deployed resource\. + +In its simplest form, adding validation actions looks like this: + +------ +#### [ TypeScript ] + +``` +// stage is a CdkStage returned by pipeline.addApplicationStage + +stage.addActions(new ShellScriptAction({ + name: 'MyValidation', + commands: ['curl -Ssf https://my.webservice.com/'], + // ... more configuration ... +})); +``` + +------ +#### [ JavaScript ] + +``` +// stage is a CdkStage returned by pipeline.addApplicationStage + +stage.addActions(new ShellScriptAction({ + name: 'MyValidation', + commands: ['curl -Ssf https://my.webservice.com/'] + // ... more configuration ... +})); +``` + +------ +#### [ Python ] + +``` +# stage is a CdkStage returned by pipeline.addApplicationStage + +stage.add_actions(ShellScriptAction(name="MyValidation", + commands=['curl -Ssf https://my.webservice.com/'], + # ... more configuration ... +)) +``` + +------ +#### [ Java ] + +``` +// stage is a CdkStage returned by pipeline.addApplicationStage + +stage.addActions(ShellScriptAction.Builder.create() + .actionName("MyValidation") + .commands(Arrays.asList("curl -Ssf https://my.webservice.com/")) + // ... more configuration ... + .build()); +``` + +------ +#### [ C\# ] + +``` +// stage is a CdkStage returned by pipeline.addApplicationStage +stage.AddActions(new ShellScriptAction(new ShellScriptActionProps +{ + ActionName = "MyValidation", + Commands = new string[] + { + "curl -Ssf https://my.webservice.com/" + // ... more configuration ... + } +})); +``` + +------ + +Because many AWS CloudFormation deployments result in the generation of resources with unpredictable names, CDK Pipelines provide a way to read AWS CloudFormation outputs after a deployment\. This makes it possible to pass \(for example\) the generated URL of a load balancer to a test action\. + +To use outputs, expose the `CfnOutput` object you're interested in and pass it `pipeline.stackOutput()`\. + +------ +#### [ TypeScript ] + +``` +export class MyLbApplication extends Stage { + public readonly loadBalancerAddress: CfnOutput; + + constructor(scope: Construct, id: string, props?: StageProps) { + super(scope, id, props); + + const lbStack = new LoadBalancerStack(this, 'Stack'); + + // Or create this in `LoadBalancerStack` directly + this.loadBalancerAddress = new CfnOutput(lbStack, 'LbAddress', { + value: `https://${lbStack.loadBalancer.loadBalancerDnsName}/` + }); + } +} + +const lbApp = new MyLbApplication(this, 'MyApp', { + env: { /* ... */ } +}); + +const stage = pipeline.addApplicationStage(lbApp); +stage.addActions(new ShellScriptAction({ + // ... + useOutputs: { + // When the test is executed, this will make $URL contain the + // load balancer address. + URL: pipeline.stackOutput(lbApp.loadBalancerAddress), + } +})); +``` + +------ +#### [ JavaScript ] + +``` +class MyLbApplication extends Stage { + + constructor(scope, id, props) { + super(scope, id, props); + + const lbStack = new LoadBalancerStack(this, 'Stack'); + + // Or create this in `LoadBalancerStack` directly + this.loadBalancerAddress = new CfnOutput(lbStack, 'LbAddress', { + value: `https://${lbStack.loadBalancer.loadBalancerDnsName}/` + }); + } +} + +const lbApp = new MyLbApplication(this, 'MyApp', { + env: { /* ... */ } +}); + +const stage = pipeline.addApplicationStage(lbApp); +stage.addActions(new ShellScriptAction({ + // ... + useOutputs: { + // When the test is executed, this will make $URL contain the + // load balancer address. + URL: pipeline.stackOutput(lbApp.loadBalancerAddress) + } +})); +``` + +------ +#### [ Python ] + +``` +class MyLbApplication(Stage): + load_balancer_address: CfnOutput = None + + def __init__(self, scope: Construct, id: str, **kwargs): + super().__init__(scope, str, **kwargs) + + lb_stack = LoadBalancerStack(self, "Stack") + + # Or create this in `LoadBalancerStack` directly + self.load_balancer_address = CfnOutput(lb_stack, "LbAddress", + value=f"https://{lb_stack.load_balancer_dns_name}") + +lb_app = MyLbApplication(self, "Myapp", + env=Environment(...)) + +stage = pipeline.add_application_stage(lb_app) +stage.add_actions(ShellScriptAction( + # ... + use_outputs=pipeline.stack_output( + # When the test is executed, this will make $URL contain the + # load balancer address. + URL=lb_app.load_balancer_address) +)) +``` + +------ +#### [ Java ] + +``` +class MyLbApplication extends Stage { + CfnOutput loadBalancerAddress; + + public MyLbApplication(Construct scope, String id, StageProps props) { + super(scope, id, props); + + LoadBalancerStack lbStack = new LoadBalancerStack(this, "Stack"); + + // Or create this in `LoadBalancerStack` directly + loadBalancerAddress = CfnOutput.Builder.create(lbStack, "LbAddress") + .value(String.format("https://%s/", lbStack.getLoadBalancer().getDnsName())) + .build(); + } + + public CfnOutput getLoadBalancerAddress() { + return loadBalancerAddress; + } +} + +// some time later... +public class MyPipelineStack extends Stack { + public MyPipelineStack(final Construct scope, final String id) { + super(scope, id, null); + } + + @SuppressWarnings("serial") + public MyPipelineStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") + // ...source and build information here + .build(); + + final MyLbApplication lbApp = // ... + + final CdkStage stage = pipeline.addApplicationStage(lbApp); + stage.addActions(ShellScriptAction.Builder.create() + // ... + .useOutputs(new HashMap() {{ + put("URL", pipeline.stackOutput(lbApp.getLoadBalancerAddress())); + }}) + .build()); + } +} +``` + +------ +#### [ C\# ] + +``` +public class MyLbApplication : Stage +{ + public CfnOutput LoadBalancerAddress { get; set; } + + public MyLbApplication(Construct scope, string id, Amazon.CDK.StageProps props) : + base(scope, id, props) + { + + LoadBalancerStack LbStack = new LoadBalancerStack(this, "Stack"); + + // Or create this in `LoadBalancerStack` directly + var loadBalancerAddress = new CfnOutput(LbStack, "LbAddress", new CfnOutputProps + { + Value = $"https://{LbStack.LoadBalancer}/" + }); + } +} + +public class MyPipelineStack : Stack +{ + public MyPipelineStack(Construct scope, string id, StackProps props = null) : base(scope, id) + { + var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps + { + // ... source and build information here + }); + + MyLbApplication LbApp = new MyLbApplication(this, "App", new Amazon.CDK.StageProps + { + // set up your application stage + }); + + CdkStage stage = pipeline.AddApplicationStage(LbApp); + stage.AddActions(new ShellScriptAction(new ShellScriptActionProps + { + // ... + UseOutputs = new Dictionary + { + ["URL"] = pipeline.StackOutput(LbApp.LoadBalancerAddress) + } + })); + } +} +``` + +------ + +The `ShellScriptAction` limits you to rather small validation tests—basically whatever you can write in a few lines of shell script\. You can bring additional files \(such as complete shell scripts, or scripts in other languages\) into the test via the `additionalArtifacts` property\. + +Bringing in files from the source repository is appropriate if the files are directly usable in the test \(for example, if they are themselves executable\)\. Pass the `sourceArtifact`: + +------ +#### [ TypeScript ] + +``` +const sourceArtifact = new codepipeline.Artifact(); + +const pipeline = new CdkPipeline(this, 'Pipeline', { + // ... +}); + +const validationAction = new ShellScriptAction({ + name: 'TestUsingSourceArtifact', + additionalArtifacts: [sourceArtifact], + + // 'test.sh' comes from the source repository + commands: ['./test.sh'], +}); +``` + +------ +#### [ JavaScript ] + +``` +const sourceArtifact = new codepipeline.Artifact(); + +const pipeline = new CdkPipeline(this, 'Pipeline', { + // ... +}); + +const validationAction = new ShellScriptAction({ + name: 'TestUsingSourceArtifact', + additionalArtifacts: [sourceArtifact], + + // 'test.sh' comes from the source repository + commands: ['./test.sh'] +}); +``` + +------ +#### [ Python ] + +``` +source_artifact = code_pipeline.Artifact() + +pipeline = CdkPipeline(self, "Pipeline", ...) + +validation_action = ShellScriptAction( + name="TestUsingSourceArtifact", + additional_artifacts=[source_artifact], + # 'test.sh' comes from the source repository + commands=["./test'sh"] +) +``` + +------ +#### [ Java ] + +``` +final Artifact sourceArtifact = new Artifact(); + +final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") + // ...source and build information here + .build(); + +ShellScriptAction validationAction = ShellScriptAction.Builder.create() + .actionName("TestUsingSourceArtifact") + .additionalArtifacts(Arrays.asList(sourceArtifact)) + // 'test.sh' comes from the source repository + .commands(Arrays.asList("./test.sh")) + .build(); +``` + +------ +#### [ C\# ] + +``` +Artifact_ sourceArtifact = new Artifact_(); + +var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps +{ + // define your pipeline +}); + +var validationAction = new ShellScriptAction(new ShellScriptActionProps { + ActionName = "TestUsingSourceArtifact", + AdditionalArtifacts = new Artifact_[] { sourceArtifact }, + Commands = new string[] { "./test.sh" } +}); +``` + +------ + +Getting the additional files from the synth step is appropriate if your tests need the compilation step that is done as part of synthesis\. On the synthesis step, specify `additionalArtifacts` to package additional subdirectories into artifacts, and use the same artifact in the `ShellScriptAction`'s `additionalArtifacts`: + +------ +#### [ TypeScript ] + +``` +// If you are using additional output artifacts from the synth step, +// they must be named. +const cloudAssemblyArtifact = new codepipeline.Artifact('CloudAsm'); +const integTestsArtifact = new codepipeline.Artifact('IntegTests'); + +const pipeline = new CdkPipeline(this, 'Pipeline', { + synthAction: SimpleSynthAction.standardNpmSynth({ + sourceArtifact, + cloudAssemblyArtifact, + buildCommand: 'npm run build', + additionalArtifacts: [ + { + directory: 'test', + artifact: integTestsArtifact, + } + ], + }), + // ... +}); + +const validationAction = new ShellScriptAction({ + actionName: 'TestUsingBuildArtifact', + additionalArtifacts: [integTestsArtifact], + // 'test.js' was produced from 'test/test.ts' during the synth step + commands: ['node ./test.js'], +}); +``` + +------ +#### [ JavaScript ] + +``` +// If you are using additional output artifacts from the synth step, +// they must be named. +const cloudAssemblyArtifact = new codepipeline.Artifact('CloudAsm'); +const integTestsArtifact = new codepipeline.Artifact('IntegTests'); + +const pipeline = new CdkPipeline(this, 'Pipeline', { + synthAction: SimpleSynthAction.standardNpmSynth({ + sourceArtifact, + cloudAssemblyArtifact, + buildCommand: 'npm run build', + additionalArtifacts: [ + { + directory: 'test', + artifact: integTestsArtifact + } + ] + }) + // ... +}); + +const validationAction = new ShellScriptAction({ + actionName: 'TestUsingBuildArtifact', + additionalArtifacts: [integTestsArtifact], + // 'test.js' was produced from 'test/test.ts' during the synth step + commands: ['node ./test.js'] +}); +``` + +------ +#### [ Python ] + +``` +# If you are using additional output artifacts from the synth step, +# they must be named. +cloud_assembly_artifact = code_pipeline.Artifact("CloudAsm") +integ_tests_artifact = code_pipeline.Artifact("IntegTests") + +pipeline = CdkPipeline(self, "Pipeline", + synth_action=SimpleSynthAction.standard_npm_synth( + source_artifact=source_artifact, + cloud_assembly_artifact=cloud_assembly_artifact, + build_command="tsc", + additional_artifacts=[dict(directory='test', + artifact=integ_tests_artifact)] + # ... + )) + +validation_action = ShellScriptAction( + action_name="TestUsingBuildArtifact", + additional_artifacts=[integ_tests_artifact], + # 'test.js' was produced from "test/test.ts" durinng the synth step + commands=["node ./test.js"] +) +``` + +------ +#### [ Java ] + +``` +// If you are using additional output artifacts from the synth step, +// they must be named. +final Artifact cloudAssemblyArtifact = new Artifact("IntegTests"); +final Artifact integTestsArtifact = new Artifact("IntegTests"); + +final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") + .synthAction(SimpleSynthAction.standardNpmSynth(new StandardNpmSynthOptions.Builder() + .sourceArtifact(sourceArtifact) + .cloudAssemblyArtifact(cloudAssemblyArtifact) + .buildCommand("npm run build") + .additionalArtifacts(Arrays.asList(new AdditionalArtifact.Builder() + .directory("test").artifact(integTestsArtifact).build())) + .build())) + .build(); + +final ShellScriptAction validationAction = ShellScriptAction.Builder.create() + .actionName("TestUsingBuildArtifact") + .additionalArtifacts(Arrays.asList(integTestsArtifact)) + // 'test.js' was produced from 'test/test.ts' during the synth step + .commands(Arrays.asList("node ./test.js")) + .build(); +``` + +------ +#### [ C\# ] + +``` +// If you are using additional output artifacts from the synth step, +// they must be named. +var sourceArtifact = new Artifact_("Source"); +var cloudAssemblyArtifact = new Artifact_("CloudAssembly"); +var integTestsArtifact = new Artifact_("IntegTests"); + +var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps +{ + SynthAction = SimpleSynthAction.StandardNpmSynth(new StandardNpmSynthOptions + { + SourceArtifact = sourceArtifact, + CloudAssemblyArtifact = cloudAssemblyArtifact, + BuildCommand = "npm run build", + AdditionalArtifacts = new AdditionalArtifact[] + { + new AdditionalArtifact + { + Directory = "test", + Artifact = integTestsArtifact + } + } + }), +}); + +var validationAction = new ShellScriptAction(new ShellScriptActionProps +{ + ActionName = "TestUsingBuildArtifact", + AdditionalArtifacts = new Artifact_[] { integTestsArtifact }, + Commands = new string[] { "node./test.js" } +}); +``` + +------ + +## Security notes + +Any form of continuous delivery has inherent security risks\. Under the AWS [Shared Responsibility Model](https://aws.amazon.com/compliance/shared-responsibility-model/), you are responsible for the security of your information in the AWS cloud\. The CDK Pipelines library gives you a head start by incorporating secure defaults and modeling best practices, but by its very nature a library that needs a high level of access to fulfill its intended purpose cannot assure complete security\. There are many attack vectors outside of AWS and your organization\. + +In particular, keep in mind the following\. ++ Be mindful of the software you depend on\. Vet all third\-party software you run on your build machine, as it has the ability to change the infrastructure that gets deployed\. ++ Use dependency locking to prevent accidental upgrades\. The default `CdkSynth` that come with CDK Pipelines respect `package-lock.json` and `yarn.lock` to ensure your dependencies are the ones you expect\. ++ Credentials for production environments should be short\-lived\. After bootstrapping and initial provisioning, there is no need for developers to have account credentials; all changes can be deployed through the pipeline\. Eliminate the possibility of credentials leaking by not needing them in the first place\! + +## Troubleshooting tips + +The following issues are commonly encountered while getting started with CDK Pipelines\. + +**Pipeline: Internal Failure** + +``` +CREATE_FAILED | AWS::CodePipeline::Pipeline | Pipeline/Pipeline +Internal Failure +``` + Check your GitHub access token\. It might be missing, or might not have the permissions to access the repository\. + +**Key: Policy contains a statement with one or more invalid principals** + +``` +CREATE_FAILED | AWS::KMS::Key | Pipeline/Pipeline/ArtifactsBucketEncryptionKey +Policy contains a statement with one or more invalid principals. +``` + One of the target environments has not been bootstrapped with the new bootstrap stack\. Make sure all your target environments are bootstrapped\. + +**Stack is in ROLLBACK\_COMPLETE state and can not be updated\.** + +``` +Stack STACK_NAME is in ROLLBACK_COMPLETE state and can not be updated. (Service: +AmazonCloudFormation; Status Code: 400; Error Code: ValidationError; Request +ID: ...) +``` +The stack failed its previous deployment and is in a non\-retryable state\. Delete the stack from the AWS CloudFormation console and retry the deployment\. + +## Known issues and limitations + +We're currently aware of the following issues with CDK Pipelines\. ++ Context queries are not supported; `Vpc.fromLookup()` and similar functions do not work\. ++ Console links to other accounts will not work\. The AWS CodePipeline console assumes links are relative to the current account\. You cannot click through to a AWS CloudFormation stack in a different account\. ++ If a changeset failed to apply, the pipeline is not retried\. The pipeline must be restarted manually from the top by clicking **Release Change**\. ++ A stack that failed to deploy must be deleted manually using the CloudFormation console before starting the pipeline again by clicking **Release Change**\. + +Please [report any other issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index b5ba1275..ec9b9f0f 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -55,6 +55,7 @@ Amazon's trademarks and trade dress may not be used in + [Create an app with multiple stacks](stack_how_to_create_multiple_stacks.md) + [Set a CloudWatch alarm](how_to_set_cw_alarm.md) + [Get a value from a context variable](get_context_var.md) + + [Continuous integration and delivery (CI/CD) using CDK Pipelines](cdk_pipeline.md) + [AWS CDK tools](tools.md) + [AWS CDK Toolkit (cdk command)](cli.md) + [AWS Toolkit for Visual Studio Code](vscode.md) From 43e3ac62973621f5851e529e509e711660499e95 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 29 Jul 2020 23:54:17 +0000 Subject: [PATCH 241/655] minor updates --- doc_source/cli.md | 472 +++++++++++++++++++------------------- doc_source/hello_world.md | 6 +- 2 files changed, 241 insertions(+), 237 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index b5646d24..145516c7 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -388,287 +388,291 @@ cdk diff --template ~/stacks/MyStack.old MyStack This section provides a reference for the AWS CDK Toolkit derived from its help, first a general reference with the options available with all commands, then \(in collapsible sections\) specific references with options available only with specific subcommands\. ``` -Usage: cdk -a COMMAND - -Commands: - - cdk list [STACKS..] Lists all stacks in the app [aliases: ls] - - cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation - template for this stack [aliases: synth] - - cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS - environment - - cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your - AWS account - - cdk destroy [STACKS..] Destroy the stack(s) named STACKS - - cdk diff [STACKS..] Compares the specified stack with the deployed - stack or a local template file, and returns - with status 1 if any difference is found - - cdk metadata [STACK] Returns all metadata associated with this - stack - - cdk init [TEMPLATE] Create a new, empty CDK project from a - template. Invoked without TEMPLATE, the app - template will be used. - - cdk context Manage cached context values - - cdk docs Opens the reference documentation in a browser - [aliases: doc] - - cdk doctor Check your set-up for potential problems - -Options: - - --app, -a REQUIRED: command-line for executing your app or a cloud - assembly directory (e.g. "node bin/my-app.js") [string] - - --context, -c Add contextual string parameter (KEY=VALUE) [array] - - --plugin, -p Name or path of a node package that extend the CDK - features. Can be specified multiple times [array] - - --trace Print trace for stack warnings [boolean] - - --strict Do not construct stacks with warnings [boolean] - - --ignore-errors Ignores synthesis errors, which will likely produce an - invalid output [boolean] [default: false] - - --json, -j Use JSON output instead of YAML when templates are - printed to STDOUT [boolean] [default: false] - - --verbose, -v Show debug logs (specify multiple times to increase - verbosity) [count] [default: false] - - --profile Use the indicated AWS profile as the default environment - [string] - - --proxy Use the indicated proxy. Will read from HTTPS_PROXY - environment variable if not specified. [string] - - --ca-bundle-path Path to CA certificate to use when validating HTTPS - requests. Will read from AWS_CA_BUNDLE environment - variable if not specified. [string] - - --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: - guess EC2 instance status. [boolean] - - --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized - templates (enabled by default) [boolean] - - --path-metadata Include "aws:cdk:path" CloudFormation metadata for each - resource (enabled by default) [boolean] [default: true] - - --asset-metadata Include "aws:asset:*" CloudFormation metadata for - resources that user assets (enabled by default) - [boolean] [default: true] - - --role-arn, -r ARN of Role to use when invoking CloudFormation [string] - - --toolkit-stack-name The name of the CDK toolkit stack [string] - - --staging Copy assets to the output directory (use --no-staging to - disable, needed for local debugging the source files - with SAM CLI) [boolean] [default: true] - - --output, -o Emits the synthesized cloud assembly into a directory - (default: cdk.out) [string] - - --no-color Removes colors and other style from console output - [boolean] [default: false] - - --fail Fail with exit code 1 in case of diff - [boolean] [default: false] - - --version Show version number [boolean] - - -h, --help Show help [boolean] - -If your app has a single stack, there is no need to specify the stack name - -If one of cdk.json or ~/.cdk.json exists, options specified there will be used +Usage: cdk -a COMMAND + +Commands: + + cdk list [STACKS..] Lists all stacks in the app [aliases: ls] + + cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation + template for this stack [aliases: synth] + + cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS + environment + + cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your + AWS account + + cdk destroy [STACKS..] Destroy the stack(s) named STACKS + + cdk diff [STACKS..] Compares the specified stack with the deployed + stack or a local template file, and returns + with status 1 if any difference is found + + cdk metadata [STACK] Returns all metadata associated with this + stack + + cdk init [TEMPLATE] Create a new, empty CDK project from a + template. Invoked without TEMPLATE, the app + template will be used. + + cdk context Manage cached context values + + cdk docs Opens the reference documentation in a browser + [aliases: doc] + + cdk doctor Check your set-up for potential problems + +Options: + + --app, -a REQUIRED: command-line for executing your app or a cloud + assembly directory (e.g. "node bin/my-app.js") [string] + + --context, -c Add contextual string parameter (KEY=VALUE) [array] + + --plugin, -p Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] + + --trace Print trace for stack warnings [boolean] + + --strict Do not construct stacks with warnings [boolean] + + --ignore-errors Ignores synthesis errors, which will likely produce an + invalid output [boolean] [default: false] + + --json, -j Use JSON output instead of YAML when templates are + printed to STDOUT [boolean] [default: false] + + --verbose, -v Show debug logs (specify multiple times to increase + verbosity) [count] [default: false] + + --profile Use the indicated AWS profile as the default environment + [string] + + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified. [string] + + --ca-bundle-path Path to CA certificate to use when validating HTTPS + requests. Will read from AWS_CA_BUNDLE environment + variable if not specified. [string] + + --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: + guess EC2 instance status. [boolean] + + --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized + templates (enabled by default) [boolean] + + --path-metadata Include "aws:cdk:path" CloudFormation metadata for each + resource (enabled by default) [boolean] [default: true] + + --asset-metadata Include "aws:asset:*" CloudFormation metadata for + resources that user assets (enabled by default) + [boolean] [default: true] + + --role-arn, -r ARN of Role to use when invoking CloudFormation [string] + + --toolkit-stack-name The name of the CDK toolkit stack [string] + + --staging Copy assets to the output directory (use --no-staging to + disable, needed for local debugging the source files + with SAM CLI) [boolean] [default: true] + + --output, -o Emits the synthesized cloud assembly into a directory + (default: cdk.out) [string] + + --no-color Removes colors and other style from console output + [boolean] [default: false] + + --fail Fail with exit code 1 in case of diff + [boolean] [default: false] + + --version Show version number [boolean] + + -h, --help Show help [boolean] + +If your app has a single stack, there is no need to specify the stack name + +If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` ### `cdk list` \(`ls`\) ``` -cdk list [STACKS..] - -Lists all stacks in the app - -Options: - - --long, -l Display environment information for each stack +cdk list [STACKS..] + +Lists all stacks in the app + +Options: + + --long, -l Display environment information for each stack [boolean] [default: false] ``` ### `cdk synthesize` \(`synth`\) ``` -cdk synthesize [STACKS..] - -Synthesizes and prints the CloudFormation template for this stack - -Options: - - --exclusively, -e Only synthesize requested stacks, don't include +cdk synthesize [STACKS..] + +Synthesizes and prints the CloudFormation template for this stack + +Options: + + --exclusively, -e Only synthesize requested stacks, don't include dependencies [boolean] ``` ### `cdk bootstrap` ``` -cdk bootstrap [ENVIRONMENTS..] - -Deploys the CDK toolkit stack into an AWS environment - -Options: - - --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket; - --toolkit-bucket-name bucket will be created and must not - exist [string] - - --bootstrap-kms-key-id AWS KMS master key ID used for the - SSE-KMS encryption [string] - - --qualifier Unique string to distinguish - multiple bootstrap stacks [string] - - --public-access-block-configuration Block public access configuration - on CDK toolkit bucket (enabled by - default) [boolean] [default: true] - - --tags, -t Tags to add for the stack - (KEY=VALUE) [array] [default: []] - - --execute Whether to execute ChangeSet - (--no-execute will NOT execute the - ChangeSet) [boolean] [default: true] - - --force, -f Always bootstrap even if it would - downgrade template version +cdk bootstrap [ENVIRONMENTS..] + +Deploys the CDK toolkit stack into an AWS environment + +Options: + + --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket; + --toolkit-bucket-name bucket will be created and must not + exist [string] + + --bootstrap-kms-key-id AWS KMS master key ID used for the + SSE-KMS encryption [string] + + --qualifier Unique string to distinguish + multiple bootstrap stacks [string] + + --public-access-block-configuration Block public access configuration + on CDK toolkit bucket (enabled by + default) [boolean] [default: true] + + --tags, -t Tags to add for the stack + (KEY=VALUE) [array] [default: []] + + --execute Whether to execute ChangeSet + (--no-execute will NOT execute the + ChangeSet) [boolean] [default: true] + + --force, -f Always bootstrap even if it would + downgrade template version + [boolean] [default: false] + + --termination-protection Toggle CloudFormation termination + protection on the bootstrap stacks [boolean] [default: false] ``` ### `cdk deploy` ``` -cdk deploy [STACKS..] - -Deploys the stack(s) named STACKS into your AWS account - -Options: - - --build-exclude, -E Do not rebuild asset with the given ID. Can be - specified multiple times. [array] [default: []] - - --exclusively, -e Only deploy requested stacks, don't include - dependencies [boolean] - - --require-approval What security-sensitive changes need manual approval - [string] [choices: "never", "any-change", "broadening"] - - --ci Force CI detection (deprecated) - [boolean] [default: false] - - --notification-arns ARNs of SNS topics that CloudFormation will notify with - stack related events [array] - - --tags, -t Tags to add to the stack (KEY=VALUE) [array] - - --execute Whether to execute ChangeSet (--no-execute will NOT - execute the ChangeSet) [boolean] [default: true] - - --force, -f Always deploy stack even if templates are identical - [boolean] [default: false] - - --parameters Additional parameters passed to CloudFormation at - deploy time (STACK:KEY=VALUE) [array] [default: {}] - - --outputs-file, -O Path to file where stack outputs will be written as - JSON [string] - - --previous-parameters Use previous values for existing parameters (you must - specify all parameters on every deployment if this is +cdk deploy [STACKS..] + +Deploys the stack(s) named STACKS into your AWS account + +Options: + + --build-exclude, -E Do not rebuild asset with the given ID. Can be + specified multiple times. [array] [default: []] + + --exclusively, -e Only deploy requested stacks, don't include + dependencies [boolean] + + --require-approval What security-sensitive changes need manual approval + [string] [choices: "never", "any-change", "broadening"] + + --ci Force CI detection (deprecated) + [boolean] [default: false] + + --notification-arns ARNs of SNS topics that CloudFormation will notify with + stack related events [array] + + --tags, -t Tags to add to the stack (KEY=VALUE) [array] + + --execute Whether to execute ChangeSet (--no-execute will NOT + execute the ChangeSet) [boolean] [default: true] + + --force, -f Always deploy stack even if templates are identical + [boolean] [default: false] + + --parameters Additional parameters passed to CloudFormation at + deploy time (STACK:KEY=VALUE) [array] [default: {}] + + --outputs-file, -O Path to file where stack outputs will be written as + JSON [string] + + --previous-parameters Use previous values for existing parameters (you must + specify all parameters on every deployment if this is disabled) [boolean] [default: true] ``` ### `cdk destroy` ``` -cdk destroy [STACKS..] - -Destroy the stack(s) named STACKS - -Options: - - --exclusively, -e Only destroy requested stacks, don't include dependees - [boolean] - - --force, -f Do not ask for confirmation before destroying the stacks +cdk destroy [STACKS..] + +Destroy the stack(s) named STACKS + +Options: + + --exclusively, -e Only destroy requested stacks, don't include dependees + [boolean] + + --force, -f Do not ask for confirmation before destroying the stacks [boolean] ``` ### `cdk diff` ``` -cdk diff [STACKS..] - -Compares the specified stack with the deployed stack or a local template file, -and returns with status 1 if any difference is found - -Options: - - --exclusively, -e Only diff requested stacks, don't include dependencies - [boolean] - - --context-lines Number of context lines to include in arbitrary JSON - diff rendering [number] [default: 3] - - --template The path to the CloudFormation template to compare with +cdk diff [STACKS..] + +Compares the specified stack with the deployed stack or a local template file, +and returns with status 1 if any difference is found + +Options: + + --exclusively, -e Only diff requested stacks, don't include dependencies + [boolean] + + --context-lines Number of context lines to include in arbitrary JSON + diff rendering [number] [default: 3] + + --template The path to the CloudFormation template to compare with [string] ``` ### `cdk init` ``` -cdk init [TEMPLATE] - -Create a new, empty CDK project from a template. Invoked without TEMPLATE, the -app template will be used. - -Options: - - --language, -l The language to be used for the new project (default can - be configured in ~/.cdk.json) - [string] [choices: "csharp", "fsharp", "java", "javascript", "python", - "typescript"] - - --list List the available templates [boolean] - - --generate-only If true, only generates project files, without executing - additional operations such as setting up a git repo, - installing dependencies or compiling the project +cdk init [TEMPLATE] + +Create a new, empty CDK project from a template. Invoked without TEMPLATE, the +app template will be used. + +Options: + + --language, -l The language to be used for the new project (default can + be configured in ~/.cdk.json) + [string] [choices: "csharp", "fsharp", "java", "javascript", "python", + "typescript"] + + --list List the available templates [boolean] + + --generate-only If true, only generates project files, without executing + additional operations such as setting up a git repo, + installing dependencies or compiling the project [boolean] [default: false] ``` ### `cdk context` ``` -cdk context - -Manage cached context values - -Options: - - --reset, -e The context key (or its index) to reset [string] - +cdk context + +Manage cached context values + +Options: + + --reset, -e The context key (or its index) to reset [string] + --clear Clear all context [boolean] ``` \ No newline at end of file diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index c171a1a9..46bf3891 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -68,7 +68,7 @@ After the app has been created, also enter the following two commands to activat ``` source .env/bin/activate -pip install -r requirements.txt +python -m pip install -r requirements.txt ``` ------ @@ -87,7 +87,7 @@ If you are using an IDE, you can now open or import the project\. In Eclipse, fo cdk init app --language csharp ``` -If you are using Visual Studio, open the solution file, `src\HelloCdk.sln`\. +If you are using Visual Studio, open the solution file in the `src` directory\. ------ @@ -707,4 +707,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file From 04396761205d990f1acf49382fc81f93ac252805 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 30 Jul 2020 01:26:48 +0000 Subject: [PATCH 242/655] tweaks and minor improvements --- doc_source/cli.md | 2 +- doc_source/codepipeline_example.md | 2 +- doc_source/parameters.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 145516c7..1da946d6 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -126,7 +126,7 @@ Use the `--profile` flag to choose a set of credentials and default region from cdk deploy --profile test PipelineStack ``` -Instead of the configuration file, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. +Instead of using the configuration files, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. You may optionally use the `--role-arn` \(or `-r`\) option to specify the ARN of an IAM role that should be used for deployment\. This role must be assumable by the AWS account being used\. diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 14044bbd..461f6ff9 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -846,7 +846,7 @@ public class PipelineStack extends Stack { "npx cdk synth -o dist")); }}); }}); - put("artifacts", new HashMap() {{ + put("artifacts", new HashMap() {{ put("base-directory", "dist"); put("files", Arrays.asList("LambdaStack.template.json")); }}); diff --git a/doc_source/parameters.md b/doc_source/parameters.md index b4e572d6..60b559bd 100644 --- a/doc_source/parameters.md +++ b/doc_source/parameters.md @@ -6,7 +6,7 @@ Using the AWS CDK, you can both define parameters, which can then be used in the When deploying the AWS CloudFormation template using the AWS CDK Toolkit, you provide the parameter values on the command line\. If you deploy the template through the AWS CloudFormation console, you are prompted for the parameter values\. -In general, we recommend against using AWS CloudFormation parameters with the AWS CDK\. Parameter values are not available at synthesis time and thus cannot be easily used in other parts of your AWS CDK app, particularly for control flow\. +In general, we recommend against using AWS CloudFormation parameters with the AWS CDK\. Unlike [context values](context.md) or environment variables, the usual way to pass values into your AWS CDK apps without hard\-coding them, parameter values are not available at synthesis time, and thus cannot be easily used in other parts of your AWS CDK app, particularly for control flow\. **Note** To do control flow with parameters, you can use [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnCondition.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnCondition.html) constructs, although this is awkward compared to native `if` statements\. From 0b6f101b0c8d3c1a4829f7e289552583ac907dbb Mon Sep 17 00:00:00 2001 From: Yerzhan <19510938+tashbenbetov@users.noreply.github.com> Date: Sun, 2 Aug 2020 21:14:25 +0300 Subject: [PATCH 243/655] Fix constructs.md Add missing s3notify.SnsDestination in NotifyingBucket construct. --- doc_source/constructs.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 99fe72bf..e6e03edb 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -835,7 +835,7 @@ export class NotifyingBucket extends Construct { super(scope, id, props); const bucket = new s3.Bucket(this, 'bucket'); this.topic = new sns.Topic(this, 'topic'); - bucket.addObjectCreatedNotification(this.topic, { prefix: props.prefix }); + bucket.addObjectCreatedNotification(new s3notify.SnsDestination(this.topic), { prefix: props.prefix }); } } ``` @@ -850,7 +850,7 @@ class NotifyingBucket extends Construct { super(scope, id, props); const bucket = new s3.Bucket(this, 'bucket'); this.topic = new sns.Topic(this, 'topic'); - bucket.addObjectCreatedNotification(this.topic, { prefix: props.prefix }); + bucket.addObjectCreatedNotification(new s3notify.SnsDestination(this.topic), { prefix: props.prefix }); } } @@ -867,7 +867,7 @@ class NotifyingBucket(core.Construct): super().__init__(scope, id, **kwargs) bucket = s3.Bucket(self, "bucket") self.topic = sns.Topic(self, "topic") - bucket.add_object_created_notification(self.topic, + bucket.add_object_created_notification(s3notify.SnsDestination(self.topic), s3.NotificationKeyFilter(prefix=prefix)) ``` @@ -974,4 +974,4 @@ var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketP images.topic.AddSubscription(new SqsSubscription(queue)); ``` ------- \ No newline at end of file +------ From 64910cb84fe2794f93dd6cf57b456c69b8f2dfdb Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 3 Aug 2020 20:48:07 +0000 Subject: [PATCH 244/655] lead with mac os x --- doc_source/cdk_pipeline.md | 6 +++--- doc_source/environments.md | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 4121b408..63be5fba 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -18,7 +18,7 @@ You may have already bootstrapped one or more environments so you can deploy ass To bootstrap an environment that will provision a pipeline: ------ -#### [ Linux/Mac OS X ] +#### [ Mac OS X/Linux ] ``` CDK_NEW_BOOTSTRAP=1 @@ -42,7 +42,7 @@ npx cdk bootstrap --profile ADMIN-PROFILE ^ To bootstrap additional environments into which AWS CDK applications will be deployed by the pipeline: ------ -#### [ Linux/Mac OS X ] +#### [ Mac OS X/Linux ] ``` CDK_NEW_BOOTSTRAP=1 @@ -168,7 +168,7 @@ python -m pip install aws_cdk.aws_codepipeline aws_cdk.aws_codepipeline_actions Freeze your dependencies in `requirements.txt`\. -**Linux/Mac OS X** +**Mac OS X/Linux** ``` python -m pip freeze | grep -v '^[-#]' > requirements.txt diff --git a/doc_source/environments.md b/doc_source/environments.md index 33b14fbc..ddd4573f 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -297,7 +297,7 @@ new MyDevStack(app, "dev", new StackProps { Env = makeEnv() }); With your stack's environment declared this way, you can now write a short script or batch file like the following to set the variables from command line arguments, then call `cdk deploy`\. Any arguments beyond the first two are passed through to `cdk deploy` and can be used to specify command\-line options or stacks\. ------ -#### [ Linux/Mac OS X ] +#### [ Mac OS X/Linux ] ``` #!/usr/bin/env bash @@ -334,14 +334,14 @@ if ($args.length -ge 2) { } ``` -The Windows version of the script uses PowerShell to provide the same functionality as the Linux/Mac OS X version\. It also contains instructions to allow it to be run as a batch file so it can be easily invoked from a command line\. It should be saved as `cdk-deploy-to.bat`\. The file `cdk-deploy-to.ps1` will be created when the batch file is invoked\. +The Windows version of the script uses PowerShell to provide the same functionality as the Mac OS X/Linux version\. It also contains instructions to allow it to be run as a batch file so it can be easily invoked from a command line\. It should be saved as `cdk-deploy-to.bat`\. The file `cdk-deploy-to.ps1` will be created when the batch file is invoked\. ------ Then you can write additional scripts that call the "deploy\-to" script to deploy to specific environments \(even multiple environments per script\): ------ -#### [ Linux/Mac OS X ] +#### [ Mac OS X/Linux ] ``` #!/usr/bin/env bash @@ -363,7 +363,7 @@ cdk-deploy-to 135792469 us-east-1 %* When deploying to multiple environments, consider whether you want to continue deploying to other environments after a deployment fails\. The following example avoids deploying to the second production environment if the first doesn't succeed\. ------ -#### [ Linux/Mac OS X ] +#### [ Mac OS X/Linux ] ``` #!/usr/bin/env bash From c3b5cb4600ec098542ad9c2f63ba4148b8f59525 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 3 Aug 2020 23:13:38 +0000 Subject: [PATCH 245/655] code fixes --- doc_source/codepipeline_example.md | 8 ++++---- doc_source/constructs.md | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 461f6ff9..8491f538 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -241,7 +241,7 @@ export class LambdaStack extends Stack { const alias = new lambda.Alias(this, 'LambdaAlias', { aliasName: 'Prod', - version: func.latestVersion, + version: func.currentVersion, }); new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', { @@ -277,7 +277,7 @@ class LambdaStack extends Stack { const alias = new lambda.Alias(this, 'LambdaAlias', { aliasName: 'Prod', - version: func.latestVersion + version: func.currentVersion }); new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', { @@ -311,7 +311,7 @@ class LambdaStack(core.Stack): ) alias = lambda_.Alias(self, "LambdaAlias", alias_name="Prod", - version=func.latest_version) + version=func.current_version) codedeploy.LambdaDeploymentGroup(self, "DeploymentGroup", alias=alias, @@ -400,7 +400,7 @@ namespace Pipeline Runtime = Runtime.NODEJS_10_X }); - var version = func.LatestVersion; + var version = func.currentVersion; var alias = new Alias(this, "LambdaAlias", new AliasProps { AliasName = "Prod", diff --git a/doc_source/constructs.md b/doc_source/constructs.md index e6e03edb..121272de 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -974,4 +974,4 @@ var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketP images.topic.AddSubscription(new SqsSubscription(queue)); ``` ------- +------ \ No newline at end of file From 3ab701922fbad6a3cb962e09d2439a537b98d2b0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 6 Aug 2020 03:45:29 +0000 Subject: [PATCH 246/655] remove some extraneous build instructions, minor tweaks and fixes --- doc_source/assets.md | 2 +- doc_source/cli.md | 4 +- doc_source/codepipeline_example.md | 14 +- doc_source/ecs_example.md | 72 ------- doc_source/environments.md | 2 +- doc_source/getting_started.md | 2 +- doc_source/hello_world.md | 184 +----------------- doc_source/home.md | 2 +- doc_source/identifiers.md | 5 +- doc_source/permissions.md | 2 +- doc_source/reference.md | 4 +- doc_source/resources.md | 6 +- doc_source/serverless_example.md | 180 ----------------- .../stack_how_to_create_multiple_stacks.md | 2 +- doc_source/stacks.md | 2 +- doc_source/tagging.md | 4 +- doc_source/work-with-cdk-java.md | 4 +- 17 files changed, 31 insertions(+), 460 deletions(-) diff --git a/doc_source/assets.md b/doc_source/assets.md index bc677522..60934f6e 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -8,7 +8,7 @@ You typically reference assets through APIs that are exposed by specific AWS con When you refer to an asset in your app, the [cloud assembly](apps.md#apps_cloud_assembly) synthesized from your application includes metadata information with instructions for the AWS CDK CLI on where to find the asset on the local disk, and what type of bundling to perform based on the type of asset, such as a directory to compress \(zip\) or a Docker image to build\. -The AWS CDK generates a source hash for assets and can be used at construction time to determine whether the contents of an asset have changed\. +The AWS CDK generates a source hash for assets, which can be used at construction time to determine whether the contents of an asset have changed\. By default, the AWS CDK creates a copy of the asset in the cloud assembly directory, which defaults to `cdk.out`, under the source hash\. This is so that the cloud assembly is self\-contained and moved over to a different host for deployment\. See [Cloud assemblies](apps.md#apps_cloud_assembly) for details\. diff --git a/doc_source/cli.md b/doc_source/cli.md index 1da946d6..4ec3a668 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -156,13 +156,13 @@ cdk --app "npx ts-node bin/hello-cdk.ts" ls Many CDK Toolkit commands \(for example, `cdk deploy`\) work on stacks defined in your app\. If your app contains only one stack, the CDK Toolkit assumes you mean that one if you don't specify a stack explicitly\. -Otherwise, you must specify the stack or stacks you want to work with\. You can do this by specifying the desired stacks by name individually on the command line\. +Otherwise, you must specify the stack or stacks you want to work with\. You can do this by specifying the desired stacks by ID individually on the command line\. Recall that the ID is the value specified by the second argument when you instantiate the stack\. ``` cdk synth PipelineStack LambdaStack ``` -You may also use wildcards to specify names that match a pattern\. +You may also use wildcards to specify IDs that match a pattern\. + ? matches any single character + \* matches any number of characters diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 8491f538..537ce2de 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -71,6 +71,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi cd pipeline cdk init --language python source .env/bin/activate + git commit -m "project started" pip install -r requirements.txt pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_s3 @@ -189,7 +190,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ``` // index.ts const GREETING = "Hello, AWS!"; - export async function handler(event: any, context: any) { + export async function main(event: any, context: any) { console.log(GREETING); return GREETING; } @@ -235,7 +236,7 @@ export class LambdaStack extends Stack { const func = new lambda.Function(this, 'Lambda', { code: this.lambdaCode, - handler: 'index.handler', + handler: 'index.main', runtime: lambda.Runtime.NODEJS_10_X, }); @@ -271,7 +272,7 @@ class LambdaStack extends Stack { const func = new lambda.Function(this, 'Lambda', { code: this.lambdaCode, - handler: 'index.handler', + handler: 'index.main', runtime: lambda.Runtime.NODEJS_10_X }); @@ -306,7 +307,7 @@ class LambdaStack(core.Stack): func = lambda_.Function(self, "Lambda", code=self.lambda_code, - handler="index.handler", + handler="index.main", runtime=lambda_.Runtime.NODEJS_10_X, ) @@ -357,7 +358,7 @@ public class LambdaStack extends Stack { Function func = Function.Builder.create(this, "Lambda") .code(lambdaCode) - .handler("index.handler") + .handler("index.main") .runtime(Runtime.NODEJS_10_X).build(); Version version = func.getCurrentVersion(); @@ -396,7 +397,7 @@ namespace Pipeline var func = new Function(this, "Lambda", new FunctionProps { Code = lambdaCode, - Handler = "index.handler", + Handler = "index.main", Runtime = Runtime.NODEJS_10_X }); @@ -1242,7 +1243,6 @@ git push Now we can deploy the pipeline\. ``` -npm run build cdk deploy PipelineDeployingLambdaStack ``` diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 24c9ec26..5846733a 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -86,46 +86,10 @@ You may now open `src/MyEcsConstruct.sln` in Visual Studio\./ Run the app and confirm that it creates an empty stack\. ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] - -``` -cdk synth -``` - ------- -#### [ Python ] - ``` cdk synth ``` ------- -#### [ Java ] - -``` -mvn compile -cdk synth -``` - ------- -#### [ C\# ] - -``` -dotnet build src -cdk synth -``` - ------- - You should see a stack like the following, where *CDK\-VERSION* is the version of the CDK and *NODE\-VERSION* is the version of Node\.js\. \(Your output may differ slightly from what's shown here\.\) ``` @@ -380,46 +344,10 @@ Replace the comment at the end of the constructor with the following code\. Save it and make sure it runs and creates a stack\. ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] - -``` -cdk synth -``` - ------- -#### [ Python ] - ``` cdk synth ``` ------- -#### [ Java ] - -``` -mvn compile -cdk synth -``` - ------- -#### [ C\# ] - -``` -dotnet build src -cdk synth -``` - ------- - The stack is hundreds of lines, so we don't show it here\. The stack should contain one default instance, a private subnet and a public subnet for the three Availability Zones, and a security group\. Deploy the stack\. diff --git a/doc_source/environments.md b/doc_source/environments.md index ddd4573f..f0511af1 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -309,7 +309,7 @@ if [[ $# -ge 2 ]]; then exit $? else echo 1>&2 "Provide AWS account and region as first two args." - echo 1>&2 "Addiitonal args are passed through to cdk deploy." + echo 1>&2 "Additional args are passed through to cdk deploy." exit 1 fi ``` diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 430fc987..168e497f 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -123,7 +123,7 @@ Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK\ You must provide your credentials and an AWS Region to use AWS CDK, if you have not already done so\. **Important** -We strongly recommend against using your AWS root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. +We strongly recommend against using your AWS root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. Best practices are to change this account's access key regularly and to use a least\-privileges role \(specifying `--role-arn`\) when deploying\. If you have the AWS CLI installed, the easiest way to satisfy this requirement is to install the AWS CLI and issue the following command: diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 46bf3891..76c253ec 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -1,6 +1,6 @@ # Your first AWS CDK app -You've read [Getting started with the AWS CDK](getting_started.md)? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. In this process you'll learn about the structure of a AWS CDK project, how to access the AWS Construct Library, and how to use the AWS CDK Toolkit command\-line tool\.\. +You've read [Getting started with the AWS CDK](getting_started.md)? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. In this process you'll learn about the structure of a AWS CDK project, how to access the AWS Construct Library, and how to use the AWS CDK Toolkit command\-line tool\. The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps to synthesize your stack to an AWS CloudFormation template and deploy it\. @@ -139,46 +139,10 @@ Don't worry about memorizing this command; in this tutorial, we'll provide it wh Just to verify everything is working correctly, list the stacks in your app\. ------- -#### [ TypeScript ] - -``` -npm run build -cdk ls -``` - ------- -#### [ JavaScript ] - ``` cdk ls ``` ------- -#### [ Python ] - -``` -cdk ls -``` - ------- -#### [ Java ] - -``` -mvn compile -cdk ls -``` - ------- -#### [ C\# ] - -``` -dotnet build src -cdk ls -``` - ------- - If you don't see `HelloCdkStack`, make sure you named your app's directory `hello-cdk`\. If you didn't, go back to [Create the app](#hello_world_tutorial_create_app) and try again\. ## Add an Amazon S3 bucket @@ -371,46 +335,10 @@ It's interesting to take note of how props are represented in the different supp Synthesize an AWS CloudFormation template for the app, as follows\. ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] - -``` -cdk synth -``` - ------- -#### [ Python ] - ``` cdk synth ``` ------- -#### [ Java ] - -``` -mvn compile -cdk synth -``` - ------- -#### [ C\# ] - -``` -dotnet build src -cdk synth -``` - ------- - If your app contained more than one stack, you'd need to specify which stack\(s\) to synthesize\. But since it only contains one, the Toolkit knows you must mean that one\. **Tip** @@ -446,46 +374,10 @@ The `cdk synth` generates a perfectly valid AWS CloudFormation template\. You co To deploy the stack using AWS CloudFormation, issue: ------- -#### [ TypeScript ] - -``` -npm run build -cdk deploy -``` - ------- -#### [ JavaScript ] - -``` -cdk deploy -``` - ------- -#### [ Python ] - ``` cdk deploy ``` ------- -#### [ Java ] - -``` -mvn compile -cdk deploy -``` - ------- -#### [ C\# ] - -``` -dotnet build src -cdk deploy -``` - ------- - As with `cdk synth`, you don't need to specify the name of the stack since there's only one in the app\. It is optional \(though good practice\) to synthesize before deploying\. The AWS CDK synthesizes your stack before each deployment\. @@ -569,46 +461,10 @@ new Bucket(this, "MyFirstBucket", new BucketProps Now we'll use the `cdk diff` command to see the differences between what's already been deployed, and the code we just changed\. ------- -#### [ TypeScript ] - -``` -npm run build -cdk diff -``` - ------- -#### [ JavaScript ] - -``` -cdk diff -``` - ------- -#### [ Python ] - -``` -cdk diff -``` - ------- -#### [ Java ] - -``` -mvn compile -cdk diff -``` - ------- -#### [ C\# ] - ``` -dotnet build src cdk diff ``` ------- - The AWS CDK Toolkit queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares it with the template it synthesized from your app\. The Resources section of the output should look like the following\. ``` @@ -629,46 +485,10 @@ You can also see that the bucket isn't going to be replaced, but will be updated Now let's deploy\. ------- -#### [ TypeScript ] - ``` -npm run build cdk deploy ``` ------- -#### [ JavaScript ] - -``` -cdk deploy -``` - ------- -#### [ Python ] - -``` -cdk deploy -``` - ------- -#### [ Java ] - -``` -mvn compile -cdk deploy -``` - ------- -#### [ C\# ] - -``` -dotnet build src -cdk deploy -``` - ------- - Enter y to approve the changes and deploy the updated stack\. The Toolkit updates the bucket configuration as you requested\. ``` @@ -695,7 +515,7 @@ cdk destroy Enter y to approve the changes and delete any stack resources\. **Note** -This wouldn't have worked if we hadn't changed tho bucket's `RemovalPolicy` just a minute ago\! +This wouldn't have worked if we hadn't changed the bucket's `RemovalPolicy` just a minute ago\! If cdk destroy fails, it probably means you put something in your Amazon S3 bucket\. AWS CloudFormation won't delete buckets with files in them\. Delete the files and try again\. diff --git a/doc_source/home.md b/doc_source/home.md index 9d1ed98a..d4400819 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -16,7 +16,7 @@ Developers can use one of the supported programming languages to define reusable ## Why use the AWS CDK? -Let's look at the power of the AWS CDK\. Here is some code in an AWS CDK project to create an AWS Fargate service \(this is the code we use in the [Creating an AWS Fargate service using the AWS CDK](ecs_example.md)\)\. +Let's look at the power of the AWS CDK\. Here is some code in an AWS CDK project to create an Amazon ECS service with AWS Fargate launch type \(this is the code we use in the [Creating an AWS Fargate service using the AWS CDK](ecs_example.md)\)\. ------ #### [ TypeScript ] diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index 13b01352..eca8b65b 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -10,7 +10,10 @@ If you attempt to create an identifier with the same value within the same scope The most common identifier, `id`, is the identifier passed as the second argument when instantiating a construct object\. This identifier, like all identifiers, need only be unique within the scope in which it is created, which is the first argument when instantiating a construct object\. -Lets look at an example where we have two constructs with the identifier `MyBucket` in our app\. However, since they are defined in different scopes, the first in the scope of the stack with the identifier `Stack1`, and the second in the scope of a stack with the identifier `Stack2`, that doesn't cause any sort of conflict, and they can co\-exist in the same app without any issues\. +**Note** +The `id` of a stack is also the identifier you use to refer to it in the [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. + +Let's look at an example where we have two constructs with the identifier `MyBucket` in our app\. However, since they are defined in different scopes, the first in the scope of the stack with the identifier `Stack1`, and the second in the scope of a stack with the identifier `Stack2`, that doesn't cause any sort of conflict, and they can co\-exist in the same app without any issues\. ------ #### [ TypeScript ] diff --git a/doc_source/permissions.md b/doc_source/permissions.md index ee6e638e..ee5e0c69 100644 --- a/doc_source/permissions.md +++ b/doc_source/permissions.md @@ -24,7 +24,7 @@ An IAM principal is an entity that can be authenticated in order to access AWS r ## Grants -Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` \(Python: `grant_read`, `grant_write`\) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. +Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` \(Python: `grant_read`, `grant_read_write`\) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)`\. diff --git a/doc_source/reference.md b/doc_source/reference.md index ba78d3c6..3dd29a80 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -32,7 +32,7 @@ For more details on the cloud assembly schema, see [Cloud Assembly Versioning](h The modules in the AWS Construct Library move through various stages as they are developed from concept to mature API\. Different stages imply different promises for API stability in subsequent versions of the AWS CDK\. Stage 0: CFN resources -All construct library modules start in stage 0 when they are auto\-generated from the AWS CloudFormation resource specification\. The goal of stage 0 is to make new AWS CloudFormation resources/properties available to CDK customers as quickly as possible\. We create tracking documents to capture the data required to decide when L2 resources to add in the future\. +All construct library modules start in stage 0 when they are auto\-generated from the AWS CloudFormation resource specification\. The goal of stage 0 is to make new AWS CloudFormation resources/properties available to AWS CDK customers as quickly as possible\. We capture feedback from customers to better understand what L2 resources to add\. AWS CloudFormation resources themselves are considered stable APIs, regardless of whether other constructs in the module are under active development\. Stage 1: Experimental @@ -45,7 +45,7 @@ At the developer preview stage, our aim is to deliver a release candidate with a We make breaking changes at this stage only when required to address unforeseen customer use cases or issues\. Since breaking changes are still possible, the package itself retains the "experimental" label while in developer preview\. Stage 3: General availability \(GA\) -The module is generally available with a backwards\-compatible guarantee across minor versions\. We will only make backward\-compatible changes to the API, so that your existing apps will continue to work until the next major AWS CDK release\. +The module is generally available with a compatibility guarantee across minor versions\. We will only make backward\-compatible changes to the API, so that your existing apps will continue to work until the next major AWS CDK release\. In some cases, we may use [feature flags](featureflags.md) to optionally enable new behavior while retaining the previous behavior to support existing apps\. For more information on these stages, see [AWS Construct Library Module Lifecycle](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0107-construct-library-module-lifecycle.md)\. diff --git a/doc_source/resources.md b/doc_source/resources.md index 4a5bc02e..36309071 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -255,8 +255,8 @@ var prod = makeEnv(account: "123456789012", region: "us-east-1"); var stack1 = new StackThatProvidesABucket(app, "Stack1", new StackProps { Env = prod }); // stack2 will take an argument "bucket" -var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = prod }, - bucket: stack1.Bucket); +var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = prod, + bucket = stack1.Bucket}); ``` ------ @@ -315,7 +315,7 @@ var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-buc Assigning physical names to resources has some disadvantages in AWS CloudFormation\. Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource's properties that are immutable after creation, will fail if a resource has a physical name assigned\. If you end up in a state like that, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again\. See the [AWS CloudFormation documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) for details\. -In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value `PhysicalName.GENERATE_IF_NEEDED,`, as follows\. +In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value `PhysicalName.GENERATE_IF_NEEDED`, as follows\. ------ #### [ TypeScript ] diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 6e781a75..971acd50 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -110,46 +110,10 @@ The important files in the blank project are as follows\. \(We will also be addi Run the app and note that it synthesizes an empty stack\. ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] - -``` -cdk synth -``` - ------- -#### [ Python ] - -``` -cdk synth -``` - ------- -#### [ Java ] - ``` -mvn compile cdk synth ``` ------- -#### [ C\# ] - -``` -dotnet build src -cdk synth -``` - ------- - You should see output like the following, where *CDK\-VERSION* is the version of the AWS CDK\. ``` @@ -225,46 +189,10 @@ exports.main = async function(event, context) { Save it and be sure the project still results in an empty stack\. We haven't yet wired the Lambda function to the AWS CDK app, so the Lambda asset doesn't appear in the output\. ------- -#### [ TypeScript ] - ``` -npm run build cdk synth ``` ------- -#### [ JavaScript ] - -``` -cdk synth -``` - ------- -#### [ Python ] - -``` -cdk synth -``` - ------- -#### [ Java ] - -``` -mvn compile -cdk synth -``` - ------- -#### [ C\# ] - -``` -dotnet build src -cdk synth -``` - ------- - ## Creating a widget service Add the API Gateway, Lambda, and Amazon S3 packages to the app\. @@ -553,46 +481,10 @@ namespace MyWidgetService Save the app and make sure it still synthesizes an empty stack\. ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] - -``` -cdk synth -``` - ------- -#### [ Python ] - ``` cdk synth ``` ------- -#### [ Java ] - -``` -mvn compile -cdk synth -``` - ------- -#### [ C\# ] - -``` -dotnet build src -cdk synth -``` - ------- - ## Add the service to the app To add the widget service to our AWS CDK app, we'll need to modify the source file that defines the stack to instantiate the service construct\. @@ -674,46 +566,10 @@ new WidgetService(this, "Widgets"); Be sure the app runs and synthesizes a stack \(we won't show the stack here: it's over 250 lines\)\. ------- -#### [ TypeScript ] - -``` -npm run build -cdk synth -``` - ------- -#### [ JavaScript ] - -``` -cdk synth -``` - ------- -#### [ Python ] - -``` -cdk synth -``` - ------- -#### [ Java ] - -``` -mvn compile -cdk synth -``` - ------- -#### [ C\# ] - ``` -dotnet build src cdk synth ``` ------- - ## Deploy and test the app Before you can deploy your first AWS CDK app containing a lambda function, you must bootstrap your AWS environment\. This creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see [Bootstrapping your AWS environment](cli.md#cli-bootstrap)\. If you've already bootstrapped, you'll get a warning and nothing will change\. @@ -995,46 +851,10 @@ File: `src/MyWidgetService/WidgetService.cs` Save and deploy the app\. ------- -#### [ TypeScript ] - ``` -npm run build cdk deploy ``` ------- -#### [ JavaScript ] - -``` -cdk deploy -``` - ------- -#### [ Python ] - -``` -cdk deploy -``` - ------- -#### [ Java ] - -``` -mvn compile -cdk deploy -``` - ------- -#### [ C\# ] - -``` -dotnet build src -cdk deploy -``` - ------- - We can now store, show, or delete an individual widget\. Use the following commands to list the widgets, create the widget **example**, list all of the widgets, show the contents of **example** \(it should show today's date\), delete **example**, and then show the list of widgets again\. ``` diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index 0b4eca19..ca6661b2 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -2,7 +2,7 @@ Most of the other code examples in the *AWS CDK Developer Guide* involve only a single stack\. However, you can create apps containing any number of stacks\. Each stack results in its own AWS CloudFormation template\. Stacks are the *unit of deployment:* each stack in an app can be synthesized and deployed individually using the `cdk deploy` command\. -This topic illustrates how to extend the `Stack` class to accept new properties or arguments, how to use these properties affect what resources the stack contains and their configuration, and how to instantiate multiple stacks from this class\. The example uses a Boolean property, named `encryptBucket` \(Python: `encrypt_bucket`\), to indicate whether an Amazon S3 bucket should be encrypted\. If so, the stack enables encryption using a key managed by AWS Key Management Service \(AWS KMS\)\. The app creates two instances of this stack, one with encryption and one without\. +This topic illustrates how to extend the `Stack` class to accept new properties or arguments, how to use these properties to affect what resources the stack contains and their configuration, and how to instantiate multiple stacks from this class\. The example uses a Boolean property, named `encryptBucket` \(Python: `encrypt_bucket`\), to indicate whether an Amazon S3 bucket should be encrypted\. If so, the stack enables encryption using a key managed by AWS Key Management Service \(AWS KMS\)\. The app creates two instances of this stack, one with encryption and one without\. ## Before you begin diff --git a/doc_source/stacks.md b/doc_source/stacks.md index d2e015b7..55b997d2 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -367,7 +367,7 @@ The scope of a nested stack must be a `Stack` or `NestedStack` construct\. The n At synthesis time, the nested stack is synthesized to its own AWS CloudFormation template, which is uploaded to the AWS CDK staging bucket at deployment\. Nested stacks are bound to their parent stack and are not treated as independent deployment artifacts; they are not listed by `cdk list` nor can they be deployed by `cdk deploy`\. - References between parent stacks and nested stacks are automatically translated to stack parameters and outputs in the generated AWS CloudFormation templates\. +References between parent stacks and nested stacks are automatically translated to stack parameters and outputs in the generated AWS CloudFormation templates, as with any [cross\-stack reference](resources.md#resource_stack)\. **Warning** Changes in security posture are not displayed before deployment for nested stacks\. This information is displayed only for top\-level stacks\. \ No newline at end of file diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 070a4258..b5135e17 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -135,7 +135,7 @@ Tag.Add(myConstruct, "key", "value", new TagProps { Priority = 300 }); `Tag.add()` supports properties that fine\-tune how tags are applied to resources\. All properties are optional\. -The following example applies the tag **tagname** with the value **value** and priority **100** to resources of type **AWS::Xxx::Yzz** in the construct, but not to instances launched in an Amazon EC2 Auto Scaling group or to resources of type **AWS::Xxx::Zss**\. +The following example applies the tag **tagname** with the value **value** and priority **100** to resources of type **AWS::Xxx::Yyy** in the construct, but not to instances launched in an Amazon EC2 Auto Scaling group or to resources of type **AWS::Xxx::Zzz**\. \(These are placeholders for two arbitrary but different AWS CloudFormation resource types\.\) ------ #### [ TypeScript ] @@ -213,7 +213,7 @@ Use this to set the priority of this operation with respect to other `Tag.add()` `Tag.remove()` supports properties to fine\-tune how tags are removed from resources\. All properties are optional\. -The following example removes the tag **tagname** with priority **200** from resources of type **AWS::Xxx::Yzz** in the construct, but not from resources of type **AWS::Xxx::Zzz**\. +The following example removes the tag **tagname** with priority **200** from resources of type **AWS::Xxx::Yyy** in the construct, but not from resources of type **AWS::Xxx::Zzz**\. ------ #### [ TypeScript ] diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 28ffc470..48e2fa8c 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -26,7 +26,7 @@ cdk init app --language java The resulting project includes a reference to the `software.amazon.awscdk.core` Maven package\. It and its dependencies are automatically installed by Maven\. -If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set ta use Java 8 \(1\.8\)\. +If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set to use Java 8 \(1\.8\)\. ## Managing AWS construct library modules @@ -110,7 +110,7 @@ In Java, missing values in AWS CDK objects such as props are represented by `nul ## Building, synthesizing, and deploying - Build your app to check for errors and to run tests\. You can do this in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn compile` at a command prompt while in your project's root directory\. +The AWS CDK automatically compiles your app before running it\. However, it can be useful to build your app manually to check for errors and to run tests\. You can do this in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn compile` at a command prompt while in your project's root directory\. Run any tests you've written by running `mvn test` at a command prompt\. From 47d681008828c322155f038abfb1c34894bdffe0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 7 Aug 2020 22:58:17 +0000 Subject: [PATCH 247/655] put Mac OS X ahead of Linux consistently (based on usage stats) --- doc_source/cli.md | 2 +- doc_source/codepipeline_example.md | 6 +++--- doc_source/getting_started.md | 2 +- doc_source/work-with-cdk-csharp.md | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 4ec3a668..19a25ab9 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -100,7 +100,7 @@ aws configure Provide your AWS access key ID, secret access key, and default region when prompted\. -You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(Linux or Mac\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. +You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(Mac OS X or Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. + In `~/.aws/config` or `%USERPROFILE%\.aws\config` ``` diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 537ce2de..a8de53ee 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -63,9 +63,9 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ------ #### [ Python ] - A couple of commands differ between Windows and Linux or Mac OS\. + A couple of commands differ between Windows and Mac OS X or Linux\. - **Linux or Mac OS X** + **Mac OS X/Linux** ``` cd pipeline @@ -149,7 +149,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi 1. If a directory named `test` exists, delete it\. We won't be using it in this example, and some of the code in the tests will cause errors because of other changes we'll be making\. ------ -#### [ Linux or Mac OS X ] +#### [ Mac OS X/Linux ] ``` rm -rf test diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 168e497f..14d482e9 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -133,7 +133,7 @@ aws configure Provide your AWS access key ID, secret access key, and default region when prompted\. -You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(Linux or Mac\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. +You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(Mac OS X or Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. + In `~/.aws/config` or `%USERPROFILE%\.aws\config` ``` diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 1c945283..0d44817f 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -4,7 +4,7 @@ You can develop AWS CDK applications in C\# using familiar tools including Visual Studio, the `dotnet` command, and the NuGet package manager\. The modules comprising the AWS Construct Library are distributed via [nuget\.org](https://www.nuget.org/packages?q=amazon.cdk.aws)\. -We suggest using [Visual Studio 2019](https://visualstudio.microsoft.com/downloads/) \(any edition\) and the Microsoft \.NET Framework on Windows to develop AWS CDK apps in C\#\. You may use other tools \(for example, Mono on Linux or Mac OS X\), but our ability to provide instruction and support for these environments may be limited\. +We suggest using [Visual Studio 2019](https://visualstudio.microsoft.com/downloads/) \(any edition\) and the Microsoft \.NET Framework on Windows to develop AWS CDK apps in C\#\. You may use other tools \(for example, Mono on Mac OS X or Linux\), but our ability to provide instruction and support for these environments may be limited\. ## Prerequisites @@ -13,7 +13,7 @@ To work with the AWS CDK, you must have an AWS account and credentials and have C\# AWS CDK applications require a \.NET Standard 2\.1 compatible implementation\. Suitable implementations include: + \.NET Core v3\.1 or later + \.NET Framework v4\.6\.1 or later -+ Mono v5\.4 or later on Linux or Mac OS X; [download here](https://www.mono-project.com/download/stable/) ++ Mono v5\.4 or later on Mac OS X or Linux; [download here](https://www.mono-project.com/download/stable/) If you have an up\-to\-date Windows 10 installation, you already have a suitable installation of \.NET Framework\. From fb15a0712056e2191e57ecb3798a47fe20d195d4 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 12 Aug 2020 00:16:22 +0000 Subject: [PATCH 248/655] improvements mainly to Python topic (plus shared content that affects other topics) --- doc_source/work-with-cdk-csharp.md | 2 +- doc_source/work-with-cdk-java.md | 2 +- doc_source/work-with-cdk-javascript.md | 2 +- doc_source/work-with-cdk-python.md | 55 ++++++++++++++------------ doc_source/work-with-cdk-typescript.md | 2 +- 5 files changed, 33 insertions(+), 30 deletions(-) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 0d44817f..96a2144c 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -163,7 +163,7 @@ cdk synth # app defines single stack cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed ``` -You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes; otherwise, the shell may try to expand \("glob"\) it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` cdk synth "Stack?" # Stack1, StackA, etc. diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 48e2fa8c..c1b2c8e6 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -125,7 +125,7 @@ cdk synth # app defines single stack cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed ``` -You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes; otherwise, the shell may try to expand \("glob"\) it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` cdk synth "Stack?" # Stack1, StackA, etc. diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index b801213f..0961fbdd 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -92,7 +92,7 @@ cdk synth # app defines single stack cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed ``` -You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes; otherwise, the shell may try to expand \("glob"\) it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` cdk synth "Stack?" # Stack1, StackA, etc. diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index f204c8c3..7a204ef4 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -1,8 +1,8 @@ # Working with the AWS CDK in Python -Python is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in Python uses familiar tools, including the standard Python implementation \(dubbed CPython\), `virtualenv`, and `pip`, the Python package installer\. The modules comprising the AWS Construct Library are distributed via [pypi\.org](https://pypi.org/search/?q=aws-cdk)\. The Python version of the AWS CDK even uses Python\-style identifiers \(for example, `snake_case` method names\)\. +Python is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in Python uses familiar tools, including the standard Python implementation \(CPython\), virtual environments with `virtualenv`, and the Python package installer `pip`\. The modules comprising the AWS Construct Library are distributed via [pypi\.org](https://pypi.org/search/?q=aws-cdk)\. The Python version of the AWS CDK even uses Python\-style identifiers \(for example, `snake_case` method names\)\. -You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://github.com/VSCodium/vscodium)\), which has good support for Python via an [official extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python), though the simple IDLE editor included with Python will suffice to get started\. The Python modules for the AWS CDK do have type hints, so you may prefer a linting tool or an IDE that supports type validation\. +You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://github.com/VSCodium/vscodium)\), which has good support for Python via an [official extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python)\. The IDLE editor included with Python will suffice to get started\. The Python modules for the AWS CDK do have type hints, which are useful for a linting tool or an IDE that supports type validation\. ## Prerequisites @@ -18,12 +18,10 @@ python -m pip install --upgrade pip python -m pip install --upgrade virtualenv ``` -If you encounter a permission error, run the above commands using `sudo` \(to install the modules system\-wide\) or add the `--user` flag to each command so that the modules are installed in your user directory\. +If you encounter a permission error, run the above commands with the `--user` flag to each command so that the modules are installed in your user directory, or use `sudo` to get the permissions to install the modules system\-wide\. **Note** -It is common for Linux distros to use the executable name `python3` for Python 3\.x, and have `python` refer to a Python 2\.x installation, and similarly for `pip`/`pip3`\. You can adjust the command used to run your application by editing `cdk.json` in the project's main directory\. - -Make sure the `pip` executable \(on Windows, `pip.exe`\) is in a directory included on the system `PATH`\. You should be able to type `pip --version` and see its version, not an error message\. +It is common for Linux distros to use the executable name `python3` for Python 3\.x, and have `python` refer to a Python 2\.x installation\. You can adjust the command used to run your application by editing `cdk.json` in the project's main directory\. ## Creating a project @@ -46,33 +44,38 @@ source .env/bin/activate Then install the app's standard dependencies: ``` -pip install -r requirements.txt +python -m pip install -r requirements.txt ``` **Important** -Activate the project's virtual environment whenever you start working on it\. If you don't, you won't have access to the modules installed there, and modules you install will go in Python's global module directory \(or will result in a permission error\)\. +Activate the project's virtual environment whenever you start working on it\. Otherwise, you won't have access to the modules installed there, and modules you install will go in the Python global module directory \(or will result in a permission error\)\. ## Managing AWS construct library modules -Use the Python package installer, `pip`, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. `pip` also installs the dependencies for those modules automatically\. +Use the Python package installer, `pip`, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. `pip` also installs the dependencies for those modules automatically\. To run `pip` without needing it installed in a special directory, invoke it as: + +``` +python -m pip PIP-COMMAND +``` AWS Construct Library modules are named like `aws-cdk.SERVICE-NAME`\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. ``` -pip install aws-cdk.aws-s3 aws-cdk.aws-lambda +python -m pip install aws-cdk.aws-s3 aws-cdk.aws-lambda ``` -After installing a module, update your project's `requirements.txt` file, which maintains your project's dependencies\. You may do this manually, by opening `requirements.txt` in your editor, or by issuing: +After installing a module, update your project's `requirements.txt` file, which lists your project's dependencies\. It is best to do this manually rather than using `pip freeze`\. `pip freeze` captures the current versions of all modules installed in your Python virtual environment, which can be useful when bundling up a project to be run elsewhere\. + +Usually, though, your `requirements.txt` should list only top\-level dependencies \(modules that your app depends on directly\) and not the dependencies of those modules\. This strategy makes updating your dependencies simpler\. Here is what your `requirements.txt` file might look like if you have installed the Amazon S3 and AWS Lambda modules as shown earlier\. ``` -pip freeze > requirements.txt +aws-cdk.aws-s3==X.YY.ZZ +aws-cdk.aws-lambda==X.YY.ZZ ``` -`pip freeze` captures the current versions of all modules installed in your virtual environment\. You can edit `requirements.txt` to allow upgrades; simply replace the `==` preceding a version number with `~=` to allow upgrades to a higher compatible version, or remove the version requirement entirely to specify the latest available version of the module\. - -You may want to remove modules that are only installed because they are dependencies of other modules; these will be installed automatically anyway, and by not listing them explicitly you will ensure that you get a version compatible with the version of the module you actually want, and no unnecessary dependencies\. +You can edit `requirements.txt` to allow upgrades; simply replace the `==` preceding a version number with `~=` to allow upgrades to a higher compatible version, or remove the version requirement entirely to specify the latest available version of the module\. -With `requirements.txt` edited appropriately to allow upgrades, issue this command to upgrade the installed modules: +With `requirements.txt` edited appropriately to allow upgrades, issue this command to upgrade your project's installed modules at any time: ``` pip install --upgrade -r requirements.txt @@ -85,7 +88,7 @@ All AWS Construct Library modules used in your project must be the same version\ ### Props -Natively, all AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. In Python, props are expressed as keyword arguments\. If an argument contains nested data structures, these are expressed using a class which takes its own keyword arguments at instantiation\. The same pattern is applied to other method calls that take a single structured argument\. @@ -104,22 +107,22 @@ bucket.add_lifecycle_rule( When extending a class or overriding a method, you may want to accept additional arguments for your own purposes that are not understood by the parent class\. In this case you should accept the arguments you don't care about using the `**kwargs` idiom, and use keyword\-only arguments to accept the arguments you're interested in\. When calling the parent's constructor or the overridden method, pass only the arguments it is expecting \(often just `**kwargs`\)\. Passing arguments that the parent class or method doesn't expect results in an error\. -Future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues for users of your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion\. You can avoid this potential problem by naming your properties so they clearly belong to your construct \(e\.g\. `bob_encryption` rather than just `encryption`, assuming you're Bob\)\. If there are many new properties, bundle them into an appropriately\-named class \(`BobBucketPoperties`?\) and pass it as a single keyword argument\. +Future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues for users of your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion\. You can avoid this potential problem by naming your properties so they clearly belong to your construct\. If there are many new properties, bundle them into an appropriately\-named class and pass it as a single keyword argument\. ### Missing values -When working with `**kwargs`, use the dictionary's `get()` method to provide a default value if a property is not provided\. Avoid using `kwargs[...]`, as this raises `KeyError` for missing values\. +The AWS CDK uses `None` to represent missing or undefined values\. When working with `**kwargs`, use the dictionary's `get()` method to provide a default value if a property is not provided\. Avoid using `kwargs[...]`, as this raises `KeyError` for missing values\. ``` -encrypted = kwargs.get("encrypted") # None if no property "encrypted" exists -encrypted = kwargs.get("encrypted", False) # specify default of False if property is missing +encrypted = kwargs.get("encrypted") # None if no property "encrypted" exists +encrypted = kwargs.get("encrypted", False) # specify default of False if property is missing ``` -Some AWS CDK methods \(such as `tryGetContext()` to get a runtime context value\) return `None` to indicate a missing value, which you will need to check for and handle\. +Some AWS CDK methods \(such as `tryGetContext()` to get a runtime context value\) may return `None`, which you will need to check explicitly\. ### Using interfaces -Python doesn't have an interface feature as some other languages do\. \(If you're not familiar with the concept, Wikipedia has [a good introduction](https://en.wikipedia.org/wiki/Interface_(computing)#In_object-oriented_languages)\.\) TypeScript, the language in which the AWS CDK is implemented does, however, and constructs and other AWS CDK objects often require an instance that adheres to a particular interface, rather than inheriting from a particular class\. So the AWS CDK provides its own interface feature as part of the [JSII](https://github.com/aws/jsii) layer\. +Python doesn't have an interface feature as some other languages do, though it does have [abstract base classes](https://docs.python.org/3/library/abc.html), which are similar\. \(If you're not familiar with interfaces, Wikipedia has [a good introduction](https://en.wikipedia.org/wiki/Interface_(computing)#In_object-oriented_languages)\.\) TypeScript, the language in which the AWS CDK is implemented, does provide intefaces, and constructs and other AWS CDK objects often require an object that adheres to a particular interface, rather than inheriting from a particular class\. So the AWS CDK provides its own interface feature as part of the [JSII](https://github.com/aws/jsii) layer\. To indicate that a class implements a particular interface, you can use the `@jsii.implements` decorator: @@ -135,9 +138,9 @@ class MyAspect(): ### Type pitfalls -Python natively uses dynamic typing, where variables may refer to a value of any type\. Parameters and return values may be annotated with types, but these are "hints" and are not enforced\. This means that in Python, it is easy to pass the incorrect type of value to a AWS CDK construct\. Instead of getting a type error during build, as you would from a statically\-typed language, you may instead get a runtime error when the JSII layer \(which translates between Python and the AWS CDK's TypeScript core\) is unable to deal with the unexpected type\. +Python uses dynamic typing, where variables may refer to a value of any type\. Parameters and return values may be annotated with types, but these are "hints" and are not enforced\. This means that in Python, it is easy to pass the incorrect type of value to a AWS CDK construct\. Instead of getting a type error during build, as you would from a statically\-typed language, you may instead get a runtime error when the JSII layer \(which translates between Python and the AWS CDK's TypeScript core\) is unable to deal with the unexpected type\. -In our experience, the type errors Python programmers make tend to fall into these categories\. Be especially alert to these pitfalls\. +In our experience, the type errors Python programmers make tend to fall into these categories\. + Passing a single value where a construct expects a container \(Python list or dictionary\) or vice versa\. + Passing a value of a type associated with a Level 1 \(`CfnXxxxxx`\) construct to a higher\-level construct, or vice versa\. @@ -156,7 +159,7 @@ cdk synth # app defines single stack cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed ``` -You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes; otherwise, the shell may try to expand \("glob"\) it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` cdk synth "Stack?" # Stack1, StackA, etc. diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index d0e679fb..acca3ab1 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -92,7 +92,7 @@ cdk synth # app defines single stack cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed ``` -You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes; otherwise, the shell may try to expand \("glob"\) it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` cdk synth "Stack?" # Stack1, StackA, etc. From 19a20df30efcbba69dac326469cddfbe72e6296b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 12 Aug 2020 00:18:29 +0000 Subject: [PATCH 249/655] typo --- doc_source/work-with-cdk-python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 7a204ef4..b3d73a30 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -122,7 +122,7 @@ Some AWS CDK methods \(such as `tryGetContext()` to get a runtime context value\ ### Using interfaces -Python doesn't have an interface feature as some other languages do, though it does have [abstract base classes](https://docs.python.org/3/library/abc.html), which are similar\. \(If you're not familiar with interfaces, Wikipedia has [a good introduction](https://en.wikipedia.org/wiki/Interface_(computing)#In_object-oriented_languages)\.\) TypeScript, the language in which the AWS CDK is implemented, does provide intefaces, and constructs and other AWS CDK objects often require an object that adheres to a particular interface, rather than inheriting from a particular class\. So the AWS CDK provides its own interface feature as part of the [JSII](https://github.com/aws/jsii) layer\. +Python doesn't have an interface feature as some other languages do, though it does have [abstract base classes](https://docs.python.org/3/library/abc.html), which are similar\. \(If you're not familiar with interfaces, Wikipedia has [a good introduction](https://en.wikipedia.org/wiki/Interface_(computing)#In_object-oriented_languages)\.\) TypeScript, the language in which the AWS CDK is implemented, does provide interfaces, and constructs and other AWS CDK objects often require an object that adheres to a particular interface, rather than inheriting from a particular class\. So the AWS CDK provides its own interface feature as part of the [JSII](https://github.com/aws/jsii) layer\. To indicate that a class implements a particular interface, you can use the `@jsii.implements` decorator: From 61aa60466d28086dad19e98ff14ba039e2a79839 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 12 Aug 2020 00:49:04 +0000 Subject: [PATCH 250/655] extract tag for ECR lookup rather than using URI --- doc_source/assets.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/doc_source/assets.md b/doc_source/assets.md index 60934f6e..dc6eb5bd 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -136,7 +136,7 @@ In most cases, you don't need to directly use the APIs in the `aws-s3-assets` mo #### Lambda function example -A common use case is to create AWS Lambda functions with the handler code, which is the entry point for the function, as an Amazon S3 asset\. +A common use case is to create AWS Lambda functions with the handler code, which is the entry point for the function, as an Amazon S3 asset\. The following example uses an Amazon S3 asset to define a Python handler in the local directory `handler` and creates a Lambda function with the local directory asset as the `code` property\. Below is the Python code for the handler\. @@ -678,7 +678,7 @@ taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions #### Deploy\-time attributes example -The following example shows how to use the deploy\-time attributes `repository` and `imageUri` to create an Amazon ECS task definition with the AWS Fargate launch type\. +The following example shows how to use the deploy\-time attributes `repository` and `imageUri` to create an Amazon ECS task definition with the AWS Fargate launch type\. Note that the Amazon ECR repo lookup requires the image's tag, not its URI, so we snip it from the end of the asset's URI\. ------ #### [ TypeScript ] @@ -698,7 +698,7 @@ const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { }); taskDefinition.addContainer("my-other-container", { - image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri) + image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri.split(":").pop()) }); ``` @@ -720,7 +720,7 @@ const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { }); taskDefinition.addContainer("my-other-container", { - image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri) + image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri.split(":").pop()) }); ``` @@ -742,7 +742,7 @@ task_definition = ecs.FargateTaskDefinition(self, "TaskDef", task_definition.add_container("my-other-container", image=ecs.ContainerImage.fromEcrRepository( - asset.repository, asset.image_uri)) + asset.repository, asset.image_uri.rpartition(":")[-1])) ``` ------ @@ -765,9 +765,13 @@ DockerImageAsset asset = DockerImageAsset.Builder.create(this, "my-image") FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create( this, "TaskDef").memoryLimitMiB(1024).cpu(512).build(); +// extract the tag from the asset's image URI for use in ECR repo lookup +String imageUri = asset.getImageUri(); +String imageTag = imageUri.substring(imageUri.lastIndexOf(":") + 1); + taskDefinition.addContainer("my-other-container", ContainerDefinitionOptions.builder().image(ContainerImage.fromEcrRepository( - asset.getRepository(), asset.getImageUri())).build()); + asset.getRepository(), imageTag)).build()); ``` ------ @@ -790,7 +794,7 @@ var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskD taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions { - Image = ContainerImage.FromEcrRepository(asset.Repository, asset.ImageUri) + Image = ContainerImage.FromEcrRepository(asset.Repository, asset.ImageUri.Split(":").Last()) }); ``` From 177f7d43bfff45eda91c1893dc950b81b3e310fb Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 12 Aug 2020 20:59:31 +0000 Subject: [PATCH 251/655] add description of cdk list, fix wrong command line --- doc_source/cli.md | 41 +++++++++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 19a25ab9..0953ee8b 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -191,7 +191,7 @@ You may also bootstrap a specific environment\. Credentials must be configured \ ``` cdk bootstrap ACCOUNT-NUMBER/REGION # e.g. cdk bootstrap 1111111111/us-east-1 -aws bootstrap --profile test 1111111111/us-east-1 +cdk bootstrap --profile test 1111111111/us-east-1 ``` **Important** @@ -232,6 +232,19 @@ The supported languages \(*LANGUAGE*\) are: The templates use the name of the project folder to generate names for files and classes inside your new app\. +## Listing stacks + +To see a list of the IDs of the stacks in your AWS CDK application, enter one of: + +``` +cdk list +cdk ls +``` + +If your app contains many stacks, you can specify full or partial stack IDs of the stacks to be listed; see [Specifying stacks](#cli-stacks)\. + +Add the `--long` flag to see additional information about the stacks, including the stack names and their environments \(AWS account and region\)\. + ## Synthesizing stacks The `cdk synthesize` command \(almost always abbreviated `synth`\) synthesizes a stack defined in your app into a CloudFormation template\. @@ -248,7 +261,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -267,7 +280,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -275,7 +288,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth –json MyStack ``` -### Specifying output directory +### Specifying output directory Add the \-\-output \(\-o\) option to write the synthesized templates to a directory other than cdk\.out\. @@ -299,7 +312,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -321,7 +334,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. @@ -496,7 +509,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -509,7 +522,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -522,7 +535,7 @@ Options: dependencies [boolean] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -561,7 +574,7 @@ Options: [boolean] [default: false] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -604,7 +617,7 @@ Options: disabled) [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -620,7 +633,7 @@ Options: [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -640,7 +653,7 @@ Options: [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -663,7 +676,7 @@ Options: [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context From 1ba335b86ee639867dad12c05fc945b9077748cf Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 12 Aug 2020 21:10:09 +0000 Subject: [PATCH 252/655] add example of module import --- doc_source/work-with-cdk-python.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index b3d73a30..4208680c 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -64,6 +64,13 @@ AWS Construct Library modules are named like `aws-cdk.SERVICE-NAME`\. For exampl python -m pip install aws-cdk.aws-s3 aws-cdk.aws-lambda ``` +Similar names are used for importing AWS Construct Library modules into your Python code \(just replace the hyphens with underscores\)\. + +``` +import aws_cdk.aws_s3 as s3 +import aws_cdk.aws_lambda as lam +``` + After installing a module, update your project's `requirements.txt` file, which lists your project's dependencies\. It is best to do this manually rather than using `pip freeze`\. `pip freeze` captures the current versions of all modules installed in your Python virtual environment, which can be useful when bundling up a project to be run elsewhere\. Usually, though, your `requirements.txt` should list only top\-level dependencies \(modules that your app depends on directly\) and not the dependencies of those modules\. This strategy makes updating your dependencies simpler\. Here is what your `requirements.txt` file might look like if you have installed the Amazon S3 and AWS Lambda modules as shown earlier\. From 3727e629e6c2025904c4a1e1ec971cf238211267 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 12 Aug 2020 21:19:25 +0000 Subject: [PATCH 253/655] fix typo in comment marker --- doc_source/work-with-cdk-csharp.md | 4 ++-- doc_source/work-with-cdk-java.md | 4 ++-- doc_source/work-with-cdk-javascript.md | 4 ++-- doc_source/work-with-cdk-python.md | 4 ++-- doc_source/work-with-cdk-typescript.md | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 96a2144c..2e8e2ce1 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -160,14 +160,14 @@ You can specify the names of multiple stacks to be synthesized or deployed in a ``` cdk synth # app defines single stack -cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed ``` You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` cdk synth "Stack?" # Stack1, StackA, etc. -cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. ``` **Tip** diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index c1b2c8e6..076b57a5 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -122,14 +122,14 @@ You can specify the names of multiple stacks to be synthesized or deployed in a ``` cdk synth # app defines single stack -cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed ``` You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` cdk synth "Stack?" # Stack1, StackA, etc. -cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. ``` **Tip** diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 0961fbdd..af3dc906 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -89,14 +89,14 @@ You can specify the names of multiple stacks to be synthesized or deployed in a ``` cdk synth # app defines single stack -cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed ``` You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` cdk synth "Stack?" # Stack1, StackA, etc. -cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. ``` **Tip** diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 4208680c..3d0c37e4 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -163,14 +163,14 @@ You can specify the names of multiple stacks to be synthesized or deployed in a ``` cdk synth # app defines single stack -cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed ``` You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` cdk synth "Stack?" # Stack1, StackA, etc. -cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. ``` **Tip** diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index acca3ab1..fa77a093 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -89,14 +89,14 @@ You can specify the names of multiple stacks to be synthesized or deployed in a ``` cdk synth # app defines single stack -cdk deploy Happy Grumpy @ app defines two or more stacks; two are deployed +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed ``` You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. ``` cdk synth "Stack?" # Stack1, StackA, etc. -cdk deploy "*Stack" @ PipeStack, LambdaStack, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. ``` **Tip** From 088ebf4ef4c1a685641c56d193b0548a037eb1b2 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 13 Aug 2020 22:02:03 +0000 Subject: [PATCH 254/655] update doc history; formatting and style tweaks --- doc_source/cli.md | 8 ++++---- doc_source/doc-history.md | 3 ++- doc_source/reference.md | 2 +- doc_source/troubleshooting.md | 2 +- doc_source/work-with-cdk-csharp.md | 4 ++-- doc_source/work-with-cdk-python.md | 2 +- doc_source/work-with-cdk-typescript.md | 2 +- 7 files changed, 12 insertions(+), 11 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 0953ee8b..fb258993 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -1,6 +1,6 @@ # AWS CDK Toolkit \(`cdk` command\) -The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting with your AWS CDK app\. It executes your app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. It also provides other features useful for creating and working with AWS CDK projects\. This topic contains information on common use cases of the CDK Toolkit\. +The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting with your AWS CDK app\. It executes your app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. It also provides other features useful for creating and working with AWS CDK projects\. This topic contains information about common use cases of the CDK Toolkit\. The AWS CDK Toolkit is installed with the Node Package Manager\. In most cases, we recommend installing it globally\. @@ -234,7 +234,7 @@ The templates use the name of the project folder to generate names for files and ## Listing stacks -To see a list of the IDs of the stacks in your AWS CDK application, enter one of: +To see a list of the IDs of the stacks in your AWS CDK application, enter one of the following equivalent commands: ``` cdk list @@ -243,7 +243,7 @@ cdk ls If your app contains many stacks, you can specify full or partial stack IDs of the stacks to be listed; see [Specifying stacks](#cli-stacks)\. -Add the `--long` flag to see additional information about the stacks, including the stack names and their environments \(AWS account and region\)\. +Add the `--long` flag to see more information about the stacks, including the stack names and their environments \(AWS account and region\)\. ## Synthesizing stacks @@ -290,7 +290,7 @@ cdk synth –json MyStack ### Specifying output directory -Add the \-\-output \(\-o\) option to write the synthesized templates to a directory other than cdk\.out\. +Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. ``` cdk synth –output=~/templates diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index e35d93c4..24a47a94 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -1,12 +1,13 @@ # AWS CDK Developer Guide history -See [Releases](https://github.com/awslabs/aws-cdk/releases) for information on AWS CDK releases\. The AWS CDK is updated approximately once a week\. Maintenance versions may be released between weekly releases to address critical issues\. Each release includes a matched AWS CDK Toolkit \(CDK CLI\), AWS Construct Library, and API Reference\. Updates to this Guide generally do not synchronize with AWS CDK releases\. +See [Releases](https://github.com/awslabs/aws-cdk/releases) for information about AWS CDK releases\. The AWS CDK is updated approximately once a week\. Maintenance versions may be released between weekly releases to address critical issues\. Each release includes a matched AWS CDK Toolkit \(CDK CLI\), AWS Construct Library, and API Reference\. Updates to this Guide generally do not synchronize with AWS CDK releases\. **Note** The table below represents significant documentation milestones\. We fix errors and improve content on an ongoing basis\. | Change | Description | Date | | --- |--- |--- | +| [Add CDK Pipelines how\-to](#doc-history) | CDK Pipelines let you easily automate the deployment of your AWS CDK apps from source control whenever they're updated\. | July 17, 2020 | | [Improve CDK Toolkit topic](#doc-history) | Include more information and examples around performing common tasks with the CLI \(and the relevant flags\) rather than just including a copy of the help\. | July 9, 2020 | | [Improve CodePipeline example](#doc-history) | Update pipeline stack to build in proper language and add more material dealing with the CodeCommit repository\. | July 6, 2020 | | [Improve Getting Started](#doc-history) | Remove extraneous material from Getting Started, use a more conversational tone, incorporate current best practices\. Break out Hello World into its own topic\. | June 17, 2020 | diff --git a/doc_source/reference.md b/doc_source/reference.md index 3dd29a80..12229f8b 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -48,7 +48,7 @@ Stage 3: General availability \(GA\) The module is generally available with a compatibility guarantee across minor versions\. We will only make backward\-compatible changes to the API, so that your existing apps will continue to work until the next major AWS CDK release\. In some cases, we may use [feature flags](featureflags.md) to optionally enable new behavior while retaining the previous behavior to support existing apps\. -For more information on these stages, see [AWS Construct Library Module Lifecycle](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0107-construct-library-module-lifecycle.md)\. +For more information about these maturity stages, see [AWS Construct Library Module Lifecycle](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0107-construct-library-module-lifecycle.md)\. ### Language binding stability diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index fb8904fa..3fc46192 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -246,7 +246,7 @@ At this writing, there is one AWS region that has only one availability zone: ap You can change this behavior by overriding your stack's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) \(Python: `availability_zones`\) property to explicitly specify the zones you want to use\. -For more information on how to specify a stack's account and region at synthesis time, while retaining the flexibility to deploy to any region, see [Environments](environments.md)\. +For more information about specifying a stack's account and region at synthesis time, while retaining the flexibility to deploy to any region, see [Environments](environments.md)\. \([back to list](#troubleshooting_top)\) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 2e8e2ce1..2e272dd6 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -55,7 +55,7 @@ Look in the **Updates** panel to install new versions of your packages\. ### The NuGet console -The NuGet console is a PowerShell\-based interface to NuGet that works in the context of a Visual Studio project\. You can open it in Visual Studio by choosing **Tools** > **NuGet Package Manager** > **Package Manager Console**\. For more information on using this tool, see [Install and Manage Packages with the Package Manager Console in Visual Studio](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-powershell)\. +The NuGet console is a PowerShell\-based interface to NuGet that works in the context of a Visual Studio project\. You can open it in Visual Studio by choosing **Tools** > **NuGet Package Manager** > **Package Manager Console**\. For more information about using this tool, see [Install and Manage Packages with the Package Manager Console in Visual Studio](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-powershell)\. ### The `dotnet` command @@ -81,7 +81,7 @@ dotnet add package Amazon.CDK.AWS.S3 -v VERSION-NUMBER To update a package, issue the same `dotnet add` command you used to install it\. If you do not specify a version number, the latest version is installed\. For experimental modules, again, you must specify an explicit version number\. -For more information on managing packages using the `dotnet` command, see [Install and Manage Packages Using the dotnet CLI](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli)\. +For more information about managing packages using the `dotnet` command, see [Install and Manage Packages Using the dotnet CLI](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli)\. ### The `nuget` command diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 3d0c37e4..6d433e5b 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -18,7 +18,7 @@ python -m pip install --upgrade pip python -m pip install --upgrade virtualenv ``` -If you encounter a permission error, run the above commands with the `--user` flag to each command so that the modules are installed in your user directory, or use `sudo` to get the permissions to install the modules system\-wide\. +If you encounter a permission error, run the above commands with the `--user` flag so that the modules are installed in your user directory, or use `sudo` to obtain the permissions to install the modules system\-wide\. **Note** It is common for Linux distros to use the executable name `python3` for Python 3\.x, and have `python` refer to a Python 2\.x installation\. You can adjust the command used to run your application by editing `cdk.json` in the project's main directory\. diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index fa77a093..5da4dbae 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -71,7 +71,7 @@ Alternatively, name your properties so that it is clear that they belong to your ### Missing values -Missing values in an object \(such as props\) have the value `undefined` in TypeScript\. Recent versions of the language include operators that simplify working with these values, making it easier to specify defaults and "short\-circuit" chaining when an undefined value is reached\. For more information on these features, see the [TypeScript 3\.7 Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html), specifically the first two features, Optional Chaining and Nullish Coalescing\. +Missing values in an object \(such as props\) have the value `undefined` in TypeScript\. Recent versions of the language include operators that simplify working with these values, making it easier to specify defaults and "short\-circuit" chaining when an undefined value is reached\. For more information about these features, see the [TypeScript 3\.7 Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html), specifically the first two features, Optional Chaining and Nullish Coalescing\. ## Building, synthesizing, and deploying From 9dcac96ff0eb0e2ff8e41b87acc7e54c6ac612e7 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 14 Aug 2020 00:40:12 +0000 Subject: [PATCH 255/655] add info about CreateAlarm() and put metric creation first since it's a prerequisite --- doc_source/how_to_set_cw_alarm.md | 126 ++++++++++++++++++++++-------- 1 file changed, 93 insertions(+), 33 deletions(-) diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index a3a6b825..2291d78e 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -1,13 +1,77 @@ # Set a CloudWatch alarm -The **aws\-cloudwatch** package supports setting CloudWatch alarms on CloudWatch metrics\. The syntax is as follows, where *METRIC* is a CloudWatch metric you have created, and the alarm is raised there are more than 100 of the measured metrics in two of the last three seconds: +The **aws\-cloudwatch** package supports setting CloudWatch alarms on CloudWatch metrics\. So the first thing you need is a metric\. You can use a predefined metric or you can create your own\. Create your own metric as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. + +------ +#### [ TypeScript ] + +``` +const metric = new cloudwatch.Metric({ + namespace: 'MyNamespace', + metricName: 'MyMetric', + dimensions: { MyDimension: 'MyDimensionValue' } +}); +``` + +------ +#### [ JavaScript ] + +``` +const metric = new cloudwatch.Metric({ + namespace: 'MyNamespace', + metricName: 'MyMetric', + dimensions: { MyDimension: 'MyDimensionValue' } +}); +``` + +------ +#### [ Python ] + +``` +metric = cloudwatch.Metric( + namespace="MyNamespace", + metric_name="MyMetric", + dimensions=dict(MyDimension="MyDimensionValue") +) +``` + +------ +#### [ Java ] + +``` +Metric metric = Metric.Builder.create() + .namespace("MyNamespace") + .metricName("MyMetric") + .dimensions(new HashMap() {{ + put("MyDimension", "MyDimensionValue"); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +var metric = new Metric(this, "Metric", new MetricProps +{ + Namespace = "MyNamespace", + MetricName = "MyMetric", + Dimensions = new Dictionary + { + { "MyDimension", "MyDimensionValue" } + } +}); +``` + +------ + +Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this case, the alarm is raised when there are more than 100 of your metric in two of the last three seconds: ------ #### [ TypeScript ] ``` const alarm = new cloudwatch.Alarm(this, 'Alarm', { - metric: metric, // see below + metric: metric, threshold: 100, evaluationPeriods: 3, datapointsToAlarm: 2, @@ -19,7 +83,7 @@ const alarm = new cloudwatch.Alarm(this, 'Alarm', { ``` const alarm = new cloudwatch.Alarm(this, 'Alarm', { - metric: metric, // see below + metric: metric, threshold: 100, evaluationPeriods: 3, datapointsToAlarm: 2 @@ -31,7 +95,7 @@ const alarm = new cloudwatch.Alarm(this, 'Alarm', { ``` alarm = cloudwatch.Alarm(self, "Alarm", - metric=metric, # see below + metric=metric, threshold=100, evaluation_periods=3, datapoints_to_alarm=2 @@ -46,7 +110,7 @@ import software.amazon.awscdk.services.cloudwatch.Alarm; import software.amazon.awscdk.services.cloudwatch.Metric; Alarm alarm = Alarm.Builder.create(this, "Alarm") - .metric(metric) // see below + .metric(metric) .threshold(100) .evaluationPeriods(3) .datapointsToAlarm(2).build(); @@ -58,7 +122,7 @@ Alarm alarm = Alarm.Builder.create(this, "Alarm") ``` var alarm = new Alarm(this, "Alarm", new AlarmProps { - Metric = metric, // see below + Metric = metric, Threshold = 100, EvaluationPeriods = 3, DatapointsToAlarm = 2 @@ -67,16 +131,16 @@ var alarm = new Alarm(this, "Alarm", new AlarmProps ------ -The syntax for creating a metric is as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. +An alternative way to create an alarm is using the metric's `createAlarm()` method, which takes essentially the same properties as the `Alarm` constructor; you just don't need to pass in the metric, since it's already known\. ------ #### [ TypeScript ] ``` -const metric = new cloudwatch.Metric({ - namespace: 'MyNamespace', - metricName: 'MyMetric', - dimensions: { MyDimension: 'MyDimensionValue' } +metric.createAlarm(this, 'Alarm', { + threshold: 100, + evaluationPeriods: 3, + datapointsToAlarm: 2, }); ``` @@ -84,10 +148,10 @@ const metric = new cloudwatch.Metric({ #### [ JavaScript ] ``` -const metric = new cloudwatch.Metric({ - namespace: 'MyNamespace', - metricName: 'MyMetric', - dimensions: { MyDimension: 'MyDimensionValue' } +metric.createAlarm(this, 'Alarm', { + threshold: 100, + evaluationPeriods: 3, + datapointsToAlarm: 2, }); ``` @@ -95,10 +159,10 @@ const metric = new cloudwatch.Metric({ #### [ Python ] ``` -metric = cloudwatch.Metric( - namespace="MyNamespace", - metric_name="MyMetric", - dimensions=dict(MyDimension="MyDimensionValue") +metric.create_alarm(this, "Alarm", + threshold=100, + evaluation_periods=3, + datapoints_to_alarm=2 ) ``` @@ -106,32 +170,28 @@ metric = cloudwatch.Metric( #### [ Java ] ``` -Metric metric = Metric.Builder.create() - .namespace("MyNamespace") - .metricName("MyMetric") - .dimensions(new HashMap() {{ - put("MyDimension", "MyDimensionValue"); - }}).build(); +metric.createAlarm(this, "Alarm", new CreateAlarmOptions.Builder() + .threshold(100) + .evaluationPeriods(3) + .datapointsToAlarm(2) + .build()); ``` ------ #### [ C\# ] ``` -var metric = new Metric(this, "Metric", new MetricProps +metric.CreateAlarm(this, "Alarm", new CreateAlarmOptions { - Namespace = "MyNamespace", - MetricName = "MyMetric", - Dimensions = new Dictionary - { - { "MyDimension", "MyDimensionValue" } - } + Threshold = 100, + EvaluationPeriods = 3, + DatapointsToAlarm = 2 }); ``` ------ -Many AWS CDK packages contain functionality to enable setting an alarm based on an existing metric\. For example, you can create an Amazon SQS alarm for the **ApproximateNumberOfMessagesVisible** metric that raises an alarm if the queue has more than 100 messages available for retrieval in two of the last three seconds\. +Many AWS Construct Library modules let you set an alarm on an existing metric\. For example, you can create an Amazon SQS alarm for the **ApproximateNumberOfMessagesVisible** metric that raises an alarm if the queue has more than 100 messages available for retrieval in two of the last three seconds\. ------ #### [ TypeScript ] From 45fe3c16ea8a13707ec7f7513b50a26ff7fcbb52 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 14 Aug 2020 00:41:05 +0000 Subject: [PATCH 256/655] add information about what to do with the result of getAtt() --- doc_source/use_cfn_template.md | 43 +++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 200f34a9..9b0c43df 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -118,4 +118,45 @@ IResolvable bucketArn = Fn.getAtt("S3Bucket", "Arn"); var bucketArn = Fn.GetAtt("S3Bucket", "Arn"); ``` ------- \ No newline at end of file +------ + +The result of a `getAtt()` call is a [token](tokens.md)\. The actual value won't be available until later in the synthesis process\. If you need to pass such an attribute to another API that requires a string, call `toString()` on the result\. + +------ +#### [ TypeScript ] + +``` +const bucketArn = cdk.Fn.getAtt("S3Bucket", "Arn").toString(); +``` + +------ +#### [ JavaScript ] + +``` +const bucketArn = cdk.Fn.getAtt("S3Bucket", "Arn").toString(); +``` + +------ +#### [ Python ] + +``` +bucket_arn = cdk.Fn.get_att("S3Bucket", "Arn").to_string() +``` + +------ +#### [ Java ] + +``` +String bucketArn = Fn.getAtt("S3Bucket", "Arn").toString(); +``` + +------ +#### [ C\# ] + +``` +var bucketArn = Fn.GetAtt("S3Bucket", "Arn").ToString(); +``` + +------ + +This string is still a token, just in a string encoding, so you still don't have the actual ARN\. But in many ways, you can treat the string as if you did have the real value \(for example, adding text to the beginning or end\) and it will work just as you expect\. \ No newline at end of file From bd67ce38348609986fe794fb88c7540be9283392 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 14 Aug 2020 00:41:18 +0000 Subject: [PATCH 257/655] change a word --- doc_source/tokens.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/tokens.md b/doc_source/tokens.md index 3b249284..7467d7de 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -143,7 +143,7 @@ if (!Token.IsUnresolved(name) && name.Length > 10) ------ -If **name** is a token, validation isn't performed, and the error could occur in a later stage in the lifecycle, such as during deployment\. +If **name** is a token, validation isn't performed, and an error could still occur in a later stage in the lifecycle, such as during deployment\. **Note** You can use token encodings to escape the type system\. For example, you could string\-encode a token that produces a number value at synthesis time\. If you use these functions, it's your responsibility to ensure that your template resolves to a usable state after synthesis\. From 5d04601563bc1c6225bb34adde616e7784f5e33c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 14 Aug 2020 02:23:26 +0000 Subject: [PATCH 258/655] remove booh and I --- doc_source/resources.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index 36309071..c840268b 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -488,7 +488,7 @@ new Function(this, "MyLambda", new FunctionProps Sometimes you already have a resource in your AWS account and want to use it in your AWS CDK app, for example, a resource that was defined through the console, the AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into an AWS CDK object in the current stack by calling a static factory method on the resource's class\. -The following example shows how to define a bucket based on the existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a VPC based on the existing VPC with the resource name `booh`\. +The following example shows how to define a bucket based on an existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a Amazon Virtual Private Cloud based on an existing VPC having a specific ID\. ------ #### [ TypeScript ] @@ -667,7 +667,7 @@ Vpc.FromLookup(this, id = "PublicVpc", new VpcLookupOptions Note that `Vpc.fromLookup()` works only in stacks that are defined with an explicit **account** and **region** in their `env` property\. If the AWS CDK attempts to look up an Amazon VPC from an [environment\-agnostic stack](stacks.md#stack_api), the CLI does not know which environment to query to find the VPC\. -Although you can use an imported resource anywhere, you cannot modify the imported resource\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an imported `s3.IBucket` does nothing\. +Although you can use an imported resource anywhere, you cannot modify the imported resource\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an imported `s3.Bucket` does nothing\. ## Permission grants From 07e9f9204f3c5cd2eebc8d39b064d987703f77d9 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 14 Aug 2020 16:16:05 +0000 Subject: [PATCH 259/655] more reorg and improvement --- doc_source/how_to_set_cw_alarm.md | 128 ++++++++++++------------------ 1 file changed, 51 insertions(+), 77 deletions(-) diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index 2291d78e..1028307a 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -1,6 +1,51 @@ # Set a CloudWatch alarm -The **aws\-cloudwatch** package supports setting CloudWatch alarms on CloudWatch metrics\. So the first thing you need is a metric\. You can use a predefined metric or you can create your own\. Create your own metric as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. +The [aws\-cloudwatch](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudwatch-readme.html) package supports setting CloudWatch alarms on CloudWatch metrics\. So the first thing you need is a metric\. You can use a predefined metric or you can create your own\. + +## Using an existing metric + +Many AWS Construct Library modules let you set an alarm on an existing metric by passing the metric's name to a convenience method on an instance of an object that has metrics\. For example, given an Amazon SQS queue, you can get the metric **ApproximateNumberOfMessagesVisible** from the queue's [metric\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-sqs.Queue.html#metricmetricname-props) method\. + +------ +#### [ TypeScript ] + +``` +const metric = queue.metric("ApproximateNumberOfMessagesVisible"); +``` + +------ +#### [ JavaScript ] + +``` +const metric = queue.metric("ApproximateNumberOfMessagesVisible"); +``` + +------ +#### [ Python ] + +``` +metric = queue.metric("ApproximateNumberOfMessagesVisible") +``` + +------ +#### [ Java ] + +``` +Metric metric = queue.metric("ApproximateNumberOfMessagesVisible"); +``` + +------ +#### [ C\# ] + +``` +var metric = queue.Metric("ApproximateNumberOfMessagesVisible"); +``` + +------ + +## Creating your own metric + +Create your own [wetric](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudwatch.Metric.html) as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. You also need to specify your metric's name and dimension\. ------ #### [ TypeScript ] @@ -64,7 +109,9 @@ var metric = new Metric(this, "Metric", new MetricProps ------ -Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this case, the alarm is raised when there are more than 100 of your metric in two of the last three seconds: +## Creating the alarm + +Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three seconds\. Assuming the metric is the **ApproximateNumberOfMessagesVisible** metric from an Amazon SQS queue, it would raise when 100 messages are visible in the queue in two of the last three seconds\. ------ #### [ TypeScript ] @@ -131,7 +178,7 @@ var alarm = new Alarm(this, "Alarm", new AlarmProps ------ -An alternative way to create an alarm is using the metric's `createAlarm()` method, which takes essentially the same properties as the `Alarm` constructor; you just don't need to pass in the metric, since it's already known\. +An alternative way to create an alarm is using the metric's [createAlarm\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudwatch.Metric.html#create-wbr-alarmscope-id-props) method, which takes essentially the same properties as the `Alarm` constructor; you just don't need to pass in the metric, since it's already known\. ------ #### [ TypeScript ] @@ -159,7 +206,7 @@ metric.createAlarm(this, 'Alarm', { #### [ Python ] ``` -metric.create_alarm(this, "Alarm", +metric.create_alarm(self, "Alarm", threshold=100, evaluation_periods=3, datapoints_to_alarm=2 @@ -189,77 +236,4 @@ metric.CreateAlarm(this, "Alarm", new CreateAlarmOptions }); ``` ------- - -Many AWS Construct Library modules let you set an alarm on an existing metric\. For example, you can create an Amazon SQS alarm for the **ApproximateNumberOfMessagesVisible** metric that raises an alarm if the queue has more than 100 messages available for retrieval in two of the last three seconds\. - ------- -#### [ TypeScript ] - -``` - const qMetric = queue.metric("ApproximateNumberOfMessagesVisible"); - - new cloudwatch.Alarm(this, "Alarm", { - metric: qMetric, - threshold: 100, - evaluationPeriods: 3, - datapointsToAlarm: 2 - }); -``` - ------- -#### [ JavaScript ] - -``` - const qMetric = queue.metric("ApproximateNumberOfMessagesVisible"); - - new cloudwatch.Alarm(this, "Alarm", { - metric: qMetric, - threshold: 100, - evaluationPeriods: 3, - datapointsToAlarm: 2 - }); -``` - ------- -#### [ Python ] - -``` -q_metric = queue.metric("ApproximateNumberOfMessagesVisible") - -cloudwatch.Alarm(self, "Alarm", - metric=q_metric, - threshold=100, - evaluation_periods=3, - datapoints_to_alarm=2 -) -``` - ------- -#### [ Java ] - -``` -Metric qMetric = queue.metric("ApproximateNumberOfMessagesVisible"); - -Alarm.Builder.create(this, "Alarm") - .metric(qMetric) - .threshold(100) - .evaluationPeriods(3) - .datapointsToAlarm(2).build(); -``` - ------- -#### [ C\# ] - -``` -var qMetric = queue.Metric("ApproximateNumberOfMessagesVisible"); - -new Alarm(this, "Alarm", new AlarmProps { - Metric = qMetric, - Threshold = 100, - EvaluationPeriods = 3, - DatapointsToAlarm = 2 -}); -``` - ------ \ No newline at end of file From 81623a99ac6be071aecb9b2704fdbfa8402ceb62 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 17 Aug 2020 15:02:47 +0000 Subject: [PATCH 260/655] describe where to find module stability level --- doc_source/reference.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc_source/reference.md b/doc_source/reference.md index 12229f8b..a13cbf89 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -48,6 +48,8 @@ Stage 3: General availability \(GA\) The module is generally available with a compatibility guarantee across minor versions\. We will only make backward\-compatible changes to the API, so that your existing apps will continue to work until the next major AWS CDK release\. In some cases, we may use [feature flags](featureflags.md) to optionally enable new behavior while retaining the previous behavior to support existing apps\. +Each module's Overview in the [API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) describes its stability level\. + For more information about these maturity stages, see [AWS Construct Library Module Lifecycle](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0107-construct-library-module-lifecycle.md)\. ### Language binding stability From 740c846cba2ba8f8ea2a08a787f47020cd94d695 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 17 Aug 2020 15:34:33 +0000 Subject: [PATCH 261/655] add note about source.bat --- doc_source/work-with-cdk-python.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 6d433e5b..c4ff5f13 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -41,6 +41,9 @@ After initializing the project, activate the project's virtual environment\. Thi source .env/bin/activate ``` +**Note** +You may recognize this as the Mac/Linux command to activate a virtual environment\. The Python templates include a batch file, `source.bat`, that allows the same command to be used on Windows\. The traditional Windows command, `.env\Scripts\activate.bat`, works, too\. + Then install the app's standard dependencies: ``` From dd80552d2dfd55ea48ce94fdfa334626e3f7c9dd Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 18 Aug 2020 15:28:59 +0000 Subject: [PATCH 262/655] test snippet --- snippets/test-1.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 snippets/test-1.txt diff --git a/snippets/test-1.txt b/snippets/test-1.txt new file mode 100644 index 00000000..ae6fc483 --- /dev/null +++ b/snippets/test-1.txt @@ -0,0 +1 @@ +// this is a test code snippet From b4273745073d0a7780572cdca911180c1b405733 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 18 Aug 2020 16:06:12 +0000 Subject: [PATCH 263/655] Add second test snippet --- snippets/test-2.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 snippets/test-2.txt diff --git a/snippets/test-2.txt b/snippets/test-2.txt new file mode 100644 index 00000000..ae6fc483 --- /dev/null +++ b/snippets/test-2.txt @@ -0,0 +1 @@ +// this is a test code snippet From e9818d41e1b737aa3a0e17a6ca97a1ea9c05fe7f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 19 Aug 2020 20:47:30 +0000 Subject: [PATCH 264/655] typo --- doc_source/how_to_set_cw_alarm.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index 1028307a..0c2659f9 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -45,7 +45,7 @@ var metric = queue.Metric("ApproximateNumberOfMessagesVisible"); ## Creating your own metric -Create your own [wetric](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudwatch.Metric.html) as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. You also need to specify your metric's name and dimension\. +Create your own [metric](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudwatch.Metric.html) as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. You also need to specify your metric's name and dimension\. ------ #### [ TypeScript ] From 8729fbb6f1ad7bf547c6bfebf0c085c4269c1924 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 19 Aug 2020 21:15:00 +0000 Subject: [PATCH 265/655] clarify instructions for including cfn template --- doc_source/tokens.md | 8 +++--- doc_source/use_cfn_template.md | 46 +++++----------------------------- 2 files changed, 10 insertions(+), 44 deletions(-) diff --git a/doc_source/tokens.md b/doc_source/tokens.md index 7467d7de..cf14052d 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -86,11 +86,11 @@ Tokens are objects that implement the [IResolvable](https://docs.aws.amazon.com/ You'll hardly ever work directly with the `IResolvable` interface\. You will most likely only see string\-encoded versions of tokens\. Other functions typically only accept arguments of basic types, such as `string` or `number`\. To use tokens in these cases, you can encode them into one of three types using static methods on the [core\.Token](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html) class\. -+ Strings using [Token\.asString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) \(Python: `as_string`\) -+ List of strings using [Token\.asList](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) \(Python: `as_list`\) -+ Number \(float\) using [Token\.asNumber](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) \(Python: `as_number`\) ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) to generate a string encocding \(or call `.toString()` on the token object\) ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) to generate a list encoding ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) to generate a numeric encoding -These take an arbitrary value, which can also be an `IResolvable` interface, and encode them into a primitive value of the appropriate type\. +These take an arbitrary value, which can be an `IResolvable`, and encode them into a primitive value of the indicated type\. **Important** Because any one of the previous types can potentially be an encoded token, be careful when you parse or try to read their contents\. For example, if you attempt to parse a string to extract a value from it, and the string is an encoded token, your parsing will fail\. Similarly, if you attempt to query the length of an array, or perform math operations with a number, you must first verify that they are not encoded tokens\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 9b0c43df..d4c8ba87 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -81,7 +81,7 @@ new CfnInclude(this, "ExistingInfrastructure", new CfnIncludeProps ------ -Then to access an attribute of the resource, such as the bucket's ARN: +Then to access an attribute of the resource, such as the bucket's ARN, call `Fn.getAtt()` with the logical name of the resource in the AWS CloudFormation template and the desired attribute of the resource\. \(The resource must be defined in the template; `Fn.getAtt()` does not query actual resources you have deployed using the template\. ------ #### [ TypeScript ] @@ -120,43 +120,9 @@ var bucketArn = Fn.GetAtt("S3Bucket", "Arn"); ------ -The result of a `getAtt()` call is a [token](tokens.md)\. The actual value won't be available until later in the synthesis process\. If you need to pass such an attribute to another API that requires a string, call `toString()` on the result\. +The result of a `getAtt()` call is a [token](tokens.md), a type of placeholder\. The actual value of the attribute isn't available until later in the synthesis process\. If you need to pass such an attribute to another API that requires a concrete value, such as a string or a number, use the following static methods of the `[Token](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html)` class to convert the token to a string, number, or list\. ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) to generate a string encocding \(or call `.toString()` on the token object\) ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) to generate a list encoding ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) to generate a numeric encoding ------- -#### [ TypeScript ] - -``` -const bucketArn = cdk.Fn.getAtt("S3Bucket", "Arn").toString(); -``` - ------- -#### [ JavaScript ] - -``` -const bucketArn = cdk.Fn.getAtt("S3Bucket", "Arn").toString(); -``` - ------- -#### [ Python ] - -``` -bucket_arn = cdk.Fn.get_att("S3Bucket", "Arn").to_string() -``` - ------- -#### [ Java ] - -``` -String bucketArn = Fn.getAtt("S3Bucket", "Arn").toString(); -``` - ------- -#### [ C\# ] - -``` -var bucketArn = Fn.GetAtt("S3Bucket", "Arn").ToString(); -``` - ------- - -This string is still a token, just in a string encoding, so you still don't have the actual ARN\. But in many ways, you can treat the string as if you did have the real value \(for example, adding text to the beginning or end\) and it will work just as you expect\. \ No newline at end of file +In our example of getting a bucket's ARN, you'd convert it to a string, but that string is still a token, just in a string encoding\. You still don't have the actual ARN\. But in many ways, you can treat the string as if you did have the real value \(for example, adding text to the beginning or end\) and it will work aas you expect\. \ No newline at end of file From 316dcb767d71d59d6d455f7228e89a30bdb61a08 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 20 Aug 2020 21:24:06 +0000 Subject: [PATCH 266/655] help update --- doc_source/cli.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index fb258993..6b23c06b 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -592,8 +592,7 @@ Options: --require-approval What security-sensitive changes need manual approval [string] [choices: "never", "any-change", "broadening"] - --ci Force CI detection (deprecated) - [boolean] [default: false] + --ci Force CI detection [boolean] [default: false] --notification-arns ARNs of SNS topics that CloudFormation will notify with stack related events [array] From 47374225c4f85c66f2ed4083060d4e573b2b8d64 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 28 Aug 2020 21:40:11 +0000 Subject: [PATCH 267/655] minor improvements --- doc_source/get_context_var.md | 2 +- doc_source/hello_world.md | 18 ++++++++++++------ doc_source/home.md | 2 +- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/doc_source/get_context_var.md b/doc_source/get_context_var.md index c7440748..74cbd767 100644 --- a/doc_source/get_context_var.md +++ b/doc_source/get_context_var.md @@ -18,7 +18,7 @@ To specify the same context variable and value in the `cdk.json` file, use the f } ``` -To get the value of a context variable in your app, use code like the following in the context of a construct \(that is, when `this`, or `self` in Python, is an instance of some construct\)\. The example gets the value of the context variable **bucket\_name**\. +To get the value of a context variable in your app, use the `TryGetContext` method in the context of a construct \(that is, when `this`, or `self` in Python, is an instance of some construct\)\. The example gets the context value **bucket\_name**\. If the requested value is not defined, `TryGetContext` returns `undefined` \(`None` in Python; `null` in Java and C\#\) rather than raising an exception\. ------ #### [ TypeScript ] diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 76c253ec..066419a5 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -1,6 +1,6 @@ # Your first AWS CDK app -You've read [Getting started with the AWS CDK](getting_started.md)? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. In this process you'll learn about the structure of a AWS CDK project, how to access the AWS Construct Library, and how to use the AWS CDK Toolkit command\-line tool\. +You've read [Getting started with the AWS CDK](getting_started.md)? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. In this tutorial you'll learn about the structure of a AWS CDK project, how to work with the AWS Construct Library, and how to use the AWS CDK Toolkit command\-line tool\. The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps to synthesize your stack to an AWS CloudFormation template and deploy it\. @@ -33,7 +33,7 @@ cd hello-cdk ``` **Important** -Be sure to use the name `hello-cdk` for your project directory, *exactly as shown here\.* The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, some of the code in this tutorial won't work\. +Be sure to name your project directory `hello-cdk`, *exactly as shown here\.* The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, some of the code in this tutorial won't work\. Now initialize the app using the cdk init command, specifying the desired template \("app"\) and programming language\. @@ -94,11 +94,13 @@ If you are using Visual Studio, open the solution file in the `src` directory\. **Tip** If you don't specify a template, the default is "app," which is the one we wanted anyway, so technically you can leave it out and save four keystrokes\. +The cdk init command creates a number of files and folders inside the `hello-cdk` directory to help you organize the source code for your AWS CDK app\. Take a moment to explore\. The structure of a basic app is all there; you'll fill in the details as you progress in this tutorial\. + If you have Git installed, each project you create using cdk init is also initialized as a Git repository\. We'll ignore that for now, but it's there when you need it\. ## Build the app -Here's how to build \(compile\) your code to find syntax and type errors\. Try it now, if you like\. It should work perfectly because you haven't yet made any changes to the template code\. +Normally, after making any changes to your code, you'd build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you so you can't forget\. But you can still build manually to catch syntax and type errors\. For reference, here's how\. ------ #### [ TypeScript ] @@ -121,9 +123,12 @@ No build step is necessary\. #### [ Java ] ``` -mvn compile +mvn compile -q ``` +**Note** +Or press Control\-B in Eclipse \(other Java IDEs may vary\) + ------ #### [ C\# ] @@ -131,9 +136,10 @@ mvn compile dotnet build src ``` ------- +**Note** +Or press F6 in Visual Studio -Don't worry about memorizing this command; in this tutorial, we'll provide it when it's needed\. +------ ## List the stacks in the app diff --git a/doc_source/home.md b/doc_source/home.md index d4400819..c5e8b322 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -247,7 +247,7 @@ In addition to this guide, the following are other resources available to AWS CD ## About Amazon Web Services -Amazon Web Services \(AWS\) is a collection of digital infrastructure services that developers can use when developing their applications\. The services include computing, storage, database, and application synchronization \(messaging and queuing\)\. +Amazon Web Services \(AWS\) is a collection of digital infrastructure services that developers can use when developing their applications\. The services include computing, storage, database, and application synchronization \(messaging and queueing\)\. AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. From 5a7b831f55aa5cadeea78c6cad2feb5324680b6b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 1 Sep 2020 22:08:51 +0000 Subject: [PATCH 268/655] master to baseline --- doc_source/testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/testing.md b/doc_source/testing.md index 31d67f3b..8e8bea72 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -3,7 +3,7 @@ With the AWS CDK, your infrastructure can be as testable as any other code you write\. This article illustrates one approach to testing AWS CDK apps written in TypeScript using the [Jest](https://jestjs.io/) test framework\. Currently, TypeScript is the only supported language for testing AWS CDK infrastructure, though we intend to eventually make this capability available in all languages supported by the AWS CDK\. There are three categories of tests you can write for AWS CDK apps\. -+ **Snapshot tests** test the synthesized AWS CloudFormation template against a previously\-stored "golden master" template\. This way, when you're refactoring your app, you can be sure that the refactored code works exactly the same way as the original\. If the changes were intentional, you can accept a new master for future tests\. ++ **Snapshot tests** test the synthesized AWS CloudFormation template against a previously\-stored baseline template\. This way, when you're refactoring your app, you can be sure that the refactored code works exactly the same way as the original\. If the changes were intentional, you can accept a new baseline for future tests\. + **Fine\-grained assertions** test specific aspects of the generated AWS CloudFormation template, such as "this resource has this property with this value\." These tests help when you're developing new features, since any code you add will cause your snapshot test to fail even if existing features still work\. When this happens, your fine\-grained tests will reassure you that the existing functionality is unaffected\. + **Validation tests** help you "fail fast" by making sure your AWS CDK constructs raise errors when you pass them invalid data\. The ability to do this type of testing is a big advantage of developing your infrastructure in a general\-purpose programming language\. From 4e7adab3118c808ff9e395fb8451c4b3236bdd57 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 1 Sep 2020 22:58:52 +0000 Subject: [PATCH 269/655] update links --- doc_source/hello_world.md | 2 +- doc_source/work-with-cdk-typescript.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 066419a5..2643ebd0 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -206,7 +206,7 @@ Or **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution* ------ -Next, define an Amazon S3 bucket in the stack using an L2 construct, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) class\. +Next, define an Amazon S3 bucket in the stack using an L2 construct, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class\. ------ #### [ TypeScript ] diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index 5da4dbae..84c27753 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -55,9 +55,9 @@ All AWS Construct Library modules used in your project must be the same version\ All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the AWS resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. -In TypeScript, the shape of `props` is defined using an interface that tells you the required and optional arguments and their types\. Such an interface is defined for each kind of `props` argument, usually specific to a single construct or method\. For example, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucket.html) construct \(in the `@aws-cdk/aws-s3 module`\) specifies a `props` argument conforming to the [BucketProps](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucketprops.html) interface\. +In TypeScript, the shape of `props` is defined using an interface that tells you the required and optional arguments and their types\. Such an interface is defined for each kind of `props` argument, usually specific to a single construct or method\. For example, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) construct \(in the `@aws-cdk/aws-s3 module`\) specifies a `props` argument conforming to the [BucketProps](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.BucketProps.html) interface\. -If a property is itself an object, for example the [websiteRedirect](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/bucketprops.html#aws_s3_BucketProps_websiteRedirect) property of `BucketProps`, that object will have its own interface to which its shape must conform, in this case [RedirectTarget](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-s3/redirecttarget.html)\. +If a property is itself an object, for example the [websiteRedirect](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.BucketProps.html#websiteredirect) property of `BucketProps`, that object will have its own interface to which its shape must conform, in this case [RedirectTarget](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.RedirectTarget.html)\. If you are subclassing an AWS Construct Library class \(or overriding a method that takes a props\-like argument\), you can inherit from the existing interface to create a new one that specifies any new props your code requires\. When calling the parent class or base method, generally you can pass the entire props argument you received, since any attributes provided in the object but not specified in the interface will be ignored\. From 58ba2c1d83d715c798c0d19e04d0e5759897862f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 2 Sep 2020 03:02:01 +0000 Subject: [PATCH 270/655] changes resulting from internal work on links --- doc_source/constructs.md | 2 +- doc_source/home.md | 4 ++-- doc_source/sam.md | 2 +- doc_source/troubleshooting.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 121272de..3f587574 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -626,7 +626,7 @@ var createJobLambda = new Function(this, "create-job", new FunctionProps ------ -For information about the most common API patterns in the AWS Construct Library, see [Resources](https://docs.aws.amazon.com/cdk/latest/guide/resources.html)\. +For information about the most common API patterns in the AWS Construct Library, see [Resources](resources.md)\. ## Authoring constructs diff --git a/doc_source/home.md b/doc_source/home.md index c5e8b322..8ed9a915 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -217,7 +217,7 @@ The [AWS CDK Toolkit](cli.md) is a command line tool for interacting with CDK ap The [AWS Construct Library](constructs.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to create resources for an Amazon or AWS service\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. **Note** -There is no charge for using the AWS CDK, but you might incur AWS charges for creating or using AWS [chargeable resources](http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Pricing Calculator](https://calculator.aws/#/) to estimate charges for the use of various AWS resources\. +There is no charge for using the AWS CDK, but you might incur AWS charges for creating or using AWS [chargeable resources](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Pricing Calculator](https://calculator.aws/#/) to estimate charges for the use of various AWS resources\. ## Contributing to the AWS CDK @@ -249,6 +249,6 @@ In addition to this guide, the following are other resources available to AWS CD Amazon Web Services \(AWS\) is a collection of digital infrastructure services that developers can use when developing their applications\. The services include computing, storage, database, and application synchronization \(messaging and queueing\)\. -AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. +AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file diff --git a/doc_source/sam.md b/doc_source/sam.md index cefecfdb..ec64abf3 100644 --- a/doc_source/sam.md +++ b/doc_source/sam.md @@ -1,6 +1,6 @@ # SAM CLI -This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. +This topic describes how to use the AWS SAM CLI with the AWS CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. 1. The first step is to create a AWS CDK application and add the Lambda package\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 3fc46192..472e2fa9 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -231,7 +231,7 @@ if (path) fs.readFile(path, 'utf8', function(err, contents) { }); else console.log("Please specify the path to the stack's output .json file"); ``` -As your stack's resource count approaches 200, consider re\-architecting to reduce the number of resources your stack contains, for example by combining some Lambda functions, or to break it up into multiple stacks\. The CDK supports [references between stacks](https://docs.aws.amazon.com/cdk/latest/guide/resources.html#resource_stack), so it is straightforward to separate your app's functionality into different stacks in whatever way makes the most sense to you\. +As your stack's resource count approaches 200, consider re\-architecting to reduce the number of resources your stack contains, for example by combining some Lambda functions, or to break it up into multiple stacks\. The CDK supports [references between stacks](resources.md#resource_stack), so it is straightforward to separate your app's functionality into different stacks in whatever way makes the most sense to you\. **Note** AWS CloudFormation experts often suggest the use of nested stacks as a solution to the 200 resource limit\. The AWS CDK supports this approach via the [`NestedStack`](stacks.md#stack_nesting) construct\. From e3b50d8d057608d869c052927b1fae15e7610ac0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 3 Sep 2020 03:31:47 +0000 Subject: [PATCH 271/655] update vscodium links --- doc_source/work-with-cdk-javascript.md | 2 +- doc_source/work-with-cdk-python.md | 4 ++-- doc_source/work-with-cdk-typescript.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index af3dc906..e185cc19 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -2,7 +2,7 @@ JavaScript is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in JavaScript uses familiar tools, including [Node\.js](https://nodejs.org/) and the Node Package Manager \(`npm`\)\. You may also use [Yarn](https://yarnpkg.com/) if you prefer, though the examples in this Guide use NPM\. The modules comprising the AWS Construct Library are distributed via the NPM repository, [npmjs\.org](https://www.npmjs.com/)\. -You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://github.com/VSCodium/vscodium)\), which has good support for JavaScript\. +You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://vscodium.com/)\), which has good support for JavaScript\. ## Prerequisites diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index c4ff5f13..b508618a 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -2,7 +2,7 @@ Python is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in Python uses familiar tools, including the standard Python implementation \(CPython\), virtual environments with `virtualenv`, and the Python package installer `pip`\. The modules comprising the AWS Construct Library are distributed via [pypi\.org](https://pypi.org/search/?q=aws-cdk)\. The Python version of the AWS CDK even uses Python\-style identifiers \(for example, `snake_case` method names\)\. -You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://github.com/VSCodium/vscodium)\), which has good support for Python via an [official extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python)\. The IDLE editor included with Python will suffice to get started\. The Python modules for the AWS CDK do have type hints, which are useful for a linting tool or an IDE that supports type validation\. +You can use any editor or IDE\. Many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://vscodium.com/)\), which has good support for Python via an [official extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python)\. The IDLE editor included with Python will suffice to get started\. The Python modules for the AWS CDK do have type hints, which are useful for a linting tool or an IDE that supports type validation\. ## Prerequisites @@ -154,7 +154,7 @@ In our experience, the type errors Python programmers make tend to fall into the + Passing a single value where a construct expects a container \(Python list or dictionary\) or vice versa\. + Passing a value of a type associated with a Level 1 \(`CfnXxxxxx`\) construct to a higher\-level construct, or vice versa\. -The AWS CDK Python modules do include type annotations\. If you are not using an IDE that supports these, such as [PyCharm](https://www.jetbrains.com/pycharm/), you might want to call the [MyPy](http://mypy-lang.org/) type validator as a step in your build process\. There are also runtime type checkers that can improve error messages for type\-related errors\. +The AWS CDK Python modules do include type annotations, so you can use tools that support them to help with types\. If you are not using an IDE that supports these, such as [PyCharm](https://www.jetbrains.com/pycharm/), you might want to call the [MyPy](http://mypy-lang.org/) type validator as a step in your build process\. There are also runtime type checkers that can improve error messages for type\-related errors\. ## Synthesizing and deploying diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index 84c27753..a4d5a0da 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -2,7 +2,7 @@ TypeScript is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in TypeScript uses familiar tools, including Microsoft's TypeScript compiler \(`tsc`\), [Node\.js](https://nodejs.org/) and the Node Package Manager \(`npm`\)\. You may also use [Yarn](https://yarnpkg.com/) if you prefer, though the examples in this Guide use NPM\. The modules comprising the AWS Construct Library are distributed via the NPM repository, [npmjs\.org](https://www.npmjs.com/)\. -You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://github.com/VSCodium/vscodium)\), which has excellent support for TypeScript\. +You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://vscodium.com/)\), which has excellent support for TypeScript\. ## Prerequisites From b311e8c0ecf517881f108483b77d2fc1c5229eda Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 3 Sep 2020 16:44:27 +0000 Subject: [PATCH 272/655] fix folder name and improve organization of bootstrapping instructions --- doc_source/cdk_pipeline.md | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 63be5fba..b51d8d2d 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -13,15 +13,19 @@ CDK Pipelines is currently in developer preview, and its API is subject to chang Before you can use CDK Pipelines, you must bootstrap the AWS environment\(s\) to which you will deploy your stacks\. An [environment](environments.md) is an account/region pair to which you want to deploy a CDK stack\. A CDK Pipeline involves at least two environments: the environment where the pipeline is provisioned, and the environment where you want to deploy the application's stacks \(or its stages, which are groups of related stacks\)\. These environments can be the same, though best practices recommend you isolate stages from each other in different AWS accounts or regions\. -You may have already bootstrapped one or more environments so you can deploy assets and Lambda functions using the AWS CDK\. Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include additional resources, so the stack has been extended to include an additional Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. This new style of CDK Toolkit stack will eventually become the default, but at this writing, you must opt in\. The AWS CDK Toolkit will upgrade your existing bootstrap stack or create a new one, as necessary\. +You may have already bootstrapped one or more environments so you can deploy assets and Lambda functions using the AWS CDK\. Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include additional resources, so the boostrap stack has been extended to include an additional Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. This new style of CDK Toolkit stack will eventually become the default, but at this writing, you must opt in\. The AWS CDK Toolkit will upgrade your existing bootstrap stack or create a new one, as necessary\. -To bootstrap an environment that will provision a pipeline: +To bootstrap an environment that can provision an AWS CDK pipeline, set the environment variable `CDK_NEW_BOOTSTRAP` before invoking `cdk bootstarp`, as shown below\. Invoking the AWS CDK Toolkit via the `npx` command installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. + +\-\-cloudformation\-execution\-policies specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The `AdministratorAccess` policy is the default; your organization may require a more constrained policy\. + +You may omit the \-\-profile option if your default AWS profile contains the necessary credentials or to instead the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to provide your AWS account credentials\. ------ #### [ Mac OS X/Linux ] ``` -CDK_NEW_BOOTSTRAP=1 +export CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ aws://ACCOUNT-ID/REGION @@ -39,13 +43,15 @@ npx cdk bootstrap --profile ADMIN-PROFILE ^ ------ -To bootstrap additional environments into which AWS CDK applications will be deployed by the pipeline: +To bootstrap additional environments into which AWS CDK applications will be deployed by the pipeline, use the commands below instead\. The `--trust` option indicates which other account should have permissions to deploy AWS CDK applications into this environment; specify the pipeline's AWS account ID\. + +Again, you may omit the \-\-profile option if your default AWS profile contains the necessary credentials or if you are using the `AWS_*` environment variables to provide your AWS account credentials\. ------ #### [ Mac OS X/Linux ] ``` -CDK_NEW_BOOTSTRAP=1 +export CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ --trust PIPELINE-ACCOUNT-ID \ @@ -65,14 +71,6 @@ npx cdk bootstrap --profile ADMIN-PROFILE ^ ------ -Note the following: -+ `CDK_NEW_BOOTSTRAP` is a variable that enables the bootstrapping of the new style of Toolkit stack required by the CDK Pipelines feature\. -+ *`ADMIN-PROFILE`* is a profile defined in your AWS configuration files that has credentials for the account and region being bootstrapped\. You may omit `--profile` and this value if you are using the default profile or the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to provide your AWS account credentials\. -+ `npx cdk` invokes the AWS CDK Toolkit, either the version installed in your project if any, or the global installation\. -+ `--cloudformation-execution-policies` specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The `AdministratorAccess` policy is the default; your organization may require a more constrained policy\. -+ `--trust` \(in the second example\) indicates which other accounts should have permissions to deploy AWS CDK applications into this environment\. This should be the pipeline's AWS account ID\. -+ `aws://ACCOUNT-ID/REGION` is the account and region we're bootstrapping\. It may be omitted if you are bootstrapping the profile's default region\. - **Tip** Use administrative credentials only to bootstrap and to provision the initial pipeline\. Drop administrative credentials as soon as possible\. @@ -80,7 +78,7 @@ If you are upgrading an existing bootstrapped environment, the old Amazon S3 buc ## Initialize project -Create a new, empty GitHub project and clone it to your workstation in the `cdk-pipeline` directory\. \(Our code examples in this topic use GitHub; you can also use BitBucket or AWS CodeCommit\.\) +Create a new, empty GitHub project and clone it to your workstation in the `my-pipeline` directory\. \(Our code examples in this topic use GitHub; you can also use BitBucket or AWS CodeCommit\.\) ``` git clone GITHUB-CLONE-URL my-pipeline From 06d34e08f96d3813b3035a2f744ab12d5b47ddbd Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 3 Sep 2020 16:44:46 +0000 Subject: [PATCH 273/655] add info on language conflicts in Python --- doc_source/work-with-cdk-python.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index b508618a..bb6d9721 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -96,6 +96,12 @@ All AWS Construct Library modules used in your project must be the same version\ ## AWS CDK idioms in Python +### Language conflicts + +In Python, `lambda` is a language keyword, so you cannot use it as a name for the AWS Lambda construct library module or Lambda functions\. The Python convention for such conflicts is to use a trailing underscore, as in `lambda_`, in the variable name\. + +By convention, the second argument to AWS CDK constructs is named `id`\. When writing your own stacks and constructs, calling a parameter `id` "shadows" the Python built\-in function `id()`, which gets an object's unique identifier\. This function isn't used very often, but if you should happen to need it in your construct, rename the argument, for example `id_`, or else call the built\-in function as `__builtins__.id()`\. + ### Props All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. From cb49c66ce92e1a43d746dc4a446153f3a7fbd137 Mon Sep 17 00:00:00 2001 From: Naresh Kumar Reddy Gaddam Date: Sat, 5 Sep 2020 02:24:59 +0200 Subject: [PATCH 274/655] Typo, change 'aas' to 'as' --- doc_source/use_cfn_template.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index d4c8ba87..4c715b85 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -125,4 +125,4 @@ The result of a `getAtt()` call is a [token](tokens.md), a type of placeholder\. + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) to generate a list encoding + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) to generate a numeric encoding -In our example of getting a bucket's ARN, you'd convert it to a string, but that string is still a token, just in a string encoding\. You still don't have the actual ARN\. But in many ways, you can treat the string as if you did have the real value \(for example, adding text to the beginning or end\) and it will work aas you expect\. \ No newline at end of file +In our example of getting a bucket's ARN, you'd convert it to a string, but that string is still a token, just in a string encoding\. You still don't have the actual ARN\. But in many ways, you can treat the string as if you did have the real value \(for example, adding text to the beginning or end\) and it will work as you expect\. From 6734ccf06852e2e11a18615b0e27c54291d57c30 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sun, 6 Sep 2020 03:02:26 +0000 Subject: [PATCH 275/655] typos --- doc_source/cdk_pipeline.md | 4 ++-- doc_source/use_cfn_template.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index b51d8d2d..091e7809 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -17,9 +17,9 @@ You may have already bootstrapped one or more environments so you can deploy ass To bootstrap an environment that can provision an AWS CDK pipeline, set the environment variable `CDK_NEW_BOOTSTRAP` before invoking `cdk bootstarp`, as shown below\. Invoking the AWS CDK Toolkit via the `npx` command installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. -\-\-cloudformation\-execution\-policies specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The `AdministratorAccess` policy is the default; your organization may require a more constrained policy\. +\-\-cloudformation\-execution\-policies specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The `AdministratorAccess` policy is the default; if you're using it, you may omit this option\. Your organization may require a more restrictive policy\. -You may omit the \-\-profile option if your default AWS profile contains the necessary credentials or to instead the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to provide your AWS account credentials\. +You may omit the \-\-profile option if your default AWS profile contains the necessary credentials or to instead use the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to provide your AWS account credentials\. ------ #### [ Mac OS X/Linux ] diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 4c715b85..aeb902d8 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -125,4 +125,4 @@ The result of a `getAtt()` call is a [token](tokens.md), a type of placeholder\. + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) to generate a list encoding + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) to generate a numeric encoding -In our example of getting a bucket's ARN, you'd convert it to a string, but that string is still a token, just in a string encoding\. You still don't have the actual ARN\. But in many ways, you can treat the string as if you did have the real value \(for example, adding text to the beginning or end\) and it will work as you expect\. +In our example of getting a bucket's ARN, you'd convert it to a string, but that string is still a token, just in a string encoding\. You still don't have the actual ARN\. But in many ways, you can treat the string as if you did have the real value \(for example, adding text to the beginning or end\) and it will work as you expect\. \ No newline at end of file From 6a221bbb95d4095ff7ddefcbe4e64fec04a1b4f0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 7 Sep 2020 14:50:52 +0000 Subject: [PATCH 276/655] typo --- doc_source/cdk_pipeline.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 091e7809..7461cf84 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -15,7 +15,7 @@ Before you can use CDK Pipelines, you must bootstrap the AWS environment\(s\) to You may have already bootstrapped one or more environments so you can deploy assets and Lambda functions using the AWS CDK\. Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include additional resources, so the boostrap stack has been extended to include an additional Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. This new style of CDK Toolkit stack will eventually become the default, but at this writing, you must opt in\. The AWS CDK Toolkit will upgrade your existing bootstrap stack or create a new one, as necessary\. -To bootstrap an environment that can provision an AWS CDK pipeline, set the environment variable `CDK_NEW_BOOTSTRAP` before invoking `cdk bootstarp`, as shown below\. Invoking the AWS CDK Toolkit via the `npx` command installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. +To bootstrap an environment that can provision an AWS CDK pipeline, set the environment variable `CDK_NEW_BOOTSTRAP` before invoking `cdk bootstrap`, as shown below\. Invoking the AWS CDK Toolkit via the `npx` command installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. \-\-cloudformation\-execution\-policies specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The `AdministratorAccess` policy is the default; if you're using it, you may omit this option\. Your organization may require a more restrictive policy\. From d89d624ffb96f82d86e477b30afd608cf8d869fe Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 8 Sep 2020 15:29:35 +0000 Subject: [PATCH 277/655] add bootstrapping topic --- doc_source/bootstrapping.md | 545 ++++++++++++++++++++++++++++++++++ doc_source/cdk_pipeline.md | 3 + doc_source/cli.md | 8 +- doc_source/environments.md | 6 +- doc_source/getting_started.md | 2 +- doc_source/index.md | 1 + doc_source/troubleshooting.md | 8 +- 7 files changed, 561 insertions(+), 12 deletions(-) create mode 100644 doc_source/bootstrapping.md diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md new file mode 100644 index 00000000..47ccb333 --- /dev/null +++ b/doc_source/bootstrapping.md @@ -0,0 +1,545 @@ +# Bootstrapping + +Deploying AWS CDK apps into an AWS [environment](environments.md) \(a combination of an AWS account and region\) may require that you provision resources the AWS CDK needs to perform the deployment\. These resources include an Amazon S3 bucket for storing files and IAM roles that grant permissions needed to perform deployments\. The process of provisioning these initial resources is called *bootstrapping*\. + +An environment needs to be bootstrapped if any of the following apply\. ++ The AWS CDK application being deployed uses [Assets](assets.md)\. ++ One or more of the AWS CloudFormation templates generated by the app exceeds 50 kilobytes\. ++ One or more of the stacks sues the `DefaultSynthesizer`\. We will explain this in more detail shortly, but in brief, the `DefaultSynthesizer` is used if you have set the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featureflags.md) in your app's `cdk.json` *or* if you explicitly create a `DefaultSynthesizer` and pass to your stack\. [CDK Pipelines](cdk_pipeline.md) use the `DefaultSynthesizer`, so if your app uses CDK Pipelines, you must bootstrap the environments you will deploy into as well as the environment that contains the pipeline\. + +The required resources are defined in a AWS CloudFormation stack, called the *bootstrap stack*, which is usually named `CDKToolkit`\. Just like any AWS CloudFormation stack, you can find it in the AWS CloudFormation console\. + +The AWS CDK supports two bootstrap templates\. At this writing, the AWS CDK is transitioning from one of these templates to the other, but the original template \(dubbed "legacy"\) is still the default\. The newer template \("modern"\) is required by CDK Pipelines now and will become the default at some point in the future\. For details, see [Bootstrapping templates](#bootstrapping-templates)\. + +Environments are independent, so if you want to deploy to multiple environments \(different AWS accounts or different regions in the same account\), each environment must be bootstrapped separately\. + +**Important** +You may incur AWS charges for data stored in the bootstrapped resources\. + +If you attempt to deploy an AWS CDK application that requires bootstrap resources into an environment that does not have them, you receive an error message telling you that you need to bootstrap\. + +If you are using CDK Pipelines to deploy into another account's environment, and you receive a message like the following: + +``` +Policy contains a statement with one or more invalid principals +``` + +This error message means that the appropriate IAM roles do not exist in the other environment, which is most likely caused by a lack of bootstrapping\. + +## How to bootstrap + +Bootstrapping is the deployment of a AWS CloudFormation template to a specific AWS environment \(account and region\)\. The bootstrapping template accepts parameters that customize some aspects of the bootstrapped resources \(see [Customizing bootstrapping](#bootstrapping-customizing)\)\. Thus, you can bootstrap in one of two ways\. ++ Use the AWS CDK Toolkit's cdk bootstrap command\. This is the simplest method and works well if you have only a few environments to bootstrap\. ++ Deploy the template provided by the AWS CDK Toolkit using another AWS CloudFormation deployment tool\. This lets you use AWS CloudFormation Stack Sets or AWS Control Tower as well as the AWS CloudFormation console or the AWS CLI\. You can even make small modifications to the template before deployment\. This approach is more flexible and is suitable for large\-scale deployments\. + +It is not an error to bootstrap an environmnt more than once\. If an environment you bootstrap has already been bootstrapped, its bootstrap stack will be upgraded if necessary; otherwise, nothing happens\. + +### Bootstrapping with the AWS CDK Toolkit + +Use the `cdk bootstrap` command to bootstrap one or more AWS environments\. In its basic form, this command bootstraps one or more specified AWS environments \(two, in this example\)\. + +``` +cdk bootstrap aws://ACCOUNT-NUMBER-1/REGION-1 aws://ACCOUNT-NUMBER-2/REGION-2 ... +``` + +The following examples illustrate bootstrapping of one and two environments, respectively\. \(Both use the same AWS account\.\) As shown in the second example, the `aws://` prefix is optional when specifying an environment\. + +``` +cdk bootstrap aws://123456789012/us-east-1 +cdk bootstrap 123456789012/us-east-1 123456789012/us-west-1 +``` + +If you do not specify at least one environment in the `cdk bootstrap` command, the AWS CDK Toolkit synthesizes the AWS CDK app in the current directory and bootstraps all the environments referenced in the app\. These references may be derived from the `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION` environment variables, which ultimately come from your default AWS profile, or another profile that you specify using the \-\-profile option\. \(See [Environments](environments.md)\.\) + +For example, the following command synthesizes the current AWS CDK app using the `prod` AWS profile, then bootstraps its environments\. + +``` +cdk bootstrap --profile prod +``` + +### Bootstrapping from the AWS CloudFormation template + +AWS CDK bootstrapping is performed by an AWS CloudFormation template\. To get a copy of this template in the file `bootstrap-template.yaml`, run the following command\. + +``` +cdk bootstrap --show-template > bootstrap-template.yaml +``` + +The template is also available in the [AWS CDK GitHub repository](https://github.com/aws/aws-cdk/blob/master/packages/aws-cdk/lib/api/bootstrap/bootstrap-template.yaml)\. + + Deploy this template using your preferred deployment mechanism for AWS CloudFormation templates\. For example, the following command deploys the template using the AWS CLI: + +------ +#### [ Mac OS X/Linux ] + +``` +aws cloudformation create-stack \ + --stack-name CDKToolkit \ + --template-body file://bootstrap-template.yaml +``` + +------ +#### [ Windows ] + +``` +aws cloudformation create-stack ^ + --stack-name CDKToolkit ^ + --template-body file://bootstrap-template.yaml +``` + +------ + +## Bootstrapping templates + +At this writing, the AWS CDK is transitioning from one set of bootstrap resources to another\. The original bootstrap template, which shipped with the very first version of the AWS CDK, is called the **legacy** template\. A newer version of the template with additional resources was added in version 1\.25\.0\. This newer template is called the **modern** template\. + +The legacy template is fully supported by the AWS CDK and is in fact the template that is selected by default when you issue `cdk bootstrap`\. The modern template is required primarily by the CDK Pipelines module, which can be used to set up a continuous delivery pipeline for your CDK applications\. More precisely, the modern template is required if you use the `DefaultSynthesizer` \(see [Stack synthesizers](#bootstrapping-synthesizers)\), + +The main differences between the templates are as follows\. + + +| Feature | Legacy | Modern | +| --- | --- | --- | +| Cross\-account deployments | Not allowed | Allowed | +| AWS CloudFormation Permissions | Deploys using current user's permissions \(determined by AWS profile, environment variables, etc\.\) | Deploys using the permissions specified when the bootstrap stack was provisioned | +| Versioning | Only one version of bootstrap stack is available | Bootstrap stack is versioned; new resources can be added in future versions, and AWS CDK apps can require a minimum version | +| Resources | Amazon S3 bucket | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) Additional resources may be added | +| Resource naming | Automatically generated | Deterministic | +| Bucket encryption | Default key | Customer\-managed key | + +At some point in the future, the modern template will become the default bootstrapping template\. Until then, you must manually select the modern template when bootstrapping by setting the `CDK_NEW_BOOTSTRAP` environment variable\. + +------ +#### [ Mac OS X/Linux ] + +``` +export CDK_NEW_BOOTSTRAP=1 +cdk bootstrap +``` + +------ +#### [ Windows ] + +``` +set CDK_NEW_BOOTSTRAP=1 +cdk bootstrap +``` + +------ + +The modern template is also selected by default when you issue cdk bootstrap in an AWS CDK app directory where the `@aws-cdk/core:newStyleStackSynthesis` feature flag is set in the app's `cdk.json` file\. + +``` +{ + // ... + "context": { + "@aws-cdk/core:newStyleStackSynthesis": "true" + } +} +``` + +**Tip** +We recommend always setting `CDK_NEW_BOOTSTRAP` when you want to bootstrap using the modern template\. The context key is supported to make sure you bootstrap correctly if your app uses the `DefaultStackSynthesizer`, but relies on you being in a particular directory when bootstrapping\. + +These two ways to specify the modern template also apply to `cdk bootstrap --show-template`, which will display the modern template depending on the presence of one or the other of these flags\. + +If the environment you are bootstrapping with the modern template has already been bootstrapped with the legacy template, the environment is upgraded to the modern template\. The Amazon S3 bucket from the legacy stack is orphaned in the process\. Re\-deploy all AWS CDK applications in the environment at least once before deleting the legacy bucket\. + +## Customizing bootstrapping + +There are two ways to customize the bootstrapping resources\. ++ Use command\-line parameters with the `cdk bootstrap` command\. This lets you tweak a few aspects of the template\. ++ Modify the default bootstrap template and deploy it yourself\. This gives you unlimited control over the bootstrap resources\. + +The following command\-line options, when used with CDK Toolkit's cdk bootstrap, modify the bootstrap template in commonly\-needed ways\. ++ \-\-bootstrap\-bucket\-name overrides the name of the Amazon S3 bucket\. May require changes to your CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. ++ \-\-bootstrap\-kms\-key\-id overrides the AWS KMS key used to encrypt the S3 bucket\. ++ \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. ++ \-\-termination\-protection prevents the bootstrap stack from being deleted\. + +The following additional switches are available only with the modern bootstrapping template\. ++ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. ++ \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. The account doing the bootstrapping is always trusted\. ++ \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + +### Customizing the template + +When you need more customization than the AWS CDK Toolkit switches can provide, you can modify the bootstrap template to suit your needs\. Remember that you can obtain the template by using the \-\-show\-template flag\. Optionally, set the CDK\_NEW\_BOOTSTRAP environment variable to get the modern template \(otherwise, you'll get the legacy template\)\. + +------ +#### [ Mac OS X/Linux ] + +``` +export CDK_NEW_BOOTSTRAP=1 +cdk bootstrap +``` + +------ +#### [ Windows ] + +``` +set CDK_NEW_BOOTSTRAP=1 +cdk bootstrap +``` + +------ + +Any modifications you make must adhere to the [bootstrapping template contract](#bootstrapping-contract)\. + +You can deploy your modified template as described in [Bootstrapping from the AWS CloudFormation template](#bootstrapping-howto-cfn), or using cdk bootstrap\. + +``` +cdk bootstrap --template bootstrap-template.yaml +``` + +## Stack synthesizers + +Your AWS CDK app needs to know about the bootstrapping resources available to it in order to successfully synthesize a stack that can be deployed\. The *stack synthesizer* is an AWS CDK class that controls how the stack's template is synthesized, including how it uses bootstrapping resources \(for example, how it refers to assets stored in the bootstrap bucket\)\. + +The AWS CDK includes two stack synthesizers: ++ `LegacyStackSynthesizer` can be used with either legacy bootstrap template or the modern bootstrap template\. \(It requires only an Amazon S3 bucket, and both templates include one\.\) ++ `DefaultStackSynthesizer` requires the modern bootstrap template\. It includes capabilities for cross\-account deployments and [CDK Pipelines](cdk_pipeline.md) deployments\. + +You can pass a stack synthesizer to a stack when you instantiate it using the synthesizer property\. + +------ +#### [ TypeScript ] + +``` +new MyStack(this, 'MyStack', { + // stack properties + synthesizer: new DefaultStackSynthesizer({ + // synthesizer properties + }), +}); +``` + +------ +#### [ JavaScript ] + +``` +new MyStack(this, 'MyStack', { + // stack properties + synthesizer: new DefaultStackSynthesizer({ + // synthesizer properties + }), +}); +``` + +------ +#### [ Python ] + +``` +MyStack(self, "MyStack", + # stack properties + synthesizer=DefaultStackSynthesizer( + # synthesizer properties +)) +``` + +------ +#### [ Java ] + +``` +new MyStack(app, "MyStack", StackProps.builder() + // stack properties + .synthesizer(DefaultStackSynthesizer.Builder.create() + // synthesizer properties + .build()) + .build(); +``` + +------ +#### [ C\# ] + +``` +new MyStack(app, "MyStack", new StackProps +// stack properties +{ + Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps + { + // synthesizer properties + }) +}); +``` + +------ + +If you don't pass a synthesizer property, the default behavior depends on whether the context key `@aws-cdk/core:newStyleStackSynthesis` is set, either in the AWS CDK app's source code or in `cdk.json`\. If it is set, synthesis uses a `DefaultStackSynthesizer`; otherwise, a `LegacyStackSynthesizer` is used\. This is the usual way of choosing a synthesizer unless you have customized the bootstrap template\. + +The most important differences between the two built\-in stack synthesizers are summarized here\. + + +| Feature | LegacyStackSynthesizer | DefaultStackSynthesizer | +| --- | --- | --- | +| Bootstrap stack | Both legacy and modern bootstrap stack | Modern bootstrap stack only | +| Deployments | AWS CDK Toolkit deployments only | AWS CDK Toolkit and CDK Pipelines deployments | +| Assets | Uses AWS CloudFormation parameters to reference assets | Expects assets to be in a predictable location | +| Docker image assets | Creates Amazon ECR repository on demand | Pushes images to Amazon ECR repository provisioned by bootstrapping | +| Roles | Uses AWS CDK Toolkit's current permissions to deploy | Uses roles and permissions provisioned by bootstrapping to deploy | +| Versioning | Not supported | Confirms versions of bootstrapping resources via embedded AWS CloudFormation rule | + +## Customizing synthesis + +If you customize your bootstrapping resources, depending on the changes you made, you may also need to customize synthesis\. The `DefaultStackSynthesizer` can be customized using the properties described below\. If none of these properties provide the customizations you require, you can write your synthesizer as a class that implements `IStackSynthesizer`\. + +**Note** +The `LegacyStackSynthesizer` does not offer any customization properties\. + +### Changing the qualifier + +The *qualifier* is added to the name of bootstrap resources to distinguish the resources in separate bootstrap stacks\. To deploy two different versions of the bootstrap stack in the same environment \(AWS account and region\), then, the stacks must have different qualifiers\. This feature is intended for naming isolation between automated tests of the CDK itself\. Unless you can very precisely scope down the IAM permissions given to the AWS CloudFormation execution role, there are no privilege isolation benefits to having two different bootstrap stacks in a single account, so there is usually no need to change this value\. + +To change the qualifier, configure the `DefaultStackSynthesizer` either by instantiating the synthesizer with the property: + +------ +#### [ TypeScript ] + +``` +new MyStack(this, 'MyStack', { + synthesizer: new DefaultStackSynthesizer({ + qualifier: 'MYQUALIFIER', + }), +}); +``` + +------ +#### [ JavaScript ] + +``` +new MyStack(this, 'MyStack', { + synthesizer: new DefaultStackSynthesizer({ + qualifier: 'MYQUALIFIER', + }), +}) +``` + +------ +#### [ Python ] + +``` +MyStack(self, "MyStack", + synthesizer=DefaultStackSynthesizer( + qualifier="MYQUALIFIER" +)) +``` + +------ +#### [ Java ] + +``` +new MyStack(app, "MyStack", StackProps.builder() + .synthesizer(DefaultStackSynthesizer.Builder.create() + .qualifier("MYQUALIFIER") + .build()) + .build(); +``` + +------ +#### [ C\# ] + +``` +new MyStack(app, "MyStack", new StackProps +{ + Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps + { + Qualifier = "MYQUALIFIER" + }) +}); +``` + +------ + +Or by configuring the qualifier as a context key in `cdk.json`\. + +``` +{ + "app": "...", + "context": { + "@aws-cdk/core:bootstrapQualifier": "MYQUALIFIER" + } +} +``` + +### Changing the resource names + +All the other `DefaultStackSynthesizer` properties relate to the names of the resources in the modern bootstrapping template\. You only need to pass any of these properties if you modified the bootstrap template and changed the resource names or naming scheme\. + +All properties accept the special placeholders `${Qualifier}`, `${AWS::Partition}`, `${AWS::AccountId}`, and `${AWS::Region}`\. These placeholders are replaced with the values of the `qualifier` parameter and with the values of the AWS partition, account ID, and region for the stack's environment, respectively\. + +The following example shows all the available properties for `DefaultStackSynthesizer` along with their default values, as if you were instantiating the synthesizer that way\. + +------ +#### [ TypeScript ] + +``` +new DefaultStackSynthesizer({ + // Name of the S3 bucket for file assets + fileAssetsBucketName: 'cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}', + + // Name of the ECR repository for Docker image assets + imageAssetsRepositoryName: 'cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}', + + // ARN of the role assumed by the CLI and Pipeline to deploy here + deployRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}', + + // ARN of the role used for file asset publishing (assumed from the deploy role) + fileAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}', + fileAssetPublishingExternalId: '', + + // ARN of the role used for Docker asset publishing (assumed from the deploy role) + imageAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}', + imageAssetPublishingExternalId: '', + + // ARN of the role passed to CloudFormation to execute the deployments + cloudFormationExecutionRole: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}', +}) +``` + +------ +#### [ JavaScript ] + +``` +new DefaultStackSynthesizer({ + // Name of the S3 bucket for file assets + fileAssetsBucketName: 'cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}', + + // Name of the ECR repository for Docker image assets + imageAssetsRepositoryName: 'cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}', + + // ARN of the role assumed by the CLI and Pipeline to deploy here + deployRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}', + + // ARN of the role used for file asset publishing (assumed from the deploy role) + fileAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}', + fileAssetPublishingExternalId: '', + + // ARN of the role used for Docker asset publishing (assumed from the deploy role) + imageAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}', + imageAssetPublishingExternalId: '', + + // ARN of the role passed to CloudFormation to execute the deployments + cloudFormationExecutionRole: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}', +}) +``` + +------ +#### [ Python ] + +``` +DefaultStackSynthesizer( + # Name of the S3 bucket for file assets + file_assets_bucket_name="cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}", + + # Name of the ECR repository for Docker image assets + image_assets_pepository_name="cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}", + + # ARN of the role assumed by the CLI and Pipeline to deploy here + deploy_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}", + + # ARN of the role used for file asset publishing (assumed from the deploy role) + file_sset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", + file_asset_publishing_external_id="", + + # ARN of the role used for Docker asset publishing (assumed from the deploy role) + image_asset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}", + image_asset_publishing_external_id="", + + # ARN of the role passed to CloudFormation to execute the deployments + cloud_formation_execution_role="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" +) +``` + +------ +#### [ Java ] + +``` +DefaultStackSynthesizer.Builder.create() + // Name of the S3 bucket for file assets + .fileAssetsBucketName("cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}") + + // Name of the ECR repository for Docker image assets + .imageAssetsRepositoryName("cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}") + + // ARN of the role assumed by the CLI and Pipeline to deploy here + .deployRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}") + + // ARN of the role used for file asset publishing (assumed from the deploy role) + .fileAssetPublishingRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}") + .fileAssetPublishingExternalId("") + + // ARN of the role used for Docker asset publishing (assumed from the deploy role) + .imageAssetPublishingRoleArn: "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}", + .imageAssetPublishingExternalId: "", + + // ARN of the role passed to CloudFormation to execute the deployments + .cloudFormationExecutionRole("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}") +.build() +``` + +------ +#### [ C\# ] + +``` +new DefaultStackSynthesizer(new DefaultStackSynthesizerProps +{ + // Name of the S3 bucket for file assets + FileAssetsBucketName = "cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}", + + // Name of the ECR repository for Docker image assets + ImageAssetsRepositoryName = "cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}", + + // ARN of the role assumed by the CLI and Pipeline to deploy here + DeployRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}", + + // ARN of the role used for file asset publishing (assumed from the deploy role) + FileAssetPublishingRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", + FileAssetPublishingExternalId = "", + + // ARN of the role used for Docker asset publishing (assumed from the deploy role) + ImageAssetPublishingRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}", + ImageAssetPublishingExternalId = "", + + // ARN of the role passed to CloudFormation to execute the deployments + CloudFormationExecutionRole = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" +}) +``` + +------ + +## The bootstrapping template contract + +The stack synthesizer's requirements of the bootstrapping stack depend on the stack synthesizer being used\. If you write your own stack synthesizer, you have complete freedom over the bootstrap resources that your synthesizer requires\. This section describes the expectations that the `DefaultStackSynthesizer` has of the bootstrapping template\. + +### Versioning + +The template should contain a resource to create an SSM parameter with a well\-known name and an output to reflect the template's version\. + +``` +Resources: + CdkBootstrapVersion: + Type: AWS::SSM::Parameter + Properties: + Type: String + Name: + Fn::Sub: '/cdk-bootstrap/${Qualifier}/version' + Value: 4 +Outputs: + BootstrapVersion: + Value: + Fn::GetAtt: [CdkBootstrapVersion, Value] +``` + +### Versioning + +The `DefaultStackSynthesizer` requires four IAM roles for four different purposes\. If these are given non\-standard ARNs, the synthesizer needs to be told about the ARNs\. The roles are: ++ The *deployment role* is assumed by the AWS CDK Toolkit and by AWS CodePipeline to deploy into an environment\. Its `AssumeRolePolicy` controls who can deploy into the environment\. The permissions this role needs can be seen in the template\. ++ The *file publishing role* and the *image publishing role* are assumed by the AWS CDK Toolkit and by AWS CodeBuild projects to publish assets into an environment: that is, to write to the S3 bucket and the ECR repository, respectively\. These roles require write access to these resources\. ++ *The AWS CloudFormation execution role* is passed to AWS CloudFormation to perform the actual deployment\. Its permissions are the permissions that the deployment will execute under\. The permissions passed the stack as a parameter that lists managed policy ARNs\. + +### Versioning + +The AWS CDK Toolkit requires that the following CloudFormation outputs exist on the bootstrap stack\. ++ `BucketName`: the name of the file asset bucket ++ `BucketDomainName`: the file asset bucket in domain name format ++ `BootstrapVersion`: the current version of the bootstrap stack \ No newline at end of file diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 7461cf84..1b1205ed 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -13,6 +13,9 @@ CDK Pipelines is currently in developer preview, and its API is subject to chang Before you can use CDK Pipelines, you must bootstrap the AWS environment\(s\) to which you will deploy your stacks\. An [environment](environments.md) is an account/region pair to which you want to deploy a CDK stack\. A CDK Pipeline involves at least two environments: the environment where the pipeline is provisioned, and the environment where you want to deploy the application's stacks \(or its stages, which are groups of related stacks\)\. These environments can be the same, though best practices recommend you isolate stages from each other in different AWS accounts or regions\. +**Note** +See [Bootstrapping](bootstrapping.md) for more information on the kinds of resources created by bootstrapping and how to customize the bootstrap stack\. + You may have already bootstrapped one or more environments so you can deploy assets and Lambda functions using the AWS CDK\. Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include additional resources, so the boostrap stack has been extended to include an additional Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. This new style of CDK Toolkit stack will eventually become the default, but at this writing, you must opt in\. The AWS CDK Toolkit will upgrade your existing bootstrap stack or create a new one, as necessary\. To bootstrap an environment that can provision an AWS CDK pipeline, set the environment variable `CDK_NEW_BOOTSTRAP` before invoking `cdk bootstrap`, as shown below\. Invoking the AWS CDK Toolkit via the `npx` command installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. diff --git a/doc_source/cli.md b/doc_source/cli.md index 6b23c06b..45284532 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -21,7 +21,7 @@ All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(` | --- | --- | | `cdk list` \(`ls`\) | Lists the stacks in the app | | `cdk synthesize` \(`synth`\) | Synthesizes and prints the CloudFormation template for the specified stack\(s\) | -| `cdk bootstrap` | Deploys the CDK Toolkit stack, required to deploy stacks containing assets | +| `cdk bootstrap` | Deploys the CDK Toolkit stack; see [Bootstrapping](bootstrapping.md) | | `cdk deploy` | Deploys the specified stack\(s\) | | `cdk destroy` | Destroys the specified stack\(s\) | | `cdk diff` | Compares the specified stack with the deployed stack or a local CloudFormation template | @@ -179,7 +179,7 @@ The CDK Toolkit does not guarantee that stacks are processed in the specified or ## Bootstrapping your AWS environment -Stacks that contain [assets](assets.md) or large AWS Lambda functions require special dedicated AWS CDK resources to be provisioned\. Currently, this is only an Amazon S3 bucket\. The `cdk bootstrap` command creates the necessary resources for you\. You only need to bootstrap if you are deploying a stack that requires these dedicated resources\. +Deploying stacks that contain [assets](assets.md), synthesize to large templates, or use [CDK Pipelines](cdk_pipeline.md) require special dedicated AWS CDK resources to be provisioned\. The `cdk bootstrap` command creates the necessary resources for you\. You only need to bootstrap if you are deploying a stack that requires these dedicated resources\. See [Bootstrapping](bootstrapping.md) for details\. ``` cdk bootstrap # bootstraps default account/region @@ -197,9 +197,7 @@ cdk bootstrap --profile test 1111111111/us-east-1 **Important** Each environment \(account/region combination\) to which you deploy such a stack must be bootstrapped separately\. -You may incur charges for what the AWS CDK stores in the bucket\. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK\. From time to time, then, you might want to clear out the bucket from the Amazon S3 console\. - -You can use the `--bootstrap-bucket-name` option of `cdk bootstrap` to specify the name of the bootstrap bucket, if the default \(`StagingBucket`\) is not suitable for some reason\. You can use the `--toolkit-stack-name` option if the standard name of the stack itself \(`CDKToolkit`\) is not suitable\. +You may incur AWS charges for what the AWS CDK stores in the bootstrapped resources\. ## Creating a new app diff --git a/doc_source/environments.md b/doc_source/environments.md index f0511af1..2db21c6c 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -1,10 +1,12 @@ # Environments -Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and AWS Region into which the stack is intended to be deployed\. +Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and region into which the stack is intended to be deployed\. + +**Note** +For all but the simplest deployments, you will need to [bootstrap](bootstrapping.md) each environment you will deploy into\. Deployment requires certain AWS resources to be availeble, and these resources are provisined by bootstrapping\. If you don't specify an environment when you define a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availablityZones` \(Python: `availability_zones`\)\. -**Note** In an environment\-agnostic stack, any constructs that use availability zones will see two of them\. This allows the stack to be deployed to almost any region, since nearly all regions have at least two availability zones\. The only exception is Osaka \(`ap-northeast-3`\), which has one\. When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Toolkit \(`cdk` command\)](cli.md) for details\. diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 14d482e9..98942b2f 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -210,7 +210,7 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Come on in; the water's fine\! Build [your first AWS CDK app](hello_world.md)\. + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. + See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite AWS services\. -+ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. ++ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index ec9b9f0f..da35d352 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -40,6 +40,7 @@ Amazon's trademarks and trade dress may not be used in + [Feature flags](featureflags.md) + [Aspects](aspects.md) + [Escape hatches](cfn_layer.md) + + [Bootstrapping](bootstrapping.md) + [API reference](reference.md) + [Examples](examples.md) + [Creating a serverless application using the AWS CDK](serverless_example.md) diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 472e2fa9..90531f7a 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -153,7 +153,9 @@ alias cdk=npx cdk \([back to list](#troubleshooting_top)\) **When deploying my AWS CDK stack, I receive a `NoSuchBucket` error** -Your AWS environment does not have a staging bucket, which the AWS CDK uses to hold resources during deployment\. Stacks require staging if they contain [Assets](assets.md) or synthesize to AWS CloudFormation templates larger than 50 kilobytes\. You can create the staging bucket with the following command: +Your AWS environment does not have a staging bucket, which the AWS CDK uses to hold resources during deployment\. Stacks require staging if they contain [Assets](assets.md) or synthesize to AWS CloudFormation templates larger than 50 kilobytes\. See [Bootstrapping](bootstrapping.md) for complete details\. + +You can create the staging bucket with the following command: ``` cdk bootstrap @@ -169,9 +171,7 @@ cdk bootstrap aws://123456789/us-east-1 You must bootstrap in every region where you will deploy stacks that require a staging bucket\. -To avoid undesired AWS charges, you can delete the contents of the staging bucket after deploying\. You can find the bucket in the Amazon S3 management console; it has a name starting with `cdktoolkit-stagingbucket` \(It is possible to specify a different name when bootstrapping, but generally you should use the default name\.\) - -You should not need to delete the bucket itself, but if you do, it is best to delete the entire `CDKToolkit` stack through the AWS CloudFormation management console\. If you delete the staging bucket entirely, you must re\-bootstrap before deploying a stack that requires staging\. +To avoid undesired AWS charges, you can delete the contents of the staging bucket after deploying\. You can find the bucket in the Amazon S3 management console; it has a name starting with `cdktoolkit-stagingbucket` \(It is possible to specify a different name when bootstrapping, but generally you should use the default name\.\) You should, however, leave the bucket itself intact\. \([back to list](#troubleshooting_top)\) From d489cb13a83353c55ffa0a3b63384d8baef72e2c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 8 Sep 2020 15:33:16 +0000 Subject: [PATCH 278/655] missing word --- doc_source/bootstrapping.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 47ccb333..deee9cda 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -5,7 +5,7 @@ Deploying AWS CDK apps into an AWS [environment](environments.md) \(a combinatio An environment needs to be bootstrapped if any of the following apply\. + The AWS CDK application being deployed uses [Assets](assets.md)\. + One or more of the AWS CloudFormation templates generated by the app exceeds 50 kilobytes\. -+ One or more of the stacks sues the `DefaultSynthesizer`\. We will explain this in more detail shortly, but in brief, the `DefaultSynthesizer` is used if you have set the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featureflags.md) in your app's `cdk.json` *or* if you explicitly create a `DefaultSynthesizer` and pass to your stack\. [CDK Pipelines](cdk_pipeline.md) use the `DefaultSynthesizer`, so if your app uses CDK Pipelines, you must bootstrap the environments you will deploy into as well as the environment that contains the pipeline\. ++ One or more of the stacks sues the `DefaultSynthesizer`\. We will explain this in more detail shortly, but in brief, the `DefaultSynthesizer` is used if you have set the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featureflags.md) in your app's `cdk.json` *or* if you explicitly create a `DefaultSynthesizer` and pass it to your stack\. [CDK Pipelines](cdk_pipeline.md) use the `DefaultSynthesizer`, so if your app uses CDK Pipelines, you must bootstrap the environments you will deploy into as well as the environment that contains the pipeline\. The required resources are defined in a AWS CloudFormation stack, called the *bootstrap stack*, which is usually named `CDKToolkit`\. Just like any AWS CloudFormation stack, you can find it in the AWS CloudFormation console\. From 959448f037f5f57439080138d57c16e768001cec Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 8 Sep 2020 16:17:41 +0000 Subject: [PATCH 279/655] more bootstrapping details --- doc_source/bootstrapping.md | 12 +++--------- doc_source/troubleshooting.md | 8 +++----- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index deee9cda..8338e385 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -49,7 +49,7 @@ cdk bootstrap aws://123456789012/us-east-1 cdk bootstrap 123456789012/us-east-1 123456789012/us-west-1 ``` -If you do not specify at least one environment in the `cdk bootstrap` command, the AWS CDK Toolkit synthesizes the AWS CDK app in the current directory and bootstraps all the environments referenced in the app\. These references may be derived from the `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION` environment variables, which ultimately come from your default AWS profile, or another profile that you specify using the \-\-profile option\. \(See [Environments](environments.md)\.\) +If you do not specify at least one environment in the `cdk bootstrap` command, the AWS CDK Toolkit synthesizes the AWS CDK app in the current directory and bootstraps all the environments referenced in the app\. If a stack is environment\-agnostic \(that is, it does not have an `env` property\), the CDK's environment \(for example, the one specified using \-\-profile, or the default AWS environment otherwise\) is applied to make the stack environment\-specific, and that environment is then bootstrapped\. For example, the following command synthesizes the current AWS CDK app using the `prod` AWS profile, then bootstraps its environments\. @@ -97,15 +97,9 @@ The legacy template is fully supported by the AWS CDK and is in fact the templat The main differences between the templates are as follows\. +[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) -| Feature | Legacy | Modern | -| --- | --- | --- | -| Cross\-account deployments | Not allowed | Allowed | -| AWS CloudFormation Permissions | Deploys using current user's permissions \(determined by AWS profile, environment variables, etc\.\) | Deploys using the permissions specified when the bootstrap stack was provisioned | -| Versioning | Only one version of bootstrap stack is available | Bootstrap stack is versioned; new resources can be added in future versions, and AWS CDK apps can require a minimum version | -| Resources | Amazon S3 bucket | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) Additional resources may be added | -| Resource naming | Automatically generated | Deterministic | -| Bucket encryption | Default key | Customer\-managed key | +\* *Additional resources may be added to Modern template as needed\.* At some point in the future, the modern template will become the default bootstrapping template\. Until then, you must manually select the modern template when bootstrapping by setting the `CDK_NEW_BOOTSTRAP` environment variable\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 90531f7a..c9834bbe 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -135,7 +135,7 @@ If, for some reason, you need to work with multiple versions of the AWS CDK Tool If you are using a language other than TypeScript or JavaScript, first create a `node_modules` folder in your project directory\. Then, regardless of language, use `npm` to install the AWS CDK Toolkit, omitting the `-g` flag and specifying the desired version\. For example: ``` -npm install aws-cdk@1.9.0 +npm install aws-cdk@1.50.0 ``` To run a locally\-installed AWS CDK Toolkit, use the command `npx cdk` rather than just `cdk`\. For example: @@ -153,9 +153,7 @@ alias cdk=npx cdk \([back to list](#troubleshooting_top)\) **When deploying my AWS CDK stack, I receive a `NoSuchBucket` error** -Your AWS environment does not have a staging bucket, which the AWS CDK uses to hold resources during deployment\. Stacks require staging if they contain [Assets](assets.md) or synthesize to AWS CloudFormation templates larger than 50 kilobytes\. See [Bootstrapping](bootstrapping.md) for complete details\. - -You can create the staging bucket with the following command: +Your AWS environment does not have a staging bucket, which the AWS CDK uses to hold resources during deployment\. Stacks require this bucket if they contain [Assets](assets.md) or synthesize to AWS CloudFormation templates larger than 50 kilobytes\. You can create the staging bucket with the following command: ``` cdk bootstrap @@ -171,7 +169,7 @@ cdk bootstrap aws://123456789/us-east-1 You must bootstrap in every region where you will deploy stacks that require a staging bucket\. -To avoid undesired AWS charges, you can delete the contents of the staging bucket after deploying\. You can find the bucket in the Amazon S3 management console; it has a name starting with `cdktoolkit-stagingbucket` \(It is possible to specify a different name when bootstrapping, but generally you should use the default name\.\) You should, however, leave the bucket itself intact\. +For more information, see [Bootstrapping](bootstrapping.md) \([back to list](#troubleshooting_top)\) From 6052f550bb6c9bb21c2b5d872749db1e51208f18 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 9 Sep 2020 04:05:05 +0000 Subject: [PATCH 280/655] tweaks to bootstrapping topic --- doc_source/bootstrapping.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 8338e385..f7ceffd0 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -3,9 +3,9 @@ Deploying AWS CDK apps into an AWS [environment](environments.md) \(a combination of an AWS account and region\) may require that you provision resources the AWS CDK needs to perform the deployment\. These resources include an Amazon S3 bucket for storing files and IAM roles that grant permissions needed to perform deployments\. The process of provisioning these initial resources is called *bootstrapping*\. An environment needs to be bootstrapped if any of the following apply\. -+ The AWS CDK application being deployed uses [Assets](assets.md)\. -+ One or more of the AWS CloudFormation templates generated by the app exceeds 50 kilobytes\. -+ One or more of the stacks sues the `DefaultSynthesizer`\. We will explain this in more detail shortly, but in brief, the `DefaultSynthesizer` is used if you have set the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featureflags.md) in your app's `cdk.json` *or* if you explicitly create a `DefaultSynthesizer` and pass it to your stack\. [CDK Pipelines](cdk_pipeline.md) use the `DefaultSynthesizer`, so if your app uses CDK Pipelines, you must bootstrap the environments you will deploy into as well as the environment that contains the pipeline\. ++ An AWS CDK stack being deployed uses [Assets](assets.md)\. ++ A AWS CloudFormation template generated by the app exceeds 50 kilobytes\. ++ One or more of the stacks sues the `DefaultSynthesizer`\. We will explain stack synthesizers in more detail shortly, but in brief, the `DefaultSynthesizer` is used if you have set the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featureflags.md) in your app's `cdk.json` *or* if you explicitly create a `DefaultSynthesizer` and pass it to your stack\. [CDK Pipelines](cdk_pipeline.md) use the `DefaultSynthesizer`, so if your app uses CDK Pipelines, you must bootstrap the environments you will deploy into as well as the environment that contains the pipeline\. The required resources are defined in a AWS CloudFormation stack, called the *bootstrap stack*, which is usually named `CDKToolkit`\. Just like any AWS CloudFormation stack, you can find it in the AWS CloudFormation console\. @@ -99,7 +99,7 @@ The main differences between the templates are as follows\. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) -\* *Additional resources may be added to Modern template as needed\.* +\* *Additional resources may be added to the modern template as needed\.* At some point in the future, the modern template will become the default bootstrapping template\. Until then, you must manually select the modern template when bootstrapping by setting the `CDK_NEW_BOOTSTRAP` environment variable\. @@ -133,7 +133,7 @@ The modern template is also selected by default when you issue cdk bootstrap in ``` **Tip** -We recommend always setting `CDK_NEW_BOOTSTRAP` when you want to bootstrap using the modern template\. The context key is supported to make sure you bootstrap correctly if your app uses the `DefaultStackSynthesizer`, but relies on you being in a particular directory when bootstrapping\. +We recommend always setting `CDK_NEW_BOOTSTRAP` when you want to bootstrap using the modern template\. The context key is supported to make sure you bootstrap correctly if your app uses the `DefaultStackSynthesizer`, but relies on you being in an app's directory when bootstrapping\. These two ways to specify the modern template also apply to `cdk bootstrap --show-template`, which will display the modern template depending on the presence of one or the other of these flags\. @@ -529,7 +529,7 @@ Outputs: The `DefaultStackSynthesizer` requires four IAM roles for four different purposes\. If these are given non\-standard ARNs, the synthesizer needs to be told about the ARNs\. The roles are: + The *deployment role* is assumed by the AWS CDK Toolkit and by AWS CodePipeline to deploy into an environment\. Its `AssumeRolePolicy` controls who can deploy into the environment\. The permissions this role needs can be seen in the template\. + The *file publishing role* and the *image publishing role* are assumed by the AWS CDK Toolkit and by AWS CodeBuild projects to publish assets into an environment: that is, to write to the S3 bucket and the ECR repository, respectively\. These roles require write access to these resources\. -+ *The AWS CloudFormation execution role* is passed to AWS CloudFormation to perform the actual deployment\. Its permissions are the permissions that the deployment will execute under\. The permissions passed the stack as a parameter that lists managed policy ARNs\. ++ *The AWS CloudFormation execution role* is passed to AWS CloudFormation to perform the actual deployment\. Its permissions are the permissions that the deployment will execute under\. The permissions are passed to the stack as a parameter that lists managed policy ARNs\. ### Versioning From ad8f93962b98b3503514e1c495fdcba9cb2d67fa Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 9 Sep 2020 15:29:41 +0000 Subject: [PATCH 281/655] further tweaks to boottrapping topic --- doc_source/bootstrapping.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index f7ceffd0..e31de063 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -99,7 +99,7 @@ The main differences between the templates are as follows\. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) -\* *Additional resources may be added to the modern template as needed\.* +\* *We will add additional resources to the modern template as needed\.* At some point in the future, the modern template will become the default bootstrapping template\. Until then, you must manually select the modern template when bootstrapping by setting the `CDK_NEW_BOOTSTRAP` environment variable\. @@ -121,7 +121,7 @@ cdk bootstrap ------ -The modern template is also selected by default when you issue cdk bootstrap in an AWS CDK app directory where the `@aws-cdk/core:newStyleStackSynthesis` feature flag is set in the app's `cdk.json` file\. +The modern template is also selected when you issue cdk bootstrap in an AWS CDK app directory where the `@aws-cdk/core:newStyleStackSynthesis` feature flag is set in the app's `cdk.json` file\. ``` { @@ -135,25 +135,25 @@ The modern template is also selected by default when you issue cdk bootstrap in **Tip** We recommend always setting `CDK_NEW_BOOTSTRAP` when you want to bootstrap using the modern template\. The context key is supported to make sure you bootstrap correctly if your app uses the `DefaultStackSynthesizer`, but relies on you being in an app's directory when bootstrapping\. -These two ways to specify the modern template also apply to `cdk bootstrap --show-template`, which will display the modern template depending on the presence of one or the other of these flags\. +These two ways to specify the modern template also apply to `cdk bootstrap --show-template`, which will display the modern template if one or the other of these flags is present\. If the environment you are bootstrapping with the modern template has already been bootstrapped with the legacy template, the environment is upgraded to the modern template\. The Amazon S3 bucket from the legacy stack is orphaned in the process\. Re\-deploy all AWS CDK applications in the environment at least once before deleting the legacy bucket\. ## Customizing bootstrapping There are two ways to customize the bootstrapping resources\. -+ Use command\-line parameters with the `cdk bootstrap` command\. This lets you tweak a few aspects of the template\. ++ Use command\-line parameters with the `cdk bootstrap` command\. This lets you modify a few aspects of the template\. + Modify the default bootstrap template and deploy it yourself\. This gives you unlimited control over the bootstrap resources\. -The following command\-line options, when used with CDK Toolkit's cdk bootstrap, modify the bootstrap template in commonly\-needed ways\. +The following command\-line options, when used with CDK Toolkit's cdk bootstrap, provide commonly\-needed adjustments to the bootstrapping template\.\. + \-\-bootstrap\-bucket\-name overrides the name of the Amazon S3 bucket\. May require changes to your CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + \-\-bootstrap\-kms\-key\-id overrides the AWS KMS key used to encrypt the S3 bucket\. + \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. -+ \-\-termination\-protection prevents the bootstrap stack from being deleted\. ++ \-\-termination\-protection prevents the bootstrap stack from being deleted \(see [Protecting a stack from being deleted](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html) in the AWS CloudFormation User Guide\) The following additional switches are available only with the modern bootstrapping template\. + \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. -+ \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. The account doing the bootstrapping is always trusted\. ++ \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an evironment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. ### Customizing the template @@ -191,10 +191,10 @@ cdk bootstrap --template bootstrap-template.yaml Your AWS CDK app needs to know about the bootstrapping resources available to it in order to successfully synthesize a stack that can be deployed\. The *stack synthesizer* is an AWS CDK class that controls how the stack's template is synthesized, including how it uses bootstrapping resources \(for example, how it refers to assets stored in the bootstrap bucket\)\. The AWS CDK includes two stack synthesizers: -+ `LegacyStackSynthesizer` can be used with either legacy bootstrap template or the modern bootstrap template\. \(It requires only an Amazon S3 bucket, and both templates include one\.\) ++ `LegacyStackSynthesizer` can be used with either bootstrap template\. \(It requires only an Amazon S3 bucket, and both templates include one\.\) + `DefaultStackSynthesizer` requires the modern bootstrap template\. It includes capabilities for cross\-account deployments and [CDK Pipelines](cdk_pipeline.md) deployments\. -You can pass a stack synthesizer to a stack when you instantiate it using the synthesizer property\. +You can pass a stack synthesizer to a stack when you instantiate it using the `synthesizer` property\. ------ #### [ TypeScript ] @@ -259,7 +259,7 @@ new MyStack(app, "MyStack", new StackProps ------ -If you don't pass a synthesizer property, the default behavior depends on whether the context key `@aws-cdk/core:newStyleStackSynthesis` is set, either in the AWS CDK app's source code or in `cdk.json`\. If it is set, synthesis uses a `DefaultStackSynthesizer`; otherwise, a `LegacyStackSynthesizer` is used\. This is the usual way of choosing a synthesizer unless you have customized the bootstrap template\. +If you don't provide the `synthesizer` property, the default behavior depends on whether the context key `@aws-cdk/core:newStyleStackSynthesis` is set, either in the AWS CDK app's source code or in `cdk.json`\. If it is set, synthesis uses a `DefaultStackSynthesizer`; otherwise, a `LegacyStackSynthesizer` is used\. This is the usual way of choosing a synthesizer unless you have customized the bootstrap template\. The most important differences between the two built\-in stack synthesizers are summarized here\. @@ -275,14 +275,14 @@ The most important differences between the two built\-in stack synthesizers are ## Customizing synthesis -If you customize your bootstrapping resources, depending on the changes you made, you may also need to customize synthesis\. The `DefaultStackSynthesizer` can be customized using the properties described below\. If none of these properties provide the customizations you require, you can write your synthesizer as a class that implements `IStackSynthesizer`\. +Depending on the changes you made to the bootstrap template, you may also need to customize synthesis\. The `DefaultStackSynthesizer` can be customized using the properties described below\. If none of these properties provide the customizations you require, you can write your synthesizer as a class that implements `IStackSynthesizer` \(perhaps deriving from `DefaultStackSynthesizer`\)\. **Note** The `LegacyStackSynthesizer` does not offer any customization properties\. ### Changing the qualifier -The *qualifier* is added to the name of bootstrap resources to distinguish the resources in separate bootstrap stacks\. To deploy two different versions of the bootstrap stack in the same environment \(AWS account and region\), then, the stacks must have different qualifiers\. This feature is intended for naming isolation between automated tests of the CDK itself\. Unless you can very precisely scope down the IAM permissions given to the AWS CloudFormation execution role, there are no privilege isolation benefits to having two different bootstrap stacks in a single account, so there is usually no need to change this value\. +The *qualifier* is added to the name of bootstrap resources to distinguish the resources in separate bootstrap stacks\. To deploy two different versions of the bootstrap stack in the same environment \(AWS account and region\), then, the stacks must have different qualifiers\. This feature is intended for name isolation between automated tests of the CDK itself\. Unless you can very precisely scope down the IAM permissions given to the AWS CloudFormation execution role, there are no privilege isolation benefits to having two different bootstrap stacks in a single account, so there is usually no need to change this value\. To change the qualifier, configure the `DefaultStackSynthesizer` either by instantiating the synthesizer with the property: @@ -357,11 +357,11 @@ Or by configuring the qualifier as a context key in `cdk.json`\. ### Changing the resource names -All the other `DefaultStackSynthesizer` properties relate to the names of the resources in the modern bootstrapping template\. You only need to pass any of these properties if you modified the bootstrap template and changed the resource names or naming scheme\. +All the other `DefaultStackSynthesizer` properties relate to the names of the resources in the modern bootstrapping template\. You only need to provide any of these properties if you modified the bootstrap template and changed the resource names or naming scheme\. All properties accept the special placeholders `${Qualifier}`, `${AWS::Partition}`, `${AWS::AccountId}`, and `${AWS::Region}`\. These placeholders are replaced with the values of the `qualifier` parameter and with the values of the AWS partition, account ID, and region for the stack's environment, respectively\. -The following example shows all the available properties for `DefaultStackSynthesizer` along with their default values, as if you were instantiating the synthesizer that way\. +The following example shows all the available properties for `DefaultStackSynthesizer` along with their default values, as if you were instantiating the synthesizer\. ------ #### [ TypeScript ] @@ -503,7 +503,7 @@ new DefaultStackSynthesizer(new DefaultStackSynthesizerProps ## The bootstrapping template contract -The stack synthesizer's requirements of the bootstrapping stack depend on the stack synthesizer being used\. If you write your own stack synthesizer, you have complete freedom over the bootstrap resources that your synthesizer requires\. This section describes the expectations that the `DefaultStackSynthesizer` has of the bootstrapping template\. +The requirements of the bootstrapping stack depend on the stack synthesizer being used\. If you write your own stack synthesizer, you have complete control of the bootstrap resources that your synthesizer requires and how the synthesizer finds them\. This section describes the expectations that the `DefaultStackSynthesizer` has of the bootstrapping template\. ### Versioning @@ -511,7 +511,7 @@ The template should contain a resource to create an SSM parameter with a well\-k ``` Resources: - CdkBootstrapVersion: + CdkBootstrapVersion:` Type: AWS::SSM::Parameter Properties: Type: String @@ -526,7 +526,7 @@ Outputs: ### Versioning -The `DefaultStackSynthesizer` requires four IAM roles for four different purposes\. If these are given non\-standard ARNs, the synthesizer needs to be told about the ARNs\. The roles are: +The `DefaultStackSynthesizer` requires four IAM roles for four different purposes\. If you are not using the default roles, the synthesizer needs to be told the ARNs for the roles you want to use\. The roles are: + The *deployment role* is assumed by the AWS CDK Toolkit and by AWS CodePipeline to deploy into an environment\. Its `AssumeRolePolicy` controls who can deploy into the environment\. The permissions this role needs can be seen in the template\. + The *file publishing role* and the *image publishing role* are assumed by the AWS CDK Toolkit and by AWS CodeBuild projects to publish assets into an environment: that is, to write to the S3 bucket and the ECR repository, respectively\. These roles require write access to these resources\. + *The AWS CloudFormation execution role* is passed to AWS CloudFormation to perform the actual deployment\. Its permissions are the permissions that the deployment will execute under\. The permissions are passed to the stack as a parameter that lists managed policy ARNs\. From 25547e3a64bdf882123ff1e800509ea6c16c6d71 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 9 Sep 2020 22:18:50 +0000 Subject: [PATCH 282/655] fix missing . in filename --- doc_source/context.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/context.md b/doc_source/context.md index c04c1ba3..75a1cec7 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -9,7 +9,7 @@ Context values are made available to your AWS CDK app in six different ways: + Through the \-\-context option to the cdk command\. + In the project's `cdk.context.json` file\. + In the project's `cdk.json` file\. -+ In the `context` key of your `~/cdk.json` file\. ++ In the `context` key of your `~/.cdk.json` file\. + In your AWS CDK app using the `construct.node.setContext` method\. The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, changing your Auto Scaling group\. The AWS CDK does not write context data to any of the other files listed\. From 6ddc318a16b3e89a36d7f87a042f5871247ed244 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 9 Sep 2020 22:31:07 +0000 Subject: [PATCH 283/655] remove prompts --- doc_source/context.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/doc_source/context.md b/doc_source/context.md index 75a1cec7..67b05163 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -51,7 +51,7 @@ Use the cdk context command to view and manage the information in your `cdk.cont ``` Context found in cdk.json: - + ┌───┬─────────────────────────────────────────────────────────────┬─────────────────────────────────────────────────────────┐ │ # │ Key │ Value │ ├───┼─────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤ @@ -66,7 +66,7 @@ Run cdk context --reset KEY_OR_NUMBER to remove a context key. If it is a cached To remove a context value, run cdk context \-\-reset, specifying the value's corresponding key or number\. The following example removes the value that corresponds to the second key in the preceding example, which is the list of availability zones in the Ireland region\. ``` -$ cdk context --reset 2 +cdk context --reset 2 ``` ``` @@ -78,13 +78,13 @@ reset. It will be refreshed on the next SDK synthesis run. Therefore, if you want to update to the latest version of the Amazon Linux AMI, you can use the preceding example to do a controlled update of the context value and reset it, and then synthesize and deploy your app again\. ``` -$ cdk synth +cdk synth ``` To clear all of the stored context values for your app, run cdk context \-\-clear, as follows\. ``` -$ cdk context --clear +cdk context --clear ``` Only context values stored in `cdk.context.json` can be reset or cleared\. The AWS CDK does not touch other context files\. To protect a context value from being reset using these commands, then, you might copy the value to `cdk.json`\. @@ -257,7 +257,7 @@ class ExistsVpcStack : Stack You can use cdk diff to see the effects of passing in a context value on the command line: ``` -$ cdk diff -c vpcid=vpc-0cb9c31031d0d3e22 +cdk diff -c vpcid=vpc-0cb9c31031d0d3e22 ``` ``` @@ -269,7 +269,7 @@ Outputs The resulting context values can be viewed as shown here\. ``` -$ cdk context -j +cdk context -j ``` ``` From a9708ca2619961ee2b0c67952c86e9b51d5c6bcf Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 9 Sep 2020 22:38:30 +0000 Subject: [PATCH 284/655] improve context example CLI commands --- doc_source/context.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/doc_source/context.md b/doc_source/context.md index 67b05163..51df8c97 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -94,18 +94,19 @@ Only context values stored in `cdk.context.json` can be reset or cleared\. The A Use the `--context` \(`-c` for short\) option to pass runtime context values to your CDK app during synthesis or deployment\. ``` -# specify a single context value cdk synth --context key=value MyStack +``` + +To specify multiple context values, repeat the \-\-context option any number of times, providing one key\-value pair each time\. -# specify multiple context values (any number) +``` cdk synth --context key1=value1 --context key2=value2 MyStack ``` When deploying multiple stacks, the specified context values are normally passed to all of them\. If you wish, you may specify different values for each stack by prefixing the stack name to the context value\. ``` -# different context values for each stack -cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 +cdk synth --context Stack1:key=value --context Stack2:key=value Stack1 Stack2 ``` ## Example From f61118e0b68ce16cc73181bde9cfaf4616356551 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 9 Sep 2020 23:53:47 +0000 Subject: [PATCH 285/655] update doc history --- doc_source/doc-history.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 24a47a94..a9536a05 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -7,6 +7,7 @@ The table below represents significant documentation milestones\. We fix errors | Change | Description | Date | | --- |--- |--- | +| [Add Bootstrapping topic](#doc-history) | A complete explanation of why and how to bootstrap AWS environments for the CDK, including a comprehensive discussion of how to customize the process\. | September 8, 2020 | | [Add CDK Pipelines how\-to](#doc-history) | CDK Pipelines let you easily automate the deployment of your AWS CDK apps from source control whenever they're updated\. | July 17, 2020 | | [Improve CDK Toolkit topic](#doc-history) | Include more information and examples around performing common tasks with the CLI \(and the relevant flags\) rather than just including a copy of the help\. | July 9, 2020 | | [Improve CodePipeline example](#doc-history) | Update pipeline stack to build in proper language and add more material dealing with the CodeCommit repository\. | July 6, 2020 | From f71897a0f2236cd66068c6e464cd0289f868de8f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 11 Sep 2020 23:48:21 +0000 Subject: [PATCH 286/655] add videos page to Markdown version of Guide --- doc_source/index.md | 1 + doc_source/videos.md | 14 ++++++++++++++ 2 files changed, 15 insertions(+) create mode 100644 doc_source/videos.md diff --git a/doc_source/index.md b/doc_source/index.md index da35d352..4168e708 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -68,5 +68,6 @@ Amazon's trademarks and trade dress may not be used in + [Resilience for the AWS Cloud Development Kit (AWS CDK)](disaster-recovery-resiliency.md) + [Infrastructure security for the AWS Cloud Development Kit (AWS CDK)](infrastructure-security.md) + [Troubleshooting common AWS CDK issues](troubleshooting.md) ++ [Videos](videos.md) + [OpenPGP keys for the AWS CDK and JSII](pgp-keys.md) + [AWS CDK Developer Guide history](doc-history.md) \ No newline at end of file diff --git a/doc_source/videos.md b/doc_source/videos.md new file mode 100644 index 00000000..e730414c --- /dev/null +++ b/doc_source/videos.md @@ -0,0 +1,14 @@ +# Videos + +Enjoy these videos presented by members of the AWS CDK team\. + +**Note** +Since the AWS CDK is always evolving, some of the code presented in these videos may not work quite the same way it did when the video was recorded\. This is especially true for modules that were under active development at the time\. It's also possible that we've since added a better way to achieve the same result\. Consult this Developer Guide and the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) for up\-to\-date information\. + +## Infrastructure *is* Code with the AWS CDK + +## Deep dive into AWS Cloud Development Kit \(AWS CDK\) + +## Contributing to the AWS Construct Library + +## How to contribute to the AWS CDK using GitPod \ No newline at end of file From 7eacea6b0b553e1a948be07af74259151246b3a8 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 12 Sep 2020 00:12:18 +0000 Subject: [PATCH 287/655] add CDK Pipelines video --- doc_source/videos.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/doc_source/videos.md b/doc_source/videos.md index e730414c..f2c160f9 100644 --- a/doc_source/videos.md +++ b/doc_source/videos.md @@ -11,4 +11,6 @@ Since the AWS CDK is always evolving, some of the code presented in these videos ## Contributing to the AWS Construct Library -## How to contribute to the AWS CDK using GitPod \ No newline at end of file +## Faster deployments with CDK Pipelines + +## How to contribute to the AWS CDK using GitPod \ No newline at end of file From 88b238fd8c90a297d714c41aba49a46e01143811 Mon Sep 17 00:00:00 2001 From: "J. Longman" Date: Sun, 13 Sep 2020 12:55:22 -0400 Subject: [PATCH 288/655] Correct typo `sues` to `uses` --- doc_source/bootstrapping.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index e31de063..10688c78 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -5,7 +5,7 @@ Deploying AWS CDK apps into an AWS [environment](environments.md) \(a combinatio An environment needs to be bootstrapped if any of the following apply\. + An AWS CDK stack being deployed uses [Assets](assets.md)\. + A AWS CloudFormation template generated by the app exceeds 50 kilobytes\. -+ One or more of the stacks sues the `DefaultSynthesizer`\. We will explain stack synthesizers in more detail shortly, but in brief, the `DefaultSynthesizer` is used if you have set the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featureflags.md) in your app's `cdk.json` *or* if you explicitly create a `DefaultSynthesizer` and pass it to your stack\. [CDK Pipelines](cdk_pipeline.md) use the `DefaultSynthesizer`, so if your app uses CDK Pipelines, you must bootstrap the environments you will deploy into as well as the environment that contains the pipeline\. ++ One or more of the stacks uses the `DefaultSynthesizer`\. We will explain stack synthesizers in more detail shortly, but in brief, the `DefaultSynthesizer` is used if you have set the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featureflags.md) in your app's `cdk.json` *or* if you explicitly create a `DefaultSynthesizer` and pass it to your stack\. [CDK Pipelines](cdk_pipeline.md) use the `DefaultSynthesizer`, so if your app uses CDK Pipelines, you must bootstrap the environments you will deploy into as well as the environment that contains the pipeline\. The required resources are defined in a AWS CloudFormation stack, called the *bootstrap stack*, which is usually named `CDKToolkit`\. Just like any AWS CloudFormation stack, you can find it in the AWS CloudFormation console\. @@ -536,4 +536,4 @@ The `DefaultStackSynthesizer` requires four IAM roles for four different purpose The AWS CDK Toolkit requires that the following CloudFormation outputs exist on the bootstrap stack\. + `BucketName`: the name of the file asset bucket + `BucketDomainName`: the file asset bucket in domain name format -+ `BootstrapVersion`: the current version of the bootstrap stack \ No newline at end of file ++ `BootstrapVersion`: the current version of the bootstrap stack From 62a30528541803de2cab2d1f9732f5e8159be35e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 16 Sep 2020 15:31:46 +0000 Subject: [PATCH 289/655] fix link text in markdown for third party bucket --- doc_source/bootstrapping.md | 2 +- doc_source/cli.md | 26 +++++++++++++------------- doc_source/home.md | 1 - doc_source/resources.md | 2 +- 4 files changed, 15 insertions(+), 16 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 10688c78..11f7666d 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -536,4 +536,4 @@ The `DefaultStackSynthesizer` requires four IAM roles for four different purpose The AWS CDK Toolkit requires that the following CloudFormation outputs exist on the bootstrap stack\. + `BucketName`: the name of the file asset bucket + `BucketDomainName`: the file asset bucket in domain name format -+ `BootstrapVersion`: the current version of the bootstrap stack ++ `BootstrapVersion`: the current version of the bootstrap stack \ No newline at end of file diff --git a/doc_source/cli.md b/doc_source/cli.md index 45284532..98728c74 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -259,7 +259,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -278,7 +278,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -286,7 +286,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth –json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -310,7 +310,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -332,7 +332,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. @@ -507,7 +507,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -520,7 +520,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -533,7 +533,7 @@ Options: dependencies [boolean] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -572,7 +572,7 @@ Options: [boolean] [default: false] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -614,7 +614,7 @@ Options: disabled) [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -630,7 +630,7 @@ Options: [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -650,7 +650,7 @@ Options: [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -673,7 +673,7 @@ Options: [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/home.md b/doc_source/home.md index 8ed9a915..1244fe98 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -227,7 +227,6 @@ Because the AWS CDK is open source, the team encourages you contribute to make i In addition to this guide, the following are other resources available to AWS CDK users: + [API Reference](https://docs.aws.amazon.com/cdk/api/latest) -+ [AWS CDK Demo at re:Invent 2018](https://www.youtube.com/watch?v=Lh-kVC2r2AU) + [AWS CDK Workshop](https://cdkworkshop.com/) + [AWS CDK Examples](https://github.com/aws-samples/aws-cdk-examples) + [AWS Developer Blog](https://aws.amazon.com/blogs/developer) diff --git a/doc_source/resources.md b/doc_source/resources.md index c840268b..381d91fd 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1121,7 +1121,7 @@ Resources besides those that store data persistently may also have a `removalPol | RemovalPolicy\.RETAIN | Keep the contents of the resource when destroying the stack \(default\)\. The resource is orphaned from the stack and must be deleted manually\. If you attempt to re\-deploy the stack while the resource still exists, you will receive an error message due to a name conflict\. | | RemovalPolicy\.DESTROY | The resource will be destroyed along with the stack\. | -AWS CloudFormation does not remove Amazon S3 buckets that contain files even if their removal policy is set to `DESTROY`\. Attempting to do so is a AWS CloudFormation error\. Delete the files from the bucket before destroying the stack\. You can automate this using a custom resource; see the third\-party construct [https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda](https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda) for an example\. +AWS CloudFormation does not remove Amazon S3 buckets that contain files even if their removal policy is set to `DESTROY`\. Attempting to do so is a AWS CloudFormation error\. Delete the files from the bucket before destroying the stack\. You can automate this using a custom resource; see the third\-party construct [auto\-delete\-bucket](https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda) for an example\. Following is an example of creating an Amazon S3 bucket with `RemovalPolicy.DESTROY`\. From fa5d24940debc0ea53a391b1c44fb537b3cdc447 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 16 Sep 2020 19:19:02 +0000 Subject: [PATCH 290/655] fix spelling of Environmentironment, I mean Environment --- doc_source/cdk_pipeline.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 1b1205ed..cf4fc9a2 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -865,7 +865,7 @@ class MyPipelineStack(Stack): # Do this as many times as necessary with any account and region # Account and region may be different from the pipeline's. pipeline.add_application_stage(MyApplication(self, 'Prod', - env=Environmentironment(account="123456789012", region="eu-west-1"))) + env=Environment(account="123456789012", region="eu-west-1"))) ``` ------ From 2b409486dd0bbbabc0d4709ac791fdd2eb3289fb Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 16 Sep 2020 22:04:18 +0000 Subject: [PATCH 291/655] add/update/improve guidance around construct library modules --- doc_source/work-with-cdk-csharp.md | 14 ++++++--- doc_source/work-with-cdk-java.md | 18 +++++++---- doc_source/work-with-cdk-javascript.md | 28 ++++++++++++++--- doc_source/work-with-cdk-python.md | 42 +++++++++++++++++++++----- doc_source/work-with-cdk-typescript.md | 31 ++++++++++++++++--- doc_source/work-with.md | 3 ++ 6 files changed, 110 insertions(+), 26 deletions(-) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 2e272dd6..345aec21 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -33,11 +33,17 @@ cdk init app --language csharp The resulting project includes a reference to the `Amazon.CDK` NuGet package\. It and its dependencies are installed automatically by NuGet\. -## Managing AWS construct library modules +## Managing AWS Construct Library modules -The \.NET ecosystem uses the NuGet package manager\. AWS Construct Library modules are named like `Amazon.CDK.AWS.SERVICE-NAME`\. For example, the NuGet package name for the Amazon S3 module is `Amazon.CDK.AWS.S3`\. +The \.NET ecosystem uses the NuGet package manager\. AWS Construct Library modules are named like `Amazon.CDK.AWS.SERVICE-NAME` where the service name is a short name without an AWS or Amazon prefix\. For example, the NuGet package name for the Amazon S3 module is `Amazon.CDK.AWS.S3`\. -**Note** +Some services' AWS Construct Library support is in more than one module\. For example, Amazon Route 53 has the three modules in addition to the main `Amazon.CDK.AWS.Route53` module, named `Route53.Patterns`, `Route53rResolver`, and `Route53.Targets`\. + +The AWS CDK's core module, which you'll need in most AWS CDK apps, is imported in C\# code as `Amazon.CDK`\. Modules for the various services in the AWS Construct Library live under `Amazon.CDK.AWS` and are named similarly to their NuGet package name\. For example, the Amazon S3 module's namespace is `Amazon.CDK.AWS.S3`\. + +We recommend writing a single C\# `using` directive for each AWS Construct Library module you use in each of your C\# source files\. You may find it convenient to use an alias for a namespace or type to help resolve name conflicts\. You can always use a type's fully\-qualfiied name \(including its namespace\) without a `using` statement\. + +**Important** All AWS Construct Library modules used in your project must be the same version\. NuGet has four standard, mostly\-equivalent interfaces; you can use the one that suits your needs and working style\. You can also use compatible tools, such as [Paket](https://fsprojects.github.io/Paket/) or [MyGet](https://fsprojects.github.io/Paket/)\. @@ -51,7 +57,7 @@ All AWS Construct Library modules deemed "experimental" \(see [Versioning](refer ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/visual-studio-nuget.png) -Look in the **Updates** panel to install new versions of your packages\. +Look on the **Updates** page to install new versions of your packages\. ### The NuGet console diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 076b57a5..7a95c6e2 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -1,6 +1,6 @@ # Working with the AWS CDK in Java -Java is a fully\-supported client platform for the AWS CDK and is considered stable\. You can develop AWS CDK applications in Java using familiar tools, including the JDK \(Oracle's, or an OpenJDK distribution such as Amazon Corretto\) and Apache Maven\. The modules comprising the AWS Construct Library are distributed via the [Maven Central Repository](https://search.maven.org/search?q=software.amazon.awscdk)\. +Java is a fully\-supported client platform for the AWS CDK and is considered stable\. You can develop AWS CDK applications in Java using familiar tools, including the JDK \(Oracle's, or an OpenJDK distribution such as Amazon Corretto\) and Apache Maven\. The modules comprising the AWS Construct Library are distributed via the [Maven Central Repository](https://search.maven.org/search?q=g:software.amazon.awscdk)\. You can use any text editor, or a Java IDE that can read Maven projects, to work on your AWS CDK apps\. We provide [Eclipse](https://www.eclipse.org/downloads/) hints in this Guide, but IntelliJ IDEA, NetBeans, and other IDEs can import Maven projects and will work fine for developing AWS CDK applications in Java\. @@ -28,11 +28,17 @@ The resulting project includes a reference to the `software.amazon.awscdk.core` If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set to use Java 8 \(1\.8\)\. -## Managing AWS construct library modules +## Managing AWS Construct Library modules -Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk` and named for their service\. For example, the Maven artifact ID for Amazon S3 is `s3`\. Its Java package name, for use in import statements, is `software.amazon.awscdk.services.s3`\. [Search the Maven Central Repository](https://search.maven.org/search?q=software.amazon.awscdk) to find the names of all AWS Construct Module libraries\. +Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk` and named with a short version \(no AWS or Amazon prefix\) of their service's name\. For example, the Maven artifact ID for Amazon S3 is `s3`\. [Search the Maven Central Repository](https://search.maven.org/search?q=sg:oftware.amazon.awscdk) to find the names of all AWS CDK and AWS Construct Module libraries\. -**Note** +Some services' AWS Construct Library support is in more than one module\. For example, Amazon Route 53 has the three modules in addition to the main `software.amazon.awscdk.route53` module, named `route53-patterns`, `route53resolver`, and `route53-targets`\. + +The AWS CDK's core module, which you'll need in most AWS CDK apps, is imported in Java code as `software.amazon.awscdk.core`\. Modules for the various services in the AWS Construct Library live under `software.amazon.awscdk.services` and are named similarly to their Maven package name\. For example, the Amazon S3 module's namespace is `software.amazon.awscdk.services.s3`\. + +We recommend writing a separate Java `import` statement for each AWS Construct Library class you use in each of your Java source files, and avoiding wildcard imports\. You can always use a type's fully\-qualified name \(including its namespace\) without an `import` statement\. + +**Important** All AWS Construct Library modules used in your project must be the same version\. Specify the modules that your application depends on by editing `pom.xml` and adding a new `` element in the `` container\. For example, the following `` element specifies the Amazon S3 construct library module: @@ -46,9 +52,9 @@ Specify the modules that your application depends on by editing `pom.xml` and ad ``` **Tip** -If you use a Java IDE, it probably has features for managing Maven dependencies\. We recommend always editing `pom.xml` directly, however, unless you are absolutely sure the IDE's functionality matches what you'd do by hand\. +If you use a Java IDE, it probably has features for managing Maven dependencies\. We recommend editing `pom.xml` directly, however, unless you are absolutely sure the IDE's functionality matches what you'd do by hand\. -The default `pom.xml` defines the variable `cdk.version` to be the version of the AWS CDK that created the project\. You can easily update the version required by updating the value of this variable, while keeping all module versions in sync\. +The default `pom.xml` defines the variable `cdk.version` to be the version of the AWS CDK that created the project\. You can easily update the version required by updating the value of this variable, which keeps all AWS Construct Library module versions in sync\. ``` 1.XX.Y diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index e185cc19..84670023 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -24,23 +24,43 @@ Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest `cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. -## Managing AWS construct library modules +## Managing AWS Construct Library modules Use the Node Package Manager \(`npm`\), included with Node\.js, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. -AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. +The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an *aws\-* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. ``` npm install @aws-cdk/aws-s3 @aws-cdk/aws-lambda ``` -Your project's dependencies are maintained in `package.json`\. You can edit this file to lock some or all of your dependencies to a specific version or to allow them to be updated to newer versions under certain criteria\. To update your project's dependencies: +Some services' Construct Library support is in more than one module\. For example, besides the `@aws-cdk/aws-route53` module, there are three additional Amazon Route 53 modules, named `aws-route53-targets`, `aws-route53-patterns`, and `aws-route53resolver`\. + +Your project's dependencies are maintained in `package.json`\. You can edit this file to lock some or all of your dependencies to a specific version or to allow them to be updated to newer versions under certain criteria\. To update your project's NPM dependencies to the latest permitted version according to the rules you specified in `package.json`: ``` npm update ``` -**Note** +In JavaScript, you import modules into your code under the same name you use to install them using NPM\. We recommend the following practices when importing AWS CDK classes and AWS Construct Library modules in your applications\. Following these guidelines will help make your code consistent with other AWS CDK applications as well as easier to understand\. ++ Use `require()`, not ES6\-style `import` directives\. Most of the versions of Node\.js that the AWS CDK runs on do not support ES6 imports, so using the older syntax is more widely compatible\. \(If you really want to use ES6 imports, use [esm](https://www.npmjs.com/package/esm) to ensure your project is compatible with all supported versions of Node\.js\.\) more widely compatible\. ++ Generally, import individual classes from `@aws-cdk/core`\. + + ``` + const { App, Construct } = require('@aws-cdk/core'); + ``` ++ If you need many classes from the core module, you may use a namespace alias of `cdk` instead of importing the individual classes\. Avoid doing both\. + + ``` + const cdk = require('@aws-cdk/core'); + ``` ++ Generally, import AWS Construct Libraries using short namespace aliases\. + + ``` + const s3 = require('@aws-cdk/aws-s3'); + ``` + +**Important** All AWS Construct Library modules used in your project must be the same version\. ## AWS CDK idioms in JavaScript diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index bb6d9721..dc38fb23 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -21,7 +21,7 @@ python -m pip install --upgrade virtualenv If you encounter a permission error, run the above commands with the `--user` flag so that the modules are installed in your user directory, or use `sudo` to obtain the permissions to install the modules system\-wide\. **Note** -It is common for Linux distros to use the executable name `python3` for Python 3\.x, and have `python` refer to a Python 2\.x installation\. You can adjust the command used to run your application by editing `cdk.json` in the project's main directory\. +It is common for Linux distros to use the executable name `python3` for Python 3\.x, and have `python` refer to a Python 2\.x installation\. Some distros have an optional package you can install that makes the `python` command refer to Python 3\. Failing that, you can adjust the command used to run your application by editing `cdk.json` in the project's main directory\. ## Creating a project @@ -53,27 +53,46 @@ python -m pip install -r requirements.txt **Important** Activate the project's virtual environment whenever you start working on it\. Otherwise, you won't have access to the modules installed there, and modules you install will go in the Python global module directory \(or will result in a permission error\)\. -## Managing AWS construct library modules +## Managing AWS Construct Library modules -Use the Python package installer, `pip`, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. `pip` also installs the dependencies for those modules automatically\. To run `pip` without needing it installed in a special directory, invoke it as: +Use the Python package installer, pip, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. pip also installs the dependencies for those modules automatically\. If your system does not recognize pip as a standalone command, invoke pip as a Python module, like this: ``` python -m pip PIP-COMMAND ``` -AWS Construct Library modules are named like `aws-cdk.SERVICE-NAME`\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. +The AWS CDK core module is named `aws-cdk.core`\. AWS Construct Library modules are named like `aws-cdk.SERVICE-NAME`\. The service name includes an *aws* prefix\. If you're unsure of a module's name, [search for it at PyPI](https://pypi.org/search/?q=aws-cdk)\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. ``` python -m pip install aws-cdk.aws-s3 aws-cdk.aws-lambda ``` -Similar names are used for importing AWS Construct Library modules into your Python code \(just replace the hyphens with underscores\)\. +Some services' Construct Library support is in more than one module\. For example, besides the `aws-cdk.aws-route53` module, there are three additional Amazon Route 53 modules, named `aws-route53-targets`, `aws-route53-patterns`, and `aws-route53resolver`\. + +The names used for importing AWS Construct Library modules into your Python code are similar to their package names\. Simply replace the hyphens with underscores\. ``` import aws_cdk.aws_s3 as s3 -import aws_cdk.aws_lambda as lam +import aws_cdk.aws_lambda as lambda_ ``` +We recommend the following practices when importing AWS CDK classes and AWS Construct Library modules in your applications\. Following these guidelines will help make your code consistent with other AWS CDK applications as well as easier to understand\. ++ Generally, import individual classes from `aws_cdk.core`\. + + ``` + from aws_cdk.core import App, Construct + ``` ++ If you need many classes from the core module, you may use a namespace alias of `cdk` instead of importing individual classes\. Avoid doing both\. + + ``` + import aws_cdk.core as cdk + ``` ++ Generally, import AWS Construct Libraries using short namespace aliases\. + + ``` + import aws_cdk.aws_s3 as s3 + ``` + After installing a module, update your project's `requirements.txt` file, which lists your project's dependencies\. It is best to do this manually rather than using `pip freeze`\. `pip freeze` captures the current versions of all modules installed in your Python virtual environment, which can be useful when bundling up a project to be run elsewhere\. Usually, though, your `requirements.txt` should list only top\-level dependencies \(modules that your app depends on directly\) and not the dependencies of those modules\. This strategy makes updating your dependencies simpler\. Here is what your `requirements.txt` file might look like if you have installed the Amazon S3 and AWS Lambda modules as shown earlier\. @@ -91,7 +110,7 @@ With `requirements.txt` edited appropriately to allow upgrades, issue this comma pip install --upgrade -r requirements.txt ``` -**Note** +**Important** All AWS Construct Library modules used in your project must be the same version\. ## AWS CDK idioms in Python @@ -100,7 +119,7 @@ All AWS Construct Library modules used in your project must be the same version\ In Python, `lambda` is a language keyword, so you cannot use it as a name for the AWS Lambda construct library module or Lambda functions\. The Python convention for such conflicts is to use a trailing underscore, as in `lambda_`, in the variable name\. -By convention, the second argument to AWS CDK constructs is named `id`\. When writing your own stacks and constructs, calling a parameter `id` "shadows" the Python built\-in function `id()`, which gets an object's unique identifier\. This function isn't used very often, but if you should happen to need it in your construct, rename the argument, for example `id_`, or else call the built\-in function as `__builtins__.id()`\. +By convention, the second argument to AWS CDK constructs is named `id`\. When writing your own stacks and constructs, calling a parameter `id` "shadows" the Python built\-in function `id()`, which returns an object's unique identifier\. This function isn't used very often, but if you should happen to need it in your construct, rename the argument, for example `id_`, or else call the built\-in function as `__builtins__.id()`\. ### Props @@ -123,6 +142,13 @@ bucket.add_lifecycle_rule( When extending a class or overriding a method, you may want to accept additional arguments for your own purposes that are not understood by the parent class\. In this case you should accept the arguments you don't care about using the `**kwargs` idiom, and use keyword\-only arguments to accept the arguments you're interested in\. When calling the parent's constructor or the overridden method, pass only the arguments it is expecting \(often just `**kwargs`\)\. Passing arguments that the parent class or method doesn't expect results in an error\. +``` +class MyConstruct(Construct): + def __init__(self, id, *, MyProperty=42, **kwargs): + super().__init__(self, id, **kwargs) + # ... +``` + Future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues for users of your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion\. You can avoid this potential problem by naming your properties so they clearly belong to your construct\. If there are many new properties, bundle them into an appropriately\-named class and pass it as a single keyword argument\. ### Missing values diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index a4d5a0da..07714159 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -14,6 +14,9 @@ You also need TypeScript itself\. If you don't already have it, you can install npm install -g typescript ``` +**Note** +If you get a permission error, and have administrator access on your system, try `sudo npm install -g typescript`\. + Keep TypeScript up to date with a regular `npm update -g typescript`\. ## Creating a project @@ -30,23 +33,43 @@ Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest `cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. -## Managing AWS construct library modules +## Managing AWS Construct Library modules Use the Node Package Manager \(`npm`\), included with Node\.js, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. -AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. +The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an * a* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. ``` npm install @aws-cdk/aws-s3 @aws-cdk/aws-lambda ``` -Your project's dependencies are maintained in `package.json`\. You can edit this file to lock some or all of your dependencies to a specific version or to allow them to be updated to newer versions under certain criteria\. To update your project's dependencies: +Some services' Construct Library support is in more than one module\. For example, besides the `@aws-cdk/aws-route53` module, there are three additional Amazon Route 53 modules, named `aws-route53-targets`, `aws-route53-patterns`, and `aws-route53resolver`\. + +Your project's dependencies are maintained in `package.json`\. You can edit this file to lock some or all of your dependencies to a specific version or to allow them to be updated to newer versions under certain criteria\. To update your project's NPM dependencies to the latest permitted version according to the rules you specified in `package.json`: ``` npm update ``` -**Note** +In TypeScript, you import modules into your code under the same name you use to install them using NPM\. We recommend the following practices when importing AWS CDK classes and AWS Construct Library modules in your applications\. Following these guidelines will help make your code consistent with other AWS CDK applications as well as easier to understand\. ++ Use ES6\-style `import` directives, not `require()`\. ++ Generally, import individual classes from `@aws-cdk/core`\. + + ``` + import { App, Construct } from '@aws-cdk/core'; + ``` ++ If you need many classes from the core module, you may use a namespace alias of `cdk` instead of importing the individual classes\. Avoid doing both\. + + ``` + import * as cdk from '@aws-cdk/core'; + ``` ++ Generally, import AWS Construct Libraries using short namespace aliases\. + + ``` + import * as s3 from '@aws-cdk/aws-s3'; + ``` + +**Important** All AWS Construct Library modules used in your project must be the same version\. ## AWS CDK idioms in TypeScript diff --git a/doc_source/work-with.md b/doc_source/work-with.md index 72015252..c6243475 100644 --- a/doc_source/work-with.md +++ b/doc_source/work-with.md @@ -22,6 +22,9 @@ After installing Node\.js, install the AWS CDK Toolkit \(the `cdk` command\): npm install -g aws-cdk ``` +**Note** +If you get a permission error, and have administrator access on your system, try `sudo npm install -g aws-cdk`\. + Test the installation by issuing `cdk --version`\. The specific language you work in also has its own prerequisites, described in the corresponding topic listed here\. From 328c9c2ce4e9819fbd3bc03298f28bc462d41ed7 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 16 Sep 2020 22:15:04 +0000 Subject: [PATCH 292/655] typo --- doc_source/environments.md | 2 +- doc_source/home.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index 2db21c6c..7c8e90c3 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -3,7 +3,7 @@ Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and region into which the stack is intended to be deployed\. **Note** -For all but the simplest deployments, you will need to [bootstrap](bootstrapping.md) each environment you will deploy into\. Deployment requires certain AWS resources to be availeble, and these resources are provisined by bootstrapping\. +For all but the simplest deployments, you will need to [bootstrap](bootstrapping.md) each environment you will deploy into\. Deployment requires certain AWS resources to be available, and these resources are provisined by bootstrapping\. If you don't specify an environment when you define a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availablityZones` \(Python: `availability_zones`\)\. diff --git a/doc_source/home.md b/doc_source/home.md index 1244fe98..79a51554 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -221,7 +221,7 @@ There is no charge for using the AWS CDK, but you might incur AWS charges for cr ## Contributing to the AWS CDK -Because the AWS CDK is open source, the team encourages you contribute to make it an even better tool\. For details, see [Contributing](https://github.com/awslabs/aws-cdk/blob/master/CONTRIBUTING.md)\. +Because the AWS CDK is open source, the team encourages you to contribute to make it an even better tool\. For details, see [Contributing](https://github.com/awslabs/aws-cdk/blob/master/CONTRIBUTING.md)\. ## Additional documentation and resources From 548b949ed1b74a0d5ce37ce1931906956af9663e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 17 Sep 2020 14:41:31 +0000 Subject: [PATCH 293/655] further tweaks to module management --- doc_source/cli.md | 26 +++++++++++++------------- doc_source/work-with-cdk-csharp.md | 7 +++++-- doc_source/work-with-cdk-java.md | 3 +++ doc_source/work-with-cdk-javascript.md | 9 +++++++-- doc_source/work-with-cdk-typescript.md | 7 ++++++- 5 files changed, 34 insertions(+), 18 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 98728c74..145a45fb 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -259,7 +259,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -278,7 +278,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -286,7 +286,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth –json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -310,7 +310,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -332,7 +332,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. @@ -507,7 +507,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -520,7 +520,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -533,7 +533,7 @@ Options: dependencies [boolean] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -572,7 +572,7 @@ Options: [boolean] [default: false] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -614,7 +614,7 @@ Options: disabled) [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -630,7 +630,7 @@ Options: [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -650,7 +650,7 @@ Options: [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -673,7 +673,7 @@ Options: [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 345aec21..90faf17f 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -35,11 +35,14 @@ The resulting project includes a reference to the `Amazon.CDK` NuGet package\. I ## Managing AWS Construct Library modules -The \.NET ecosystem uses the NuGet package manager\. AWS Construct Library modules are named like `Amazon.CDK.AWS.SERVICE-NAME` where the service name is a short name without an AWS or Amazon prefix\. For example, the NuGet package name for the Amazon S3 module is `Amazon.CDK.AWS.S3`\. +The \.NET ecosystem uses the NuGet package manager\. AWS Construct Library modules are named like `Amazon.CDK.AWS.SERVICE-NAME` where the service name is a short name without an AWS or Amazon prefix\. For example, the NuGet package name for the Amazon S3 module is `Amazon.CDK.AWS.S3`\. If you can't find a package you want, [search Nuget\.org](https://www.nuget.org/packages?q=amazon.cdk.aws)\. + +**Note** +The [\.NET edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/dotnet/api/index.html) also shows the package names\. Some services' AWS Construct Library support is in more than one module\. For example, Amazon Route 53 has the three modules in addition to the main `Amazon.CDK.AWS.Route53` module, named `Route53.Patterns`, `Route53rResolver`, and `Route53.Targets`\. -The AWS CDK's core module, which you'll need in most AWS CDK apps, is imported in C\# code as `Amazon.CDK`\. Modules for the various services in the AWS Construct Library live under `Amazon.CDK.AWS` and are named similarly to their NuGet package name\. For example, the Amazon S3 module's namespace is `Amazon.CDK.AWS.S3`\. +The AWS CDK's core module, which you'll need in most AWS CDK apps, is imported in C\# code as `Amazon.CDK`\. Modules for the various services in the AWS Construct Library live under `Amazon.CDK.AWS` and are named the same as their NuGet package name\. For example, the Amazon S3 module's namespace is `Amazon.CDK.AWS.S3`\. We recommend writing a single C\# `using` directive for each AWS Construct Library module you use in each of your C\# source files\. You may find it convenient to use an alias for a namespace or type to help resolve name conflicts\. You can always use a type's fully\-qualfiied name \(including its namespace\) without a `using` statement\. diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 7a95c6e2..068648e6 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -32,6 +32,9 @@ If you are using an IDE, you can now open or import the project\. In Eclipse, fo Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk` and named with a short version \(no AWS or Amazon prefix\) of their service's name\. For example, the Maven artifact ID for Amazon S3 is `s3`\. [Search the Maven Central Repository](https://search.maven.org/search?q=sg:oftware.amazon.awscdk) to find the names of all AWS CDK and AWS Construct Module libraries\. +**Note** +The [Java edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/java/index.html) also shows the package names\. + Some services' AWS Construct Library support is in more than one module\. For example, Amazon Route 53 has the three modules in addition to the main `software.amazon.awscdk.route53` module, named `route53-patterns`, `route53resolver`, and `route53-targets`\. The AWS CDK's core module, which you'll need in most AWS CDK apps, is imported in Java code as `software.amazon.awscdk.core`\. Modules for the various services in the AWS Construct Library live under `software.amazon.awscdk.services` and are named similarly to their Maven package name\. For example, the Amazon S3 module's namespace is `software.amazon.awscdk.services.s3`\. diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 84670023..3e02d13d 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -28,7 +28,12 @@ Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest Use the Node Package Manager \(`npm`\), included with Node\.js, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. -The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an *aws\-* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. +The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an *aws\-* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. + +**Note** +The [CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) also shows the package names\. + +For example, the command below installs the modules for Amazon S3 and AWS Lambda\. ``` npm install @aws-cdk/aws-s3 @aws-cdk/aws-lambda @@ -43,7 +48,7 @@ npm update ``` In JavaScript, you import modules into your code under the same name you use to install them using NPM\. We recommend the following practices when importing AWS CDK classes and AWS Construct Library modules in your applications\. Following these guidelines will help make your code consistent with other AWS CDK applications as well as easier to understand\. -+ Use `require()`, not ES6\-style `import` directives\. Most of the versions of Node\.js that the AWS CDK runs on do not support ES6 imports, so using the older syntax is more widely compatible\. \(If you really want to use ES6 imports, use [esm](https://www.npmjs.com/package/esm) to ensure your project is compatible with all supported versions of Node\.js\.\) more widely compatible\. ++ Use `require()`, not ES6\-style `import` directives\. Most of the versions of Node\.js that the AWS CDK runs on do not support ES6 imports, so using the older syntax is more widely compatible\. \(If you really want to use ES6 imports, use [esm](https://www.npmjs.com/package/esm) to ensure your project is compatible with all supported versions of Node\.js\.\) + Generally, import individual classes from `@aws-cdk/core`\. ``` diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index 07714159..d1fd5120 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -37,7 +37,12 @@ Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest Use the Node Package Manager \(`npm`\), included with Node\.js, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. -The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an * a* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. +The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an * a* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. + +**Note** +The [CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) also shows the package names\. + +For example, the command below installs the modules for Amazon S3 and AWS Lambda\. ``` npm install @aws-cdk/aws-s3 @aws-cdk/aws-lambda From fe7f3b4bb139bbc366a49fdc0702ca5358c42014 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 18 Sep 2020 20:17:21 +0000 Subject: [PATCH 294/655] update CDK help --- doc_source/cli.md | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 145a45fb..05000849 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -554,7 +554,7 @@ Options: --public-access-block-configuration Block public access configuration on CDK toolkit bucket (enabled by - default) [boolean] [default: true] + default) [boolean] --tags, -t Tags to add for the stack (KEY=VALUE) [array] [default: []] @@ -569,7 +569,18 @@ Options: --termination-protection Toggle CloudFormation termination protection on the bootstrap stacks - [boolean] [default: false] + [boolean] + + --show-template Instead of actual bootstrapping, + print the current CLI's + bootstrapping template to stdout for + customization. + [boolean] [default: false] + + --template Use the template from the given file + instead of the built-in one (use + --show-template to obtain an + example). [string] ``` ### `cdk deploy` @@ -595,7 +606,8 @@ Options: --notification-arns ARNs of SNS topics that CloudFormation will notify with stack related events [array] - --tags, -t Tags to add to the stack (KEY=VALUE) [array] + --tags, -t Tags to add to the stack (KEY=VALUE), overrides tags + from Cloud Assembly [array] --execute Whether to execute ChangeSet (--no-execute will NOT execute the ChangeSet) [boolean] [default: true] @@ -611,7 +623,10 @@ Options: --previous-parameters Use previous values for existing parameters (you must specify all parameters on every deployment if this is - disabled) [boolean] [default: true] + disabled) [boolean] [default: true] + + --progress Display mode for stack activity events. + [string] [choices: "bar", "events"] ``` ### `cdk destroy` From 8a7a4eb9f8cb60771473230441b10c4a536f5061 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 21 Sep 2020 15:34:26 +0000 Subject: [PATCH 295/655] link to AWS Solutions Constructs --- doc_source/cli.md | 26 +++++++++++++------------- doc_source/home.md | 1 + 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 05000849..7eaa2f7c 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -259,7 +259,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -278,7 +278,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -286,7 +286,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth –json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -310,7 +310,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -332,7 +332,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. @@ -507,7 +507,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -520,7 +520,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -533,7 +533,7 @@ Options: dependencies [boolean] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -583,7 +583,7 @@ Options: example). [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -629,7 +629,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -645,7 +645,7 @@ Options: [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -665,7 +665,7 @@ Options: [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -688,7 +688,7 @@ Options: [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/home.md b/doc_source/home.md index 79a51554..9baf542d 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -229,6 +229,7 @@ In addition to this guide, the following are other resources available to AWS CD + [API Reference](https://docs.aws.amazon.com/cdk/api/latest) + [AWS CDK Workshop](https://cdkworkshop.com/) + [AWS CDK Examples](https://github.com/aws-samples/aws-cdk-examples) ++ [AWS Solutions Constructs](http://aws.amazon.com/solutions/constructs/) + [AWS Developer Blog](https://aws.amazon.com/blogs/developer) + [Gitter Channel](https://gitter.im/awslabs/aws-cdk) + [Stack Overflow](https://stackoverflow.com/questions/tagged/aws-cdk) From f98955dcf19959fdb537e1389c6d6e3833840c98 Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Mon, 21 Sep 2020 12:04:26 -0700 Subject: [PATCH 296/655] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 652e671c..b5caa99e 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,7 @@ # Welcome to the AWS CDK Developer Guide This is the GitHub repository for the [AWS CDK Developer Guide](https://docs.aws.amazon.com/cdk/latest/guide/home.html). -You're welcome to [report issues](https://github.com/awsdocs/aws-cdk-guide/issues/new) with the documentation here or, if you have a moment, to submit a Pull Request with your -suggested changes. +You're welcome to [report issues](https://github.com/awsdocs/aws-cdk-guide/issues/new) with the documentation here or, if you have a moment, to submit a Pull Request with your suggested changes. PRs should target the main branch, not master, which has been deprecated. Issues reported through the Feedback link at the bottom of the individual pages of the AWS CDK Developer Guide go to an internal Amazon issue tracker and may not appear here. However, we try to track most substantive AWS CDK Developer Guide work on GitHub From cb4202eee0ec96b9f7cbd7f701f22699aa7b7b8a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 5 Oct 2020 20:46:09 +0000 Subject: [PATCH 297/655] update resources; add new section on construct tree --- doc_source/cli.md | 26 +++++++++++----------- doc_source/constructs.md | 48 +++++++++++++++++++++++++++++++--------- doc_source/home.md | 4 +++- 3 files changed, 54 insertions(+), 24 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 7eaa2f7c..63a95949 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -259,7 +259,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -278,7 +278,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -286,7 +286,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth –json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -310,7 +310,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -332,7 +332,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. @@ -507,7 +507,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -520,7 +520,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -533,7 +533,7 @@ Options: dependencies [boolean] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -583,7 +583,7 @@ Options: example). [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -629,7 +629,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -645,7 +645,7 @@ Options: [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -665,7 +665,7 @@ Options: [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -688,7 +688,7 @@ Options: [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 3f587574..69cb5b3c 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -2,7 +2,7 @@ Constructs are the basic building blocks of AWS CDK apps\. A construct represents a "cloud component" and encapsulates everything AWS CloudFormation needs to create the component\. -A construct can represent a single resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can represent a higher\-level component consisting of multiple AWS CDK resources\. Examples of such components include a worker queue with its associated compute capacity, a cron job with monitoring resources and a dashboard, or even an entire app spanning multiple AWS accounts and regions\. +A construct can represent a single resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can represent a higher\-level component consisting of multiple AWS resources\. Examples of such components include a worker queue with its associated compute capacity, a cron job with monitoring resources and a dashboard, or even an entire app spanning multiple AWS accounts and regions\. ## AWS Construct library @@ -10,7 +10,7 @@ The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html)` class represents an Amazon DynamoDB table\. -There are different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "level 1"\)\. These constructs directly represent all of the AWS resources that are available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [s3\.CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) CFN Resource\. When you use CFN resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. +There are different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "level 1"\) or Cfn resources\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#add-wbr-lifecycle-wbr-rulerule), which adds a lifecycle rule to the bucket\. @@ -20,16 +20,16 @@ For more information about how to navigate the library and discover constructs t ## Composition -The key pattern for defining higher\-level abstractions through constructs is called *composition*\. A high\-level construct can be composed from any number of lower\-level constructs, and in turn, those could be composed from even lower\-level constructs\. To enable this pattern, constructs are always defined within the scope of another construct\. This scoping pattern results in a hierarchy of constructs known as a *construct tree*\. In the AWS CDK, the root of the tree represents your entire **[AWS CDK app](apps.md)**\. Within the app, you typically define one or more **[stacks](stacks.md)**, which are the unit of deployment, analogous to AWS CloudFormation stacks\. Within stacks, you define resources, or other constructs that eventually contain resources\. +*Composition* is the key pattern for defining higher\-level abstractions through constructs\. A high\-level construct can be composed from any number of lower\-level constructs, and in turn, those could be composed from even lower\-level constructs, which eventually are composed from AWS resources\. From a bottom\-up perspective, you use constructs to organize the individual AWS resources you want to deploy using whatever abstractions are convenient for your purpose, with as many layers as you need\. -Composition of constructs means that you can define reusable components and share them like any other code\. For example, a central team can define a construct that implements the company's best practice for a DynamoDB table with backup, global replication, auto\-scaling, and monitoring, and share it with teams across a company or publicly\. Teams can now use this construct as they would any other library package in their favorite programming language to define their tables and comply with their team's best practices\. When the library is updated, developers can pick up the updates and enjoy any bug fixes and improvements through the workflows they already have for their other types of code\. +Composition lets you define reusable components and share them like any other code\. For example, a team can define a construct that implements the company's best practice for a DynamoDB table with backup, global replication, auto\-scaling, and monitoring, and share it with other teams in their organization, or publicly\. Teams can now use this construct as they would any other library package in their preferred programming language to define their tables and comply with their team's best practices\. When the library is updated, developers will get access to the new version's bug fixes and improvements through the workflows they already have for their other types of code\. ## Initialization Constructs are implemented in classes that extend the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html) base class\. You define a construct by instantiating the class\. All constructs take three parameters when they are initialized: -+ **Scope** – The construct within which this construct is defined\. You should almost always pass `this` for the scope, because it represents the current scope in which you are defining the construct\. -+ **id** – An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's encapsulated within the scope's subtree and is used to allocate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. -+ **Props** – A set of properties or keyword arguments, depending upon the supported language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. ++ **Scope** – The construct within which this construct is defined\. You should usually pass `this` for the scope, because it represents the current scope in which you are defining the construct\. ++ **id** – An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to allocate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. ++ **Props** – A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html) or for specifying where the constructs will be deployed\. @@ -628,9 +628,9 @@ var createJobLambda = new Function(this, "create-job", new FunctionProps For information about the most common API patterns in the AWS Construct Library, see [Resources](resources.md)\. -## Authoring constructs +## Writing your own constructs -In addition to using existing constructs like `s3.Bucket`, you can also author your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct imported from a third\-party library that someone published on npm or Maven or PyPI—or to your company's internal package repository\. +In addition to using existing constructs like `s3.Bucket`, you can also write your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct imported from a third\-party library that someone published via NPM or Maven or PyPI—or to your company's internal package repository\. To declare a new construct, create a class that extends the [Construct](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html) base class, then follow the pattern for initializer arguments\. @@ -974,4 +974,32 @@ var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketP images.topic.AddSubscription(new SqsSubscription(queue)); ``` ------- \ No newline at end of file +------ + +## The construct tree + +As we've already seen, in AWS CDK apps, you define constructs "inside" other constructs using the `scope` argument passed to every construct\. In this way, an AWS CDK app defines a hierarchy of constructs known as the *construct tree*\. + +The root of this tree is your app—that is, an instance of the `App` class\. Within the app, you instantiate one or more stacks\. Within stacks, you instantiate either AWS CloudFormation resources or higher\-level constructs, which may themselves instantiate resources or other constructs, and so on down the tree\. + +Constructs are *always* explicitly defined within the scope of another construct, so there is never any doubt about the relationships between constructs\. Almost always, you should pass `this` \(in Python, `self`\) as the scope, indicating that the new construct is a child of the current construct\. The intended pattern is that you derive your construct from [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html), then instantiate the constructs it uses in its constructor\. + +Passing the scope explicitly allows each construct to add itself to the tree, with this behavior entirely contained within the [`Construct` base class](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html)\. It works the same way in every language supported by the AWS CDK and does not require introspection or other "magic\." + +**Important** +Technically, it's possible to pass some scope other than `this` when instantiating a construct, which allows you to add constructs anywhere in the tree, even in another stack entirely\. For example, you could write a mixin\-style function that adds constructs to a scope passed in as an argument\. The practical difficulty here is that it you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope\. The practice also makes your code more difficult to understand, maintain, and reuse\. It is virtually always better to find a way to express your intent without resorting to abusing the `scope` argument\. + +The AWS CDK uses the IDs of all constructs in the path from the tree's root to each child construct to generate the unique IDs required by AWS CloudFormation\. This approach means that construct IDs need be unique only within their scope, rather than within the entire stack as in native AWS CloudFormation\. It does, however, mean that if you move a construct to a different scope, its generated stack\-unique ID will change, and AWS CloudFormation will no longer consider it the same resource\. + +The construct tree is separate from the constructs you define in your AWS CDK code, but it is accessible through any construct's `node` attribute, which is a reference to the node that represents that construct in the tree\. Each node is a [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.ConstructNode.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.ConstructNode.html) instance, the attributes of which provide access to the tree's root and to the node's parent scopes and children\. ++ `node.children` – The direct children of the construct\. ++ `node.id` – The identifier of the construct within its scope\. ++ `node.path` – The full path of the construct including the IDs of all of its parents\. ++ `node.root` – The root of the construct tree \(the app\)\. ++ `node.scope` – The scope \(parent\) of the construct, or undefined if the node is the root\. ++ `node.scopes` – All parents of the construct, up to the root\. ++ `node.uniqueId` – The unique alphanumeric identifier for this construct within the tree \(by default, generated from `node.path` and a hash\)\. + +The construct tree defines an implicit order in which constructs are synthesized to resources in the final AWS CloudFormation template: depth\-first traversal of the scopes, and in order of construct instantiation within each scope\. Where one resource must be created before another, AWS CloudFormation or the AWS Construct Library will generally infer the dependency and make sure the resources are created in the right order\. You can also add an explicit dependency between two nodes using `node.addDependency()`; see [Dependencies](https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html#dependencies) in the AWS CDK API Reference\. + +The AWS CDK provides a simple way to visit every node in the construct tree and perform an operation on each one\. See [Aspects](aspects.md)\. \ No newline at end of file diff --git a/doc_source/home.md b/doc_source/home.md index 9baf542d..02491ebf 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -228,10 +228,12 @@ Because the AWS CDK is open source, the team encourages you to contribute to mak In addition to this guide, the following are other resources available to AWS CDK users: + [API Reference](https://docs.aws.amazon.com/cdk/api/latest) + [AWS CDK Workshop](https://cdkworkshop.com/) ++ [cdk\.dev](https://cdk.dev/) community hub, including a Slack channel + [AWS CDK Examples](https://github.com/aws-samples/aws-cdk-examples) ++ [CDK Patterns](https://cdkpatterns.com/) ++ [Awesome CDK](https://github.com/kolomied/awesome-cdk) + [AWS Solutions Constructs](http://aws.amazon.com/solutions/constructs/) + [AWS Developer Blog](https://aws.amazon.com/blogs/developer) -+ [Gitter Channel](https://gitter.im/awslabs/aws-cdk) + [Stack Overflow](https://stackoverflow.com/questions/tagged/aws-cdk) + [GitHub Repository](https://github.com/awslabs/aws-cdk) + [Issues](https://github.com/awslabs/aws-cdk/issues) From 62c7066a2d0dceb39a4197246f9e465d8be2edf6 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 8 Oct 2020 17:14:01 +0000 Subject: [PATCH 298/655] tweak --- doc_source/constructs.md | 2 +- doc_source/stack_how_to_create_multiple_stacks.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 69cb5b3c..f1cbfceb 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -1000,6 +1000,6 @@ The construct tree is separate from the constructs you define in your AWS CDK co + `node.scopes` – All parents of the construct, up to the root\. + `node.uniqueId` – The unique alphanumeric identifier for this construct within the tree \(by default, generated from `node.path` and a hash\)\. -The construct tree defines an implicit order in which constructs are synthesized to resources in the final AWS CloudFormation template: depth\-first traversal of the scopes, and in order of construct instantiation within each scope\. Where one resource must be created before another, AWS CloudFormation or the AWS Construct Library will generally infer the dependency and make sure the resources are created in the right order\. You can also add an explicit dependency between two nodes using `node.addDependency()`; see [Dependencies](https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html#dependencies) in the AWS CDK API Reference\. +The construct tree defines an implicit order in which constructs are synthesized to resources in the final AWS CloudFormation template\. Where one resource must be created before another, AWS CloudFormation or the AWS Construct Library will generally infer the dependency and make sure the resources are created in the right order\. You can also add an explicit dependency between two nodes using `node.addDependency()`; see [Dependencies](https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html#dependencies) in the AWS CDK API Reference\. The AWS CDK provides a simple way to visit every node in the construct tree and perform an operation on each one\. See [Aspects](aspects.md)\. \ No newline at end of file diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index ca6661b2..ec05d6e2 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -35,7 +35,7 @@ cdk init --language=javascript mkdir multistack cd multistack cdk init --language=python -source ./env/bin/activate +source .env/bin/activate pip install -r requirements.txt ``` From 701ea95a821d444be628774a7baa86dd72844b44 Mon Sep 17 00:00:00 2001 From: Daniel Lorch Date: Sun, 11 Oct 2020 15:18:14 +0200 Subject: [PATCH 299/655] Fix link --- doc_source/home.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/home.md b/doc_source/home.md index 02491ebf..b60eff86 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -176,7 +176,7 @@ public class MyEcsConstructStack : Stack ------ -This class produces an AWS CloudFormation [template of more than 500 lines](https://github.com/awsdocs/aws-cdk-guide/blob/master/doc_source/my_ecs_construct-stack.yaml); deploying the AWS CDK app produces more than 50 resources of the following types\. +This class produces an AWS CloudFormation [template of more than 500 lines](https://github.com/awsdocs/aws-cdk-guide/blob/main/doc_source/my_ecs_construct-stack.yaml); deploying the AWS CDK app produces more than 50 resources of the following types\. + [AWS::EC2::EIP](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html) + [AWS::EC2::InternetGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html) + [AWS::EC2::NatGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html) @@ -253,4 +253,4 @@ Amazon Web Services \(AWS\) is a collection of digital infrastructure services t AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. -To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file +To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. From ed2105e95f7179f038d337f2a46c5bf5555ba50f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 13 Oct 2020 15:17:05 +0000 Subject: [PATCH 300/655] fixes for bootstrapping topic --- doc_source/bootstrapping.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 11f7666d..f54dc8ed 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -9,7 +9,7 @@ An environment needs to be bootstrapped if any of the following apply\. The required resources are defined in a AWS CloudFormation stack, called the *bootstrap stack*, which is usually named `CDKToolkit`\. Just like any AWS CloudFormation stack, you can find it in the AWS CloudFormation console\. -The AWS CDK supports two bootstrap templates\. At this writing, the AWS CDK is transitioning from one of these templates to the other, but the original template \(dubbed "legacy"\) is still the default\. The newer template \("modern"\) is required by CDK Pipelines now and will become the default at some point in the future\. For details, see [Bootstrapping templates](#bootstrapping-templates)\. +The AWS CDK supports two bootstrap templates\. At this writing, the AWS CDK is transitioning from one of these templates to the other, but the original template \(dubbed "legacy"\) is still the default\. The newer template \("modern"\) is required by CDK Pipelines today, and will become the default at some point in the future\. For details, see [Bootstrapping templates](#bootstrapping-templates)\. Environments are independent, so if you want to deploy to multiple environments \(different AWS accounts or different regions in the same account\), each environment must be bootstrapped separately\. @@ -93,7 +93,7 @@ aws cloudformation create-stack ^ At this writing, the AWS CDK is transitioning from one set of bootstrap resources to another\. The original bootstrap template, which shipped with the very first version of the AWS CDK, is called the **legacy** template\. A newer version of the template with additional resources was added in version 1\.25\.0\. This newer template is called the **modern** template\. -The legacy template is fully supported by the AWS CDK and is in fact the template that is selected by default when you issue `cdk bootstrap`\. The modern template is required primarily by the CDK Pipelines module, which can be used to set up a continuous delivery pipeline for your CDK applications\. More precisely, the modern template is required if you use the `DefaultSynthesizer` \(see [Stack synthesizers](#bootstrapping-synthesizers)\), +The legacy template is fully supported by the AWS CDK and is in fact the template that is selected by default when you issue `cdk bootstrap`\. The modern template is required primarily by the CDK Pipelines module, which can be used to set up a continuous delivery pipeline for your CDK applications\. More precisely, the modern template is used by the `DefaultSynthesizer` \(see [Stack synthesizers](#bootstrapping-synthesizers)\), and CDK Pipelines requires this synthesizer, The main differences between the templates are as follows\. @@ -101,7 +101,7 @@ The main differences between the templates are as follows\. \* *We will add additional resources to the modern template as needed\.* -At some point in the future, the modern template will become the default bootstrapping template\. Until then, you must manually select the modern template when bootstrapping by setting the `CDK_NEW_BOOTSTRAP` environment variable\. +At some point in the future, the modern template will become the default bootstrapping template\. Until then, manually select the modern template when bootstrapping by setting the `CDK_NEW_BOOTSTRAP` environment variable\. ------ #### [ Mac OS X/Linux ] @@ -165,7 +165,7 @@ When you need more customization than the AWS CDK Toolkit switches can provide, ``` export CDK_NEW_BOOTSTRAP=1 -cdk bootstrap +cdk bootstrap --show-template ``` ------ @@ -173,14 +173,14 @@ cdk bootstrap ``` set CDK_NEW_BOOTSTRAP=1 -cdk bootstrap +cdk bootstrap --show-template ``` ------ Any modifications you make must adhere to the [bootstrapping template contract](#bootstrapping-contract)\. -You can deploy your modified template as described in [Bootstrapping from the AWS CloudFormation template](#bootstrapping-howto-cfn), or using cdk bootstrap\. +Deploy your modified template as described in [Bootstrapping from the AWS CloudFormation template](#bootstrapping-howto-cfn), or using cdk bootstrap \-\-template\. ``` cdk bootstrap --template bootstrap-template.yaml @@ -503,7 +503,7 @@ new DefaultStackSynthesizer(new DefaultStackSynthesizerProps ## The bootstrapping template contract -The requirements of the bootstrapping stack depend on the stack synthesizer being used\. If you write your own stack synthesizer, you have complete control of the bootstrap resources that your synthesizer requires and how the synthesizer finds them\. This section describes the expectations that the `DefaultStackSynthesizer` has of the bootstrapping template\. +The requirements of the bootstrapping stack depend on the stack synthesizer in use\. If you write your own stack synthesizer, you have complete control of the bootstrap resources that your synthesizer requires and how the synthesizer finds them\. This section describes the expectations that the `DefaultStackSynthesizer` has of the bootstrapping template\. ### Versioning @@ -524,14 +524,14 @@ Outputs: Fn::GetAtt: [CdkBootstrapVersion, Value] ``` -### Versioning +### Roles The `DefaultStackSynthesizer` requires four IAM roles for four different purposes\. If you are not using the default roles, the synthesizer needs to be told the ARNs for the roles you want to use\. The roles are: + The *deployment role* is assumed by the AWS CDK Toolkit and by AWS CodePipeline to deploy into an environment\. Its `AssumeRolePolicy` controls who can deploy into the environment\. The permissions this role needs can be seen in the template\. + The *file publishing role* and the *image publishing role* are assumed by the AWS CDK Toolkit and by AWS CodeBuild projects to publish assets into an environment: that is, to write to the S3 bucket and the ECR repository, respectively\. These roles require write access to these resources\. + *The AWS CloudFormation execution role* is passed to AWS CloudFormation to perform the actual deployment\. Its permissions are the permissions that the deployment will execute under\. The permissions are passed to the stack as a parameter that lists managed policy ARNs\. -### Versioning +### Outputs The AWS CDK Toolkit requires that the following CloudFormation outputs exist on the bootstrap stack\. + `BucketName`: the name of the file asset bucket From 58ef2f8a2287ba6a7bb9c6f9a587052b0329599e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 13 Oct 2020 16:56:23 +0000 Subject: [PATCH 301/655] clarity --- doc_source/bootstrapping.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index f54dc8ed..d453e046 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -4,10 +4,10 @@ Deploying AWS CDK apps into an AWS [environment](environments.md) \(a combinatio An environment needs to be bootstrapped if any of the following apply\. + An AWS CDK stack being deployed uses [Assets](assets.md)\. -+ A AWS CloudFormation template generated by the app exceeds 50 kilobytes\. ++ An AWS CloudFormation template generated by the app exceeds 50 kilobytes\. + One or more of the stacks uses the `DefaultSynthesizer`\. We will explain stack synthesizers in more detail shortly, but in brief, the `DefaultSynthesizer` is used if you have set the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featureflags.md) in your app's `cdk.json` *or* if you explicitly create a `DefaultSynthesizer` and pass it to your stack\. [CDK Pipelines](cdk_pipeline.md) use the `DefaultSynthesizer`, so if your app uses CDK Pipelines, you must bootstrap the environments you will deploy into as well as the environment that contains the pipeline\. -The required resources are defined in a AWS CloudFormation stack, called the *bootstrap stack*, which is usually named `CDKToolkit`\. Just like any AWS CloudFormation stack, you can find it in the AWS CloudFormation console\. +The required resources are defined in a AWS CloudFormation stack, called the *bootstrap stack*, which is usually named `CDKToolkit`\. Like any AWS CloudFormation stack, it appears in the AWS CloudFormation console once it has been deployed\. The AWS CDK supports two bootstrap templates\. At this writing, the AWS CDK is transitioning from one of these templates to the other, but the original template \(dubbed "legacy"\) is still the default\. The newer template \("modern"\) is required by CDK Pipelines today, and will become the default at some point in the future\. For details, see [Bootstrapping templates](#bootstrapping-templates)\. From 3e3f83240746725f61df573d508d35da0d2485da Mon Sep 17 00:00:00 2001 From: akria18 <44463531+akria18@users.noreply.github.com> Date: Fri, 16 Oct 2020 14:31:37 +0200 Subject: [PATCH 302/655] update the extension of python file --- doc_source/cdk_pipeline.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index cf4fc9a2..c3c901bf 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -379,7 +379,7 @@ app.synth(); ------ #### [ Python ] -In `my-pipeline/my-pipeline-stack.js` \(may vary if your project folder isn't named `my-pipeline`\): +In `my-pipeline/my-pipeline-stack.py` \(may vary if your project folder isn't named `my-pipeline`\): ``` from aws_cdk.core import Stack, StackProps, Construct, SecretValue @@ -1770,4 +1770,4 @@ We're currently aware of the following issues with CDK Pipelines\. + If a changeset failed to apply, the pipeline is not retried\. The pipeline must be restarted manually from the top by clicking **Release Change**\. + A stack that failed to deploy must be deleted manually using the CloudFormation console before starting the pipeline again by clicking **Release Change**\. -Please [report any other issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. \ No newline at end of file +Please [report any other issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. From 124219a9de930eda3702889b3c1ff62435d2a5fc Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Oct 2020 17:43:46 +0000 Subject: [PATCH 303/655] new cfn-include material and other minor fixes --- doc_source/cdk_pipeline.md | 2 +- doc_source/cli.md | 26 +- doc_source/environments.md | 2 +- doc_source/home.md | 4 +- doc_source/use_cfn_template.md | 678 ++++++++++++++++++++++++++++- doc_source/work-with-cdk-csharp.md | 2 +- 6 files changed, 691 insertions(+), 23 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index c3c901bf..abca1111 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -1770,4 +1770,4 @@ We're currently aware of the following issues with CDK Pipelines\. + If a changeset failed to apply, the pipeline is not retried\. The pipeline must be restarted manually from the top by clicking **Release Change**\. + A stack that failed to deploy must be deleted manually using the CloudFormation console before starting the pipeline again by clicking **Release Change**\. -Please [report any other issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. +Please [report any other issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. \ No newline at end of file diff --git a/doc_source/cli.md b/doc_source/cli.md index 63a95949..7962873a 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -259,7 +259,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -278,7 +278,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -286,7 +286,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth –json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -310,7 +310,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -332,7 +332,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. @@ -507,7 +507,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -520,7 +520,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -533,7 +533,7 @@ Options: dependencies [boolean] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -583,7 +583,7 @@ Options: example). [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -629,7 +629,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -645,7 +645,7 @@ Options: [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -665,7 +665,7 @@ Options: [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -688,7 +688,7 @@ Options: [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/environments.md b/doc_source/environments.md index 7c8e90c3..9a64e06b 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -5,7 +5,7 @@ Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated **Note** For all but the simplest deployments, you will need to [bootstrap](bootstrapping.md) each environment you will deploy into\. Deployment requires certain AWS resources to be available, and these resources are provisined by bootstrapping\. -If you don't specify an environment when you define a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availablityZones` \(Python: `availability_zones`\)\. +If you don't specify an environment when you define a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availabilityZones` \(Python: `availability_zones`\)\. In an environment\-agnostic stack, any constructs that use availability zones will see two of them\. This allows the stack to be deployed to almost any region, since nearly all regions have at least two availability zones\. The only exception is Osaka \(`ap-northeast-3`\), which has one\. diff --git a/doc_source/home.md b/doc_source/home.md index b60eff86..cc662e44 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -233,7 +233,7 @@ In addition to this guide, the following are other resources available to AWS CD + [CDK Patterns](https://cdkpatterns.com/) + [Awesome CDK](https://github.com/kolomied/awesome-cdk) + [AWS Solutions Constructs](http://aws.amazon.com/solutions/constructs/) -+ [AWS Developer Blog](https://aws.amazon.com/blogs/developer) ++ [AWS Developer Blog](https://aws.amazon.com/blogs/developer/category/developer-tools/aws-cloud-development-kit) CDK category + [Stack Overflow](https://stackoverflow.com/questions/tagged/aws-cdk) + [GitHub Repository](https://github.com/awslabs/aws-cdk) + [Issues](https://github.com/awslabs/aws-cdk/issues) @@ -253,4 +253,4 @@ Amazon Web Services \(AWS\) is a collection of digital infrastructure services t AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. -To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. +To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index aeb902d8..84376f4a 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -1,13 +1,23 @@ # Use an existing AWS CloudFormation template -The AWS CDK provides a mechanism that you can use to incorporate resources from an existing AWS CloudFormation template into your AWS CDK app\. For example, suppose you have a template, `my-template.json`, with the following resource, where *S3Bucket* is the logical ID of the bucket in your template: +The AWS CDK provides two mechanisms to incorporate resources from an existing AWS CloudFormation template into your AWS CDK app\. ++ [`core.CfnInclude`](#use_cfn_template_core) \- Includes an AWS CloudFormation template in the current stack, merging its resources with those defined in your AWS CDK code\. You can access attributes of the imported resources using [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Fn.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Fn.html), but these resources are not actually AWS CDK constructs and do not provide the functionality of real constructs\. ++ [`cloudformation-include.CfnInclude`](#use_cfn_template_cfninclude) \- This construct, currently in developer preview, actually converts the resources in the imported AWS CloudFormation template to AWS CDK L1 constructs\. You can work with these in your app just as if they were defined in AWS CDK code, even using them within higher\-level AWS CDK constructs, letting you use \(for example\) the L2 permission grant methods with the resources they define\. + + This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by giving them the API they expect\. + +## Using `core.CfnInclude` + +An AWS CloudFormation template included using [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html) provides your AWS CDK app basic access to the resources contained in the template\. + +Suppose you have a template, `my-template.json`, with the following resource, where *S3Bucket* is the logical ID of the bucket in your template: ``` { - "S3Bucket": { + "MyBucket": { "Type": "AWS::S3::Bucket", "Properties": { - "prop1": "value1" + "BucketName": "MyBucket", } } } @@ -81,7 +91,7 @@ new CfnInclude(this, "ExistingInfrastructure", new CfnIncludeProps ------ -Then to access an attribute of the resource, such as the bucket's ARN, call `Fn.getAtt()` with the logical name of the resource in the AWS CloudFormation template and the desired attribute of the resource\. \(The resource must be defined in the template; `Fn.getAtt()` does not query actual resources you have deployed using the template\. +Then to access an attribute of the resource, such as the bucket's ARN, call `Fn.getAtt()` with the logical name of the resource in the AWS CloudFormation template and the name of the resource's attribute\. \(The desired resource and attribute must be defined in the template; `Fn.getAtt()` does not query actual resources you have deployed using the template\.\) ------ #### [ TypeScript ] @@ -125,4 +135,662 @@ The result of a `getAtt()` call is a [token](tokens.md), a type of placeholder\. + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) to generate a list encoding + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) to generate a numeric encoding -In our example of getting a bucket's ARN, you'd convert it to a string, but that string is still a token, just in a string encoding\. You still don't have the actual ARN\. But in many ways, you can treat the string as if you did have the real value \(for example, adding text to the beginning or end\) and it will work as you expect\. \ No newline at end of file +In our example of getting a bucket's ARN, you'd convert it to a string, but that string is still a token, just in a string encoding\. You still don't have the actual ARN\. But in many ways, you can treat the string as if you did have the real value \(for example, adding text to the beginning or end\) and it will work as you expect\. + +## Using `cloudformation-include.CfnInclude` + +The [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html) construct imports the resources in an AWS CloudFormation template as AWS CDK L1 constructs, allowing you to use them in your app as you would any other AWS CDK construct\. You can then wrap these in L2 constructs to gain their higher\-level abstractions\. This capability can help you migrate an AWS CloudFormation stack to the AWS CDK without making any unexpected changes to the underlying AWS resources, or to add an AWS CDK API "wrapper" to an existing AWS CloudFormation template\. + +**Warning** +This construct is currently in developer preview, which means its API is generally considered stable, but may still undergo breaking changes when necessary\. + + Here is a simple AWS CloudFormation template \(the same one we used in the preceding section, in fact\) which we'll use for the examples in this topic\. Save it as `my-template.json`\. You might also use a template for an actual stack you have already deployed, obtained from the AWS CloudFormation console\. + +**Tip** +You can use either a JSON or YAML template\. We recommend JSON if available, since YAML parsers can vary slightly in what they accept\. + +``` +{ + "MyBucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": "MyBucket", + } + } +} +``` + +And here's how you might import it into your stack using the new `cloudformation-include `module\. + +------ +#### [ TypeScript ] + +``` +import * as cdk from '@aws-cdk/core'; +import * as cfn_inc from '@aws-cdk/cloudformation-include'; + +export class MyStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const template = new cfn_inc.CfnInclude(this, 'Template', { + templateFile: 'my-template.json', + }); + } +} +``` + +------ +#### [ JavaScript ] + +``` +cost cdk = require('@aws-cdk/core'); +const cfn_inc = require('@aws-cdk/cloudformation-include'); + +class MyStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const template = new cfn_inc.CfnInclude(this, 'Template', { + templateFile: 'my-template.json', + }); + } +} + +module.exports = { MyStack } +``` + +------ +#### [ Python ] + +``` +from aws_cdk import core +from aws_cdk import cloudformation_include as cfn_inc + +class MyStack(core.Stack): + + def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + template = cfn_inc.CfnInclude(self, "Template", + template_file="my-template.json") +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.core.Construct; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; +import software.amazon.awscdk.cloudformation.include.CfnInclude; + +public class MyStack extends Stack { + public MyStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + CfnInclude template = CfnInclude.Builder.create(this, "Template") + .templateFile("my-template.json") + .build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using cfn_inc = Amazon.CDK.CloudFormation.Include; + +namespace MyApp +{ + public class MyStack : Stack + { + internal MyStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) + { + var template = new cfn_inc.CfnInclude(this, "Template", new cfn_inc.CfnIncludeProps + { + TemplateFile = "my-template.json" + }); + } + } +} +``` + +------ + +By default, importing preserves the original logical IDs from the template\. This behavior is suitable for migrating an AWS CloudFormation template to the AWS CDK\. If you are instead developing an AWS CDK construct wrapper for the template so it can be reused elsewhere \("vending"\), have the AWS CDK generate new resource IDs instead, so the construct can be used multiple times in a stack without name conflicts\. To do this, set the `preserveLogicalIds` property to false when importing the template\. + +------ +#### [ TypeScript ] + +``` +const template = new cfn_inc.CfnInclude(this, 'MyConstruct', { + templateFile: 'my-template.json', + preserveLogicalIds: false +}); +``` + +------ +#### [ JavaScript ] + +``` +const template = new cfn_inc.CfnInclude(this, 'MyConstruct', { + templateFile: 'my-template.json', + preserveLogicalIds: false +}); +``` + +------ +#### [ Python ] + +``` +template = cfn_inc.CfnInclude(self, "Template", + template_file="my-template.json", + preserve_logical_ids=False) +``` + +------ +#### [ Java ] + +``` +CfnInclude template = CfnInclude.Builder.create(this, "Template") + .templateFile("my-template.json") + .preserveLogicalIds(false) + .build(); +``` + +------ +#### [ C\# ] + +``` +var template = new cfn_inc.CfnInclude(this, "Template", new cfn_inc.CfnIncludeProps +{ + TemplateFile = "my-template.json", + PreserveLogicalIds = false +}); +``` + +------ + +To put the imported resources under the control of your AWS CDK app, simply add the stack to the `App` as usual\. + +------ +#### [ TypeScript ] + +``` +import * as cdk from '@aws-cdk/core'; +import { MyStack } from '../lib/my-stack'; + +const app = new cdk.App(); +new MyStack(app, 'MyStack'); +``` + +------ +#### [ JavaScript ] + +``` +const cdk = require('@aws-cdk/core'); +const { MyStack } = require('../lib/my-stack'); + +const app = new cdk.App(); +new MyStack(app, 'MyStack'); +``` + +------ +#### [ Python ] + +``` +from aws_cdk import core +from mystack.my_stack import MyStack + +app = core.App() +MyStack(app, "MyStack") +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.core.App; + +public class MyApp { + public static void main(final String[] args) { + App app = new App(); + + new MyStack(app, "MyStack"); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; + +namespace CdkApp +{ + sealed class Program + { + public static void Main(string[] args) + { + var app = new App(); + new MyStack(app, "MyStack"); + } + } +} +``` + +------ + +To verify that there will be no unintended changes to the AWS resources in the stack, perform a diff, omitting the AWS CDK\-specific metadata\. + +``` +cdk diff --no-version-reporting --no-path-metadata --no-asset-metadata +``` + +When you `cdk deploy` the stack, your AWS CDK app becomes the source of truth for the stack\. Going forward, make changes to the AWS CDK app, not to the AWS CloudFormation template\. + +### Accessing imported resources + +The name `template` in the example code represents the included AWS CloudFormation template\. To access a resource from it, use this object's [https://docs.aws.amazon.com/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) method\. To access the returned resource as a specific kind of resource, cast the result to the desired type \(except in Python and JavaScript, where types are not enforced\)\. + +------ +#### [ TypeScript ] + +``` +const cfnBucket = template.getResource('MyBucket') as s3.CfnBucket; +``` + +------ +#### [ JavaScript ] + +``` +const cfnBucket = template.getResource('MyBucket') as s3.CfnBucket; +``` + +------ +#### [ Python ] + +``` +cfn_bucket = template.get_resource("MyBucket") +``` + +------ +#### [ Java ] + +``` +CfnBucket cfnBucket = (CfnBucket)template.getResource("MyBucket"); +``` + +------ +#### [ C\# ] + +``` +var cfnBucket = (CfnBucket)template.GetResource("MyBucket"); +``` + +------ + +In our example, `cfnBucket` is now an instance of the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) class, a L1 construct that exactly represents the corresponding AWS CloudFormation resource\. You can treat it like any other resource of its type, for example getting its ARN by way of the `bucket.attrArn` property\. + +To wrap the L1 `CfnBucket` resource in a L2 [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) instance instead, use the static methods [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-arnscope-id-bucketarn](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-arnscope-id-bucketarn), [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-attributesscope-id-attrs](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-attributesscope-id-attrs), or [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-namescope-id-bucketname](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-namescope-id-bucketname)\. Usually the `fromBucketName()` method is the most convenient\. For example: + +------ +#### [ TypeScript ] + +``` +const bucket = s3.Bucket.fromBucketName(this, 'Bucket', cfnBucket.ref); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = s3.Bucket.fromBucketName(this, 'Bucket', cfnBucket.ref); +``` + +------ +#### [ Python ] + +``` +bucket = s3.Bucket.from_bucket_name(this, "Bucket", cfn_bucket.ref) +``` + +------ +#### [ Java ] + +``` +Bucket bucket = (Bucket)Bucket.fromBucketName(this, "Bucket", cfnBucket.getRef()); +``` + +------ +#### [ C\# ] + +``` +var bucket = (Bucket)Bucket.FromBucketName(this, "Bucket", cfnBucket.Ref); +``` + +------ + +Other L2 constructs have similar methods for creating the construct from an existing resource\. + +Constructing the `Bucket` this way doesn't create a second Amazon S3 bucket; instead, the new `Bucket` instance encapsulates the existing `CfnBucket`\. + +In the example, `bucket` is now an L2 `Bucket` construct that you can use as you would one you declared yourself\. For example, if `lambdaFunc` is an AWS Lambda function, and you wish to grant it write access to the bucket, you can do so using the bucket's convenient [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-wbr-read-wbr-writeidentity-objectskeypattern](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-wbr-read-wbr-writeidentity-objectskeypattern) method, without needing to construct the necessary IAM policy yourself\. + +------ +#### [ TypeScript ] + +``` +bucket.grantWrite(lambdaFunc); +``` + +------ +#### [ JavaScript ] + +``` +bucket.grantWrite(lambdaFunc); +``` + +------ +#### [ Python ] + +``` +bucket.grant_write(lambda_func) +``` + +------ +#### [ Java ] + +``` +bucket.grantWrite(lambdaFunc); +``` + +------ +#### [ C\# ] + +``` +bucket.GrantWrite(lambdaFunc); +``` + +------ + +### Replacing parameters + +If your included AWS CloudFormation template has parameters, you can replace these with build\-time values when you import the template, using the `parameters` property\. In the example below, we replace the `UploadBucket` parameter with the ARN of a bucket defined elsewhere in our AWS CDK code\. + +------ +#### [ TypeScript ] + +``` +const template = new cfn_inc.CfnInclude(this, 'Template', { + templateFile: 'my-template.json', + parameters: { + 'UploadBucket': bucket.bucketArn, + }, +}); +``` + +------ +#### [ JavaScript ] + +``` +const template = new cfn_inc.CfnInclude(this, 'Template', { + templateFile: 'my-template.json', + parameters: { + 'UploadBucket': bucket.bucketArn, + }, +}); +``` + +------ +#### [ Python ] + +``` +template = cfn_inc.CfnInclude(self, "Template", + template_file="my-template.json", + parameters=dict(UploadBucket=bucket.bucket_arn) +) +``` + +------ +#### [ Java ] + +``` +CfnInclude template = CfnInclude.Builder.create(this, "Template") + .templateFile("my-template.json") + .parameters(new HashMap() {{ + put("UploadBucket", bucket.getBucketArn()); + }}) + .build(); +``` + +------ +#### [ C\# ] + +``` +var template = new cfn_inc.CfnInclude(this, "Template", new cfn_inc.CfnIncludeProps +{ + TemplateFile = "my-template.json", + Parameters = new Dictionary + { + { "UploadBucket", bucket.BucketArn } + } +}); +``` + +------ + +### Other template elements + +You can import any AWS CloudFormation template element, not just resources\. The imported elements become part of the AWS CDK stack\. To import these elements, use the following methods of the `CfnInclude` object\. ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-conditionconditionname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-conditionconditionname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [conditions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-hookhooklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-hookhooklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [hooks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/blue-green.html) for blue\-green deployments ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-mappingmappingname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-mappingmappingname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [mappings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-outputlogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-outputlogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-parameterparametername-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-parameterparametername-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-rulerulename-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-rulerulename-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [rules](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/reference-template_constraint_rules.html) for Service Catalog templates + +Each of these methods returns an instance of a class representing the specific type of AWS CloudFormation element\. These objects are mutable; changes will appear in the template generated from the AWS CDK stack\. The code below, for example, imports a parameter from the template and modifies its default\. + +------ +#### [ TypeScript ] + +``` +const param = template.getParameter('MyParameter'); +param.default = "AWS CDK" +``` + +------ +#### [ JavaScript ] + +``` +const param = template.getParameter('MyParameter'); +param.default = "AWS CDK" +``` + +------ +#### [ Python ] + +``` +param = template.get_parameter("MyParameter") +param.default = "AWS CDK" +``` + +------ +#### [ Java ] + +``` +CfnParameter param = template.getParameter("MyParameter"); +param.setDefaultValue("AWS CDK") +``` + +------ +#### [ C\# ] + +``` +var cfnBucket = (CfnBucket)template.GetResource("MyBucket"); +var param = template.GetParameter("MyParameter"); +param.Default = "AWS CDK"; +``` + +------ + +### Nested stacks + +You may import [nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html) by specifying them either when you import their main template, or at some later point\. The nested template must be stored in a local file, but referenced in as a `NestedStack` resource in the main template, and the resource name used in the AWS CDK code must match the name used for the nested stack in the main template\. + +Given this resource definition in the main template, the following code shows how to import the referenced nested stack both ways\. + +``` +"NestedStack": { + "Type": "AWS::CloudFormation::Stack", + "Properties": { + "TemplateURL": "https://my-s3-template-source.s3.amazonaws.com/nested-stack.json" + } +``` + +------ +#### [ TypeScript ] + +``` +// include nested stack when importing main stack +const mainTemplate = new cfn_inc.CfnInclude(this, 'MainStack', { + templateFile: 'main-template.json', + loadNestedStacks: { + 'NestedStack': { + templateFile: 'nested-template.json', + }, + }, +}); + +// or add it some time after importing the main stack +const nestedTemplate = mainTemplate.loadNestedStack('NestedTemplate', { + templateFile: 'nested-template.json', +}); +``` + +------ +#### [ JavaScript ] + +``` +// include nested stack when importing main stack +const mainTemplate = new cfn_inc.CfnInclude(this, 'MainStack', { + templateFile: 'main-template.json', + loadNestedStacks: { + 'NestedStack': { + templateFile: 'nested-template.json', + }, + }, +}); + +// or add it some time after importing the main stack +const nestedTemplate = mainTemplate.loadNestedStack('NestedStack', { + templateFile: 'my-nested-template.json', +}); +``` + +------ +#### [ Python ] + +``` +# include nested stack when importing main stack +main_template = cfn_inc.CfnInclude(self, "MainStack", + template_file="main-template.json", + load_nested_stacks=dict(NestedStack= + cfn_inc.CfnIncludeProps(template_file="nested-template.json"))) + +# or add it some time after importing the main stack +nested_template = main_template.load_nested_stack("NestedStack", + template_file="nested-template.json") +``` + +------ +#### [ Java ] + +``` +CfnInclude mainTemplate = CfnInclude.Builder.create(this, "MainStack") + .templateFile("main-template.json") + .loadNestedStacks(new HashMap() {{ + put("NestedStack", CfnIncludeProps.builder() + .templateFile("nested-template.json").build()); + }}) + .build(); + +// or add it some time after importing the main stack +IncludedNestedStack nestedTemplate = mainTemplate.loadNestedStack("NestedTemplate", CfnIncludeProps.builder() + .templateFile("nested-template.json") + .build()); +``` + +------ +#### [ C\# ] + +``` +// include nested stack when importing main stack +var mainTemplate = new cfn_inc.CfnInclude(this, "MainStack", new cfn_inc.CfnIncludeProps +{ + TemplateFile = "main-template.json", + LoadNestedStacks = new Dictionary + { + { "NestedStack", new cfn_inc.CfnIncludeProps { TemplateFile = "nested-template.json" } } + } +}); + +// or add it some time after importing the main stack +var nestedTemplate = mainTemplate.LoadNestedStack("NestedTemplate", new cfn_inc.CfnIncludeProps { + TemplateFile = 'nested-template.json' +}); +``` + +------ + +You can import multiple nested stacks with either or both methods\. When importing the main template, you provide a mapping between the resource name of each nested stack and its template file, and this mapping can contain any number of entries\. To do it after the initial import, call `loadNestedStack()` for each nested stack\. + +After importing a nested stack, you can access it using the main template's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-nested-wbr-stacklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-nested-wbr-stacklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) method\. + +------ +#### [ TypeScript ] + +``` +const nestedStack = mainTemplate.getNestedStack('NestedStack').stack; +``` + +------ +#### [ JavaScript ] + +``` +const nestedStack = mainTemplate.getNestedStack('NestedStack').stack; +``` + +------ +#### [ Python ] + +``` +nested_stack = main_template.get_nested_stack("NestedStack").stack +``` + +------ +#### [ Java ] + +``` +NestedStack nestedStack = mainTemplate.getNestedStack("NestedStack").getStack(); +``` + +------ +#### [ C\# ] + +``` +var nestedStack = mainTemplate.GetNestedStack("NestedStack").Stack; +``` + +------ + +The `getNestedStack()` method returns an [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.IncludedNestedStack.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.IncludedNestedStack.html) instance, from which you can access the AWS CDK [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.NestedStack.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.NestedStack.html) instance via the `stack` property \(as shown in the example\) or the original AWS CloudFormation template object via `includedTemplate`, from which you can load resources and other AWS CloudFormation elements\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 90faf17f..ed19ed2a 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -139,7 +139,7 @@ var bucket = new MyBucket(this, "MyBucket", new MimeBucketProps { When calling the parent class's initializer or overridden method, you can generally pass the props you received\. The new type is compatible with its parent, and extra props you added are ignored\. -Keep in mind that future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues using your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion for your construct's users\. You can avoid this potential problem by naming your properties so they clearly belong to your construct \(e\.g\. `BobEncryption` rather than just `encryption`, assuming you're Bob\)\. If there are many new properties, bundle them into an appropriately\-named class \(`BobBucketPoperties`?\) and pass them as a single property\. +Keep in mind that future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues using your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion for your construct's users\. You can avoid this potential problem by naming your properties so they clearly belong to your construct\. If there are many new properties, bundle them into an appropriately\-named class and pass them as a single property\. ### Generic structures From f5ef1c7d5f48d7605274c5faf43eaeb92eaeb6cc Mon Sep 17 00:00:00 2001 From: Lock128 Date: Tue, 20 Oct 2020 15:46:45 +0200 Subject: [PATCH 304/655] Fixed Missing line in Java example Added a line for defining the widget in the Java example. :-) --- doc_source/serverless_example.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 971acd50..2fb30804 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -811,6 +811,8 @@ File: `my_widget_service/widget_service.py` File: `src/src/main/java/com/myorg/WidgetService.java` ``` + Resource widget = api.getRoot().addResource("{id}"); + // Add new widget to bucket with: POST /{id} LambdaIntegration postWidgetIntegration = new LambdaIntegration(handler); @@ -874,4 +876,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` \ No newline at end of file +``` From efee779b509db46981b2be5cf4bd30caf73d5dec Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Oct 2020 20:24:02 +0000 Subject: [PATCH 305/655] fix en dashes that should be -- --- doc_source/cli.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 7962873a..f1ea01ff 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -265,7 +265,7 @@ Use the `--context` or `-c` option to pass [runtime context](context.md) values ``` # specify a single context value -cdk synth –context key=value MyStack +cdk synth --context key=value MyStack # specify multiple context values (any number) cdk synth --context key1=value1 --context key2=value2 MyStack @@ -283,7 +283,7 @@ cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. ``` -cdk synth –json MyStack +cdk synth --json MyStack ``` ### Specifying output directory @@ -291,7 +291,7 @@ cdk synth –json MyStack Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. ``` -cdk synth –output=~/templates +cdk synth --output=~/templates ``` ## Deploying stacks @@ -337,7 +337,7 @@ By default, the AWS CDK retains values of parameters from previous deployments a If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. ``` -cdk deploy –output-file outputs.json MyStack +cdk deploy --output-file outputs.json MyStack ``` ## Security\-related changes From af2c7ebcc20492e16a7cfe69ad35501cdda04aeb Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Oct 2020 20:38:44 +0000 Subject: [PATCH 306/655] remove empty program listing --- doc_source/cdk_pipeline.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index abca1111..ce271245 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -209,9 +209,6 @@ Edit your project's `pom.xml` and add a `` element for the `pipeline ``` -``` -``` - ------ #### [ C\# ] From db9f5f94a28536d91afa568b67420c5dc4f959b3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Oct 2020 20:39:01 +0000 Subject: [PATCH 307/655] beef up wildcard note --- doc_source/cli.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index f1ea01ff..fb432b74 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -166,12 +166,12 @@ You may also use wildcards to specify IDs that match a pattern\. + ? matches any single character + \* matches any number of characters -When using wildcards, enclose the pattern in quotes\. If you don't, your shell may try to expand the pattern to the names of files in the current directory\. At best, this won't do what you expect; at worst, you could deploy stacks you didn't intend to\. +When using wildcards, enclose the pattern in quotes or escape the wildcards with `\`\. If you don't, your shell may try to expand the pattern to the names of files in the current directory\. At best, this won't do what you expect; at worst, you could deploy stacks you didn't intend to\. This isn't strictly necessary on Windows because `cmd.exe` does not expand wildcards, but is good practice regardless\. ``` cdk synth "*Stack" # PipelineStack, LambdaStack, etc. -cdk synth "Stack?" # StackA, StackB, Stack1, etc. -cdk synth "*" # All stacks in the app +cdk synth 'Stack?' # StackA, StackB, Stack1, etc. +cdk synth \* # All stacks in the app ``` **Note** From 8e1817dbabf2e595b61b86c43dc0ec0da017a2fb Mon Sep 17 00:00:00 2001 From: pvbouwel Date: Thu, 22 Oct 2020 19:31:45 +0200 Subject: [PATCH 308/655] Update tokens.md Fix typo `encocding` into `encoding`. --- doc_source/tokens.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/tokens.md b/doc_source/tokens.md index cf14052d..955539a8 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -86,7 +86,7 @@ Tokens are objects that implement the [IResolvable](https://docs.aws.amazon.com/ You'll hardly ever work directly with the `IResolvable` interface\. You will most likely only see string\-encoded versions of tokens\. Other functions typically only accept arguments of basic types, such as `string` or `number`\. To use tokens in these cases, you can encode them into one of three types using static methods on the [core\.Token](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html) class\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) to generate a string encocding \(or call `.toString()` on the token object\) ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) to generate a string encoding \(or call `.toString()` on the token object\) + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) to generate a list encoding + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) to generate a numeric encoding @@ -424,4 +424,4 @@ var stringVal = stack.ToJsonString(new Dictionary }); ``` ------- \ No newline at end of file +------ From e7e65fa536893e9cbf4f7d6f577c45de29812847 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 22 Oct 2020 23:06:16 +0000 Subject: [PATCH 309/655] change title of CfnInclude topic to reference import or migrate --- doc_source/get_cfn_param.md | 2 +- doc_source/index.md | 2 +- doc_source/tokens.md | 2 +- doc_source/use_cfn_template.md | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/doc_source/get_cfn_param.md b/doc_source/get_cfn_param.md index 5f9582fb..9607aa96 100644 --- a/doc_source/get_cfn_param.md +++ b/doc_source/get_cfn_param.md @@ -2,4 +2,4 @@ See [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for information about using the optional *Parameters* section to customize your AWS CloudFormation templates\. -You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [Use an existing AWS CloudFormation template](use_cfn_template.md)\. \ No newline at end of file +You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [Import or migrate an existing AWS CloudFormation template](use_cfn_template.md)\. \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index 4168e708..29b3f553 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -50,7 +50,7 @@ Amazon's trademarks and trade dress may not be used in + [AWS CDK how-tos](how_tos.md) + [Get a value from an environment variable](get_env_var.md) + [Use an AWS CloudFormation parameter](get_cfn_param.md) - + [Use an existing AWS CloudFormation template](use_cfn_template.md) + + [Import or migrate an existing AWS CloudFormation template](use_cfn_template.md) + [Get a value from the Systems Manager Parameter Store](get_ssm_value.md) + [Get a value from AWS Secrets Manager](get_secrets_manager_value.md) + [Create an app with multiple stacks](stack_how_to_create_multiple_stacks.md) diff --git a/doc_source/tokens.md b/doc_source/tokens.md index 955539a8..b92c8a75 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -424,4 +424,4 @@ var stringVal = stack.ToJsonString(new Dictionary }); ``` ------- +------ \ No newline at end of file diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 84376f4a..9ed8a8fa 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -1,4 +1,4 @@ -# Use an existing AWS CloudFormation template +# Import or migrate an existing AWS CloudFormation template The AWS CDK provides two mechanisms to incorporate resources from an existing AWS CloudFormation template into your AWS CDK app\. + [`core.CfnInclude`](#use_cfn_template_core) \- Includes an AWS CloudFormation template in the current stack, merging its resources with those defined in your AWS CDK code\. You can access attributes of the imported resources using [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Fn.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Fn.html), but these resources are not actually AWS CDK constructs and do not provide the functionality of real constructs\. @@ -131,7 +131,7 @@ var bucketArn = Fn.GetAtt("S3Bucket", "Arn"); ------ The result of a `getAtt()` call is a [token](tokens.md), a type of placeholder\. The actual value of the attribute isn't available until later in the synthesis process\. If you need to pass such an attribute to another API that requires a concrete value, such as a string or a number, use the following static methods of the `[Token](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html)` class to convert the token to a string, number, or list\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) to generate a string encocding \(or call `.toString()` on the token object\) ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) to generate a string encoding \(or call `.toString()` on the token object\) + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) to generate a list encoding + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) to generate a numeric encoding From 404bd02df0cb861dafccf42f10b40ae4bb5519b1 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 23 Oct 2020 00:20:03 +0000 Subject: [PATCH 310/655] update CloudFormation resource limit to 500 --- doc_source/stacks.md | 2 +- doc_source/troubleshooting.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/stacks.md b/doc_source/stacks.md index 55b997d2..6eb5308d 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -361,7 +361,7 @@ The [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack ## Nested stacks -The [NestedStack](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudformation.NestedStack.html) construct offers a way around the AWS CloudFormation 200\-resource limit for stacks\. A nested stack counts as only one resource in the stack that contains it, but can itself contain up to 200 resources, including additional nested stacks\. +The [NestedStack](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudformation.NestedStack.html) construct offers a way around the AWS CloudFormation 500\-resource limit for stacks\. A nested stack counts as only one resource in the stack that contains it, but can itself contain up to 500 resources, including additional nested stacks\. The scope of a nested stack must be a `Stack` or `NestedStack` construct\. The nested stack needn't be declared lexically inside its parent stack; it is necessary only to pass the parent stack as the first parameter \(`scope`\) when instantiating the nested stack\. Aside from this restriction, defining constructs in a nested stack works exactly the same as in an ordinary stack\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index c9834bbe..7cc78f37 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -202,7 +202,7 @@ cdk synth --app "npx ts-node my-cdk-app.ts" MyStack \([back to list](#troubleshooting_top)\) **When deploying an AWS CDK stack, I receive an error because the AWS CloudFormation template contains too many resources** -The AWS CDK generates and deploys AWS CloudFormation templates\. AWS CloudFormation has a hard limit of 200 resources per stack\. With the AWS CDK, you can run up against this limit more quickly than you might expect, especially if you haven't already worked with AWS CloudFormation enough to know what resources are being generated by the AWS Construct Library constructs you're using\. +The AWS CDK generates and deploys AWS CloudFormation templates\. AWS CloudFormation has a hard limit of 500 resources per stack\. With the AWS CDK, you can run up against this limit more quickly than you might expect, especially if you haven't already worked with AWS CloudFormation enough to know what resources are being generated by the AWS Construct Library constructs you're using\. The AWS Construct Library's higher\-level, intent\-based constructs automatically provision any auxiliary resources that are needed for logging, key management, authorization, and other purposes\. For example, granting one resource access to another generates any IAM objects needed for the relevant services to communicate\. @@ -229,10 +229,10 @@ if (path) fs.readFile(path, 'utf8', function(err, contents) { }); else console.log("Please specify the path to the stack's output .json file"); ``` -As your stack's resource count approaches 200, consider re\-architecting to reduce the number of resources your stack contains, for example by combining some Lambda functions, or to break it up into multiple stacks\. The CDK supports [references between stacks](resources.md#resource_stack), so it is straightforward to separate your app's functionality into different stacks in whatever way makes the most sense to you\. +As your stack's resource count approaches 500, consider re\-architecting to reduce the number of resources your stack contains, for example by combining some Lambda functions, or to break it up into multiple stacks\. The CDK supports [references between stacks](resources.md#resource_stack), so it is straightforward to separate your app's functionality into different stacks in whatever way makes the most sense to you\. **Note** -AWS CloudFormation experts often suggest the use of nested stacks as a solution to the 200 resource limit\. The AWS CDK supports this approach via the [`NestedStack`](stacks.md#stack_nesting) construct\. +AWS CloudFormation experts often suggest the use of nested stacks as a solution to the resource limit\. The AWS CDK supports this approach via the [`NestedStack`](stacks.md#stack_nesting) construct\. \([back to list](#troubleshooting_top)\) From f3fa71531ae1573ae2a6d064144f6a8a71b8f905 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 27 Oct 2020 17:12:29 +0000 Subject: [PATCH 311/655] recent improvements --- doc_source/cli.md | 4 ++-- doc_source/context.md | 2 ++ doc_source/resources.md | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index fb432b74..30640086 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -334,10 +334,10 @@ By default, the AWS CDK retains values of parameters from previous deployments a ### Specifying outputs file -If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--output-file` flag\. +If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. ``` -cdk deploy --output-file outputs.json MyStack +cdk deploy --outputs-file outputs.json MyStack ``` ## Security\-related changes diff --git a/doc_source/context.md b/doc_source/context.md index 51df8c97..706b2fa8 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -2,6 +2,8 @@ Context values are key\-value pairs that can be associated with a stack or construct\. The AWS CDK uses context to cache information from your AWS account, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs used to start your instances\. [Feature flags](featureflags.md) are also context values\. You can create your own context values for use by your apps or constructs\. +Context keys and values are strings\. If you want to pass other types of value, such as numbers but also including structured data such as JSON, it must be passed as a string\. Code that consumes such a context value will need to convert or parse the data as appropriate\. + ## Construct context Context values are made available to your AWS CDK app in six different ways: diff --git a/doc_source/resources.md b/doc_source/resources.md index 381d91fd..ea6faeb4 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1110,7 +1110,7 @@ bucket.AddObjectCreatedNotification(new s3Nots.LambdaDestination(handler)); ## Removal policies -Resources that maintain persistent data, such as databases and Amazon S3 buckets, have a *removal policy* that indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the AWS CDK `core` module\. +Resources that maintain persistent data, such as databases and Amazon S3 buckets and even Amazon ECR registries, have a *removal policy* that indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the AWS CDK `core` module\. **Note** Resources besides those that store data persistently may also have a `removalPolicy` that is used for a different purpose\. For example, a Lambda function version uses a `removalPolicy` attribute to determine whether a given version is retained when a new version is deployed\. These have different meanings and defaults compared to the removal policy on an Amazon S3 bucket or DynamoDB table\. From 17219e0f42c091f217809376c83c405a8b4defb5 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 28 Oct 2020 17:03:32 +0000 Subject: [PATCH 312/655] add common error message to mismatched version discussion --- doc_source/troubleshooting.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 7cc78f37..9c38e682 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -13,6 +13,8 @@ This topic describes how to troubleshoot the following issues with the AWS CDK\. **After updating the AWS CDK, code that used to work fine now results in errors** Errors in code that used to work is typically a symptom of having mismatched versions of AWS Construct Library modules\. Make sure all library modules are the same version and up\-to\-date\. +An error message commonly seen in this situation is `unable to determine cloud assembly output directory. Assets must be defined indirectly within a "Stage" or an "App" scope`\. + The modules that make up the AWS Construct Library are a matched set\. They are released together and are intended to be used together\. Interfaces between modules are considered private; we may change them when necessary to implement new features in the library\. We also update the libraries that are used by the AWS Construct Library from time to time, and different versions of the library modules may have incompatible dependencies\. Synchronizing the versions of the library modules will also address this issue\. @@ -47,7 +49,7 @@ npm install @aws-cdk/aws-s3@1.9.0 Repeat these commands for each module your project uses\. -You can edit your `package.json` file to lock the AWS Construct Library modules to a specific version, so `npm update` won't update them\. You can also specify a version using `~` or `^` to allow modules to be updated to versions that are API\-compatible with the current version, such as `^1.0.0` to accept any update API\-compatible with version 1\.x\. Use the same version specification for all AWS Construct Library modules within a project\. +You can edit your `package.json` file to lock the AWS Construct Library modules to a specific version, so `npm update` won't update them\. You can also specify a version using `~` or `^` to allow modules to be updated to versions that are API\-compatible with the current version, such as `^1.0.0` to accept any update API\-compatible with version 1\.x\. Use the same version specification for all AWS Construct Library modules within a project, including these special characters\. Otherwise, Node\.js may not resolve all these specifications to the same concrete version, resulting in a mismatch\. ------ #### [ Python ] From 0d846cecee396ebd520a817f7beeb6ad612e15d7 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 28 Oct 2020 18:16:43 +0000 Subject: [PATCH 313/655] boostrap fix for Halloween --- doc_source/cdk_pipeline.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index ce271245..dc6b5340 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -16,7 +16,7 @@ Before you can use CDK Pipelines, you must bootstrap the AWS environment\(s\) to **Note** See [Bootstrapping](bootstrapping.md) for more information on the kinds of resources created by bootstrapping and how to customize the bootstrap stack\. -You may have already bootstrapped one or more environments so you can deploy assets and Lambda functions using the AWS CDK\. Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include additional resources, so the boostrap stack has been extended to include an additional Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. This new style of CDK Toolkit stack will eventually become the default, but at this writing, you must opt in\. The AWS CDK Toolkit will upgrade your existing bootstrap stack or create a new one, as necessary\. +You may have already bootstrapped one or more environments so you can deploy assets and Lambda functions using the AWS CDK\. Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include additional resources, so the bootstrap stack has been extended to include an additional Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. This new style of CDK Toolkit stack will eventually become the default, but at this writing, you must opt in\. The AWS CDK Toolkit will upgrade your existing bootstrap stack or create a new one, as necessary\. To bootstrap an environment that can provision an AWS CDK pipeline, set the environment variable `CDK_NEW_BOOTSTRAP` before invoking `cdk bootstrap`, as shown below\. Invoking the AWS CDK Toolkit via the `npx` command installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. From 08533445088bdcdad789babf30472b32f8b6a443 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 28 Oct 2020 19:40:04 +0000 Subject: [PATCH 314/655] typos --- doc_source/bootstrapping.md | 6 +++--- doc_source/cdk_pipeline.md | 2 +- doc_source/cli.md | 2 +- doc_source/get_env_var.md | 2 +- doc_source/resources.md | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index d453e046..1e2ee158 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -32,7 +32,7 @@ Bootstrapping is the deployment of a AWS CloudFormation template to a specific A + Use the AWS CDK Toolkit's cdk bootstrap command\. This is the simplest method and works well if you have only a few environments to bootstrap\. + Deploy the template provided by the AWS CDK Toolkit using another AWS CloudFormation deployment tool\. This lets you use AWS CloudFormation Stack Sets or AWS Control Tower as well as the AWS CloudFormation console or the AWS CLI\. You can even make small modifications to the template before deployment\. This approach is more flexible and is suitable for large\-scale deployments\. -It is not an error to bootstrap an environmnt more than once\. If an environment you bootstrap has already been bootstrapped, its bootstrap stack will be upgraded if necessary; otherwise, nothing happens\. +It is not an error to bootstrap an environment more than once\. If an environment you bootstrap has already been bootstrapped, its bootstrap stack will be upgraded if necessary; otherwise, nothing happens\. ### Bootstrapping with the AWS CDK Toolkit @@ -153,7 +153,7 @@ The following command\-line options, when used with CDK Toolkit's cdk bootstrap, The following additional switches are available only with the modern bootstrapping template\. + \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. -+ \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an evironment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. ++ \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. ### Customizing the template @@ -426,7 +426,7 @@ DefaultStackSynthesizer( file_assets_bucket_name="cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}", # Name of the ECR repository for Docker image assets - image_assets_pepository_name="cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}", + image_assets_repository_name="cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}", # ARN of the role assumed by the CLI and Pipeline to deploy here deploy_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}", diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index dc6b5340..8c7d878a 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -1651,7 +1651,7 @@ pipeline = CdkPipeline(self, "Pipeline", validation_action = ShellScriptAction( action_name="TestUsingBuildArtifact", additional_artifacts=[integ_tests_artifact], - # 'test.js' was produced from "test/test.ts" durinng the synth step + # 'test.js' was produced from "test/test.ts" during the synth step commands=["node ./test.js"] ) ``` diff --git a/doc_source/cli.md b/doc_source/cli.md index 30640086..b77ba1c8 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -65,7 +65,7 @@ The `AWS::CDK::Metadata` resource looks something like the following\. CDKMetadata: Type: "AWS::CDK::Metadata" Properties: - Modules: "@aws-cdk/core=X.YY.Z,@aws-cdk/s3=X.YY.Z,@aws-solutions-consturcts/aws-apigateway-lambda=X.YY.Z,aws-rfdk=X.YY.Z" + Modules: "@aws-cdk/core=X.YY.Z,@aws-cdk/s3=X.YY.Z,@aws-solutions-constrccts/aws-apigateway-lambda=X.YY.Z,aws-rfdk=X.YY.Z" ``` To opt out of version reporting, use one of the following methods: diff --git a/doc_source/get_env_var.md b/doc_source/get_env_var.md index 77ee780a..7d4439eb 100644 --- a/doc_source/get_env_var.md +++ b/doc_source/get_env_var.md @@ -47,7 +47,7 @@ bucket_name = os.getenv("MYBUCKET", "DefaultName") // Sets bucketName to null if environment variable doesn't exist String bucketName = System.getenv("MYBUCKET"); -// Sets bucketName to a defalut if env var doesn't exist +// Sets bucketName to a default if env var doesn't exist String bucketName = System.getenv("MYBUCKET"); if (bucketName == null) bucketName = "DefaultName"; ``` diff --git a/doc_source/resources.md b/doc_source/resources.md index ea6faeb4..1cbcf310 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1018,7 +1018,7 @@ fleet.connections.allowToDefaultPort(rdsDatabase, 'Fleet can access database'); ``` listener.connections.allow_default_port_from_any_ipv4("Allow public access") -fleet.connections.allow_to_default_port(rds_database, "Fleet can acceess database") +fleet.connections.allow_to_default_port(rds_database, "Fleet can access database") ``` ------ From b2d222af23962c224ca6ed5b94bf5196e98af571 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 30 Oct 2020 18:47:42 +0000 Subject: [PATCH 315/655] update .env to .venv for Python virtual environments --- doc_source/codepipeline_example.md | 4 ++-- doc_source/ecs_example.md | 2 +- doc_source/serverless_example.md | 2 +- doc_source/stack_how_to_create_multiple_stacks.md | 2 +- doc_source/work-with-cdk-python.md | 4 ++-- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index a8de53ee..9a9bc918 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -70,7 +70,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ``` cd pipeline cdk init --language python - source .env/bin/activate + source .venv/bin/activate git commit -m "project started" pip install -r requirements.txt pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline @@ -83,7 +83,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ``` cd pipeline cdk init --language python - .env\Scripts\activate.bat + .venv\Scripts\activate.bat pip install -r requirements.txt pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_s3 diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 5846733a..325986fa 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -56,7 +56,7 @@ cdk init --language javascript mkdir MyEcsConstruct cd MyEcsConstruct cdk init --language python -source .env/bin/activate +source .venv/bin/activate pip install -r requirements.txt ``` diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 971acd50..4043694e 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -51,7 +51,7 @@ cdk init ‐-language javascript mkdir MyWidgetService cd MyWidgetService cdk init --language python -source .env/bin/activate +source .venv/bin/activate pip install -r requirements.txt ``` diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index ec05d6e2..3bad0f86 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -35,7 +35,7 @@ cdk init --language=javascript mkdir multistack cd multistack cdk init --language=python -source .env/bin/activate +source .venv/bin/activate pip install -r requirements.txt ``` diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index dc38fb23..34d95dab 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -38,11 +38,11 @@ cdk init app --language python After initializing the project, activate the project's virtual environment\. This allows the project's dependencies to be installed locally in the project folder, instead of globally\. ``` -source .env/bin/activate +source .venv/bin/activate ``` **Note** -You may recognize this as the Mac/Linux command to activate a virtual environment\. The Python templates include a batch file, `source.bat`, that allows the same command to be used on Windows\. The traditional Windows command, `.env\Scripts\activate.bat`, works, too\. +You may recognize this as the Mac/Linux command to activate a virtual environment\. The Python templates include a batch file, `source.bat`, that allows the same command to be used on Windows\. The traditional Windows command, `.venv\Scripts\activate.bat`, works, too\. Then install the app's standard dependencies: From 40ca8973088ecbe5e1e1d8a341497bb6a1f14193 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 30 Oct 2020 22:46:42 +0000 Subject: [PATCH 316/655] update info about dependencies --- doc_source/cli.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index b77ba1c8..e7e971ca 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -175,7 +175,7 @@ cdk synth \* # All stacks in the app ``` **Note** -The CDK Toolkit does not guarantee that stacks are processed in the specified order\. If for some reason the order of the stacks is important, use multiple `cdk` commands\. +The order in which you specify the stacks is not necessarily the order in which they will be processed\. The AWS CDK Toolkit takes into account dependencies between stacks when deciding the order in which to process them\. For example, if one stack uses a value produced by another \(such as the ARN of a resource defined in the second stack\), the second stack is synthesized before the first one because of this dependency\. You can add dependencies between stacks manually using the stack's [https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html#core_Stack_addDependency](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html#core_Stack_addDependency) method\. ## Bootstrapping your AWS environment @@ -259,7 +259,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -278,7 +278,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -286,7 +286,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -310,7 +310,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -332,7 +332,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -507,7 +507,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -520,7 +520,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -533,7 +533,7 @@ Options: dependencies [boolean] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -583,7 +583,7 @@ Options: example). [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -629,7 +629,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -645,7 +645,7 @@ Options: [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -665,7 +665,7 @@ Options: [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -688,7 +688,7 @@ Options: [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context From a04012e3ad79c219fdd4a9d1edb45454f2a550fe Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 2 Nov 2020 20:23:07 +0000 Subject: [PATCH 317/655] use new tagging api --- doc_source/tagging.md | 130 +++++++++++++++++++----------------------- 1 file changed, 59 insertions(+), 71 deletions(-) diff --git a/doc_source/tagging.md b/doc_source/tagging.md index b5135e17..e5040d25 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -1,47 +1,47 @@ # Tagging -The `Tag` class includes two methods that you can use to create and delete tags: -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props) applies a new tag to a construct and all of its children\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props) removes a tag from a construct and any of its children, including tags a child construct may have applied to itself\. +Tags are informational key\-value elements that you can add to constructs in your AWS CDK app\. A tag applied to a given construct also applies to all of its taggable children\. The [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props) applies a new tag to the given construct and all of its children\. ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props) removes a tag from the given construct and any of its children, including tags a child construct may have applied to itself\. **Note** Tagging is implemented using [Aspects](aspects.md)\. Aspects are a way to apply an operation \(such as tagging\) to all constructs in a given scope\. -Let's look at a couple of examples\. The following example applies the tag **key** with the value **value** to a construct\. +The following example applies the tag **key** with the value **value** to a construct\. ------ #### [ TypeScript ] ``` -Tag.add(myConstruct, 'key', 'value'); +Tags.of(myConstruct).add('key', 'value'); ``` ------ #### [ JavaScript ] ``` -Tag.add(myConstruct, 'key', 'value'); +Tags.of(myConstruct).add('key', 'value'); ``` ------ #### [ Python ] ``` -Tag.add(my_construct, "key", "value") +Tags.of(my_construct).add("key", "value") ``` ------ #### [ Java ] ``` -Tag.add(myConstruct, "key", "value"); +Tags.of(myConstruct).add("key", "value"); ``` ------ #### [ C\# ] ``` -Tag.Add(myConstruct, "key", "value"); +Tags.Of(myConstruct).Add("key", "value"); ``` ------ @@ -52,40 +52,42 @@ The following example deletes the tag **key** from a construct\. #### [ TypeScript ] ``` -Tag.remove(my_construct, 'key'); +Tags.of(myConstruct).remove('key'); ``` ------ #### [ JavaScript ] ``` -Tag.remove(my_construct, 'key'); +Tags.of(myConstruct).remove('key'); ``` ------ #### [ Python ] ``` -Tag.remove(my_construct, "key") +Tags.of(my_construct).remove("key") ``` ------ #### [ Java ] ``` -Tag.remove(myConstruct, "key"); +Tags.of(myConstruct).remove("key"); ``` ------ #### [ C\# ] ``` -Tag.Remove(myConstruct, "key"); +Tags.Of(myConstruct).Remove("key"); ``` ------ -The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. If the priorities are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 and removing a tag has a priority of 200\. To change the priority of applying a tag, pass a `priority` property to `Tag.add()` or `Tag.remove()`\. +## Tag priorities + +The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. The following applies a tag with a priority of 300 to a construct\. @@ -93,7 +95,7 @@ The following applies a tag with a priority of 300 to a construct\. #### [ TypeScript ] ``` -Tag.add(myConstruct, 'key', 'value', { +Tags.of(myConstruct).add('key', 'value', { priority: 300 }); ``` @@ -102,7 +104,7 @@ Tag.add(myConstruct, 'key', 'value', { #### [ JavaScript ] ``` -Tag.add(myConstruct, 'key', 'value', { +Tags.of(myConstruct).add('key', 'value', { priority: 300 }); ``` @@ -111,14 +113,14 @@ Tag.add(myConstruct, 'key', 'value', { #### [ Python ] ``` -Tag.add(my_construct, "key", "value", priority=300) +Tags.of(my_construct).add("key", "value", priority=300) ``` ------ #### [ Java ] ``` -Tag.add(myConstruct, "key", "value", TagProps.builder() +Tags.of(myConstruct).add("key", "value", TagProps.builder() .priority(300).build()); ``` @@ -126,14 +128,23 @@ Tag.add(myConstruct, "key", "value", TagProps.builder() #### [ C\# ] ``` -Tag.Add(myConstruct, "key", "value", new TagProps { Priority = 300 }); +Tags.Of(myConstruct).Add("key", "value", new TagProps { Priority = 300 }); ``` ------ -## Tag\.add\(\) +## Optional properties + +Tags support [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.TagProps.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.TagProps.html) that fine\-tune how tags are applied to, or removed from, resources\. All properties are optional\. + +`applyToLaunchedInstances` \(Python: `apply_to_launched_instances`\) +Available for add\(\) only\. By default, tags are applied to instances launched in an Auto Scaling group\. Set this property to **false** to ignore instances launched in an Auto Scaling group\. + +`includeResourceTypes`/`excludeResourceTypes` \(Python: `include_resource_types`/`exclude_resource_types`\) +Use these to manipulate tags only on a subset of resources, based on AWS CloudFormation resource types\. By default, the operation is applied to all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. -`Tag.add()` supports properties that fine\-tune how tags are applied to resources\. All properties are optional\. +`priority` +Use this to set the priority of this operation with respect to other `Tags.add()` and `Tags.remove()` operations\. Higher values take precedence over lower values\. The default is 100 for add operations \(50 for tags applied directly to AWS CloudFormation resources\) and 200 for remove operations\. The following example applies the tag **tagname** with the value **value** and priority **100** to resources of type **AWS::Xxx::Yyy** in the construct, but not to instances launched in an Amazon EC2 Auto Scaling group or to resources of type **AWS::Xxx::Zzz**\. \(These are placeholders for two arbitrary but different AWS CloudFormation resource types\.\) @@ -141,7 +152,7 @@ The following example applies the tag **tagname** with the value **value** and p #### [ TypeScript ] ``` -Tag.add(myConstruct, 'tagname', 'value', { +Tags.of(myConstruct).add('tagname', 'value', { applyToLaunchedInstances: false, includeResourceTypes: ['AWS::Xxx::Yyy'], excludeResourceTypes: ['AWS::Xxx::Zzz'], @@ -153,7 +164,7 @@ Tag.add(myConstruct, 'tagname', 'value', { #### [ JavaScript ] ``` -Tag.add(myConstruct, 'tagname', 'value', { +Tags.of(myConstruct).add('tagname', 'value', { applyToLaunchedInstances: false, includeResourceTypes: ['AWS::Xxx::Yyy'], excludeResourceTypes: ['AWS::Xxx::Zzz'], @@ -165,7 +176,7 @@ Tag.add(myConstruct, 'tagname', 'value', { #### [ Python ] ``` -Tag.add(my_construct, "tagname", "value", +Tags.of((my_construct).add("tagname", "value", apply_to_launched_instances=False, include_resource_types=["AWS::Xxx::Yyy"], exclude_resource_types=["AWS::Xxx::Zzz"], @@ -176,7 +187,7 @@ Tag.add(my_construct, "tagname", "value", #### [ Java ] ``` -Tag.add(myConstruct, "key", "value", TagProps.builder() +Tags.of(myConstruct).add("key", "value", TagProps.builder() .applyToLaunchedInstances(false) .includeResourceTypes(Arrays.asList("AWS::Xxx::Yyy")) .excludeResourceTypes(Arrays.asList("AWS::Xxx::Zzz")) @@ -187,7 +198,7 @@ Tag.add(myConstruct, "key", "value", TagProps.builder() #### [ C\# ] ``` -Tag.Add(myConstruct, "tagname", "value", new TagProps +Tags.Of(myConstruct).Add("tagname", "value", new TagProps { ApplyToLaunchedInstances = false, IncludeResourceTypes = ["AWS::Xxx::Yyy"], @@ -198,28 +209,13 @@ Tag.Add(myConstruct, "tagname", "value", new TagProps ------ -These properties have the following meanings\. - -applyToLaunchedInstances \(Python: apply\_to\_launched\_instances\) -By default, tags are applied to instances launched in an Auto Scaling group\. Set this property to **false** to not apply tags to instances launched in an Auto Scaling group\. - -includeResourceTypes/excludeResourceTypes \(Python: include\_resource\_types, exclude\_resource\_types\) - Use these to apply tags only to a subset of resources, based on AWS CloudFormation resource types\. By default, the tag is applied to all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. - -priority -Use this to set the priority of this operation with respect to other `Tag.add()` and `Tag.remove()` operations\. Higher values take precedence over lower values\. The default is 100\. - -## Tag\.remove\(\) - - `Tag.remove()` supports properties to fine\-tune how tags are removed from resources\. All properties are optional\. - The following example removes the tag **tagname** with priority **200** from resources of type **AWS::Xxx::Yyy** in the construct, but not from resources of type **AWS::Xxx::Zzz**\. ------ #### [ TypeScript ] ``` -Tag.remove(myConstruct, 'tagname', { +Tags.of(myConstruct).remove('tagname', { includeResourceTypes: ['AWS::Xxx::Yyy'], excludeResourceTypes: ['AWS::Xxx::Zzz'], priority: 200, @@ -230,7 +226,7 @@ Tag.remove(myConstruct, 'tagname', { #### [ JavaScript ] ``` -Tag.remove(myConstruct, 'tagname', { +Tags.of(myConstruct).remove('tagname', { includeResourceTypes: ['AWS::Xxx::Yyy'], excludeResourceTypes: ['AWS::Xxx::Zzz'], priority: 200 @@ -241,7 +237,7 @@ Tag.remove(myConstruct, 'tagname', { #### [ Python ] ``` -Tag.remove(my_construct, "tagname", +Tags.rof(my_construct).remove("tagname", include_resource_types=["AWS::Xxx::Yyy"], exclude_resource_types=["AWS::Xxx::Zzz"], priority=200,) @@ -251,7 +247,7 @@ Tag.remove(my_construct, "tagname", #### [ Java ] ``` -Tag.remove(myConstruct, "tagname", TagProps.builder() +Tags.of((myConstruct).remove("tagname", TagProps.builder() .includeResourceTypes(Arrays.asList("AWS::Xxx::Yyy")) .excludeResourceTypes(Arrays.asList("AWS::Xxx::Zzz")) .priority(100).build()); @@ -261,7 +257,7 @@ Tag.remove(myConstruct, "tagname", TagProps.builder() #### [ C\# ] ``` -Tag.Remove(myConstruct, "tagname", "value", new TagProps +Tags.Of(myConstruct).Remove("tagname", new TagProps { IncludeResourceTypes = ["AWS::Xxx::Yyy"], ExcludeResourceTypes = ["AWS::Xxx::Zzz"], @@ -271,14 +267,6 @@ Tag.Remove(myConstruct, "tagname", "value", new TagProps ------ -These properties have the following meanings\. - -includeResourceTypes/excludeResourceTypes -\(Python: include\_resource\_types/exclude\_resource\_types\) Use these properties to remove tags only from subset of resources based on AWS CloudFormation resource types\. By default, the tag is removed from all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. - -priority -Use this property to specify the priority of this operation with respect to other `Tag.add()` and `Tag.remove()` operations\. Higher values take precedence over lower values\. The default is 200\. - ## Example The following example adds the tag key **StackType** with value **TheBest** to any resource created within the Stack named `MarketingSystem`\. Then it removes it again from all resources except Amazon EC2 VPC subnets\. The result is that only the subnets have the tag applied\. @@ -287,16 +275,16 @@ The following example adds the tag key **StackType** with value **TheBest** to a #### [ TypeScript ] ``` -import { App, Stack, Tag } from '@aws-cdk/core'; +import { App, Stack, Tags } from '@aws-cdk/core'; const app = new App(); const theBestStack = new Stack(app, 'MarketingSystem'); // Add a tag to all constructs in the stack -Tag.add(theBestStack, 'StackType', 'TheBest'); +Tags.of(theBestStack).add('StackType', 'TheBest'); // Remove the tag from all resources except subnet resources -Tag.remove(theBestStack, 'StackType', { +Tags.of(theBestStack).remove('StackType', { excludeResourceTypes: ['AWS::EC2::Subnet'] }); ``` @@ -311,10 +299,10 @@ const app = new App(); const theBestStack = new Stack(app, 'MarketingSystem'); // Add a tag to all constructs in the stack -Tag.add(theBestStack, 'StackType', 'TheBest'); +Tags.of(theBestStack).add('StackType', 'TheBest'); // Remove the tag from all resources except subnet resources -Tag.remove(theBestStack, 'StackType', { +Tags.of(theBestStack).remove'StackType', { excludeResourceTypes: ['AWS::EC2::Subnet'] }); ``` @@ -329,10 +317,10 @@ app = App(); the_best_stack = Stack(app, 'MarketingSystem') # Add a tag to all constructs in the stack -Tag.add(the_best_stack, "StackType", "TheBest") +Tags.of(the_best_stack).add("StackType", "TheBest") # Remove the tag from all resources except subnet resources -Tag.remove(the_best_stack, "StackType", +Tags.of(the_best_stack).remove("StackType", exclude_resource_types=["AWS::EC2::Subnet"]) ``` @@ -344,10 +332,10 @@ import software.amazon.awscdk.core.App; import software.amazon.awscdk.core.Tag; // Add a tag to all constructs in the stack -Tag.add(theBestStack, "StackType", "TheBest"); +Tags.of(theBestStack).add("StackType", "TheBest"); // Remove the tag from all resources except subnet resources -Tag.remove(theBestStack, "StackType", TagProps.builder() +Tags.of(theBestStack).remove("StackType", TagProps.builder() .excludeResourceTypes(Arrays.asList("AWS::EC2::Subnet")) .build()); ``` @@ -362,10 +350,10 @@ var app = new App(); var theBestStack = new Stack(app, 'MarketingSystem'); // Add a tag to all constructs in the stack -Tag.Add(theBestStack, "StackType", "TheBest"); +Tags.Of(theBestStack).Add("StackType", "TheBest"); // Remove the tag from all resources except subnet resources -Tag.Remove(theBestStack, "StackType", new TagProps +Tags.Of(theBestStack).Remove("StackType", new TagProps { ExcludeResourceTypes = ["AWS::EC2::Subnet"] }); @@ -379,7 +367,7 @@ The following code achieves the same result\. Consider which approach \(inclusio #### [ TypeScript ] ``` -Tag.add(theBestStack, 'StackType', 'TheBest', +Tags.of(theBestStack).add('StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet']}); ``` @@ -387,7 +375,7 @@ Tag.add(theBestStack, 'StackType', 'TheBest', #### [ JavaScript ] ``` -Tag.add(theBestStack, 'StackType', 'TheBest', +Tags.of(theBestStack).add('StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet']}); ``` @@ -395,7 +383,7 @@ Tag.add(theBestStack, 'StackType', 'TheBest', #### [ Python ] ``` -Tag.add(the_best_stack, "StackType", "TheBest", +Tags.of(the_best_stack).add("StackType", "TheBest", include_resource_types=["AWS::EC2::Subnet"]) ``` @@ -403,7 +391,7 @@ Tag.add(the_best_stack, "StackType", "TheBest", #### [ Java ] ``` -Tag.add(theBestStack, "StackType", "TheBest", TagProps.builder() +Tags.of(theBestStack).add("StackType", "TheBest", TagProps.builder() .includeResourceTypes(Arrays.asList("AWS::EC2::Subnet")) .build()); ``` @@ -412,7 +400,7 @@ Tag.add(theBestStack, "StackType", "TheBest", TagProps.builder() #### [ C\# ] ``` -Tag.Add(theBestStack, "StackType", "TheBest", new TagProps { +Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps { IncludeResourceTypes = ["AWS::EC2::Subnet"] }); ``` From ae09976868fa304dab2a26f81e1714eb8bad148b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 2 Nov 2020 20:23:32 +0000 Subject: [PATCH 318/655] remind where virtualenv used to be --- doc_source/work-with-cdk-python.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 34d95dab..43664097 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -42,9 +42,10 @@ source .venv/bin/activate ``` **Note** -You may recognize this as the Mac/Linux command to activate a virtual environment\. The Python templates include a batch file, `source.bat`, that allows the same command to be used on Windows\. The traditional Windows command, `.venv\Scripts\activate.bat`, works, too\. +You may recognize this as the Mac/Linux command to activate a virtual environment\. The Python templates include a batch file, `source.bat`, that allows the same command to be used on Windows\. The traditional Windows command, `.venv\Scripts\activate.bat`, works, too\. +If you initialized your AWS CDK project using CDK Toolkit v1\.70\.0 or earlier, your vertual environment is in the `.env` directory instead of `.venv`\. -Then install the app's standard dependencies: +After activating your virtual environment, install the app's standard dependencies: ``` python -m pip install -r requirements.txt From 555f9710f4e00fd9031208e00469c66a708b3c2a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 2 Nov 2020 20:23:48 +0000 Subject: [PATCH 319/655] bulid system changed some IDs --- doc_source/cli.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index e7e971ca..46c7299b 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -259,7 +259,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -278,7 +278,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -286,7 +286,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -310,7 +310,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -332,7 +332,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -507,7 +507,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -520,7 +520,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -533,7 +533,7 @@ Options: dependencies [boolean] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -583,7 +583,7 @@ Options: example). [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -629,7 +629,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -645,7 +645,7 @@ Options: [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -665,7 +665,7 @@ Options: [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -688,7 +688,7 @@ Options: [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context From 916bddfe0f58d3a194432ebf3bda081e3ddd06c0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 3 Nov 2020 22:27:30 +0000 Subject: [PATCH 320/655] use new Aspects API --- doc_source/aspects.md | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/doc_source/aspects.md b/doc_source/aspects.md index 080bb27e..ad2ee822 100644 --- a/doc_source/aspects.md +++ b/doc_source/aspects.md @@ -1,51 +1,51 @@ # Aspects -Aspects are the way to apply an operation to all constructs in a given scope\. The functionality could modify the constructs, such as by adding tags, or it could be verifying something about the state of the constructs, such as ensuring that all buckets are encrypted\. +Aspects are a way to apply an operation to all constructs in a given scope\. The aspect could modify the constructs, such as by adding tags, or it could verify something about the state of the constructs, such as ensuring that all buckets are encrypted\. -To apply an aspect to a construct and all constructs in the same scope, call [node\.applyAspect](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.ConstructNode.html#apply-aspectaspect) \(Python: `apply_aspect`\) with a new aspect, as shown in the following example\. +To apply an aspect to a construct and all constructs in the same scope, call [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Aspects.html#static-ofscope](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Aspects.html#static-ofscope)`.of(SCOPE).add()` with a new aspect, as shown in the following example\. ------ #### [ TypeScript ] ``` -myConstruct.node.applyAspect(new SomeAspect(/*...*/)); +Aspects.of(myConstruct).add(new SomeAspect(...)); ``` ------ #### [ JavaScript ] ``` -myConstruct.node.applyAspect(new SomeAspect()); +Aspects.of(myConstruct).add(new SomeAspect(...)); ``` ------ #### [ Python ] ``` -my_construct.node.apply_aspect(SomeAspect(...)) +Aspects.of(my_construct).add(SomeAspect(...)) ``` ------ #### [ Java ] ``` -myConstruct.getNode().applyAspect(new SomeAspect(...)); +Aspects.of(myConstruct).add(new SomeAspect(...)); ``` ------ #### [ C\# ] ``` -myConstruct.Node.ApplyAspect(new SomeAspect(...)); +Aspects.Of(myConstruct).add(new SomeAspect(...)); ``` ------ -The AWS CDK currently uses aspects only to [tag resources](tagging.md), but the framework is extensible and can also be used for other purposes\. For example, you can use it to validate or change the AWS CloudFormation resources that are defined for you\. +The AWS CDK currently uses aspects only to [tag resources](tagging.md), but the framework is extensible and can also be used for other purposes\. For example, you can use it to validate or change the AWS CloudFormation resources that are defined for you by higher\-level constructs\. ## Aspects in detail -The AWS CDK implements tagging using a more generic system, called *aspects*, which is an instance of the visitor pattern\. An aspect is a class that implements the following interface\. +Aspects employ the [visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern)\. An aspect is a class that implements the following interface\. ------ #### [ TypeScript ] @@ -86,11 +86,11 @@ public interface IAspect ------ -When you call `construct.node.applyAspect(aspect)` \(Python: `apply_aspect`\) the construct adds the aspect to an internal list of aspects\. +When you call `Aspects.of(SCOPE).add(...)`, the construct adds the aspect to an internal list of aspects\. You can obtain the list with `Aspects.of(SCOPE)`\. During the [prepare phase](apps.md#lifecycle), the AWS CDK calls the `visit` method of the object for the construct and each of its children in top\-down order\. -Although the aspect object is free to change any aspect of the construct object, it only operates on a specific subset of construct types\. After determining the construct type, it can call any method and inspect or assign any property on the construct\. +Although the aspect object is free to change any aspect of the construct, it only operates on a specific subset of construct types\. After determining the construct type, it can call any method and inspect or assign any property on the construct\. ## Example @@ -116,8 +116,8 @@ class BucketVersioningChecker implements IAspect { } } -// Apply to the stack -stack.node.applyAspect(new BucketVersioningChecker()); +// Later, apply to the stack +Aspects.of(stack).add(new BucketVersioningChecker()); ``` ------ @@ -140,8 +140,8 @@ class BucketVersioningChecker { } } -// Apply to the stack -stack.node.applyAspect(new BucketVersioningChecker()); +// Later, apply to the stack +Aspects.of(stack).add(new BucketVersioningChecker()); ``` ------ @@ -163,8 +163,8 @@ class BucketVersioningChecker: node.node.add_error('Bucket versioning is not enabled') -# Apply to the stack -stack.node.apply_aspect(BucketVersioningChecker()) +# Later, apply to the stack +Aspects.of(stack).add(BucketVersioningChecker()) ``` ------ @@ -188,6 +188,10 @@ public class BucketVersioningChecker implements IAspect } } } + + +// Later, apply to the stack +Aspects.of(stack).add(new BucketVersioningChecker()); ``` ------ @@ -209,6 +213,9 @@ class BucketVersioningChecker : Amazon.Jsii.Runtime.DeputyBase, IAspect } } } + +// Later, apply to the stack +Aspects.Of(stack).add(new BucketVersioningChecker()); ``` ------ \ No newline at end of file From 66a9a2d0b931593c70a56fa7f26a6bc4fef1db61 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 3 Nov 2020 22:28:21 +0000 Subject: [PATCH 321/655] make imports consistent --- doc_source/hello_world.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 2643ebd0..8243e87d 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -214,11 +214,11 @@ Next, define an Amazon S3 bucket in the stack using an L2 construct, the [Bucket In `lib/hello-cdk-stack.ts`: ``` -import * as core from '@aws-cdk/core'; +import * as cdk from '@aws-cdk/core'; import * as s3 from '@aws-cdk/aws-s3'; -export class HelloCdkStack extends core.Stack { - constructor(scope: core.App, id: string, props?: core.StackProps) { +export class HelloCdkStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); new s3.Bucket(this, 'MyFirstBucket', { @@ -234,10 +234,10 @@ export class HelloCdkStack extends core.Stack { In `lib/hello-cdk-stack.js`: ``` -const core = require('@aws-cdk/core'); +const cdk = require('@aws-cdk/core'); const s3 = require('@aws-cdk/aws-s3'); -class HelloCdkStack extends core.Stack { +class HelloCdkStack extends cdk.Stack { constructor(scope, id, props) { super(scope, id, props); @@ -258,7 +258,7 @@ Replace the first import statement in `hello_cdk_stack.py` in the `hello_cdk` di ``` from aws_cdk import ( aws_s3 as s3, - core + core as cdk ) ``` @@ -406,7 +406,7 @@ Update `lib/hello-cdk-stack.ts` ``` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, - removalPolicy: core.RemovalPolicy.DESTROY + removalPolicy: cdk.RemovalPolicy.DESTROY }); ``` @@ -418,7 +418,7 @@ Update `lib/hello-cdk-stack.js`\. ``` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, - removalPolicy: core.RemovalPolicy.DESTROY + removalPolicy: cdk.RemovalPolicy.DESTROY }); ``` @@ -431,7 +431,7 @@ Update `hello_cdk/hello_cdk_stack.py` bucket = s3.Bucket(self, "MyFirstBucket", versioned=True, - removal_policy=core.RemovalPolicy.DESTROY) + removal_policy=cdk.RemovalPolicy.DESTROY) ``` ------ From d7fc7611494b8cf45c927e17bf4ce27339d4d445 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 3 Nov 2020 22:29:17 +0000 Subject: [PATCH 322/655] change Java keywords that sneaked into C# example --- doc_source/work-with-cdk-csharp.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index ed19ed2a..b7b5b5c5 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -125,7 +125,7 @@ class MimeBucketProps : BucketProps { // hypothetical bucket that enforces MIME type of objects inside it class MimeBucket : Bucket { - public MimeBucket(final Construct scope, final string id, final MimeBucketProps props=null) : base(scope, id, props) { + public MimeBucket( readonly Construct scope, readonly string id, readonly MimeBucketProps props=null) : base(scope, id, props) { // ... } } From 2e6e281efe41400027a9b1f1b7f9283f79474c7d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 3 Nov 2020 22:29:51 +0000 Subject: [PATCH 323/655] add missing line to Java snippet --- doc_source/serverless_example.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index d4f493ca..a0571eb7 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -812,7 +812,7 @@ File: `src/src/main/java/com/myorg/WidgetService.java` ``` Resource widget = api.getRoot().addResource("{id}"); - + // Add new widget to bucket with: POST /{id} LambdaIntegration postWidgetIntegration = new LambdaIntegration(handler); @@ -876,4 +876,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` +``` \ No newline at end of file From 1e1e8f4b33bc115a43cf2054bf118f793f10a25f Mon Sep 17 00:00:00 2001 From: Erik Karlsson Date: Wed, 4 Nov 2020 00:56:18 +0100 Subject: [PATCH 324/655] Added examples of overrides of properties in lists Looked around the internet and tested a lot of ways, before realizing how to override properties burried in listed objects Was thinking it would be nice to have such an example in the documentation as well! --- doc_source/cfn_layer.md | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index e97e37b6..ae16d370 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -329,11 +329,15 @@ const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; // Use dot notation to address inside the resource template fragment cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); +cfnBucket.addOverride('Properties.Tags.0.Value', 'NewValue'); +cfnBucket.addDeletionOverride('Properties.Tags.0'); -// addPropertyOverride is a convenience function, which implies the +// AddPropertyOverride is a convenience function, which implies the // path starts with "Properties." cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); +cfnBucket.addPropertyOverride('Tags.0.Value', 'NewValue'); +cfnBucket.addPropertyDeletionOverride('Tags.0'); ``` ------ @@ -346,11 +350,15 @@ const cfnBucket = bucket.node.defaultChild ; // Use dot notation to address inside the resource template fragment cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); +cfnBucket.addOverride('Properties.Tags.0.Value', 'NewValue'); +cfnBucket.addDeletionOverride('Properties.Tags.0'); -// addPropertyOverride is a convenience function, which implies the +// AddPropertyOverride is a convenience function, which implies the // path starts with "Properties." cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); +cfnBucket.addPropertyOverride('Tags.0.Value', 'NewValue'); +cfnBucket.addPropertyDeletionOverride('Tags.0'); ``` ------ @@ -363,11 +371,15 @@ cfn_bucket = bucket.node.default_child # Use dot notation to address inside the resource template fragment cfn_bucket.add_override("Properties.VersioningConfiguration.Status", "NewStatus") cfn_bucket.add_deletion_override("Properties.VersioningConfiguration.Status") +cfn_bucket.add_override("Properties.Tags.0.Value", "NewValue"); +cfn_bucket.add_deletion_override("Properties.Tags.0"); # add_property_override is a convenience function, which implies the # path starts with "Properties." cfn_bucket.add_property_override("VersioningConfiguration.Status", "NewStatus") cfn_bucket.add_property_deletion_override("VersioningConfiguration.Status") +cfn_bucket.add_property_override("Tags.0.Value", "NewValue"); +cfn_bucket.add_property_deletion_override("Tags.0"); ``` ------ @@ -380,11 +392,15 @@ CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); // Use dot notation to address inside the resource template fragment cfnBucket.addOverride("Properties.VersioningConfiguration.Status", "NewStatus"); cfnBucket.addDeletionOverride("Properties.VersioningConfiguration.Status"); +cfnBucket.addOverride("Properties.Tags.0.Value", "NewValue"); +cfnBucket.addDeletionOverride("Properties.Tags.0"); -// addPropertyOverride is a convenience function, which implies the +// AddPropertyOverride is a convenience function, which implies the // path starts with "Properties." cfnBucket.addPropertyOverride("VersioningConfiguration.Status", "NewStatus"); cfnBucket.addPropertyDeletionOverride("VersioningConfiguration.Status"); +cfnBucket.addPropertyOverride("Tags.0.Value", "NewValue"); +cfnBucket.addPropertyDeletionOverride("Tags.0"); ``` ------ @@ -397,11 +413,15 @@ var cfnBucket = (CfnBucket)bucket.node.defaultChild; // Use dot notation to address inside the resource template fragment cfnBucket.AddOverride("Properties.VersioningConfiguration.Status", "NewStatus"); cfnBucket.AddDeletionOverride("Properties.VersioningConfiguration.Status"); +cfnBucket.AddOverride("Properties.Tags.0.Value", "NewValue"); +cfnBucket.AddDeletionOverride("Properties.Tags.0"); // AddPropertyOverride is a convenience function, which implies the // path starts with "Properties." cfnBucket.AddPropertyOverride("VersioningConfiguration.Status", "NewStatus"); cfnBucket.AddPropertyDeletionOverride("VersioningConfiguration.Status"); +cfnBucket.AddPropertyOverride("Tags.0.Value", "NewValue"); +cfnBucket.AddPropertyDeletionOverride("Tags.0"); ``` ------ @@ -415,4 +435,4 @@ Building a custom resource involves writing a Lambda function that responds to a The subject is too broad to completely cover here, but the following links should get you started: + [Custom Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) + [Custom\-Resource Example](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) -+ For a more fully fledged example, see the [DnsValidatedCertificate](https://github.com/awslabs/aws-cdk/blob/master/packages/@aws-cdk/aws-certificatemanager/lib/dns-validated-certificate.ts) class in the CDK standard library\. This is implemented as a custom resource\. \ No newline at end of file ++ For a more fully fledged example, see the [DnsValidatedCertificate](https://github.com/awslabs/aws-cdk/blob/master/packages/@aws-cdk/aws-certificatemanager/lib/dns-validated-certificate.ts) class in the CDK standard library\. This is implemented as a custom resource\. From b27355995f85ef6b8f857735c1cffc93d6e70991 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 9 Nov 2020 17:41:21 +0000 Subject: [PATCH 325/655] typo --- doc_source/constructs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index f1cbfceb..aa0a997f 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -987,7 +987,7 @@ Constructs are *always* explicitly defined within the scope of another construct Passing the scope explicitly allows each construct to add itself to the tree, with this behavior entirely contained within the [`Construct` base class](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html)\. It works the same way in every language supported by the AWS CDK and does not require introspection or other "magic\." **Important** -Technically, it's possible to pass some scope other than `this` when instantiating a construct, which allows you to add constructs anywhere in the tree, even in another stack entirely\. For example, you could write a mixin\-style function that adds constructs to a scope passed in as an argument\. The practical difficulty here is that it you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope\. The practice also makes your code more difficult to understand, maintain, and reuse\. It is virtually always better to find a way to express your intent without resorting to abusing the `scope` argument\. +Technically, it's possible to pass some scope other than `this` when instantiating a construct, which allows you to add constructs anywhere in the tree, even in another stack entirely\. For example, you could write a mixin\-style function that adds constructs to a scope passed in as an argument\. The practical difficulty here is that you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope\. The practice also makes your code more difficult to understand, maintain, and reuse\. It is virtually always better to find a way to express your intent without resorting to abusing the `scope` argument\. The AWS CDK uses the IDs of all constructs in the path from the tree's root to each child construct to generate the unique IDs required by AWS CloudFormation\. This approach means that construct IDs need be unique only within their scope, rather than within the entire stack as in native AWS CloudFormation\. It does, however, mean that if you move a construct to a different scope, its generated stack\-unique ID will change, and AWS CloudFormation will no longer consider it the same resource\. From 86cd39aa3b3fa9518c5402625ff0910944dbd057 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 9 Nov 2020 17:41:52 +0000 Subject: [PATCH 326/655] add example of overriding element in list (tag in this case), tweaks to PR279 --- doc_source/cfn_layer.md | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index ae16d370..4679bb50 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -329,11 +329,12 @@ const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; // Use dot notation to address inside the resource template fragment cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); + +// use index (0 here) to address an element of a list cfnBucket.addOverride('Properties.Tags.0.Value', 'NewValue'); cfnBucket.addDeletionOverride('Properties.Tags.0'); -// AddPropertyOverride is a convenience function, which implies the -// path starts with "Properties." +// addPropertyOverride is a convenience function for paths starting with "Properties." cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); cfnBucket.addPropertyOverride('Tags.0.Value', 'NewValue'); @@ -350,11 +351,12 @@ const cfnBucket = bucket.node.defaultChild ; // Use dot notation to address inside the resource template fragment cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); + +// use index (0 here) to address an element of a list cfnBucket.addOverride('Properties.Tags.0.Value', 'NewValue'); cfnBucket.addDeletionOverride('Properties.Tags.0'); -// AddPropertyOverride is a convenience function, which implies the -// path starts with "Properties." +// addPropertyOverride is a convenience function for paths starting with "Properties." cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); cfnBucket.addPropertyOverride('Tags.0.Value', 'NewValue'); @@ -371,15 +373,16 @@ cfn_bucket = bucket.node.default_child # Use dot notation to address inside the resource template fragment cfn_bucket.add_override("Properties.VersioningConfiguration.Status", "NewStatus") cfn_bucket.add_deletion_override("Properties.VersioningConfiguration.Status") -cfn_bucket.add_override("Properties.Tags.0.Value", "NewValue"); -cfn_bucket.add_deletion_override("Properties.Tags.0"); -# add_property_override is a convenience function, which implies the -# path starts with "Properties." +# use index (0 here) to address an element of a list +cfn_bucket.add_override("Properties.Tags.0.Value", "NewValue") +cfn_bucket.add_deletion_override("Properties.Tags.0") + +# addPropertyOverride is a convenience function for paths starting with "Properties." cfn_bucket.add_property_override("VersioningConfiguration.Status", "NewStatus") cfn_bucket.add_property_deletion_override("VersioningConfiguration.Status") -cfn_bucket.add_property_override("Tags.0.Value", "NewValue"); -cfn_bucket.add_property_deletion_override("Tags.0"); +cfn_bucket.add_property_override("Tags.0.Value", "NewValue") +cfn_bucket.add_property_deletion_override("Tags.0") ``` ------ @@ -392,11 +395,12 @@ CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); // Use dot notation to address inside the resource template fragment cfnBucket.addOverride("Properties.VersioningConfiguration.Status", "NewStatus"); cfnBucket.addDeletionOverride("Properties.VersioningConfiguration.Status"); + +// use index (0 here) to address an element of a list cfnBucket.addOverride("Properties.Tags.0.Value", "NewValue"); cfnBucket.addDeletionOverride("Properties.Tags.0"); -// AddPropertyOverride is a convenience function, which implies the -// path starts with "Properties." +// addPropertyOverride is a convenience function for paths starting with "Properties." cfnBucket.addPropertyOverride("VersioningConfiguration.Status", "NewStatus"); cfnBucket.addPropertyDeletionOverride("VersioningConfiguration.Status"); cfnBucket.addPropertyOverride("Tags.0.Value", "NewValue"); @@ -413,11 +417,12 @@ var cfnBucket = (CfnBucket)bucket.node.defaultChild; // Use dot notation to address inside the resource template fragment cfnBucket.AddOverride("Properties.VersioningConfiguration.Status", "NewStatus"); cfnBucket.AddDeletionOverride("Properties.VersioningConfiguration.Status"); + +// use index (0 here) to address an element of a list cfnBucket.AddOverride("Properties.Tags.0.Value", "NewValue"); cfnBucket.AddDeletionOverride("Properties.Tags.0"); -// AddPropertyOverride is a convenience function, which implies the -// path starts with "Properties." +// addPropertyOverride is a convenience function for paths starting with "Properties." cfnBucket.AddPropertyOverride("VersioningConfiguration.Status", "NewStatus"); cfnBucket.AddPropertyDeletionOverride("VersioningConfiguration.Status"); cfnBucket.AddPropertyOverride("Tags.0.Value", "NewValue"); @@ -435,4 +440,4 @@ Building a custom resource involves writing a Lambda function that responds to a The subject is too broad to completely cover here, but the following links should get you started: + [Custom Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) + [Custom\-Resource Example](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) -+ For a more fully fledged example, see the [DnsValidatedCertificate](https://github.com/awslabs/aws-cdk/blob/master/packages/@aws-cdk/aws-certificatemanager/lib/dns-validated-certificate.ts) class in the CDK standard library\. This is implemented as a custom resource\. ++ For a more fully fledged example, see the [DnsValidatedCertificate](https://github.com/awslabs/aws-cdk/blob/master/packages/@aws-cdk/aws-certificatemanager/lib/dns-validated-certificate.ts) class in the CDK standard library\. This is implemented as a custom resource\. \ No newline at end of file From 0a82eb0901ef44428e1c5c4797ae3c820a66feb9 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 9 Nov 2020 23:50:05 +0000 Subject: [PATCH 327/655] update .NET requirements --- doc_source/getting_started.md | 21 ++++++++------------- doc_source/work-with-cdk-csharp.md | 15 +++++---------- 2 files changed, 13 insertions(+), 23 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 98942b2f..1219e454 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -115,17 +115,12 @@ Furthermore, since TypeScript was the first language supported by the AWS CDK, m With the concepts out of the way, here's what you need to have on your workstation before you install the AWS CDK and start developing\. -All CDK developers need to [install Node\.js](https://nodejs.org/en/download/) 10\.3\.0 or later, even those working in languages other than TypeScript or JavaScript\. The AWS CDK Toolkit \(cdk command\-line tool\) and the AWS Construct Library are developed in TypeScript and run on Node\.js\. The bindings for other supported languages use this back end and tool set\. We suggest the latest LTS version\. +All CDK developers need to [install Node\.js](https://nodejs.org/en/download/) 10\.3\.0 or later, even those working in languages other than TypeScript or JavaScript\. The AWS CDK Toolkit \(cdk command\-line tool\) and the AWS Construct Library run on Node\.js\. The bindings for other supported languages use this back end and tool set\. We suggest the latest LTS version\. **Important** Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK\. -You must provide your credentials and an AWS Region to use AWS CDK, if you have not already done so\. - -**Important** -We strongly recommend against using your AWS root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. Best practices are to change this account's access key regularly and to use a least\-privileges role \(specifying `--role-arn`\) when deploying\. - -If you have the AWS CLI installed, the easiest way to satisfy this requirement is to install the AWS CLI and issue the following command: +You must provide your credentials and an AWS Region to use AWS CDK, if you have not already done so\. If you have the AWS CLI installed, the easiest way to satisfy this requirement is to install the AWS CLI and issue the following command: ``` aws configure @@ -150,7 +145,10 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials Finally, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. -Other prerequisites depend on your development language and are as follows\. +**Important** +We strongly recommend against using your AWS root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. Best practices are to change this account's access key regularly and to use a least\-privileges role \(specifying `--role-arn`\) when deploying\. + +Other prerequisites depend on the language in which you develop AWS CDK applications and are as follows\. ------ #### [ TypeScript ] @@ -175,12 +173,9 @@ Java IDE recommended \(we use Eclipse in some examples in this Developer Guide\) ------ #### [ C\# ] -A \.NET Standard 2\.1\-compatible implementation is required, such as\. -+ \.NET Core 3\.1 or later -+ \.NET Framework 4\.6\.1 or later -+ Mono 5\.4 or later +\.NET Core 3\.1 or later\. -Visual Studio 2019 \(any edition\) recommended\. +Visual Studio 2019 \(any edition\) or Visual Studio Code recommended\. ------ diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index b7b5b5c5..94df3278 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -1,23 +1,18 @@ # Working with the AWS CDK in C\# -\.NET is a fully\-supported client platform for the AWS CDK and is considered stable\. Our \.NET code examples are in C\#\. It is possible to write AWS CDK applications in other \.NET languages, such as Visual Basic or F\#, but we are unable to provide support for these languages\. +\.NET is a fully\-supported client platform for the AWS CDK and is considered stable\. C\# is the main \.NET language we for which provide examples and support\. You can choose to write AWS CDK applications in other \.NET languages, such as Visual Basic or F\#, but AWS offers limited support for these languages\. -You can develop AWS CDK applications in C\# using familiar tools including Visual Studio, the `dotnet` command, and the NuGet package manager\. The modules comprising the AWS Construct Library are distributed via [nuget\.org](https://www.nuget.org/packages?q=amazon.cdk.aws)\. +You can develop AWS CDK applications in C\# using familiar tools including Visual Studio, Visual Studio Code, the `dotnet` command, and the NuGet package manager\. The modules comprising the AWS Construct Library are distributed via [nuget\.org](https://www.nuget.org/packages?q=amazon.cdk.aws)\. -We suggest using [Visual Studio 2019](https://visualstudio.microsoft.com/downloads/) \(any edition\) and the Microsoft \.NET Framework on Windows to develop AWS CDK apps in C\#\. You may use other tools \(for example, Mono on Mac OS X or Linux\), but our ability to provide instruction and support for these environments may be limited\. +We suggest using [Visual Studio 2019](https://visualstudio.microsoft.com/downloads/) \(any edition\) on Windows to develop AWS CDK apps in C\#\. ## Prerequisites To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. -C\# AWS CDK applications require a \.NET Standard 2\.1 compatible implementation\. Suitable implementations include: -+ \.NET Core v3\.1 or later -+ \.NET Framework v4\.6\.1 or later -+ Mono v5\.4 or later on Mac OS X or Linux; [download here](https://www.mono-project.com/download/stable/) +C\# AWS CDK applications require \.NET Core v3\.1 or later, [available here](https://dotnet.microsoft.com/download/dotnet-core/3.1)\. -If you have an up\-to\-date Windows 10 installation, you already have a suitable installation of \.NET Framework\. - -The \.NET Standard toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if you are using Visual Studio, this command is useful for batch operations and for installing AWS Construct Library packages\. +The \.NET Standard toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if work mainly in Visual Studio, this command can be useful for batch operations and for installing AWS Construct Library packages\. ## Creating a project From 3d31443e121397daf2c7675f87098bd7f878308b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 11 Nov 2020 17:58:28 +0000 Subject: [PATCH 328/655] accidentally a word --- doc_source/work-with-cdk-csharp.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 94df3278..d736c091 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -12,7 +12,7 @@ To work with the AWS CDK, you must have an AWS account and credentials and have C\# AWS CDK applications require \.NET Core v3\.1 or later, [available here](https://dotnet.microsoft.com/download/dotnet-core/3.1)\. -The \.NET Standard toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if work mainly in Visual Studio, this command can be useful for batch operations and for installing AWS Construct Library packages\. +The \.NET Standard toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if you work mainly in Visual Studio, this command can be useful for batch operations and for installing AWS Construct Library packages\. ## Creating a project From 8a55f65555af45520d2c28aaf5053223b87fe65d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 11 Nov 2020 23:54:49 +0000 Subject: [PATCH 329/655] fix syntax error in Python code snippet --- doc_source/work-with-cdk-python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 43664097..54a17317 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -43,7 +43,7 @@ source .venv/bin/activate **Note** You may recognize this as the Mac/Linux command to activate a virtual environment\. The Python templates include a batch file, `source.bat`, that allows the same command to be used on Windows\. The traditional Windows command, `.venv\Scripts\activate.bat`, works, too\. -If you initialized your AWS CDK project using CDK Toolkit v1\.70\.0 or earlier, your vertual environment is in the `.env` directory instead of `.venv`\. +If you initialized your AWS CDK project using CDK Toolkit v1\.70\.0 or earlier, your virtual environment is in the `.env` directory instead of `.venv`\. After activating your virtual environment, install the app's standard dependencies: From a4ba5f4d2845e533011421ac28ca9599c969c4e0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 11 Nov 2020 23:55:10 +0000 Subject: [PATCH 330/655] fix typo --- doc_source/tagging.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/tagging.md b/doc_source/tagging.md index e5040d25..3f087305 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -176,11 +176,11 @@ Tags.of(myConstruct).add('tagname', 'value', { #### [ Python ] ``` -Tags.of((my_construct).add("tagname", "value", +Tags.of(my_construct).add("tagname", "value", apply_to_launched_instances=False, include_resource_types=["AWS::Xxx::Yyy"], exclude_resource_types=["AWS::Xxx::Zzz"], - priority=100,) + priority=100) ``` ------ From 67f60e3e40894b69c1cec22c32cb9f5f2746ef81 Mon Sep 17 00:00:00 2001 From: Pavle Portic Date: Thu, 12 Nov 2020 13:42:50 +0100 Subject: [PATCH 331/655] Remove semicolons from python examples --- doc_source/context.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/context.md b/doc_source/context.md index 706b2fa8..48034a3d 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -184,10 +184,10 @@ class ExistsVpcStack(cdk.Stack): super().__init__(scope, id, **kwargs) - vpcid = self.node.try_get_context("vpcid"); + vpcid = self.node.try_get_context("vpcid") vpc = ec2.Vpc.from_lookup(self, "VPC", vpc_id=vpcid) - pubsubnets = vpc.select_subnets(subnetType=ec2.SubnetType.PUBLIC); + pubsubnets = vpc.select_subnets(subnetType=ec2.SubnetType.PUBLIC) cdk.CfnOutput(self, "publicsubnets", value=pubsubnets.subnet_ids.to_string()) From f8afba641a4a4ec2763d288ad4381d8e807b3823 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 16 Nov 2020 03:24:37 +0000 Subject: [PATCH 332/655] minor wording change --- doc_source/hello_world.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 8243e87d..e8841362 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -100,7 +100,7 @@ If you have Git installed, each project you create using cdk init is also initia ## Build the app -Normally, after making any changes to your code, you'd build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you so you can't forget\. But you can still build manually to catch syntax and type errors\. For reference, here's how\. +In most programming environments, after making changes to your code, you'd build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you so you can't forget\. But you can still build manually to catch syntax and type errors\. For reference, here's how\. ------ #### [ TypeScript ] From 5134be155e3ea6d462c4cdce906c08eb78b0f956 Mon Sep 17 00:00:00 2001 From: "Brent D. Eggleston" Date: Tue, 17 Nov 2020 12:21:07 -0700 Subject: [PATCH 333/655] Correct Python API Update the python example to use the 1.74.0 API. See: https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_s3.html See: https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_s3/RedirectTarget.html --- doc_source/getting_started.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 1219e454..c90fd7dc 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -67,8 +67,8 @@ const bucket = new s3.Bucket(this, 'MyBucket', { #### [ Python ] ``` -bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=true, - website_redirect=s3.WebsiteRedirect(host_name="aws.amazon.com")) +bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=True, + website_redirect=s3.RedirectTarget(host_name="aws.amazon.com")) ``` ------ @@ -208,4 +208,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? From 01b519201443e6dcb4c4c98a788a93161b0b2129 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 17 Nov 2020 22:17:40 +0000 Subject: [PATCH 334/655] change WebsiteRedirect to RedirectTarget --- doc_source/getting_started.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index c90fd7dc..8042ecc5 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -78,7 +78,7 @@ bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=True, Bucket bucket = Bucket.Builder.create(self, "MyBucket") .bucketName("my-bucket") .versioned(true) - .websiteRedirect(new websiteRedirect.Builder() + .websiteRedirect(new RedirectTarget.Builder() .hostName("aws.amazon.com").build()) .build(); ``` @@ -90,7 +90,7 @@ Bucket bucket = Bucket.Builder.create(self, "MyBucket") var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-bucket", Versioned = true, - WebsiteRedirect = new WebsiteRedirect { + WebsiteRedirect = new RedirectTarget { HostName = "aws.amazon.com" }}); ``` @@ -208,4 +208,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file From 0fd22fff658b26631a19a0941edad86a8230d250 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 17 Nov 2020 22:30:09 +0000 Subject: [PATCH 335/655] update guidance for building --- doc_source/hello_world.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index e8841362..33e191c7 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -100,7 +100,7 @@ If you have Git installed, each project you create using cdk init is also initia ## Build the app -In most programming environments, after making changes to your code, you'd build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you so you can't forget\. But you can still build manually to catch syntax and type errors\. For reference, here's how\. +In most programming environments, after making changes to your code, you'd build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you so you can't forget\. But you can still build manually whenever you want to catch syntax and type errors\. For reference, here's how\. ------ #### [ TypeScript ] @@ -141,6 +141,9 @@ Or press F6 in Visual Studio ------ +**Note** +If your project was created with an older version of the AWS CDK Toolkit, it may not automatically build when you run it\. If changes you make in your code fail to be reflected in the synthesized template, try a manual build\. Make sure you are using the latest available version of the AWS CDK for this tutorial\. + ## List the stacks in the app Just to verify everything is working correctly, list the stacks in your app\. From 167742938995494d9731589323dafb04bcb3108c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 17 Nov 2020 23:48:40 +0000 Subject: [PATCH 336/655] update CLI help, add info on options/values, note about CMK --- doc_source/cli.md | 290 ++++++++++++++++++++++++++++------------------ 1 file changed, 175 insertions(+), 115 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 46c7299b..c8f9e2d7 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -33,6 +33,33 @@ All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(` For the options available for each command, see [Toolkit reference](#cli-ref) or [Built\-in help](#cli-help)\. +## Specifying options and their values + +Command line options begin with two hyphens \(`--`\)\. Some frequently\-used options have single\-letter synonyms that begin with a single hyphen \(for example, `--app` has a synonym `-a`\)\. The order of options in an AWS CDK Toolkit command is not important\. + +All options accept a value, which must follow the option name\. The value may be separated from the name by whitespace or by an equals sign `=`\. The following two options are equivalent + +``` +--toolkit-stack-name MyBootstrapStack +--toolkit-stack-name=MyBootstrapStack +``` + +Some options are flags \(Booleans\)\. You may specify `true` or `false` as their value\. If you do not provide a value, the value is taken to be `true`\. You may also prefix the option name with `no-` to imply `false`\. + +``` +# sets staging flag to true +--staging +--staging=true +--staging true + +# sets staging flag to false +--no-staging +--staging=false +--staging false +``` + +A few flags, namely `--context`, `--parameters`, `--plugin`, `--tags`, and `--trust`, may be specified more than once to specify multiple values\. These are noted as having `[array]` type in the CDK Toolkit help\. + ## Built\-in help The AWS CDK Toolkit has integrated help\. You can see general help about the utility and a list of the provided subcommands by issuing: @@ -197,7 +224,10 @@ cdk bootstrap --profile test 1111111111/us-east-1 **Important** Each environment \(account/region combination\) to which you deploy such a stack must be bootstrapped separately\. -You may incur AWS charges for what the AWS CDK stores in the bootstrapped resources\. +You may incur AWS charges for what the AWS CDK stores in the bootstrapped resources\. Additionally, if you use `-bootstrap-customer-key`, a Customer Master Key \(CMK\) will be created, which also incurs charges per environment\. + +**Note** +Older versions of the modern template created a Customer Master Key by default\. To avoid charges, re\-bootstrap using `--no-bootstrap-customer-key`\. ## Creating a new app @@ -259,7 +289,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -278,7 +308,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -286,7 +316,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -310,7 +340,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -332,7 +362,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -342,9 +372,7 @@ cdk deploy --outputs-file outputs.json MyStack ## Security\-related changes -To protect you against unintended changes that affect your security posture, the AWS CDK Toolkit prompts you to approve security\-related changes before deploying them\. - -You can change the level of change that requires approval by specifying: +To protect you against unintended changes that affect your security posture, the AWS CDK Toolkit prompts you to approve security\-related changes before deploying them\. You can specify the level of change that requires approval: ``` cdk deploy --require-approval LEVEL @@ -424,8 +452,7 @@ Commands: stack cdk init [TEMPLATE] Create a new, empty CDK project from a - template. Invoked without TEMPLATE, the app - template will be used. + template. cdk context Manage cached context values @@ -436,70 +463,78 @@ Commands: Options: - --app, -a REQUIRED: command-line for executing your app or a cloud - assembly directory (e.g. "node bin/my-app.js") [string] + -a, --app REQUIRED: command-line for executing your app or a + cloud assembly directory (e.g. "node bin/my-app.js") + [string] + + -c, --context Add contextual string parameter (KEY=VALUE) [array] - --context, -c Add contextual string parameter (KEY=VALUE) [array] + -p, --plugin Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] - --plugin, -p Name or path of a node package that extend the CDK - features. Can be specified multiple times [array] + --trace Print trace for stack warnings [boolean] - --trace Print trace for stack warnings [boolean] + --strict Do not construct stacks with warnings [boolean] - --strict Do not construct stacks with warnings [boolean] + --ignore-errors Ignores synthesis errors, which will likely produce + an invalid output [boolean] [default: false] - --ignore-errors Ignores synthesis errors, which will likely produce an - invalid output [boolean] [default: false] + -j, --json Use JSON output instead of YAML when templates are + printed to STDOUT [boolean] [default: false] - --json, -j Use JSON output instead of YAML when templates are - printed to STDOUT [boolean] [default: false] + -v, --verbose Show debug logs (specify multiple times to increase + verbosity) [count] [default: false] - --verbose, -v Show debug logs (specify multiple times to increase - verbosity) [count] [default: false] + --debug Enable emission of additional debugging information, + such as creation stack traces of tokens + [boolean] [default: false] - --profile Use the indicated AWS profile as the default environment - [string] + --profile Use the indicated AWS profile as the default + environment [string] - --proxy Use the indicated proxy. Will read from HTTPS_PROXY - environment variable if not specified. [string] + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified [string] - --ca-bundle-path Path to CA certificate to use when validating HTTPS - requests. Will read from AWS_CA_BUNDLE environment - variable if not specified. [string] + --ca-bundle-path Path to CA certificate to use when validating HTTPS + requests. Will read from AWS_CA_BUNDLE environment + variable if not specified [string] - --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: - guess EC2 instance status. [boolean] + -i, --ec2creds Force trying to fetch EC2 instance credentials. + Default: guess EC2 instance status [boolean] - --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized - templates (enabled by default) [boolean] + --version-reporting Include the "AWS::CDK::Metadata" resource in + synthesized templates (enabled by default) [boolean] - --path-metadata Include "aws:cdk:path" CloudFormation metadata for each - resource (enabled by default) [boolean] [default: true] + --path-metadata Include "aws:cdk:path" CloudFormation metadata for + each resource (enabled by default) + [boolean] [default: true] - --asset-metadata Include "aws:asset:*" CloudFormation metadata for - resources that user assets (enabled by default) + --asset-metadata Include "aws:asset:*" CloudFormation metadata for + resources that user assets (enabled by default) [boolean] [default: true] - --role-arn, -r ARN of Role to use when invoking CloudFormation [string] + -r, --role-arn ARN of Role to use when invoking CloudFormation + [string] - --toolkit-stack-name The name of the CDK toolkit stack [string] + --toolkit-stack-name The name of the CDK toolkit stack [string] - --staging Copy assets to the output directory (use --no-staging to - disable, needed for local debugging the source files - with SAM CLI) [boolean] [default: true] + --staging Copy assets to the output directory (use + --no-staging to disable, needed for local debugging + the source files with SAM CLI) + [boolean] [default: true] - --output, -o Emits the synthesized cloud assembly into a directory - (default: cdk.out) [string] + -o, --output Emits the synthesized cloud assembly into a + directory (default: cdk.out) [string] - --no-color Removes colors and other style from console output + --no-color Removes colors and other style from console output [boolean] [default: false] - --fail Fail with exit code 1 in case of diff + --fail Fail with exit code 1 in case of diff [boolean] [default: false] - --version Show version number [boolean] + --version Show version number [boolean] - -h, --help Show help [boolean] + -h, --help Show help [boolean] If your app has a single stack, there is no need to specify the stack name @@ -507,7 +542,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -516,11 +551,11 @@ Lists all stacks in the app Options: - --long, -l Display environment information for each stack + -l, --long Display environment information for each stack [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -529,11 +564,11 @@ Synthesizes and prints the CloudFormation template for this stack Options: - --exclusively, -e Only synthesize requested stacks, don't include - dependencies [boolean] + -e, --exclusively Only synthesize requested stacks, don't include + dependencies [boolean] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -542,48 +577,67 @@ Deploys the CDK toolkit stack into an AWS environment Options: - --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket; + -b, --bootstrap-bucket-name, The name of the CDK toolkit bucket; --toolkit-bucket-name bucket will be created and must not exist [string] - --bootstrap-kms-key-id AWS KMS master key ID used for the + --bootstrap-kms-key-id AWS KMS master key ID used for the SSE-KMS encryption [string] - --qualifier Unique string to distinguish + --bootstrap-customer-key Create a Customer Master Key (CMK) + for the bootstrap bucket (you will + be charged but can customize + permissions, modern bootstrapping + only) [boolean] + + --qualifier Unique string to distinguish multiple bootstrap stacks [string] - --public-access-block-configuration Block public access configuration + --public-access-block-configuration Block public access configuration on CDK toolkit bucket (enabled by default) [boolean] - --tags, -t Tags to add for the stack + -t, --tags Tags to add for the stack (KEY=VALUE) [array] [default: []] - --execute Whether to execute ChangeSet + --execute Whether to execute ChangeSet (--no-execute will NOT execute the ChangeSet) [boolean] [default: true] - --force, -f Always bootstrap even if it would + --trust The AWS account IDs that should be + trusted to perform deployments into + this environment (may be repeated, + modern bootstrapping only) + [array] [default: []] + + --cloudformation-execution-policies The Managed Policy ARNs that should + be attached to the role performing + deployments into this environment + (may be repeated, modern + bootstrapping only) + [array] [default: []] + + -f, --force Always bootstrap even if it would downgrade template version [boolean] [default: false] - --termination-protection Toggle CloudFormation termination + --termination-protection Toggle CloudFormation termination protection on the bootstrap stacks [boolean] - --show-template Instead of actual bootstrapping, + --show-template Instead of actual bootstrapping, print the current CLI's bootstrapping template to stdout for - customization. + customization [boolean] [default: false] - --template Use the template from the given file + --template Use the template from the given file instead of the built-in one (use --show-template to obtain an - example). [string] + example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -592,44 +646,48 @@ Deploys the stack(s) named STACKS into your AWS account Options: - --build-exclude, -E Do not rebuild asset with the given ID. Can be - specified multiple times. [array] [default: []] + --all Deploy all available stacks + [boolean] [default: false] + + -E, --build-exclude Do not rebuild asset with the given ID. Can be + specified multiple times [array] [default: []] - --exclusively, -e Only deploy requested stacks, don't include - dependencies [boolean] + -e, --exclusively Only deploy requested stacks, don't include + dependencies [boolean] - --require-approval What security-sensitive changes need manual approval + --require-approval What security-sensitive changes need manual + approval [string] [choices: "never", "any-change", "broadening"] - --ci Force CI detection [boolean] [default: false] + --ci Force CI detection [boolean] [default: false] - --notification-arns ARNs of SNS topics that CloudFormation will notify with - stack related events [array] + --notification-arns ARNs of SNS topics that CloudFormation will notify + with stack related events [array] - --tags, -t Tags to add to the stack (KEY=VALUE), overrides tags - from Cloud Assembly [array] + -t, --tags Tags to add to the stack (KEY=VALUE), overrides + tags from Cloud Assembly (deprecated) [array] - --execute Whether to execute ChangeSet (--no-execute will NOT - execute the ChangeSet) [boolean] [default: true] + --execute Whether to execute ChangeSet (--no-execute will NOT + execute the ChangeSet) [boolean] [default: true] - --force, -f Always deploy stack even if templates are identical + -f, --force Always deploy stack even if templates are identical [boolean] [default: false] - --parameters Additional parameters passed to CloudFormation at - deploy time (STACK:KEY=VALUE) [array] [default: {}] + --parameters Additional parameters passed to CloudFormation at + deploy time (STACK:KEY=VALUE) [array] [default: {}] - --outputs-file, -O Path to file where stack outputs will be written as - JSON [string] + -O, --outputs-file Path to file where stack outputs will be written as + JSON [string] - --previous-parameters Use previous values for existing parameters (you must - specify all parameters on every deployment if this is - disabled) [boolean] [default: true] + --previous-parameters Use previous values for existing parameters (you + must specify all parameters on every deployment if + this is disabled) [boolean] [default: true] - --progress Display mode for stack activity events. + --progress Display mode for stack activity events [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -638,14 +696,17 @@ Destroy the stack(s) named STACKS Options: - --exclusively, -e Only destroy requested stacks, don't include dependees - [boolean] + --all Destroy all available stacks + [boolean] [default: false] + + -e, --exclusively Only destroy requested stacks, don't include + dependees [boolean] - --force, -f Do not ask for confirmation before destroying the stacks - [boolean] + -f, --force Do not ask for confirmation before destroying the + stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -655,40 +716,39 @@ and returns with status 1 if any difference is found Options: - --exclusively, -e Only diff requested stacks, don't include dependencies - [boolean] + -e, --exclusively Only diff requested stacks, don't include + dependencies [boolean] - --context-lines Number of context lines to include in arbitrary JSON - diff rendering [number] [default: 3] + --context-lines Number of context lines to include in arbitrary JSON + diff rendering [number] [default: 3] - --template The path to the CloudFormation template to compare with - [string] + --template The path to the CloudFormation template to compare + with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] -Create a new, empty CDK project from a template. Invoked without TEMPLATE, the -app template will be used. +Create a new, empty CDK project from a template. Options: - --language, -l The language to be used for the new project (default can - be configured in ~/.cdk.json) + -l, --language The language to be used for the new project (default + can be configured in ~/.cdk.json) [string] [choices: "csharp", "fsharp", "java", "javascript", "python", "typescript"] - --list List the available templates [boolean] + --list List the available templates [boolean] - --generate-only If true, only generates project files, without executing - additional operations such as setting up a git repo, - installing dependencies or compiling the project - [boolean] [default: false] + --generate-only If true, only generates project files, without + executing additional operations such as setting up a + git repo, installing dependencies or compiling the + project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context @@ -697,7 +757,7 @@ Manage cached context values Options: - --reset, -e The context key (or its index) to reset [string] + -e, --reset The context key (or its index) to reset [string] - --clear Clear all context [boolean] + --clear Clear all context [boolean] ``` \ No newline at end of file From a052d0a4f44a34ce5f5933a4d01d77a126547416 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 17 Nov 2020 23:48:55 +0000 Subject: [PATCH 337/655] add info on Customer Master Key (CMK) --- doc_source/bootstrapping.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 1e2ee158..09500a90 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -16,6 +16,9 @@ Environments are independent, so if you want to deploy to multiple environments **Important** You may incur AWS charges for data stored in the bootstrapped resources\. +**Note** +Older versions of the modern template created a Customer Master Key \(CMK\) in each bootstrapped environment by default\. To avoid charges for the CMK, re\-bootstrap these environments using `--no-bootstrap-customer-key`\. The current default is to not use a CMK to avoid these charges\. + If you attempt to deploy an AWS CDK application that requires bootstrap resources into an environment that does not have them, you receive an error message telling you that you need to bootstrap\. If you are using CDK Pipelines to deploy into another account's environment, and you receive a message like the following: From 7c14c0c32772ffe785078dad336830f6dfb7fe83 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 18 Nov 2020 15:50:39 +0000 Subject: [PATCH 338/655] add more context for what tags are and how they're used --- doc_source/tagging.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 3f087305..6f43bfc6 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -1,6 +1,11 @@ # Tagging -Tags are informational key\-value elements that you can add to constructs in your AWS CDK app\. A tag applied to a given construct also applies to all of its taggable children\. The [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. +Tags are informational key\-value elements that you can add to constructs in your AWS CDK app\. A tag applied to a given construct also applies to all of its taggable children\. Tags are included in the AWS CloudFormation template synthesized from your app and are applied to the AWS resources it deploys\. You can use tags to identify and categorize resources to simplify management, in cost allocation, and for access control, as well as for any other purposes you devise\. + +**Tip** +For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf)\. + +The [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props) applies a new tag to the given construct and all of its children\. + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props) removes a tag from the given construct and any of its children, including tags a child construct may have applied to itself\. @@ -85,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. From 532da6b87556dc6780b45b1d72b26a7f4ba7281d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 18 Nov 2020 17:05:42 +0000 Subject: [PATCH 339/655] update First App to show security change in diff among other improvements (same diff is also used in CLI doc) --- doc_source/cli.md | 13 ++++++++- doc_source/hello_world.md | 57 +++++++++++++++++++++++++++------------ 2 files changed, 52 insertions(+), 18 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index c8f9e2d7..2c047b9e 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -398,9 +398,20 @@ The setting can also be configured in the `cdk.json` file\. ## Comparing stacks -The `cdk diff` command compares the current version of a stack defined in your app with the already\-deployed version, or with a saved AWS CloudFormation template, and displays a list of differences\. +The `cdk diff` command compares the current version of a stack defined in your app with the already\-deployed version, or with a saved AWS CloudFormation template, and displays a list of changes \. ``` +Stack HelloCdkStack +IAM Statement Changes +┌───┬────────────────────────┬────────┬──────────────┬───────────┬───────────┐ +│ │ Resource │ Effect │ Action │ Principal │ Condition │ +├───┼────────────────────────┼────────┼──────────────┼───────────┼───────────┤ +│ + │ ${MyFirstBucket.Arn}/* │ Allow │ s3:GetObject │ * │ │ +└───┴────────────────────────┴────────┴──────────────┴───────────┴───────────┘ +(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299) + +Resources +[+] AWS::S3::BucketPolicy MyFirstBucket/Policy MyFirstBucketPolicy3243DEFD [~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 ├─ [~] DeletionPolicy │ ├─ [-] Retain diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 33e191c7..b17f63c6 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -194,7 +194,8 @@ Add the following to the `` container of `pom.xml`\. ``` -If you are using a Java IDE, it probably has a simpler way to add this dependency to your project\. Resist temptation and edit `pom.xml` by hand\. +**Tip** +If you are using a Java IDE, it probably has a simpler way to add this dependency to your project, such as a GUI for editing the POM\. We recommend editing `pom.xml` by hand because of the use of the `cdk.version` variable, which helps keep the versions of installed modules consistent\. ------ #### [ C\# ] @@ -301,7 +302,7 @@ public class HelloCdkStack extends Stack { ------ #### [ C\# ] -Update `HelloCdkStack.cs` to look like this\. +In `HelloCdkStack.cs`: ``` using Amazon.CDK; @@ -399,16 +400,17 @@ You've deployed your first stack using the AWS CDK—congratulations\! But that' ## Modifying the app -The AWS CDK can update your deployed resources after you modify your app\. Let's make a little change to our bucket\. We want to be able to delete the bucket automatically when we delete the stack, so we'll change the `RemovalPolicy`\. +The AWS CDK can update your deployed resources after you modify your app\. Let's make a couple of changes to our bucket\. First, we'll enable public read access, so people out in the world can access the files we store in the bucket\. We also want to be able to delete the bucket automatically when we delete the stack, so we'll change its `RemovalPolicy`\. ------ #### [ TypeScript ] -Update `lib/hello-cdk-stack.ts` +Update `lib/hello-cdk-stack.ts`\. ``` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, + publicReadAccess: true, removalPolicy: cdk.RemovalPolicy.DESTROY }); ``` @@ -420,27 +422,29 @@ Update `lib/hello-cdk-stack.js`\. ``` new s3.Bucket(this, 'MyFirstBucket', { - versioned: true, - removalPolicy: cdk.RemovalPolicy.DESTROY + versioned: true, + publicReadAccess: true, + removalPolicy: cdk.RemovalPolicy.DESTROY }); ``` ------ #### [ Python ] -Update `hello_cdk/hello_cdk_stack.py` +Update `hello_cdk/hello_cdk_stack.py`\. ``` bucket = s3.Bucket(self, - "MyFirstBucket", + "MyFirstBucket", versioned=True, + public_read_access=True, removal_policy=cdk.RemovalPolicy.DESTROY) ``` ------ #### [ Java ] -Update `src/main/java/com/myorg/HelloCdkStack.java`\. +Update `src/main/java/com/myorg/HelloCdkStack.java`, adding the new import and updating the bucket definition in the appropriate places\. ``` import software.amazon.awscdk.services.s3.BucketEncryption; @@ -449,6 +453,7 @@ import software.amazon.awscdk.services.s3.BucketEncryption; ``` Bucket.Builder.create(this, "MyFirstBucket") .versioned(true) + .publicReadAccess(true) .removalPolicy(RemovalPolicy.DESTROY) .build(); ``` @@ -462,21 +467,33 @@ Update `HelloCdkStack.cs`\. new Bucket(this, "MyFirstBucket", new BucketProps { Versioned = true, + PublicReadAccess = true, RemovalPolicy = RemovalPolicy.DESTROY }); ``` ------ -Now we'll use the `cdk diff` command to see the differences between what's already been deployed, and the code we just changed\. +Now we'll use the `cdk diff` command to see the differences between what's already been deployed, and the app as it stands right now\. ``` cdk diff ``` -The AWS CDK Toolkit queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares it with the template it synthesized from your app\. The Resources section of the output should look like the following\. +The AWS CDK Toolkit queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares it with the template it just synthesized from your app\. The Resources section of the output should look like the following\. ``` +Stack HelloCdkStack +IAM Statement Changes +┌───┬────────────────────────┬────────┬──────────────┬───────────┬───────────┐ +│ │ Resource │ Effect │ Action │ Principal │ Condition │ +├───┼────────────────────────┼────────┼──────────────┼───────────┼───────────┤ +│ + │ ${MyFirstBucket.Arn}/* │ Allow │ s3:GetObject │ * │ │ +└───┴────────────────────────┴────────┴──────────────┴───────────┴───────────┘ +(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299) + +Resources +[+] AWS::S3::BucketPolicy MyFirstBucket/Policy MyFirstBucketPolicy3243DEFD [~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 ├─ [~] DeletionPolicy │ ├─ [-] Retain @@ -486,11 +503,16 @@ The AWS CDK Toolkit queries your AWS account for the current AWS CloudFormation └─ [+] Delete ``` -As you can see, the diff indicates that the `DeletionPolicy` property of the bucket is now set to `Delete`, enabling the bucket to be deleted when its stack is deleted\. The `UpdateReplacePolicy `is also changed\. +The diff indicates two things\. First, that the stack has a new IAM policy statement that grants everyone \(principal `*`\) read access \(`s3:GetObject` action\) to our bucket\. Note that we didn't need to create this statement; the AWS CDK did it for us\. All we needed to do was set the `publicReadAccess` property when instantiating the bucket\. -Don't be confused by the difference in name\. The AWS CDK calls it `RemovalPolicy` because its meaning is slightly different from AWS CloudFormation's `DeletionPolicy`: the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it\. See [Removal policies](resources.md#resources_removal) for further details\. +**Note** +It's informative to look at the output of cdk synth here and see the twenty additional lines of AWS CloudFormation template that the AWS CDK generated for us when we changed one property of our bucket\. + +Besides the new policy, we can also see the `DeletionPolicy` property is set to `Delete`, enabling the bucket to be deleted when its stack is deleted\. The `UpdateReplacePolicy `is also changed to cause the bucket to be deleted if it were to be replaced with a new one\. -You can also see that the bucket isn't going to be replaced, but will be updated instead\. +Don't be confused by the difference between `RemovalPolicy` in your AWS CDK app and `DeletionPolicy` in the resulting AWS CloudFormation template\. The AWS CDK calls it `RemovalPolicy` because its semantics are slightly different from AWS CloudFormation's `DeletionPolicy`: the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it\. See [Removal policies](resources.md#resources_removal) for further details\. + +You can also see that the bucket isn't going to be replaced, but will be updated with the new properties\. Now let's deploy\. @@ -498,7 +520,7 @@ Now let's deploy\. cdk deploy ``` -Enter y to approve the changes and deploy the updated stack\. The Toolkit updates the bucket configuration as you requested\. +The AWS CDK warns you about the security policy change we previously saw in the diff\. Enter y to approve the changes and deploy the updated stack\. The Toolkit updates the bucket configuration as you requested\. ``` HelloCdkStack: deploying... @@ -524,9 +546,10 @@ cdk destroy Enter y to approve the changes and delete any stack resources\. **Note** -This wouldn't have worked if we hadn't changed the bucket's `RemovalPolicy` just a minute ago\! +This wouldn't have worked if we hadn't changed the bucket's `RemovalPolicy`\! Instead, the stack deletion would complete successfully, and the bucket would become orphaned \(no longer associated with the stack\)\. -If cdk destroy fails, it probably means you put something in your Amazon S3 bucket\. AWS CloudFormation won't delete buckets with files in them\. Delete the files and try again\. +**Tip** +If the bucket still exists after you delete the stack, it probably means you put something in it\. AWS CloudFormation won't delete buckets with files in them\. Delete the files and try again\. ## Next steps From 1360956aff8544c0366ecb74ce77fee9f5b73e07 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 19 Nov 2020 19:49:54 +0000 Subject: [PATCH 340/655] fix typo --- doc_source/use_cfn_template.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 9ed8a8fa..9c1b2fbf 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -645,7 +645,7 @@ param.Default = "AWS CDK"; ### Nested stacks -You may import [nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html) by specifying them either when you import their main template, or at some later point\. The nested template must be stored in a local file, but referenced in as a `NestedStack` resource in the main template, and the resource name used in the AWS CDK code must match the name used for the nested stack in the main template\. +You may import [nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html) by specifying them either when you import their main template, or at some later point\. The nested template must be stored in a local file, but referenced as a `NestedStack` resource in the main template, and the resource name used in the AWS CDK code must match the name used for the nested stack in the main template\. Given this resource definition in the main template, the following code shows how to import the referenced nested stack both ways\. From 48eacecb8137382174b89d7395e177f35a0f0002 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 19 Nov 2020 19:50:14 +0000 Subject: [PATCH 341/655] update history --- doc_source/doc-history.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index a9536a05..5642b36e 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -7,6 +7,8 @@ The table below represents significant documentation milestones\. We fix errors | Change | Description | Date | | --- |--- |--- | +| [Import or migrate AWS CloudFormation template](#doc-history) | Add description of the new `cloudformation-include.CfnInclude` class, a powerful way to import and migrate AWS CloudFormation templates, or to vend them as AWS CDK constructs\.\. | October 15, 2020 | +| [Add construct tree section](#doc-history) | Information about the construct tree and its relation to the constructs you define in your AWS CDK app\. | October 5, 2020 | | [Add Bootstrapping topic](#doc-history) | A complete explanation of why and how to bootstrap AWS environments for the CDK, including a comprehensive discussion of how to customize the process\. | September 8, 2020 | | [Add CDK Pipelines how\-to](#doc-history) | CDK Pipelines let you easily automate the deployment of your AWS CDK apps from source control whenever they're updated\. | July 17, 2020 | | [Improve CDK Toolkit topic](#doc-history) | Include more information and examples around performing common tasks with the CLI \(and the relevant flags\) rather than just including a copy of the help\. | July 9, 2020 | From de75155ec8feeb5842990470e4979f25185ce23f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 25 Nov 2020 03:44:01 +0000 Subject: [PATCH 342/655] fix typos and other minor improvements --- doc_source/environments.md | 2 +- doc_source/work-with-cdk-javascript.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index 9a64e06b..133b3549 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -3,7 +3,7 @@ Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and region into which the stack is intended to be deployed\. **Note** -For all but the simplest deployments, you will need to [bootstrap](bootstrapping.md) each environment you will deploy into\. Deployment requires certain AWS resources to be available, and these resources are provisined by bootstrapping\. +For all but the simplest deployments, you will need to [bootstrap](bootstrapping.md) each environment you will deploy into\. Deployment requires certain AWS resources to be available, and these resources are provisioned by bootstrapping\. If you don't specify an environment when you define a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availabilityZones` \(Python: `availability_zones`\)\. diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 3e02d13d..c99ac392 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -253,7 +253,7 @@ Knowing how to identify and remove these TypeScript features goes a long way tow ## Migrating to TypeScript -As their projects get larger and more complex, many JavaScript developers move to [TypeScript](https://www.typescriptlang.org/)\. TypeScript is a superset of JavaScript—all JavaScript code is valid TypeScript code, so no changes to your code are required—and it is also a supported AWS CDK language\. Type annotations and other TypeScript features are optional and can be added to your AWS CDK app as you find value in them\. TypeScript also gives you early access to new JavaScript features, such as optional chaining and nullish coalescing, before they're finalized—and without requiring that you upgrade Node\.js\. +Many JavaScript developers move to [TypeScript](https://www.typescriptlang.org/) as their projects get larger and more complex\. TypeScript is a superset of JavaScript—all JavaScript code is valid TypeScript code, so no changes to your code are required—and it is also a supported AWS CDK language\. Type annotations and other TypeScript features are optional and can be added to your AWS CDK app as you find value in them\. TypeScript also gives you early access to new JavaScript features, such as optional chaining and nullish coalescing, before they're finalized—and without requiring that you upgrade Node\.js\. TypeScript's "shape\-based" interfaces, which define bundles of required and optional properties \(and their types\) within an object, allow common mistakes to be caught while you're writing the code, and make it easier for your IDE to provide robust autocomplete and other real\-time coding advice\. From 76724add10ebebbc6b603a984f168b02a9e6b956 Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Wed, 25 Nov 2020 13:39:56 -0800 Subject: [PATCH 343/655] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b5caa99e..d5e75146 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ so the community can see, comment, and contribute. > :memo: **NOTE** - > The Markdown files in this repository are an *output* of the AWS CDK Developer Guide build process, not the actual source files. -Periodically, we update the Markdown files here from our builds. This means that changes may appear on docs.aws.amazon.com before they appear +Periodically, we update the Markdown files here from our builds. Changes may appear on docs.aws.amazon.com before they appear here. ## Other Documentation Issues From 2dad13ef4f6cd9db346ea7e4d6e58d231d8dff79 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 1 Dec 2020 02:04:51 +0000 Subject: [PATCH 344/655] fix last .env, remove unneeded imports --- doc_source/cdk_pipeline.md | 2 +- doc_source/codepipeline_example.md | 26 ++++++-------------------- doc_source/hello_world.md | 2 +- 3 files changed, 8 insertions(+), 22 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 8c7d878a..45474212 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -117,7 +117,7 @@ cdk init app --language python After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install its dependencies\. ``` -source .env/bin/activate +source .venv/bin/activate python -m pip install -r requirements.txt ``` diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 9a9bc918..87c99d9a 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -47,7 +47,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi cd pipeline cdk init --language typescript npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline - npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 + npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions ``` ------ @@ -57,7 +57,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi cd pipeline cdk init ‐-language javascript npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline - npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions @aws-cdk/aws-s3 + npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions ``` ------ @@ -74,7 +74,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi git commit -m "project started" pip install -r requirements.txt pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline - pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_s3 + pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions pip freeze | grep -v '-e git' > requirements.txt ``` @@ -86,7 +86,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi .venv\Scripts\activate.bat pip install -r requirements.txt pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline - pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions aws_cdk.aws_s3 + pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions pip freeze | find /V "-e git" > requirements.txt ``` @@ -100,19 +100,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi You can import the resulting Maven project into your Java IDE\. - Using the Maven integration in your IDE \(for example, in Eclipse, right\-click the project and choose **Maven** > **Add Dependency**\), add the following packages in the group `software.amazon.awscdk`\. - - ``` - lambda - codedeploy - codebuild - codecommit - codepipeline - codepipeline-actions - s3 - ``` - - Alternatively, add `` elements like the following to `pom.xml`\. You can copy the existing dependency for the AWS CDK core module and modify it\. For example, a dependency for the AWS Lambda module looks like this\. + Add `` elements like the following to `pom.xml`\. You can copy the existing dependency for the AWS CDK core module and modify it\. For example, a dependency for the AWS Lambda module looks like this\. ``` @@ -141,7 +129,6 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi Amazon.CDK.AWS.CodePipeline Amazon.CDK.AWS.CodePipeline.Actions Amazon.CDK.AWS.Lambda - Amazon.CDK.AWS.S3 ``` ------ @@ -450,7 +437,6 @@ import * as codecommit from '@aws-cdk/aws-codecommit'; import * as codepipeline from '@aws-cdk/aws-codepipeline'; import * as codepipeline_actions from '@aws-cdk/aws-codepipeline-actions'; import * as lambda from '@aws-cdk/aws-lambda'; -import * as s3 from '@aws-cdk/aws-s3'; import { App, Stack, StackProps } from '@aws-cdk/core'; export interface PipelineStackProps extends StackProps { @@ -706,7 +692,7 @@ from aws_cdk import (core, aws_codebuild as codebuild, aws_codecommit as codecommit, aws_codepipeline as codepipeline, aws_codepipeline_actions as codepipeline_actions, - aws_lambda as lambda_, aws_s3 as s3) + aws_lambda as lambda_) class PipelineStack(core.Stack): diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index b17f63c6..ace65a4f 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -67,7 +67,7 @@ cdk init app --language python After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install its dependencies\. ``` -source .env/bin/activate +source .venv/bin/activate python -m pip install -r requirements.txt ``` From 1056e5dd1188edc5b56b2fc1cf3d8a59d52074aa Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 7 Dec 2020 21:20:28 +0000 Subject: [PATCH 345/655] remove info on core.CfnInclude (deprecated) and other tweaks --- doc_source/apps.md | 2 +- doc_source/cli.md | 26 ++--- doc_source/doc-history.md | 2 +- doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 168 +++------------------------------ 5 files changed, 31 insertions(+), 169 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index a7df08fc..88a9b73a 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -235,7 +235,7 @@ All constructs that have implemented the `prepare` method participate in a final All constructs that have implemented the `validate` method can validate themselves to ensure that they're in a state that will correctly deploy\. You will get notified of any validation failures that happen during this phase\. Generally, we recommend that you perform validation as soon as possible \(usually as soon as you get some input\) and throw exceptions as early as possible\. Performing validation early improves diagnosability as stack traces will be more accurate, and ensures that your code can continue to execute safely\. 4\. Synthesis -This is the final stage of the execution of your AWS CDK app\. It's triggered by a call to `app.synth()`, and it traverses the construct tree and invokes the `synthesize` method on all constructs\. Constructs that implement `synthesize` can participate in synthesis and emit deployment artifacts to the resulting cloud assembly\. These constructs include AWS CloudFormation templates, AWS Lambda application bundles, file and Docker image assets, and other deployment artifacts\. [Cloud assemblies](#apps_cloud_assembly) describes the output of this phase\. In most cases, you won't need to implement the `synthesize` method +This is the final stage of the execution of your AWS CDK app\. It's triggered by a call to `app.synth()`, and it traverses the construct tree and invokes the `synthesize` method on all constructs\. Constructs that implement `synthesize` can participate in synthesis and emit deployment artifacts to the resulting cloud assembly\. These artifacts include AWS CloudFormation templates, AWS Lambda application bundles, file and Docker image assets, and other deployment artifacts\. [Cloud assemblies](#apps_cloud_assembly) describes the output of this phase\. In most cases, you won't need to implement the `synthesize` method 5\. Deployment In this phase, the AWS CDK CLI takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. diff --git a/doc_source/cli.md b/doc_source/cli.md index 2c047b9e..80750729 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -289,7 +289,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -308,7 +308,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -316,7 +316,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -340,7 +340,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -362,7 +362,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -553,7 +553,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -566,7 +566,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -579,7 +579,7 @@ Options: dependencies [boolean] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -648,7 +648,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -698,7 +698,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -717,7 +717,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -737,7 +737,7 @@ Options: with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -759,7 +759,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index 5642b36e..db7baffd 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -7,7 +7,7 @@ The table below represents significant documentation milestones\. We fix errors | Change | Description | Date | | --- |--- |--- | -| [Import or migrate AWS CloudFormation template](#doc-history) | Add description of the new `cloudformation-include.CfnInclude` class, a powerful way to import and migrate AWS CloudFormation templates, or to vend them as AWS CDK constructs\.\. | October 15, 2020 | +| [Import or migrate AWS CloudFormation template](#doc-history) | Add description of the new `cloudformation-include.CfnInclude` class, a powerful way to import and migrate AWS CloudFormation templates, or to vend them as AWS CDK constructs\. | October 15, 2020 | | [Add construct tree section](#doc-history) | Information about the construct tree and its relation to the constructs you define in your AWS CDK app\. | October 5, 2020 | | [Add Bootstrapping topic](#doc-history) | A complete explanation of why and how to bootstrap AWS environments for the CDK, including a comprehensive discussion of how to customize the process\. | September 8, 2020 | | [Add CDK Pipelines how\-to](#doc-history) | CDK Pipelines let you easily automate the deployment of your AWS CDK apps from source control whenever they're updated\. | July 17, 2020 | diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 6f43bfc6..706ad73f 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 9c1b2fbf..f196df42 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -1,150 +1,10 @@ # Import or migrate an existing AWS CloudFormation template -The AWS CDK provides two mechanisms to incorporate resources from an existing AWS CloudFormation template into your AWS CDK app\. -+ [`core.CfnInclude`](#use_cfn_template_core) \- Includes an AWS CloudFormation template in the current stack, merging its resources with those defined in your AWS CDK code\. You can access attributes of the imported resources using [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Fn.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Fn.html), but these resources are not actually AWS CDK constructs and do not provide the functionality of real constructs\. -+ [`cloudformation-include.CfnInclude`](#use_cfn_template_cfninclude) \- This construct, currently in developer preview, actually converts the resources in the imported AWS CloudFormation template to AWS CDK L1 constructs\. You can work with these in your app just as if they were defined in AWS CDK code, even using them within higher\-level AWS CDK constructs, letting you use \(for example\) the L2 permission grant methods with the resources they define\. +The [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html) construct converts the resources in an imported AWS CloudFormation template to AWS CDK L1 constructs\. You can work with these in your app just as if they were defined in AWS CDK code, even using them within higher\-level AWS CDK constructs, letting you use \(for example\) the L2 permission grant methods with the resources they define\. - This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by giving them the API they expect\. +This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Using `core.CfnInclude` - -An AWS CloudFormation template included using [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html) provides your AWS CDK app basic access to the resources contained in the template\. - -Suppose you have a template, `my-template.json`, with the following resource, where *S3Bucket* is the logical ID of the bucket in your template: - -``` -{ - "MyBucket": { - "Type": "AWS::S3::Bucket", - "Properties": { - "BucketName": "MyBucket", - } - } -} -``` - -You can include this bucket in your AWS CDK app, as shown in the following example\. - ------- -#### [ TypeScript ] - -``` -import * as cdk from "@aws-cdk/core"; -import * as fs from "fs"; - -new cdk.CfnInclude(this, "ExistingInfrastructure", { - template: JSON.parse(fs.readFileSync("my-template.json").toString()) -}); -``` - ------- -#### [ JavaScript ] - -``` -const cdk = require("@aws-cdk/core"); -const fs = require("fs"); - -new cdk.CfnInclude(this, "ExistingInfrastructure", { - template: JSON.parse(fs.readFileSync("my-template.json").toString()) -}); -``` - ------- -#### [ Python ] - -``` -import json - -cdk.CfnInclude(self, "ExistingInfrastructure", - template=json.load(open("my-template.json")) -``` - ------- -#### [ Java ] - -``` -import java.util.*; -import java.io.File; - -import software.amazon.awscdk.core.CfnInclude; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; - -CfnInclude.Builder.create(this, "ExistingInfrastructure") - .template((ObjectNode)new ObjectMapper().readTree(new File("my-template.json"))) - .build(); -``` - ------- -#### [ C\# ] - -``` -using Newtonsoft.Json.Linq; - -new CfnInclude(this, "ExistingInfrastructure", new CfnIncludeProps -{ - Template = JObject.Parse(File.ReadAllText("my-template.json")) -}); -``` - ------- - -Then to access an attribute of the resource, such as the bucket's ARN, call `Fn.getAtt()` with the logical name of the resource in the AWS CloudFormation template and the name of the resource's attribute\. \(The desired resource and attribute must be defined in the template; `Fn.getAtt()` does not query actual resources you have deployed using the template\.\) - ------- -#### [ TypeScript ] - -``` -const bucketArn = cdk.Fn.getAtt("S3Bucket", "Arn"); -``` - ------- -#### [ JavaScript ] - -``` -const bucketArn = cdk.Fn.getAtt("S3Bucket", "Arn"); -``` - ------- -#### [ Python ] - -``` -bucket_arn = cdk.Fn.get_att("S3Bucket", "Arn") -``` - ------- -#### [ Java ] - -``` -IResolvable bucketArn = Fn.getAtt("S3Bucket", "Arn"); -``` - ------- -#### [ C\# ] - -``` -var bucketArn = Fn.GetAtt("S3Bucket", "Arn"); -``` - ------- - -The result of a `getAtt()` call is a [token](tokens.md), a type of placeholder\. The actual value of the attribute isn't available until later in the synthesis process\. If you need to pass such an attribute to another API that requires a concrete value, such as a string or a number, use the following static methods of the `[Token](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html)` class to convert the token to a string, number, or list\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) to generate a string encoding \(or call `.toString()` on the token object\) -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) to generate a list encoding -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) to generate a numeric encoding - -In our example of getting a bucket's ARN, you'd convert it to a string, but that string is still a token, just in a string encoding\. You still don't have the actual ARN\. But in many ways, you can treat the string as if you did have the real value \(for example, adding text to the beginning or end\) and it will work as you expect\. - -## Using `cloudformation-include.CfnInclude` - -The [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html) construct imports the resources in an AWS CloudFormation template as AWS CDK L1 constructs, allowing you to use them in your app as you would any other AWS CDK construct\. You can then wrap these in L2 constructs to gain their higher\-level abstractions\. This capability can help you migrate an AWS CloudFormation stack to the AWS CDK without making any unexpected changes to the underlying AWS resources, or to add an AWS CDK API "wrapper" to an existing AWS CloudFormation template\. - -**Warning** -This construct is currently in developer preview, which means its API is generally considered stable, but may still undergo breaking changes when necessary\. - - Here is a simple AWS CloudFormation template \(the same one we used in the preceding section, in fact\) which we'll use for the examples in this topic\. Save it as `my-template.json`\. You might also use a template for an actual stack you have already deployed, obtained from the AWS CloudFormation console\. + Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. **Tip** You can use either a JSON or YAML template\. We recommend JSON if available, since YAML parsers can vary slightly in what they accept\. @@ -160,7 +20,7 @@ You can use either a JSON or YAML template\. We recommend JSON if available, sin } ``` -And here's how you might import it into your stack using the new `cloudformation-include `module\. +And here's how you import it into your stack using `cloudformation-include`\. ------ #### [ TypeScript ] @@ -264,7 +124,9 @@ namespace MyApp ------ -By default, importing preserves the original logical IDs from the template\. This behavior is suitable for migrating an AWS CloudFormation template to the AWS CDK\. If you are instead developing an AWS CDK construct wrapper for the template so it can be reused elsewhere \("vending"\), have the AWS CDK generate new resource IDs instead, so the construct can be used multiple times in a stack without name conflicts\. To do this, set the `preserveLogicalIds` property to false when importing the template\. +By default, importing a resource preserves the resource's original logical ID from the template\. This behavior is suitable for migrating an AWS CloudFormation template to the AWS CDK, where the logical IDs must be retained for AWS CloudFormation to recognize these as the same resources from the AWS CloudFormation template\. + +If you are instead developing an AWS CDK construct wrapper for the template so it can be used by AWS CDK developers \("vending"\), have the AWS CDK generate new resource IDs instead, so the construct can be used multiple times in a stack without name conflicts\. To do this, set the `preserveLogicalIds` property to false when importing the template\. ------ #### [ TypeScript ] @@ -318,7 +180,7 @@ var template = new cfn_inc.CfnInclude(this, "Template", new cfn_inc.CfnIncludePr ------ -To put the imported resources under the control of your AWS CDK app, simply add the stack to the `App` as usual\. +To put the imported resources under the control of your AWS CDK app, add the stack to the `App` as usual\. ------ #### [ TypeScript ] @@ -397,9 +259,9 @@ cdk diff --no-version-reporting --no-path-metadata --no-asset-metadata When you `cdk deploy` the stack, your AWS CDK app becomes the source of truth for the stack\. Going forward, make changes to the AWS CDK app, not to the AWS CloudFormation template\. -### Accessing imported resources +## Accessing imported resources -The name `template` in the example code represents the included AWS CloudFormation template\. To access a resource from it, use this object's [https://docs.aws.amazon.com/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) method\. To access the returned resource as a specific kind of resource, cast the result to the desired type \(except in Python and JavaScript, where types are not enforced\)\. +The name `template` in the example code represents the imported AWS CloudFormation template\. To access a resource from it, use this object's [https://docs.aws.amazon.com/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) method\. To access the returned resource as a specific kind of resource, cast the result to the desired type\. \(Casting is not necessary in Python and JavaScript\.\) ------ #### [ TypeScript ] @@ -522,7 +384,7 @@ bucket.GrantWrite(lambdaFunc); ------ -### Replacing parameters +## Replacing parameters If your included AWS CloudFormation template has parameters, you can replace these with build\-time values when you import the template, using the `parameters` property\. In the example below, we replace the `UploadBucket` parameter with the ARN of a bucket defined elsewhere in our AWS CDK code\. @@ -588,7 +450,7 @@ var template = new cfn_inc.CfnInclude(this, "Template", new cfn_inc.CfnIncludePr ------ -### Other template elements +## Other template elements You can import any AWS CloudFormation template element, not just resources\. The imported elements become part of the AWS CDK stack\. To import these elements, use the following methods of the `CfnInclude` object\. + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-conditionconditionname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-conditionconditionname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [conditions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) @@ -598,7 +460,7 @@ You can import any AWS CloudFormation template element, not just resources\. The + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-parameterparametername-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-parameterparametername-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) + [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-rulerulename-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-rulerulename-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [rules](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/reference-template_constraint_rules.html) for Service Catalog templates -Each of these methods returns an instance of a class representing the specific type of AWS CloudFormation element\. These objects are mutable; changes will appear in the template generated from the AWS CDK stack\. The code below, for example, imports a parameter from the template and modifies its default\. +Each of these methods returns an instance of a class representing the specific type of AWS CloudFormation element\. These objects are mutable; changes you make to them will appear in the template generated from the AWS CDK stack\. The code below, for example, imports a parameter from the template and modifies its default\. ------ #### [ TypeScript ] @@ -643,7 +505,7 @@ param.Default = "AWS CDK"; ------ -### Nested stacks +## Nested stacks You may import [nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html) by specifying them either when you import their main template, or at some later point\. The nested template must be stored in a local file, but referenced as a `NestedStack` resource in the main template, and the resource name used in the AWS CDK code must match the name used for the nested stack in the main template\. @@ -752,7 +614,7 @@ var nestedTemplate = mainTemplate.LoadNestedStack("NestedTemplate", new cfn_inc. ------ -You can import multiple nested stacks with either or both methods\. When importing the main template, you provide a mapping between the resource name of each nested stack and its template file, and this mapping can contain any number of entries\. To do it after the initial import, call `loadNestedStack()` for each nested stack\. +You can import multiple nested stacks with either or both methods\. When importing the main template, you provide a mapping between the resource name of each nested stack and its template file, and this mapping can contain any number of entries\. To do it after the initial import, call `loadNestedStack()` once for each nested stack\. After importing a nested stack, you can access it using the main template's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-nested-wbr-stacklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-nested-wbr-stacklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) method\. From b9dd911400fe7b98086e613f002b05ac9230f84d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 7 Dec 2020 21:45:09 +0000 Subject: [PATCH 346/655] add section header for importing --- doc_source/use_cfn_template.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index f196df42..88e68a59 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,6 +4,8 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-inc This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. +## Importing an AWS CloudFormation template + Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. **Tip** From 4f19549d41b19e6f4332ed6340ac9b2bc5dd072a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 7 Dec 2020 22:18:58 +0000 Subject: [PATCH 347/655] update CLI help --- doc_source/cli.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/doc_source/cli.md b/doc_source/cli.md index 80750729..9b7d7b93 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -487,6 +487,10 @@ Options: --strict Do not construct stacks with warnings [boolean] + --lookups Perform context lookups (synthesis fails if this is + disabled and context lookups need to be performed) + [boolean] [default: true] + --ignore-errors Ignores synthesis errors, which will likely produce an invalid output [boolean] [default: false] From fb1b6d0649ea75e02c246c94f84d8d39eebe1aa0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 16 Dec 2020 19:02:21 +0000 Subject: [PATCH 348/655] improve description of YAML/JSON and cdk.out --- doc_source/hello_world.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index ace65a4f..76c7b2c0 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -354,7 +354,7 @@ If your app contained more than one stack, you'd need to specify which stack\(s\ **Tip** If you received an error like `--app is required...`, it's probably because you are running the command from a subdirectory\. Navigate to the main app directory and try again\. -The `cdk synth` command executes your app, which causes the resources defined in it to be translated to an AWS CloudFormation template\. The output of `cdk synth` is a YAML\-format AWS CloudFormation template, which looks something like this\. +The `cdk synth` command executes your app, which causes the resources defined in it to be translated to an AWS CloudFormation template\. The displayed output of `cdk synth` is a YAML\-format template; our app's output is shown below\. The template is also saved in the `cdk.out` directory in JSON format\. ``` Resources: From b13be09f49dfd798a2d37d6b3db46ae1af4b3da2 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 19 Dec 2020 03:55:46 +0000 Subject: [PATCH 349/655] fixes to lambda function definition to make blue-green work --- doc_source/codepipeline_example.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 87c99d9a..ae75cce6 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -225,6 +225,7 @@ export class LambdaStack extends Stack { code: this.lambdaCode, handler: 'index.main', runtime: lambda.Runtime.NODEJS_10_X, + description: `Function generated on: ${new Date().toISOString()}`, }); const alias = new lambda.Alias(this, 'LambdaAlias', { @@ -260,7 +261,8 @@ class LambdaStack extends Stack { const func = new lambda.Function(this, 'Lambda', { code: this.lambdaCode, handler: 'index.main', - runtime: lambda.Runtime.NODEJS_10_X + runtime: lambda.Runtime.NODEJS_10_X, + description: `Function generated on: ${new Date().toISOString()}`, }); const alias = new lambda.Alias(this, 'LambdaAlias', { @@ -285,6 +287,7 @@ File: `pipeline/lambda_stack.py` ``` from aws_cdk import core, aws_codedeploy as codedeploy, aws_lambda as lambda_ +import datetime class LambdaStack(core.Stack): def __init__(self, app: core.App, id: str, **kwargs): @@ -296,6 +299,7 @@ class LambdaStack(core.Stack): code=self.lambda_code, handler="index.main", runtime=lambda_.Runtime.NODEJS_10_X, + description="Function generated on {}".format(datetime.datetime.now()), ) alias = lambda_.Alias(self, "LambdaAlias", alias_name="Prod", @@ -324,6 +328,8 @@ import software.amazon.awscdk.services.codedeploy.*; import software.amazon.awscdk.services.lambda.*; import software.amazon.awscdk.services.lambda.Runtime; +import java.time.Instant; + public class LambdaStack extends Stack { // private attribute to hold our Lambda's code, with public getters @@ -346,7 +352,9 @@ public class LambdaStack extends Stack { Function func = Function.Builder.create(this, "Lambda") .code(lambdaCode) .handler("index.main") - .runtime(Runtime.NODEJS_10_X).build(); + .runtime(Runtime.NODEJS_10_X) + .description(String.format("Function generated on %s", Instant.now())) + .build(); Version version = func.getCurrentVersion(); Alias alias = Alias.Builder.create(this, "LambdaAlias") @@ -370,6 +378,8 @@ using Amazon.CDK; using Amazon.CDK.AWS.CodeDeploy; using Amazon.CDK.AWS.Lambda; +using System; + namespace Pipeline { public class LambdaStack : Stack @@ -385,7 +395,8 @@ namespace Pipeline { Code = lambdaCode, Handler = "index.main", - Runtime = Runtime.NODEJS_10_X + Runtime = Runtime.NODEJS_10_X, + Description = "Function generated at " + DateTime.Now.ToString("s") }); var version = func.currentVersion; From c368d500a04be2b618cd122cf9fbdddc184fc6a1 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 5 Jan 2021 06:16:28 +0000 Subject: [PATCH 350/655] tweaks and fixes --- doc_source/bootstrapping.md | 2 ++ doc_source/cdk_pipeline.md | 6 ++++-- doc_source/getting_started.md | 2 +- doc_source/hello_world.md | 2 +- doc_source/serverless_example.md | 6 +++--- doc_source/use_cfn_template.md | 2 +- 6 files changed, 12 insertions(+), 8 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 09500a90..5a1f960c 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -237,6 +237,8 @@ MyStack(self, "MyStack", ------ #### [ Java ] + + ``` new MyStack(app, "MyStack", StackProps.builder() // stack properties diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 45474212..8382a2ac 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -20,7 +20,9 @@ You may have already bootstrapped one or more environments so you can deploy ass To bootstrap an environment that can provision an AWS CDK pipeline, set the environment variable `CDK_NEW_BOOTSTRAP` before invoking `cdk bootstrap`, as shown below\. Invoking the AWS CDK Toolkit via the `npx` command installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. -\-\-cloudformation\-execution\-policies specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The `AdministratorAccess` policy is the default; if you're using it, you may omit this option\. Your organization may require a more restrictive policy\. +\-\-cloudformation\-execution\-policies specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The default `AdministratorAccess` policy ensures that your pipeline can deploy every type of AWS resource\. If you use this policy, make sure you trust all the code and dependencies that make up your AWS CDK app\. + +Most organizations mandate stricter controls on what kinds of resources can be deployed by automation\. Check with the appropriate department within your organization to determine the policy your pipeline should use\. You may omit the \-\-profile option if your default AWS profile contains the necessary credentials or to instead use the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to provide your AWS account credentials\. @@ -128,7 +130,7 @@ python -m pip install -r requirements.txt cdk init app --language java ``` -If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set ta use Java 8 \(1\.8\)\. +If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set to use Java 8 \(1\.8\)\. ------ #### [ C\# ] diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 8042ecc5..ecedb221 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -195,7 +195,7 @@ cdk --version ## AWS CDK tools -We've already been using the AWS CDK Toolkit, also known as the Command Line Interface \(CLI\)\. It's the main tool you use to interact with your AWS CDK app\. It executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CDK templates it generates\. It also has deployment, diff, deletion, and troubleshooting capabilities\. For more information, see cdk \-\-help or [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. +The AWS CDK Toolkit, also known as the Command Line Interface \(CLI\), is the main tool you use to interact with your AWS CDK app\. It executes your code and produces and deploys the AWS CloudFormation templates it generates\. It also has deployment, diff, deletion, and troubleshooting capabilities\. For more information, see cdk \-\-help or [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open\-source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the plug\-in](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 76c7b2c0..b5263e32 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -78,7 +78,7 @@ python -m pip install -r requirements.txt cdk init app --language java ``` -If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set ta use Java 8 \(1\.8\)\. +If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set to use Java 8 \(1\.8\)\. ------ #### [ C\# ] diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index a0571eb7..16615051 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -267,7 +267,7 @@ export class WidgetService extends core.Construct { const handler = new lambda.Function(this, "WidgetHandler", { runtime: lambda.Runtime.NODEJS_10_X, // So we can use async in widget.js - code: lambda.Code.asset("resources"), + code: lambda.Code.fromAsset("resources"), handler: "widgets.main", environment: { BUCKET: bucket.bucketName @@ -309,7 +309,7 @@ class WidgetService extends core.Construct { const handler = new lambda.Function(this, "WidgetHandler", { runtime: lambda.Runtime.NODEJS_10_X, // So we can use async in widget.js - code: lambda.Code.asset("resources"), + code: lambda.Code.fromAsset("resources"), handler: "widgets.main", environment: { BUCKET: bucket.bucketName @@ -353,7 +353,7 @@ class WidgetService(core.Construct): handler = lambda_.Function(self, "WidgetHandler", runtime=lambda_.Runtime.NODEJS_10_X, - code=lambda_.Code.asset("resources"), + code=lambda_.Code.from_asset("resources"), handler="widgets.main", environment=dict( BUCKET=bucket.bucket_name) diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 88e68a59..84101409 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -324,7 +324,7 @@ const bucket = s3.Bucket.fromBucketName(this, 'Bucket', cfnBucket.ref); #### [ Python ] ``` -bucket = s3.Bucket.from_bucket_name(this, "Bucket", cfn_bucket.ref) +bucket = s3.Bucket.from_bucket_name(self, "Bucket", cfn_bucket.ref) ``` ------ From 9b5f78ad613a090c9cac1f934ac701c6bbab308d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 7 Jan 2021 04:36:21 +0000 Subject: [PATCH 351/655] fix typo --- doc_source/work-with-cdk-csharp.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index d736c091..8d6c843c 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -35,7 +35,7 @@ The \.NET ecosystem uses the NuGet package manager\. AWS Construct Library modul **Note** The [\.NET edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/dotnet/api/index.html) also shows the package names\. -Some services' AWS Construct Library support is in more than one module\. For example, Amazon Route 53 has the three modules in addition to the main `Amazon.CDK.AWS.Route53` module, named `Route53.Patterns`, `Route53rResolver`, and `Route53.Targets`\. +Some services' AWS Construct Library support is in more than one module\. For example, Amazon Route 53 has the three modules in addition to the main `Amazon.CDK.AWS.Route53` module, named `Route53.Patterns`, `Route53.Resolver`, and `Route53.Targets`\. The AWS CDK's core module, which you'll need in most AWS CDK apps, is imported in C\# code as `Amazon.CDK`\. Modules for the various services in the AWS Construct Library live under `Amazon.CDK.AWS` and are named the same as their NuGet package name\. For example, the Amazon S3 module's namespace is `Amazon.CDK.AWS.S3`\. From 5f965a4ebd28ec2182197a45b75cdcd344657043 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 25 Jan 2021 21:38:06 +0000 Subject: [PATCH 352/655] fix broken links --- doc_source/home.md | 2 +- doc_source/use_cfn_template.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/home.md b/doc_source/home.md index cc662e44..37161469 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -238,7 +238,7 @@ In addition to this guide, the following are other resources available to AWS CD + [GitHub Repository](https://github.com/awslabs/aws-cdk) + [Issues](https://github.com/awslabs/aws-cdk/issues) + [Examples](https://github.com/aws-samples/aws-cdk-examples) - + [Documentation Source](https://github.com/awsdocs/aws-cdk-user-guide/tree/master/doc_source) + + [Documentation Source](https://github.com/awsdocs/aws-cdk-guide) + [License](https://github.com/awslabs/aws-cdk/blob/master/LICENSE) + [Releases](https://github.com/awslabs/aws-cdk/releases) + [AWS CDK OpenPGP key](pgp-keys.md#cdk_pgp_key) diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 84101409..589670f5 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -1,6 +1,6 @@ # Import or migrate an existing AWS CloudFormation template -The [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html) construct converts the resources in an imported AWS CloudFormation template to AWS CDK L1 constructs\. You can work with these in your app just as if they were defined in AWS CDK code, even using them within higher\-level AWS CDK constructs, letting you use \(for example\) the L2 permission grant methods with the resources they define\. +The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-readme.html](https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-readme.html) construct converts the resources in an imported AWS CloudFormation template to AWS CDK L1 constructs\. You can work with these in your app just as if they were defined in AWS CDK code, even using them within higher\-level AWS CDK constructs, letting you use \(for example\) the L2 permission grant methods with the resources they define\. This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. From 1a8d48b7eda5e7ce2747eeeb718c1a0cbf8beb18 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 25 Jan 2021 22:04:10 +0000 Subject: [PATCH 353/655] how to resolve cloud assembly versioning issue --- doc_source/reference.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc_source/reference.md b/doc_source/reference.md index a13cbf89..54284567 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -24,6 +24,8 @@ Cloud assembly schema version mismatch: Maximum schema version supported is 3.0. Please upgrade your CLI in order to interact with this app. ``` +To resolve this error, update the AWS CDK Toolkit to a version compatible with the required cloud assembly version, or simply to the latest available version\. The alternative \(downgrading the construct library modules your app uses\) is generally not desirable\. + **Note** For more details on the cloud assembly schema, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/cloud-assembly-schema#versioning)\. From bbd63404db4af166212f5307b4b18e09f47f3565 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 26 Jan 2021 02:01:09 +0000 Subject: [PATCH 354/655] add info on what resources have addRemovalPolicy methods --- doc_source/resources.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index 1cbcf310..f6956075 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1216,7 +1216,7 @@ public CdkTestStack(Construct scope, string id, IStackProps props) : base(scope, ------ -You can also apply a removal policy directly to the underlying AWS CloudFormation resource via the `applyRemovalPolicy()` method\. +You can also apply a removal policy directly to the underlying AWS CloudFormation resource via the `applyRemovalPolicy()` method\. This method is available on some stateful resources that do not have a `removalPolicy` property in their L2 resource's props, including AWS CloudFormation stacks, Amazon Cognito user pools, Amazon DocumentDB database instances, Amazon EC2 volumes, Amazon Elasticsearch Service domains, Amazon FSx file systems, and Amazon SQS queues\. ------ #### [ TypeScript ] From c1651556c64a8db2cdf75af4c946ecf7f23ff1e3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 2 Feb 2021 16:53:50 +0000 Subject: [PATCH 355/655] update CDK Toolkit help reference and elaborate on resource count --- doc_source/cli.md | 31 +++++++++++++++++-------------- doc_source/tagging.md | 2 +- doc_source/troubleshooting.md | 15 +++++++++------ doc_source/use_cfn_template.md | 2 +- 4 files changed, 28 insertions(+), 22 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 9b7d7b93..a07dfd25 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -289,7 +289,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -308,7 +308,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -316,7 +316,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -340,7 +340,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -362,7 +362,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -557,7 +557,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -570,7 +570,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -580,10 +580,13 @@ Synthesizes and prints the CloudFormation template for this stack Options: -e, --exclusively Only synthesize requested stacks, don't include - dependencies [boolean] + dependencies [boolean] + + -q, --quiet Do not output CloudFormation Template to stdout + [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -652,7 +655,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -702,7 +705,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -721,7 +724,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -741,7 +744,7 @@ Options: with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -763,7 +766,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 706ad73f..eaa5cde3 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 9c38e682..36ce0e7f 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -6,7 +6,7 @@ This topic describes how to troubleshoot the following issues with the AWS CDK\. + [When deploying my AWS CDK stack, I receive a `NoSuchBucket` error](#troubleshooting_nobucket) + [When deploying my AWS CDK stack, I receive a `forbidden: null` message](#troubleshooting_forbidden_null) + [When synthesizing an AWS CDK stack, I get the message `--app is required either in command-line, in cdk.json or in ~/.cdk.json`](#troubleshooting_app_required) -+ [When deploying an AWS CDK stack, I receive an error because the AWS CloudFormation template contains too many resources](#troubleshooting_resource_count) ++ [When synthesizing an AWS CDK stack, I receive an error because the AWS CloudFormation template contains too many resources](#troubleshooting_resource_count) + [I specified three \(or more\) Availability Zones for my EC2 Auto\-Scaling Group or Virtual Private Cloud, but it was only deployed in two](#troubleshooting_availability_zones) + [My S3 bucket, DynamoDB table, or other resource is not deleted when I issue `cdk destroy`](#troubleshooting_resource_not_deleted) @@ -203,8 +203,11 @@ cdk synth --app "npx ts-node my-cdk-app.ts" MyStack \([back to list](#troubleshooting_top)\) -**When deploying an AWS CDK stack, I receive an error because the AWS CloudFormation template contains too many resources** -The AWS CDK generates and deploys AWS CloudFormation templates\. AWS CloudFormation has a hard limit of 500 resources per stack\. With the AWS CDK, you can run up against this limit more quickly than you might expect, especially if you haven't already worked with AWS CloudFormation enough to know what resources are being generated by the AWS Construct Library constructs you're using\. +**When synthesizing an AWS CDK stack, I receive an error because the AWS CloudFormation template contains too many resources** +The AWS CDK generates and deploys AWS CloudFormation templates\. AWS CloudFormation has a hard limit on the number of resources a stack can contain\. With the AWS CDK, you can run up against this limit more quickly than you might expect\. + +**Note** +The AWS CloudFormation resource limit is 500 at this writing\. See [AWS CloudFormation quotas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html) for the current resource limit\. The AWS Construct Library's higher\-level, intent\-based constructs automatically provision any auxiliary resources that are needed for logging, key management, authorization, and other purposes\. For example, granting one resource access to another generates any IAM objects needed for the relevant services to communicate\. @@ -212,10 +215,10 @@ In our experience, real\-world use of intent\-based constructs results in 1–5 Patterns, which represent a higher level of abstraction, let you define even more AWS resources with even less code\. The AWS CDK code in [Creating an AWS Fargate service using the AWS CDK](ecs_example.md), for example, generates more than fifty AWS CloudFormation resources while defining only three constructs\! -Synthesize regularly and keep an eye on how many resources your stack contains\. You'll quickly get a feel for how many resources will be generated by the constructs you use most frequently\. +Exceeding the AWS CloudFormation resource limit is an error during AWS CloudFormation synthesis\. The AWS CDK issues a warning if your stack exceeds 80% of the limit\. You can use a different limit by setting the `maxResources` property on your stack, or disable validation by setting `maxResources` to 0\. **Tip** -You can count the resources in your synthesized output using the following short script\. \(Since every CDK user has Node\.js installed, it is written in JavaScript\.\) +You can get an exact count of the resources in your synthesized output using the following utility script\. \(Since every AWS CDK user has Node\.js installed to run the CDK, the script is written in JavaScript\.\) ``` // rescount.js - count the resources defined in a stack @@ -231,7 +234,7 @@ if (path) fs.readFile(path, 'utf8', function(err, contents) { }); else console.log("Please specify the path to the stack's output .json file"); ``` -As your stack's resource count approaches 500, consider re\-architecting to reduce the number of resources your stack contains, for example by combining some Lambda functions, or to break it up into multiple stacks\. The CDK supports [references between stacks](resources.md#resource_stack), so it is straightforward to separate your app's functionality into different stacks in whatever way makes the most sense to you\. +As your stack's resource count approaches the limit, consider re\-architecting to reduce the number of resources your stack contains: for example, by combining some Lambda functions, or by breaking your stack into multiple stacks\. The CDK supports [references between stacks](resources.md#resource_stack), so it is straightforward to separate your app's functionality into different stacks in whatever way makes the most sense to you\. **Note** AWS CloudFormation experts often suggest the use of nested stacks as a solution to the resource limit\. The AWS CDK supports this approach via the [`NestedStack`](stacks.md#stack_nesting) construct\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 589670f5..fe08cbc4 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 607307d33630fb4ba9fad9d8d783f7f627312c6e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 2 Feb 2021 17:13:45 +0000 Subject: [PATCH 356/655] change Mac OS X to macOS (changed in 10.12) --- doc_source/bootstrapping.md | 6 +++--- doc_source/cdk_pipeline.md | 6 +++--- doc_source/cli.md | 2 +- doc_source/codepipeline_example.md | 6 +++--- doc_source/environments.md | 8 ++++---- doc_source/getting_started.md | 2 +- doc_source/work-with-cdk-python.md | 2 +- 7 files changed, 16 insertions(+), 16 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 5a1f960c..cef2fa76 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -73,7 +73,7 @@ The template is also available in the [AWS CDK GitHub repository](https://github Deploy this template using your preferred deployment mechanism for AWS CloudFormation templates\. For example, the following command deploys the template using the AWS CLI: ------ -#### [ Mac OS X/Linux ] +#### [ macOS/Linux ] ``` aws cloudformation create-stack \ @@ -107,7 +107,7 @@ The main differences between the templates are as follows\. At some point in the future, the modern template will become the default bootstrapping template\. Until then, manually select the modern template when bootstrapping by setting the `CDK_NEW_BOOTSTRAP` environment variable\. ------ -#### [ Mac OS X/Linux ] +#### [ macOS/Linux ] ``` export CDK_NEW_BOOTSTRAP=1 @@ -164,7 +164,7 @@ The following additional switches are available only with the modern bootstrappi When you need more customization than the AWS CDK Toolkit switches can provide, you can modify the bootstrap template to suit your needs\. Remember that you can obtain the template by using the \-\-show\-template flag\. Optionally, set the CDK\_NEW\_BOOTSTRAP environment variable to get the modern template \(otherwise, you'll get the legacy template\)\. ------ -#### [ Mac OS X/Linux ] +#### [ macOS/Linux ] ``` export CDK_NEW_BOOTSTRAP=1 diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 8382a2ac..bc595e13 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -27,7 +27,7 @@ Most organizations mandate stricter controls on what kinds of resources can be d You may omit the \-\-profile option if your default AWS profile contains the necessary credentials or to instead use the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to provide your AWS account credentials\. ------ -#### [ Mac OS X/Linux ] +#### [ macOS/Linux ] ``` export CDK_NEW_BOOTSTRAP=1 @@ -53,7 +53,7 @@ To bootstrap additional environments into which AWS CDK applications will be dep Again, you may omit the \-\-profile option if your default AWS profile contains the necessary credentials or if you are using the `AWS_*` environment variables to provide your AWS account credentials\. ------ -#### [ Mac OS X/Linux ] +#### [ macOS/Linux ] ``` export CDK_NEW_BOOTSTRAP=1 @@ -171,7 +171,7 @@ python -m pip install aws_cdk.aws_codepipeline aws_cdk.aws_codepipeline_actions Freeze your dependencies in `requirements.txt`\. -**Mac OS X/Linux** +**macOS/Linux** ``` python -m pip freeze | grep -v '^[-#]' > requirements.txt diff --git a/doc_source/cli.md b/doc_source/cli.md index a07dfd25..d8d2304c 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -127,7 +127,7 @@ aws configure Provide your AWS access key ID, secret access key, and default region when prompted\. -You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(Mac OS X or Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. +You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(macOS/Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. + In `~/.aws/config` or `%USERPROFILE%\.aws\config` ``` diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index ae75cce6..722133eb 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -63,9 +63,9 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ------ #### [ Python ] - A couple of commands differ between Windows and Mac OS X or Linux\. + A couple of commands differ between Windows and macOS/Linux\. - **Mac OS X/Linux** + **macOS/Linux** ``` cd pipeline @@ -136,7 +136,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi 1. If a directory named `test` exists, delete it\. We won't be using it in this example, and some of the code in the tests will cause errors because of other changes we'll be making\. ------ -#### [ Mac OS X/Linux ] +#### [ macOS/Linux ] ``` rm -rf test diff --git a/doc_source/environments.md b/doc_source/environments.md index 133b3549..bcd85cfd 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -299,7 +299,7 @@ new MyDevStack(app, "dev", new StackProps { Env = makeEnv() }); With your stack's environment declared this way, you can now write a short script or batch file like the following to set the variables from command line arguments, then call `cdk deploy`\. Any arguments beyond the first two are passed through to `cdk deploy` and can be used to specify command\-line options or stacks\. ------ -#### [ Mac OS X/Linux ] +#### [ macOS/Linux ] ``` #!/usr/bin/env bash @@ -336,14 +336,14 @@ if ($args.length -ge 2) { } ``` -The Windows version of the script uses PowerShell to provide the same functionality as the Mac OS X/Linux version\. It also contains instructions to allow it to be run as a batch file so it can be easily invoked from a command line\. It should be saved as `cdk-deploy-to.bat`\. The file `cdk-deploy-to.ps1` will be created when the batch file is invoked\. +The Windows version of the script uses PowerShell to provide the same functionality as the macOS/Linux version\. It also contains instructions to allow it to be run as a batch file so it can be easily invoked from a command line\. It should be saved as `cdk-deploy-to.bat`\. The file `cdk-deploy-to.ps1` will be created when the batch file is invoked\. ------ Then you can write additional scripts that call the "deploy\-to" script to deploy to specific environments \(even multiple environments per script\): ------ -#### [ Mac OS X/Linux ] +#### [ macOS/Linux ] ``` #!/usr/bin/env bash @@ -365,7 +365,7 @@ cdk-deploy-to 135792469 us-east-1 %* When deploying to multiple environments, consider whether you want to continue deploying to other environments after a deployment fails\. The following example avoids deploying to the second production environment if the first doesn't succeed\. ------ -#### [ Mac OS X/Linux ] +#### [ macOS/Linux ] ``` #!/usr/bin/env bash diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index ecedb221..2e7d3d48 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -128,7 +128,7 @@ aws configure Provide your AWS access key ID, secret access key, and default region when prompted\. -You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(Mac OS X or Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. +You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(macOS/Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. + In `~/.aws/config` or `%USERPROFILE%\.aws\config` ``` diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 54a17317..c4915d4a 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -8,7 +8,7 @@ You can use any editor or IDE\. Many AWS CDK developers use [Visual Studio Code] To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. -Python AWS CDK applications require Python 3\.6 or later\. If you don't already have it installed, [download a compatible version](https://www.python.org/downloads/) for your platform at [python\.org](https://www.python.org/)\. If you run Linux, your system may have come with a compatible version, or you may install it using your distro's package manager \(`yum`, `apt`, etc\.\)\. Mac users may be interested in [Homebrew](https://brew.sh/), a Linux\-style package manager for Mac OS X\. +Python AWS CDK applications require Python 3\.6 or later\. If you don't already have it installed, [download a compatible version](https://www.python.org/downloads/) for your platform at [python\.org](https://www.python.org/)\. If you run Linux, your system may have come with a compatible version, or you may install it using your distro's package manager \(`yum`, `apt`, etc\.\)\. Mac users may be interested in [Homebrew](https://brew.sh/), a Linux\-style package manager for macOS\. The Python package installer, `pip`, and virtual environment manager, `virtualenv`, are also required\. Windows installations of compatible Python versions include these tools\. On Linux, `pip` and `virtualenv` may be provided as separate packages in your package manager\. Alternatively, you may install them with the following commands: From 9bdd2c396264516cbbf5b39e8db569ca7e25d5eb Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 5 Feb 2021 03:41:52 +0000 Subject: [PATCH 357/655] tweaks --- doc_source/aspects.md | 14 +++++++------- doc_source/cli.md | 26 +++++++++++++------------- doc_source/constructs.md | 2 +- doc_source/ecs_example.md | 2 +- doc_source/hello_world.md | 6 +++--- doc_source/parameters.md | 4 ++-- doc_source/tagging.md | 2 +- doc_source/tokens.md | 2 +- doc_source/use_cfn_template.md | 4 ++-- 9 files changed, 31 insertions(+), 31 deletions(-) diff --git a/doc_source/aspects.md b/doc_source/aspects.md index ad2ee822..2235199b 100644 --- a/doc_source/aspects.md +++ b/doc_source/aspects.md @@ -90,11 +90,11 @@ When you call `Aspects.of(SCOPE).add(...)`, the construct adds the aspect to an During the [prepare phase](apps.md#lifecycle), the AWS CDK calls the `visit` method of the object for the construct and each of its children in top\-down order\. -Although the aspect object is free to change any aspect of the construct, it only operates on a specific subset of construct types\. After determining the construct type, it can call any method and inspect or assign any property on the construct\. +The `visit` method is free to change anything in the construct\. In strongly\-typed languages, cast the received construct to a more specific type before accessing construct\-specific properties or methods\. ## Example -The following example validates that all buckets created in the stack have versioning enabled\. The aspect adds an error to the constructs that fail the validation, which results in the synth operation failing and prevents deploying the resulting cloud assembly\. +The following example validates that all buckets created in the stack have versioning enabled\. The aspect adds an error annotation to the constructs that fail the validation, which results in the synth operation failing and prevents deploying the resulting cloud assembly\. ------ #### [ TypeScript ] @@ -110,7 +110,7 @@ class BucketVersioningChecker implements IAspect { if (!node.versioningConfiguration || (!Tokenization.isResolvable(node.versioningConfiguration) && node.versioningConfiguration.status !== 'Enabled')) { - node.node.addError('Bucket versioning is not enabled'); + Annotations.of(node).addError('Bucket versioning is not enabled'); } } } @@ -134,7 +134,7 @@ class BucketVersioningChecker { if ( !node.versioningConfiguration || !Tokenization.isResolvable(node.versioningConfiguration) && node.versioningConfiguration.status !== 'Enabled') { - node.node.addError('Bucket versioning is not enabled'); + Annotations.of(node).addError('Bucket versioning is not enabled'); } } } @@ -161,7 +161,7 @@ class BucketVersioningChecker: !Tokenization.is_resolvable(node.versioning_configuration) and node.versioning_configuration.status != "Enabled"): - node.node.add_error('Bucket versioning is not enabled') + Annotations.of(node).add_error('Bucket versioning is not enabled') # Later, apply to the stack Aspects.of(stack).add(BucketVersioningChecker()) @@ -184,7 +184,7 @@ public class BucketVersioningChecker implements IAspect if (versioningConfiguration == null || !Tokenization.isResolvable(versioningConfiguration.toString()) && !versioningConfiguration.toString().contains("Enabled") - bucket.getNode().addError("Bucket versioning is not enabled"); + Annotations.of(bucket.getNode()).addError("Bucket versioning is not enabled"); } } } @@ -209,7 +209,7 @@ class BucketVersioningChecker : Amazon.Jsii.Runtime.DeputyBase, IAspect if (bucket.VersioningConfiguration is null || !Tokenization.IsResolvable(bucket.VersioningConfiguration) && !bucket.VersioningConfiguration.ToString().Contains("Enabled") - bucket.Node.AddError("Bucket versioning is not enabled"); + Annotations.Of(bucket.Node).AddError("Bucket versioning is not enabled"); } } } diff --git a/doc_source/cli.md b/doc_source/cli.md index d8d2304c..6646c1a2 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -289,7 +289,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -308,7 +308,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -316,7 +316,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -340,7 +340,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -362,7 +362,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -557,7 +557,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -570,7 +570,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -586,7 +586,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -655,7 +655,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -705,7 +705,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -724,7 +724,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -744,7 +744,7 @@ Options: with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -766,7 +766,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/constructs.md b/doc_source/constructs.md index aa0a997f..bdc77a03 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -10,7 +10,7 @@ The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html)` class represents an Amazon DynamoDB table\. -There are different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "level 1"\) or Cfn resources\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. +There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "level 1"\) or Cfn \(short for CloudFormation\) resources\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#add-wbr-lifecycle-wbr-rulerule), which adds a lifecycle rule to the bucket\. diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 325986fa..bcd86cdf 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -80,7 +80,7 @@ cd MyEcsConstruct cdk init --language csharp ``` -You may now open `src/MyEcsConstruct.sln` in Visual Studio\./ +You may now open `src/MyEcsConstruct.sln` in Visual Studio\. ------ diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index b5263e32..624efcbe 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -152,7 +152,7 @@ Just to verify everything is working correctly, list the stacks in your app\. cdk ls ``` -If you don't see `HelloCdkStack`, make sure you named your app's directory `hello-cdk`\. If you didn't, go back to [Create the app](#hello_world_tutorial_create_app) and try again\. +If you don't see `hello-cdk` stack, make sure you named your app's directory `hello-cdk`\. If you didn't, go back to [Create the app](#hello_world_tutorial_create_app) and try again\. ## Add an Amazon S3 bucket @@ -262,7 +262,7 @@ Replace the first import statement in `hello_cdk_stack.py` in the `hello_cdk` di ``` from aws_cdk import ( aws_s3 as s3, - core as cdk + core ) ``` @@ -438,7 +438,7 @@ bucket = s3.Bucket(self, "MyFirstBucket", versioned=True, public_read_access=True, - removal_policy=cdk.RemovalPolicy.DESTROY) + removal_policy=core.RemovalPolicy.DESTROY) ``` ------ diff --git a/doc_source/parameters.md b/doc_source/parameters.md index 60b559bd..a90b4814 100644 --- a/doc_source/parameters.md +++ b/doc_source/parameters.md @@ -19,10 +19,10 @@ There are, however, use cases to which AWS CloudFormation parameters are uniquel ## Defining parameters -Use the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnParameter.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnParameter.html) class to define a parameter\. You'll want to specify at least a type and a description for most parameters, though both are technically optional\. The description appears when the user is prompted to enter the parameter's value in the AWS CloudFormation console\. +Use the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnParameter.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnParameter.html) class to define a parameter\. You'll want to specify at least a type and a description for most parameters, though both are technically optional\. The description appears when the user is prompted to enter the parameter's value in the AWS CloudFormation console\. For more information on the available types, see [Types](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#parameters-section-structure-properties-type)\. **Note** -We recommend defining parameters at the stack level to ensure that their logical ID does not change when you refactor your code\. +You can define parameters in any scope, but we recommend defining parameters at the stack level so that their logical ID does not change when you refactor your code\. ------ #### [ TypeScript ] diff --git a/doc_source/tagging.md b/doc_source/tagging.md index eaa5cde3..c5f82efd 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/tokens.md b/doc_source/tokens.md index b92c8a75..01342ede 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -1,6 +1,6 @@ # Tokens -Tokens represent values that can only be resolved at a later time in the lifecycle of an app \(see [App lifecycle](apps.md#lifecycle)\)\. For example, the name of an Amazon S3 bucket that you define in your AWS CDK app is only allocated by AWS CloudFormation when you deploy your app\. If you print the `bucket.bucketName` attribute, which is a string, you see it contains something like the following\. +Tokens represent values that can only be resolved at a later time in the lifecycle of an app \(see [App lifecycle](apps.md#lifecycle)\)\. For example, the name of an Amazon S3 bucket that you define in your AWS CDK app is only allocated when the AWS CloudFormation template is synthesized\. If you print the `bucket.bucketName` attribute, which is a string, you see it contains something like the following\. ``` ${TOKEN[Bucket.Name.1234]} diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index fe08cbc4..7bad660f 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. @@ -263,7 +263,7 @@ When you `cdk deploy` the stack, your AWS CDK app becomes the source of truth fo ## Accessing imported resources -The name `template` in the example code represents the imported AWS CloudFormation template\. To access a resource from it, use this object's [https://docs.aws.amazon.com/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) method\. To access the returned resource as a specific kind of resource, cast the result to the desired type\. \(Casting is not necessary in Python and JavaScript\.\) +The name `template` in the example code represents the imported AWS CloudFormation template\. To access a resource from it, use this object's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) method\. To access the returned resource as a specific kind of resource, cast the result to the desired type\. \(Casting is not necessary in Python and JavaScript\.\) ------ #### [ TypeScript ] From 967ede47fd937239c547f070ff2d8867e52a2455 Mon Sep 17 00:00:00 2001 From: "Simon Cornelius P. Umacob" Date: Tue, 9 Feb 2021 10:10:59 +0800 Subject: [PATCH 358/655] Fix the dash. --- doc_source/codepipeline_example.md | 4 ++-- doc_source/serverless_example.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 722133eb..ce548d56 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -55,7 +55,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ``` cd pipeline - cdk init ‐-language javascript + cdk init --language javascript npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions ``` @@ -1275,4 +1275,4 @@ cdk destroy LambdaStack cdk destroy PipelineDeployingLambdaStack ``` -Finally, delete your AWS CodeCommit repository from the AWS Console\. \ No newline at end of file +Finally, delete your AWS CodeCommit repository from the AWS Console\. diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 16615051..4e2b10de 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -41,7 +41,7 @@ cdk init --language typescript ``` mkdir MyWidgetService cd MyWidgetService -cdk init ‐-language javascript +cdk init --language javascript ``` ------ @@ -876,4 +876,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` \ No newline at end of file +``` From d227b7559f4f8d379c8bf908da68297fa9c4de75 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 11 Feb 2021 22:08:41 +0000 Subject: [PATCH 359/655] tweaks --- doc_source/codepipeline_example.md | 2 +- doc_source/serverless_example.md | 2 +- doc_source/work-with-cdk-csharp.md | 6 +++--- doc_source/work-with-cdk-java.md | 8 ++++---- doc_source/work-with-cdk-javascript.md | 4 ++-- doc_source/work-with-cdk-python.md | 4 ++-- doc_source/work-with-cdk-typescript.md | 4 ++-- 7 files changed, 15 insertions(+), 15 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index ce548d56..fc31ec6e 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -1275,4 +1275,4 @@ cdk destroy LambdaStack cdk destroy PipelineDeployingLambdaStack ``` -Finally, delete your AWS CodeCommit repository from the AWS Console\. +Finally, delete your AWS CodeCommit repository from the AWS Console\. \ No newline at end of file diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 4e2b10de..35f8e796 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -876,4 +876,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` +``` \ No newline at end of file diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 8d6c843c..376c8535 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -97,7 +97,7 @@ We do not recommend the use of the `nuget` tool with AWS CDK projects created by ### Props -All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. In C\#, props are expressed using a props type\. In idiomatic C\# fashion, we can use an object initializer to set the various properties\. Here we're creating an Amazon S3 bucket using the `Bucket` construct; its corresponding props type is `BucketProps`\. @@ -134,11 +134,11 @@ var bucket = new MyBucket(this, "MyBucket", new MimeBucketProps { When calling the parent class's initializer or overridden method, you can generally pass the props you received\. The new type is compatible with its parent, and extra props you added are ignored\. -Keep in mind that future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues using your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion for your construct's users\. You can avoid this potential problem by naming your properties so they clearly belong to your construct\. If there are many new properties, bundle them into an appropriately\-named class and pass them as a single property\. +A future release of the AWS CDK could coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues using your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion for your construct's users\. You can avoid this potential problem by naming your properties so they clearly belong to your construct\. If there are many new properties, bundle them into an appropriately\-named class and pass them as a single property\. ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In C\#, objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` in C\#\. +In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In C\#, these objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` in C\#\. ### Missing values diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 068648e6..13f4ef9b 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -69,7 +69,7 @@ This value can be any valid Maven version specifier\. For example, `[1.XX.Y,2.0) ### Props -All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. In Java, props are expressed using the [Builder pattern](https://en.wikipedia.org/wiki/Builder_pattern)\. Each construct type has a corresponding props type; for example, the `Bucket` construct \(which represents an Amazon S3 bucket\) takes as its props an instance of `BucketProps`\. @@ -91,11 +91,11 @@ Bucket bucket = Bucket.Builder.create(this, "MyBucket") .build(); ``` -When deriving your own construct from an existing construct, you may want to accept additional properties\. We recommend that you follow these builder patterns\. However, this isn't as simple as subclassing a construct class\. You must provide the moving parts of the two new `Builder` classes yourself\. Given this fact, you may prefer to simply have your construct accept additional arguments\. In this case, provide additional constructors when an argument is optional\. +When deriving your own construct from an existing construct, you may want to accept additional properties\. We recommend that you follow these builder patterns\. However, this isn't as simple as subclassing a construct class\. You must provide the moving parts of the two new `Builder` classes yourself\. You may prefer to simply have your construct accept one or more additional arguments\. You should provide additional constructors when an argument is optional\. ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects or as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Java, objects are represented as `java.util.Map`\. In cases where the values are all strings, you can use `Map`\. It is convenient to use double braces to define `HashMap`s\. +In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Java, these objects are represented as `java.util.Map`\. In cases where the values are all strings, you can use `Map`\. It is convenient to use double braces to define `HashMap`s\. ``` new HashMap() {{ @@ -105,7 +105,7 @@ new HashMap() {{ ``` **Note** -The double\-brace notation \(which technically declares an anonymous inner class\) is sometimes considered an anti\-pattern\. However, its disadvantages are not very relevant to this use case, and it is a reasonably compact way to write what would be object or dictionary literals in other languages\. +The double\-brace notation \(which technically declares an anonymous inner class\) is sometimes considered an anti\-pattern\. However, its disadvantages are not very relevant to using it in CDK apps\. It is a reasonable substitute for what would be object or dictionary literals in other languages\. JavaScript arrays are represented as `List` or `List` in Java\. The method `java.util.Arrays.asList` is convenient for defining short `ArrayList`s\. diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index c99ac392..6af7a834 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -72,13 +72,13 @@ All AWS Construct Library modules used in your project must be the same version\ ### Props -All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the AWS resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the AWS resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. Using an IDE or editor that has good JavaScript autocomplete will help avoid misspelling property names\. If a construct is expecting an `encryptionKeys` property, and you spell it `encryptionkeys`, when instantiating the construct, you haven't passed the value you intended\. This can cause an error at synthesis time if the property is required, or cause the property to be silently ignored if it is optional\. In the latter case, you may get a default behavior you intended to override\. Take special care here\. When subclassing an AWS Construct Library class \(or overriding a method that takes a props\-like argument\), you may want to accept additional properties for your own use\. These values will be ignored by the parent class or overridden method, because they are never accessed in that code, so you can generally pass on all the props you received\. -However, we do occasionally add properties to constructs\. If a property we add in a later version happens to have the same name as one you're accepting, passing it up the chain can cause unexpected behavior\. It's safer to pass a shallow copy of the props you received with your property removed or set to undefined\. For example: +A future release of the AWS CDK could coincidentally add a new property with a name you used for your own property\. Passing the value you receive up the inheritance chain can then cause unexpected behavior\. It's safer to pass a shallow copy of the props you received with your property removed or set to `undefined`\. For example: ``` super(scope, name, {...props, encryptionKeys: undefined}); diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index c4915d4a..da40925f 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -124,7 +124,7 @@ By convention, the second argument to AWS CDK constructs is named `id`\. When wr ### Props -All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. In Python, props are expressed as keyword arguments\. If an argument contains nested data structures, these are expressed using a class which takes its own keyword arguments at instantiation\. The same pattern is applied to other method calls that take a single structured argument\. @@ -150,7 +150,7 @@ class MyConstruct(Construct): # ... ``` -Future releases of the AWS CDK may coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues for users of your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion\. You can avoid this potential problem by naming your properties so they clearly belong to your construct\. If there are many new properties, bundle them into an appropriately\-named class and pass it as a single keyword argument\. +A future release of the AWS CDK could coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues for users of your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion\. You can avoid this potential problem by naming your properties so they clearly belong to your construct\. If there are many new properties, bundle them into an appropriately\-named class and pass it as a single keyword argument\. ### Missing values diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index d1fd5120..c80574f2 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -81,7 +81,7 @@ All AWS Construct Library modules used in your project must be the same version\ ### Props -All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), a *name*, and *props*, a bundle of key/value pairs that the construct uses to configure the AWS resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the AWS resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. In TypeScript, the shape of `props` is defined using an interface that tells you the required and optional arguments and their types\. Such an interface is defined for each kind of `props` argument, usually specific to a single construct or method\. For example, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) construct \(in the `@aws-cdk/aws-s3 module`\) specifies a `props` argument conforming to the [BucketProps](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.BucketProps.html) interface\. @@ -89,7 +89,7 @@ If a property is itself an object, for example the [websiteRedirect](https://doc If you are subclassing an AWS Construct Library class \(or overriding a method that takes a props\-like argument\), you can inherit from the existing interface to create a new one that specifies any new props your code requires\. When calling the parent class or base method, generally you can pass the entire props argument you received, since any attributes provided in the object but not specified in the interface will be ignored\. -However, we do occasionally add properties to constructs\. If a property we add in a later version happens to have the same name as one you're accepting, passing it up the chain can cause unexpected behavior\. It's safer to pass a shallow copy of the props you received with your property removed or set to `undefined`\. For example: +A future release of the AWS CDK could coincidentally add a new property with a name you used for your own property\. Passing the value you receive up the inheritance chain can then cause unexpected behavior\. It's safer to pass a shallow copy of the props you received with your property removed or set to `undefined`\. For example: ``` super(scope, name, {...props, encryptionKeys: undefined}); From b1c9a387ab11a6e3c0a08fb9db5f0d4ff63704e3 Mon Sep 17 00:00:00 2001 From: sharmaprateek <230600+sharmaprateek@users.noreply.github.com> Date: Thu, 11 Feb 2021 21:02:03 -0800 Subject: [PATCH 360/655] Update apps.md typo: there was no space between 'cdk.json' and the 'file' keyword. --- doc_source/apps.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index 88a9b73a..486e483c 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -258,7 +258,7 @@ To work with the CDK CLI, you need to let it know how to execute an AWS CDK app\ cdk --app executable cdk-command ``` -The \-\-app option instructs the CLI to run your AWS CDK app, and its contents depend on the programming language you use\. Eventually it should be a program that the operating system can run\. You can also create the `cdk.json`file and add information to it so that you need to call only `cdk cdk-command`\. For example, for JavaScript apps, the `cdk.json` file might look like the following, where `node bin/my-app.js` executes a Node\.js program\. +The \-\-app option instructs the CLI to run your AWS CDK app, and its contents depend on the programming language you use\. Eventually it should be a program that the operating system can run\. You can also create the `cdk.json` file and add information to it so that you need to call only `cdk cdk-command`\. For example, for JavaScript apps, the `cdk.json` file might look like the following, where `node bin/my-app.js` executes a Node\.js program\. ------ #### [ TypeScript ] @@ -316,4 +316,4 @@ The CLI can also interact directly with an already synthesized cloud assembly\. ``` cdk --app ./my-cloud-assembly ls -``` \ No newline at end of file +``` From 667c9fa4607eb69d77dd4c85680d62d6484f98b1 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 12 Feb 2021 22:51:00 +0000 Subject: [PATCH 361/655] update cdk app commands and improve explanation --- doc_source/apps.md | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index 486e483c..dff61448 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -250,22 +250,16 @@ The call to `app.synth()` is what tells the AWS CDK to synthesize a cloud assemb See the [cloud assembly specification](https://github.com/aws/aws-cdk/blob/master/design/cloud-assembly.md) for details on how cloud assemblies are formatted\. -To interact with the cloud assembly that your AWS CDK app creates, you typically use the AWS CDK CLI\. But any tool that can read the cloud assembly format can be used to deploy your app\. +To interact with the cloud assembly that your AWS CDK app creates, you typically use the AWS CDK Toolkit, a command\-line tool\. But any tool that can read the cloud assembly format can be used to deploy your app\. -To work with the CDK CLI, you need to let it know how to execute an AWS CDK app\. - -``` -cdk --app executable cdk-command -``` - -The \-\-app option instructs the CLI to run your AWS CDK app, and its contents depend on the programming language you use\. Eventually it should be a program that the operating system can run\. You can also create the `cdk.json` file and add information to it so that you need to call only `cdk cdk-command`\. For example, for JavaScript apps, the `cdk.json` file might look like the following, where `node bin/my-app.js` executes a Node\.js program\. +The CDK Toolkit needs to know how to execute your AWS CDK app\. If you created the project from a template using the `cdk init` command, your app's `cdk.json` file includes an `app` key that specifies the necessary command for the language the app is written in\. If your language requires compilation, the command line performs this step before running the app, so you can't forget to do it\. ------ #### [ TypeScript ] ``` { - "app": "node bin/my-app.js" + "app": "npx ts-node --prefer-ts-exts bin/my-app.ts" } ``` @@ -292,7 +286,7 @@ The \-\-app option instructs the CLI to run your AWS CDK app, and its contents d ``` { - "app": "mvn -q exec:java", + "app": "mvn -e -q compile exec:java" } ``` @@ -301,19 +295,22 @@ The \-\-app option instructs the CLI to run your AWS CDK app, and its contents d ``` { - "app": "dotnet run -p src/project-name/project-name.csproj" + "app": "dotnet run -p src/MyApp/MyApp.csproj" } ``` ------ -**Note** -Use the `cdk init` command to create a language\-specific project, with a `cdk.json` file containing the correct configuration for the programming language you specify\. +If you did not create your project using the CDK Toolkit, or wish to override the command line given in `cdk.json`, you can use the \-\-app option when issuing the `cdk` command\. -The *cdk\-command* part of the AWS CDK CLI command represents what you want the AWS CDK to do with the app\. +``` +cdk --app 'executable' cdk-command ... +``` -The CLI can also interact directly with an already synthesized cloud assembly\. To do that, just pass the directory in which the cloud assembly is stored in `--app`\. The following example lists the stacks defined in the cloud assembly stored under `./my-cloud-assembly`\. +The *executable* part of the command indicates the command that should be run to execute your CDK application\. Use quotation marks as shown, since such commands contain spaces\. The *cdk\-command* is a subcommand like synth or deploy that tells the CDK Toolkit what you want to do with your app\. Follow this with any additional options needed for that subcommand\. + +The CLI can also interact directly with an already\-synthesized cloud assembly\. To do that, just pass the directory in which the cloud assembly is stored in \-\-app\. The following example lists the stacks defined in the cloud assembly stored under `./my-cloud-assembly`\. ``` cdk --app ./my-cloud-assembly ls -``` +``` \ No newline at end of file From e258772a53270260fcb3179b036596e372918811 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 13 Feb 2021 01:06:33 +0000 Subject: [PATCH 362/655] use new API for unique IDs and add info on addresses --- doc_source/identifiers.md | 53 +++++++++++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 7 deletions(-) diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index eca8b65b..76e1bcd2 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -186,43 +186,82 @@ string path = myConstruct.Node.Path; ## Unique IDs -Since AWS CloudFormation requires that all logical IDs in a template are unique, the AWS CDK must be able to generate a unique identifier for each construct in an application\. Since the AWS CDK already has paths that are globally unique, the AWS CDK generates these unique identifiers by concatenating the elements of the path, and adds an 8\-digit hash\. The hash is necessary, as otherwise two distinct paths, such as `A/B/C` and `A/BC` would result in the same identifier\. The AWS CDK calls this concatenated path elements and hash the *unique ID* of the construct\. +Since AWS CloudFormation requires that all logical IDs in a template are unique, the AWS CDK must be able to generate a unique identifier for each construct in an application\. Resources have paths that are globally unique \(the names of all scopes from the stack to a specific resource\) so the AWS CDK generates the necessary unique identifiers by concatenating the elements of the path and adding an 8\-digit hash\. \(The hash is necessary to distinguish distinct paths, such as `A/B/C` and `A/BC`, that would result in the same AWS CloudFormation identifier, since AWS CloudFormation identifiers are alphanumeric and cannot contain slashes or other separator characters\.\) The AWS CDK calls this string the *unique ID* of the construct\. -You can access the unique ID of any construct programmatically, as shown in the following example, which gets the unique ID of `myConstruct` \(or `my_construct` in Python conventions\)\. Since ids must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. +In general, your AWS CDK app should not need to know about unique IDs\. You can, however, access the unique ID of any construct programmatically, as shown in the following example\. ------ #### [ TypeScript ] ``` -const uid: string = myConstruct.node.uniqueId; +const uid: string = Names.uniqueId(myConstruct); ``` ------ #### [ JavaScript ] ``` -const uid = myConstruct.node.uniqueId; +const uid = Names.uniqueId(myConstruct); ``` ------ #### [ Python ] ``` -uid = my_construct.node.unique_id +uid = Names.unique_id(my_construct) ``` ------ #### [ Java ] ``` -String uid = myConstruct.getNode().getUniqueId(); +String uid = Names.uniqueId(myConstruct); ``` ------ #### [ C\# ] ``` -string uid = myConstruct.Node.UniqueId; +string uid = Names.Uniqueid(myConstruct); +``` + +------ + +The *address* is another kind of unique identifier that uniquely distinguishes CDK resources\. Derived from the SHA\-1 hash of the path, it is not human\-readable, but its constant, relatively short length \(always 42 hexadecimal characters\) makes it useful in situations where the "traditional" unique ID might be too long\. Some constructs may use the address in the synthesized AWS CloudFormation template instead of the unique ID\. Again, your app generally should not need to know about its constructs' addresses, but you can retrieve a construct's address as follows\. + +------ +#### [ TypeScript ] + +``` +const addr: string = myConstruct.node.addr; +``` + +------ +#### [ JavaScript ] + +``` +const addr = myConstruct.node.addr; +``` + +------ +#### [ Python ] + +``` +addr = my_construct.node.addr +``` + +------ +#### [ Java ] + +``` +String addr = myConstruct.getNode().getAddr(); +``` + +------ +#### [ C\# ] + +``` +string addr = myConstruct.Node.Addr; ``` ------ From b601f7a6cfda59e10ad9bb7cf80b6ece0431e44b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 15 Feb 2021 19:41:33 +0000 Subject: [PATCH 363/655] make package imports more consistent with their language --- doc_source/use_cfn_template.md | 36 +++++++++++++++++----------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 7bad660f..cef68c1e 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -29,13 +29,13 @@ And here's how you import it into your stack using `cloudformation-include`\. ``` import * as cdk from '@aws-cdk/core'; -import * as cfn_inc from '@aws-cdk/cloudformation-include'; +import * as cfninc from '@aws-cdk/cloudformation-include'; export class MyStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); - const template = new cfn_inc.CfnInclude(this, 'Template', { + const template = new cfninc.CfnInclude(this, 'Template', { templateFile: 'my-template.json', }); } @@ -47,13 +47,13 @@ export class MyStack extends cdk.Stack { ``` cost cdk = require('@aws-cdk/core'); -const cfn_inc = require('@aws-cdk/cloudformation-include'); +const cfninc = require('@aws-cdk/cloudformation-include'); class MyStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); - const template = new cfn_inc.CfnInclude(this, 'Template', { + const template = new cfninc.CfnInclude(this, 'Template', { templateFile: 'my-template.json', }); } @@ -107,7 +107,7 @@ public class MyStack extends Stack { ``` using Amazon.CDK; -using cfn_inc = Amazon.CDK.CloudFormation.Include; +using cfnInc = Amazon.CDK.CloudFormation.Include; namespace MyApp { @@ -115,7 +115,7 @@ namespace MyApp { internal MyStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { - var template = new cfn_inc.CfnInclude(this, "Template", new cfn_inc.CfnIncludeProps + var template = new cfnInc.CfnInclude(this, "Template", new cfnInc.CfnIncludeProps { TemplateFile = "my-template.json" }); @@ -134,7 +134,7 @@ If you are instead developing an AWS CDK construct wrapper for the template so i #### [ TypeScript ] ``` -const template = new cfn_inc.CfnInclude(this, 'MyConstruct', { +const template = new cfninc.CfnInclude(this, 'MyConstruct', { templateFile: 'my-template.json', preserveLogicalIds: false }); @@ -144,7 +144,7 @@ const template = new cfn_inc.CfnInclude(this, 'MyConstruct', { #### [ JavaScript ] ``` -const template = new cfn_inc.CfnInclude(this, 'MyConstruct', { +const template = new cfninc.CfnInclude(this, 'MyConstruct', { templateFile: 'my-template.json', preserveLogicalIds: false }); @@ -173,7 +173,7 @@ CfnInclude template = CfnInclude.Builder.create(this, "Template") #### [ C\# ] ``` -var template = new cfn_inc.CfnInclude(this, "Template", new cfn_inc.CfnIncludeProps +var template = new cfnInc.CfnInclude(this, "Template", new cfn_inc.CfnIncludeProps { TemplateFile = "my-template.json", PreserveLogicalIds = false @@ -394,7 +394,7 @@ If your included AWS CloudFormation template has parameters, you can replace the #### [ TypeScript ] ``` -const template = new cfn_inc.CfnInclude(this, 'Template', { +const template = new cfninc.CfnInclude(this, 'Template', { templateFile: 'my-template.json', parameters: { 'UploadBucket': bucket.bucketArn, @@ -406,7 +406,7 @@ const template = new cfn_inc.CfnInclude(this, 'Template', { #### [ JavaScript ] ``` -const template = new cfn_inc.CfnInclude(this, 'Template', { +const template = new cfninc.CfnInclude(this, 'Template', { templateFile: 'my-template.json', parameters: { 'UploadBucket': bucket.bucketArn, @@ -440,7 +440,7 @@ CfnInclude template = CfnInclude.Builder.create(this, "Template") #### [ C\# ] ``` -var template = new cfn_inc.CfnInclude(this, "Template", new cfn_inc.CfnIncludeProps +var template = new cfnInc.CfnInclude(this, "Template", new cfnInc.CfnIncludeProps { TemplateFile = "my-template.json", Parameters = new Dictionary @@ -526,7 +526,7 @@ Given this resource definition in the main template, the following code shows ho ``` // include nested stack when importing main stack -const mainTemplate = new cfn_inc.CfnInclude(this, 'MainStack', { +const mainTemplate = new cfninc.CfnInclude(this, 'MainStack', { templateFile: 'main-template.json', loadNestedStacks: { 'NestedStack': { @@ -546,7 +546,7 @@ const nestedTemplate = mainTemplate.loadNestedStack('NestedTemplate', { ``` // include nested stack when importing main stack -const mainTemplate = new cfn_inc.CfnInclude(this, 'MainStack', { +const mainTemplate = new cfninc.CfnInclude(this, 'MainStack', { templateFile: 'main-template.json', loadNestedStacks: { 'NestedStack': { @@ -599,17 +599,17 @@ IncludedNestedStack nestedTemplate = mainTemplate.loadNestedStack("NestedTemplat ``` // include nested stack when importing main stack -var mainTemplate = new cfn_inc.CfnInclude(this, "MainStack", new cfn_inc.CfnIncludeProps +var mainTemplate = new cfnInc.CfnInclude(this, "MainStack", new cfnInc.CfnIncludeProps { TemplateFile = "main-template.json", - LoadNestedStacks = new Dictionary + LoadNestedStacks = new Dictionary { - { "NestedStack", new cfn_inc.CfnIncludeProps { TemplateFile = "nested-template.json" } } + { "NestedStack", new cfnInc.CfnIncludeProps { TemplateFile = "nested-template.json" } } } }); // or add it some time after importing the main stack -var nestedTemplate = mainTemplate.LoadNestedStack("NestedTemplate", new cfn_inc.CfnIncludeProps { +var nestedTemplate = mainTemplate.LoadNestedStack("NestedTemplate", new cfnInc.CfnIncludeProps { TemplateFile = 'nested-template.json' }); ``` From a044618dc766982b7ea3ad2214e74d8a08e18c80 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 15 Feb 2021 23:56:07 +0000 Subject: [PATCH 364/655] .env to .venv --- doc_source/troubleshooting.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 36ce0e7f..c8bd1d0b 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -54,7 +54,7 @@ You can edit your `package.json` file to lock the AWS Construct Library modules ------ #### [ Python ] -Use a virtual environment to manage your project's AWS Construct Library modules\. For your convenience, `cdk init` creates a virtual environment for new Python projects in the project's `.env` directory\. +Use a virtual environment to manage your project's AWS Construct Library modules\. For your convenience, `cdk init` creates a virtual environment for new Python projects in the project's `.venv` directory\. Add the AWS Construct Library modules your project uses to its `requirements.txt` file\. Use the `=` syntax to specify an exact version, or the `~=` syntax to constrain updates to versions without breaking API changes\. For example, the following specifies the latest version of the listed modules that are API\-compatible with version 1\.x: From f8488634f962922d62eca367657b517a10453e38 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 17 Feb 2021 21:59:46 +0000 Subject: [PATCH 365/655] add info on breaking deadlock on shared resources --- doc_source/cli.md | 26 +++++++++++++------------- doc_source/resources.md | 4 ++++ doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- 4 files changed, 19 insertions(+), 15 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 6646c1a2..912141f2 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -289,7 +289,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -308,7 +308,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -316,7 +316,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -340,7 +340,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -362,7 +362,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -557,7 +557,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -570,7 +570,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -586,7 +586,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -655,7 +655,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -705,7 +705,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -724,7 +724,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -744,7 +744,7 @@ Options: with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -766,7 +766,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/resources.md b/doc_source/resources.md index f6956075..09da612e 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -263,6 +263,10 @@ var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = p If the AWS CDK determines that the resource is in the same account and Region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. +Referencing a resource from one stack in a different stack creates a dependency between the two stacks,\. Once this dependency is established, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure if the AWS CDK Toolkit deploys the producing stack before the consuming stack\. This happens if there is another dependency between the two stacks, but it can also happen that the producing stack is chosen by the AWS CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it is no longer needed, but the exported resource is still being used in the consuming stack because its update has not yet been deployed, so deploying the producer stack fails\. + +To break this deadlock, remove the use of the shared resource from the consuming stack \(which will remove the automatic export from the producing stack\), then manually add the same export to the producing stack using exactly the same logical ID as the automatically\-generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then remove the manual export \(and the shared resource if it is no longer nededed\), and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#exportwbrvalueexportedvalue-options)` method is a convenient way to create the manual export for this purpose \(see the example in the linked method reference\)\. + ## Physical names The logical names of resources in AWS CloudFormation are different from the names of resources that are shown in the AWS Management Console after AWS CloudFormation has deployed the resources\. The AWS CDK calls these final names *physical names*\. diff --git a/doc_source/tagging.md b/doc_source/tagging.md index c5f82efd..31aff59b 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index cef68c1e..2f5f98a6 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From f16155bc96d2f23f86953d5a76b857a3541bbd94 Mon Sep 17 00:00:00 2001 From: Jarold Wong Date: Thu, 18 Feb 2021 16:06:16 -0800 Subject: [PATCH 366/655] update cdk ls output --- doc_source/hello_world.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 624efcbe..52d0a3b9 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -152,7 +152,7 @@ Just to verify everything is working correctly, list the stacks in your app\. cdk ls ``` -If you don't see `hello-cdk` stack, make sure you named your app's directory `hello-cdk`\. If you didn't, go back to [Create the app](#hello_world_tutorial_create_app) and try again\. +If you don't see `HelloCdkStack`, make sure you named your app's directory `hello-cdk`\. If you didn't, go back to [Create the app](#hello_world_tutorial_create_app) and try again\. ## Add an Amazon S3 bucket From 325e66c4af0263706e26d3df4555cc9c7f23aa2a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 19 Feb 2021 03:56:52 +0000 Subject: [PATCH 367/655] tweak --- doc_source/hello_world.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 52d0a3b9..e8987fa7 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -480,7 +480,7 @@ Now we'll use the `cdk diff` command to see the differences between what's alrea cdk diff ``` -The AWS CDK Toolkit queries your AWS account for the current AWS CloudFormation template for the `hello-cdk` stack, and compares it with the template it just synthesized from your app\. The Resources section of the output should look like the following\. +The AWS CDK Toolkit queries your AWS account for the current AWS CloudFormation template for the `HelloCdkStack` and compares it with the template it just synthesized from your app\. The Resources section of the output should look like the following\. ``` Stack HelloCdkStack From a6c1a036aaa89e29cf00bd150befe6ac47ea0ac5 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 19 Feb 2021 15:44:25 +0000 Subject: [PATCH 368/655] fix class name --- doc_source/constructs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index bdc77a03..9f91d4de 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -273,7 +273,7 @@ var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps ------ -In Python, Java, and C\#, L1 construct properties that aren't simple Booleans, strings, numbers, or containers are represented by types defined as inner classes of the L1 construct\. For example, the optional property `corsConfiguration` of a `CfnBucket` requires a wrapper of type `Cfn.CorsConfigurationProperty`\. Here we are defining `corsConfiguration` on a `CfnBucket` instance\. +In Python, Java, and C\#, L1 construct properties that aren't simple Booleans, strings, numbers, or containers are represented by types defined as inner classes of the L1 construct\. For example, the optional property `corsConfiguration` of a `CfnBucket` requires a wrapper of type `CfnBucket.CorsConfigurationProperty`\. Here we are defining `corsConfiguration` on a `CfnBucket` instance\. ------ #### [ TypeScript ] From 55947389f9898bb4f85065733c746a9260b4c73a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 19 Feb 2021 21:49:27 +0000 Subject: [PATCH 369/655] add info about autoDeleteObjects in S3 buckets --- doc_source/cli.md | 26 +++++++++++++------------- doc_source/hello_world.md | 15 ++++++++++----- doc_source/resources.md | 17 +++++++++++------ doc_source/tagging.md | 2 +- doc_source/troubleshooting.md | 3 +-- doc_source/use_cfn_template.md | 2 +- 6 files changed, 37 insertions(+), 28 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 912141f2..b0f6a297 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -289,7 +289,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -308,7 +308,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -316,7 +316,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -340,7 +340,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -362,7 +362,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -557,7 +557,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -570,7 +570,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -586,7 +586,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -655,7 +655,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -705,7 +705,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -724,7 +724,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -744,7 +744,7 @@ Options: with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -766,7 +766,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index e8987fa7..31a427d7 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -400,7 +400,7 @@ You've deployed your first stack using the AWS CDK—congratulations\! But that' ## Modifying the app -The AWS CDK can update your deployed resources after you modify your app\. Let's make a couple of changes to our bucket\. First, we'll enable public read access, so people out in the world can access the files we store in the bucket\. We also want to be able to delete the bucket automatically when we delete the stack, so we'll change its `RemovalPolicy`\. +The AWS CDK can update your deployed resources after you modify your app\. Let's make a couple of changes to our bucket\. First, we'll enable public read access, so people out in the world can access the files we store in the bucket\. We also want to be able to delete the bucket automatically when we delete the stack, so we'll change its `RemovalPolicy`\. Finally, because AWS CloudFormation won't delete Amazon S3 buckets that contain any objects, we'll ask the AWS CDK to delete the objects from our bucket before destroying the bucket\. ------ #### [ TypeScript ] @@ -411,7 +411,8 @@ Update `lib/hello-cdk-stack.ts`\. new s3.Bucket(this, 'MyFirstBucket', { versioned: true, publicReadAccess: true, - removalPolicy: cdk.RemovalPolicy.DESTROY + removalPolicy: cdk.RemovalPolicy.DESTROY, + autoDeleteObjects: true }); ``` @@ -424,7 +425,8 @@ Update `lib/hello-cdk-stack.js`\. new s3.Bucket(this, 'MyFirstBucket', { versioned: true, publicReadAccess: true, - removalPolicy: cdk.RemovalPolicy.DESTROY + removalPolicy: cdk.RemovalPolicy.DESTROY, + autoDeleteObjects: true }); ``` @@ -438,7 +440,8 @@ bucket = s3.Bucket(self, "MyFirstBucket", versioned=True, public_read_access=True, - removal_policy=core.RemovalPolicy.DESTROY) + removal_policy=core.RemovalPolicy.DESTROY + auto_delete_objects=True) ``` ------ @@ -455,6 +458,7 @@ Bucket.Builder.create(this, "MyFirstBucket") .versioned(true) .publicReadAccess(true) .removalPolicy(RemovalPolicy.DESTROY) + .autoDeleteObjects(true) .build(); ``` @@ -468,7 +472,8 @@ new Bucket(this, "MyFirstBucket", new BucketProps { Versioned = true, PublicReadAccess = true, - RemovalPolicy = RemovalPolicy.DESTROY + RemovalPolicy = RemovalPolicy.DESTROY, + AutoDeleteObjects = true }); ``` diff --git a/doc_source/resources.md b/doc_source/resources.md index 09da612e..c69054f5 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1125,9 +1125,9 @@ Resources besides those that store data persistently may also have a `removalPol | RemovalPolicy\.RETAIN | Keep the contents of the resource when destroying the stack \(default\)\. The resource is orphaned from the stack and must be deleted manually\. If you attempt to re\-deploy the stack while the resource still exists, you will receive an error message due to a name conflict\. | | RemovalPolicy\.DESTROY | The resource will be destroyed along with the stack\. | -AWS CloudFormation does not remove Amazon S3 buckets that contain files even if their removal policy is set to `DESTROY`\. Attempting to do so is a AWS CloudFormation error\. Delete the files from the bucket before destroying the stack\. You can automate this using a custom resource; see the third\-party construct [auto\-delete\-bucket](https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda) for an example\. +AWS CloudFormation does not remove Amazon S3 buckets that contain files even if their removal policy is set to `DESTROY`\. Attempting to do so is a AWS CloudFormation error\. To have the AWS CDK delete all files from the bucket before destroying it, set the bucket's `autoDeleteObjects` property to `true`\. -Following is an example of creating an Amazon S3 bucket with `RemovalPolicy.DESTROY`\. +Following is an example of creating an Amazon S3 bucket with `RemovalPolicy` of `DESTROY` and `autoDeleteOjbects` set to `true`\. \. ------ #### [ TypeScript ] @@ -1142,6 +1142,7 @@ export class CdkTestStack extends cdk.Stack { const bucket = new s3.Bucket(this, 'Bucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, + autoDeleteObjects: true }); } } @@ -1159,7 +1160,8 @@ class CdkTestStack extends cdk.Stack { super(scope, id, props); const bucket = new s3.Bucket(this, 'Bucket', { - removalPolicy: cdk.RemovalPolicy.DESTROY + removalPolicy: cdk.RemovalPolicy.DESTROY, + autoDeleteObjects: true }); } } @@ -1179,7 +1181,8 @@ class CdkTestStack(cdk.stack): super().__init__(scope, id, **kwargs) bucket = s3.Bucket(self, "Bucket", - removal_policy=cdk.RemovalPolicy.DESTROY) + removal_policy=cdk.RemovalPolicy.DESTROY, + auto_delete_objects=True) ``` ------ @@ -1198,7 +1201,8 @@ public class CdkTestStack extends Stack { super(scope, id, props); Bucket.Builder.create(this, "Bucket") - .removalPolicy(RemovalPolicy.DESTROY).build(); + .removalPolicy(RemovalPolicy.DESTROY) + .autoDeleteObjects(true).build(); } } ``` @@ -1213,7 +1217,8 @@ using Amazon.CDK.AWS.S3; public CdkTestStack(Construct scope, string id, IStackProps props) : base(scope, id, props) { new Bucket(this, "Bucket", new BucketProps { - RemovalPolicy = RemovalPolicy.DESTROY + RemovalPolicy = RemovalPolicy.DESTROY, + AutoDeleteObjects = true }); } ``` diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 31aff59b..6ce0d157 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index c8bd1d0b..36e797b9 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -350,7 +350,6 @@ public CdkTestStack(Construct scope, string id, IStackProps props) : base(scope, ------ **Note** -AWS CloudFormation cannot delete a non\-empty Amazon S3 bucket\. If you set an Amazon S3 bucket's removal policy to `DESTROY`, and it contains data, attempting to destroy the stack will fail because the bucket cannot be deleted\. -It is possible to handle the destruction of an Amazon S3 bucket using an AWS CloudFormation [custom resource](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) that deletes the bucket's contents before attempting to delete the bucket itself\. The third\-party construct [https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda](https://github.com/mobileposse/auto-delete-bucket/tree/master/src/lambda), for example, uses such a custom resource\. +AWS CloudFormation cannot delete a non\-empty Amazon S3 bucket\. If you set an Amazon S3 bucket's removal policy to `DESTROY`, and it contains data, attempting to destroy the stack will fail because the bucket cannot be deleted\. You can have the AWS CDK delete the objects in the bucket before attempting to destroy it by setting the bucket's `autoDeleteObjects` prop to `true`\. \([back to list](#troubleshooting_top)\) \ No newline at end of file diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 2f5f98a6..20f46c05 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 112a6e26b0b5bdbb1dd70cc29934d87ff6780481 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 20 Feb 2021 02:18:52 +0000 Subject: [PATCH 370/655] add guidance about committing context files --- doc_source/cdk_pipeline.md | 5 ++++- doc_source/context.md | 2 +- doc_source/resources.md | 4 +++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index bc595e13..41576d98 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -4,7 +4,7 @@ CDK Pipelines are self\-updating: if you add new application stages or new stacks, the pipeline automatically reconfigures itself to deploy those new stages and/or stacks\. -If you've looked at our [AWS CodePipeline example](codepipeline_example.md), CDK Pipelines can do everything that example does, and more, with less code\. Going forward, we anticipate widespread adoption of CDK Pipelines by AWS CDK users\. +If you've looked at our [AWS CodePipeline example](codepipeline_example.md), CDK Pipelines can do everything that example does, and more, with less code\. Going forward, we anticipate widespread adoption of CDK Pipelines by AWS CDK developers\. **Note** CDK Pipelines is currently in developer preview, and its API is subject to change\. Breaking API changes will be announced in the AWS CDK [Release Notes](https://github.com/aws/aws-cdk/releases)\. @@ -145,6 +145,9 @@ If you are using Visual Studio, open the solution file in the `src` directory\. Install the CDK Pipelines module along with others you'll be using\. +**Tip** +Be sure to commit your `cdk.json` and `cdk.context.json` files in source control\. The context information \(such as feature flags and cached values retrieved from your AWS account\) are part of your project's state\. In particular, any cached values are critical to successful deployment, since your app won't be able to retrieve such values from your AWS account while running in the CI/CD environment\. + ------ #### [ TypeScript ] diff --git a/doc_source/context.md b/doc_source/context.md index 48034a3d..9c297849 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -16,7 +16,7 @@ Context values are made available to your AWS CDK app in six different ways: The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, changing your Auto Scaling group\. The AWS CDK does not write context data to any of the other files listed\. -We recommend that your project's context files be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. +We recommend that your project's context files be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. It is also critical to successful automated deployment of stacks that rely on context values \(for example, using [CDK Pipelines](cdk_pipeline.md)\): since the deployment system won't have access to your AWS account, it will rely on the cached values in the context files\. Context values are scoped to the construct that created them; they are visible to child constructs, but not to siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), whether automatically, from a file, or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in the app\. diff --git a/doc_source/resources.md b/doc_source/resources.md index c69054f5..2ca8724d 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -669,7 +669,9 @@ Vpc.FromLookup(this, id = "PublicVpc", new VpcLookupOptions ------ -Note that `Vpc.fromLookup()` works only in stacks that are defined with an explicit **account** and **region** in their `env` property\. If the AWS CDK attempts to look up an Amazon VPC from an [environment\-agnostic stack](stacks.md#stack_api), the CLI does not know which environment to query to find the VPC\. +`Vpc.fromLookup()` works only in stacks that are defined with an explicit **account** and **region** in their `env` property\. If the AWS CDK attempts to look up an Amazon VPC from an [environment\-agnostic stack](stacks.md#stack_api), the CLI does not know which environment to query to find the VPC\. + +Results of `Vpc.fromLookup()` are cached in the project's `cdk.context.json` file\. Commit this file to version control if you will be deploying the stack in an environment that does not have access to the AWS account that defines the VPC, such as [CDK Pipelines](cdk_pipeline.md)\. Although you can use an imported resource anywhere, you cannot modify the imported resource\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an imported `s3.Bucket` does nothing\. From fcb1161a3798dbdba8d288c3e228aea26aaf278e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 24 Feb 2021 20:51:40 +0000 Subject: [PATCH 371/655] add missing comma --- doc_source/hello_world.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 31a427d7..e5fe2185 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -440,7 +440,7 @@ bucket = s3.Bucket(self, "MyFirstBucket", versioned=True, public_read_access=True, - removal_policy=core.RemovalPolicy.DESTROY + removal_policy=core.RemovalPolicy.DESTROY, auto_delete_objects=True) ``` From fb5d7753ee5308de5f8b0ff2151c23ac89a6d03d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 24 Feb 2021 22:21:45 +0000 Subject: [PATCH 372/655] fix typo --- doc_source/tagging.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 6ce0d157..dddc9320 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -242,7 +242,7 @@ Tags.of(myConstruct).remove('tagname', { #### [ Python ] ``` -Tags.rof(my_construct).remove("tagname", +Tags.of(my_construct).remove("tagname", include_resource_types=["AWS::Xxx::Yyy"], exclude_resource_types=["AWS::Xxx::Zzz"], priority=200,) From fd5fb6d3b7b2ada2c088e0c7078ad4be4b0d7d67 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 27 Feb 2021 01:11:03 +0000 Subject: [PATCH 373/655] update Getting Started and Hello World to not grant public read access to the bucket, other tweaks --- doc_source/cli.md | 32 ++++++-- doc_source/context.md | 2 +- doc_source/getting_started.md | 10 ++- doc_source/hello_world.md | 150 ++++++++++++++++++++-------------- 4 files changed, 125 insertions(+), 69 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index b0f6a297..3f00ddf5 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -403,15 +403,37 @@ The `cdk diff` command compares the current version of a stack defined in your a ``` Stack HelloCdkStack IAM Statement Changes -┌───┬────────────────────────┬────────┬──────────────┬───────────┬───────────┐ -│ │ Resource │ Effect │ Action │ Principal │ Condition │ -├───┼────────────────────────┼────────┼──────────────┼───────────┼───────────┤ -│ + │ ${MyFirstBucket.Arn}/* │ Allow │ s3:GetObject │ * │ │ -└───┴────────────────────────┴────────┴──────────────┴───────────┴───────────┘ +┌───┬──────────────────────────────┬────────┬──────────────────────────────┬──────────────────────────────┬───────────┐ +│ │ Resource │ Effect │ Action │ Principal │ Condition │ +├───┼──────────────────────────────┼────────┼──────────────────────────────┼──────────────────────────────┼───────────┤ +│ + │ ${Custom::S3AutoDeleteObject │ Allow │ sts:AssumeRole │ Service:lambda.amazonaws.com │ │ +│ │ sCustomResourceProvider/Role │ │ │ │ │ +│ │ .Arn} │ │ │ │ │ +├───┼──────────────────────────────┼────────┼──────────────────────────────┼──────────────────────────────┼───────────┤ +│ + │ ${MyFirstBucket.Arn} │ Allow │ s3:DeleteObject* │ AWS:${Custom::S3AutoDeleteOb │ │ +│ │ ${MyFirstBucket.Arn}/* │ │ s3:GetBucket* │ jectsCustomResourceProvider/ │ │ +│ │ │ │ s3:GetObject* │ Role.Arn} │ │ +│ │ │ │ s3:List* │ │ │ +└───┴──────────────────────────────┴────────┴──────────────────────────────┴──────────────────────────────┴───────────┘ +IAM Policy Changes +┌───┬────────────────────────────────────────────────────────┬────────────────────────────────────────────────────────┐ +│ │ Resource │ Managed Policy ARN │ +├───┼────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤ +│ + │ ${Custom::S3AutoDeleteObjectsCustomResourceProvider/Ro │ {"Fn::Sub":"arn:${AWS::Partition}:iam::aws:policy/serv │ +│ │ le} │ ice-role/AWSLambdaBasicExecutionRole"} │ +└───┴────────────────────────────────────────────────────────┴────────────────────────────────────────────────────────┘ (NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299) +Parameters +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/S3Bucket AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3BucketBF7A7F3F: {"Type":"String","Description":"S3 bucket for asset \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/S3VersionKey AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3VersionKeyFAF93626: {"Type":"String","Description":"S3 key for asset version \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/ArtifactHash AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392ArtifactHashE56CD69A: {"Type":"String","Description":"Artifact hash for asset \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} + Resources [+] AWS::S3::BucketPolicy MyFirstBucket/Policy MyFirstBucketPolicy3243DEFD +[+] Custom::S3AutoDeleteObjects MyFirstBucket/AutoDeleteObjectsCustomResource MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E +[+] AWS::IAM::Role Custom::S3AutoDeleteObjectsCustomResourceProvider/Role CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092 +[+] AWS::Lambda::Function Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F [~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 ├─ [~] DeletionPolicy │ ├─ [-] Retain diff --git a/doc_source/context.md b/doc_source/context.md index 9c297849..145714e2 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -89,7 +89,7 @@ To clear all of the stored context values for your app, run cdk context \-\-clea cdk context --clear ``` -Only context values stored in `cdk.context.json` can be reset or cleared\. The AWS CDK does not touch other context files\. To protect a context value from being reset using these commands, then, you might copy the value to `cdk.json`\. +Only context values stored in `cdk.context.json` can be reset or cleared\. The AWS CDK does not touch other context values\. To protect a context value from being reset using these commands, then, you might copy the value to `cdk.json`\. ## AWS CDK Toolkit `--context` flag diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 2e7d3d48..c4d35d48 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -109,7 +109,7 @@ To help you use the AWS CDK in your favorite language, this Guide includes topic + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) -Furthermore, since TypeScript was the first language supported by the AWS CDK, much AWS CDK example code is written in TypeScript\. For this reason, this Guide also includes a topic specifically to show how to adapt TypeScript AWS CDK code for use with the other supported languages\. See [Translating TypeScript AWS CDK code to other languages](multiple_languages.md)\. +TypeScript was the first language supported by the AWS CDK, and much AWS CDK example code is written in TypeScript\. This Guide includes a topic specifically to show how to adapt TypeScript AWS CDK code for use with the other supported languages\. See [Translating TypeScript AWS CDK code to other languages](multiple_languages.md)\. ## Prerequisites @@ -193,6 +193,14 @@ Run the following command to verify correct installation and print the version n cdk --version ``` +## Bootstrapping + +Many AWS CDK stacks that you write will include [assets](assets.md): external files that are deployed with the stack, such as AWS Lambda functions Docker images\. The AWS CDK uploads these to an Amazon S3 bucket or other container so they are available to AWS CloudFormation during deployment\. Deployment requires that these containers already exist in the account and region you are deploying into\. Creating them is called [bootstrapping](bootstrapping.md)\. To bootstrap, issue: + +``` +cdk bootstrap +``` + ## AWS CDK tools The AWS CDK Toolkit, also known as the Command Line Interface \(CLI\), is the main tool you use to interact with your AWS CDK app\. It executes your code and produces and deploys the AWS CloudFormation templates it generates\. It also has deployment, diff, deletion, and troubleshooting capabilities\. For more information, see cdk \-\-help or [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index e5fe2185..11cc072f 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -1,8 +1,10 @@ # Your first AWS CDK app -You've read [Getting started with the AWS CDK](getting_started.md)? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. In this tutorial you'll learn about the structure of a AWS CDK project, how to work with the AWS Construct Library, and how to use the AWS CDK Toolkit command\-line tool\. +You've read [Getting started with the AWS CDK](getting_started.md) and set up your development environment for writing AWS CDK apps? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. -The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps to synthesize your stack to an AWS CloudFormation template and deploy it\. +In this tutorial, you'll learn about the structure of a AWS CDK project, how to use the AWS Construct Library to define AWS resources using code, and how to synthesize, diff, and deploy collections of resources using the AWS CDK Toolkit command\-line tool\. + +The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps\. 1. Create the app from a template provided by the AWS CDK @@ -16,7 +18,7 @@ The standard AWS CDK development workflow is similar to the workflow you're alre The build step catches syntax and type errors\. The synthesis step catches logical errors in defining your AWS resources\. The deployment may find permission issues\. As always, you go back to the code, find the problem, fix it, then build, synthesize and deploy again\. -**Note** +**Tip** Don't forget to keep your AWS CDK code under version control\! This tutorial walks you through creating and deploying a simple AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. The app contains one stack, which contains one resource: an Amazon S3 bucket\. @@ -27,21 +29,15 @@ We'll also show what happens when you make a change and re\-deploy, and how to c Each AWS CDK app should be in its own directory, with its own local module dependencies\. Create a new directory for your app\. Starting in your home directory, or another directory if you prefer, issue the following commands\. -``` -mkdir hello-cdk -cd hello-cdk -``` - **Important** -Be sure to name your project directory `hello-cdk`, *exactly as shown here\.* The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, some of the code in this tutorial won't work\. - -Now initialize the app using the cdk init command, specifying the desired template \("app"\) and programming language\. +Be sure to name your project directory `hello-cdk`, *exactly as shown here\.* The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, the code in this tutorial won't work\. ``` -cdk init TEMPLATE --language LANGUAGE +mkdir hello-cdk +cd hello-cdk ``` -That is: +Now initialize the app using the cdk init command, specifying the desired template \("app"\) and programming language\. That is: ------ #### [ TypeScript ] @@ -94,7 +90,7 @@ If you are using Visual Studio, open the solution file in the `src` directory\. **Tip** If you don't specify a template, the default is "app," which is the one we wanted anyway, so technically you can leave it out and save four keystrokes\. -The cdk init command creates a number of files and folders inside the `hello-cdk` directory to help you organize the source code for your AWS CDK app\. Take a moment to explore\. The structure of a basic app is all there; you'll fill in the details as you progress in this tutorial\. +The cdk init command creates a number of files and folders inside the `hello-cdk` directory to help you organize the source code for your AWS CDK app\. Take a moment to explore\. The structure of a basic app is all there; you'll fill in the details in this tutorial\. If you have Git installed, each project you create using cdk init is also initialized as a Git repository\. We'll ignore that for now, but it's there when you need it\. @@ -126,7 +122,6 @@ No build step is necessary\. mvn compile -q ``` -**Note** Or press Control\-B in Eclipse \(other Java IDEs may vary\) ------ @@ -136,7 +131,6 @@ Or press Control\-B in Eclipse \(other Java IDEs may vary\) dotnet build src ``` -**Note** Or press F6 in Visual Studio ------ @@ -156,7 +150,7 @@ If you don't see `HelloCdkStack`, make sure you named your app's directory `hell ## Add an Amazon S3 bucket -At this point, your app doesn't do anything useful because the stack doesn't define any resources\. Let's define an Amazon S3 bucket\. +At this point, your app doesn't do anything because the stack it contains doesn't define any resources\. Let's add an Amazon S3 bucket\. Install the Amazon S3 package from the AWS Construct Library\. @@ -210,7 +204,7 @@ Or **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution* ------ -Next, define an Amazon S3 bucket in the stack using an L2 construct, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class\. +Next, define an Amazon S3 bucket in the stack using the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) construct\. ------ #### [ TypeScript ] @@ -335,10 +329,10 @@ All constructs take these same three arguments, so it's easy to stay oriented as **Tip** If all a construct's props are optional, you can omit the third parameter entirely\. -It's interesting to take note of how props are represented in the different supported languages\. +Props are represented differently in the languages supported by the AWS CDK\. + In TypeScript and JavaScript, `props` is a single argument and you pass in an object containing the desired properties\. -+ In Python, props are represented as keyword arguments\. -+ In Java, a Builder is provided to pass the props\. \(Two, actually; one for `BucketProps`, and a second for `Bucket` to let you build the construct and its props object in one step\. This code uses the latter\.\) ++ In Python, props are passed as keyword arguments\. ++ In Java, a Builder is provided to pass the props\. Two, actually; one for `BucketProps`, and a second for `Bucket` to let you build the construct and its props object in one step\. This code uses the latter\. + In C\#, you instantiate a `BucketProps` object using an object initializer and pass it as the third parameter\. ## Synthesize an AWS CloudFormation template @@ -349,12 +343,12 @@ Synthesize an AWS CloudFormation template for the app, as follows\. cdk synth ``` -If your app contained more than one stack, you'd need to specify which stack\(s\) to synthesize\. But since it only contains one, the Toolkit knows you must mean that one\. +If your app contained more than one stack, you'd need to specify which stack\(s\) to synthesize\. But since it only contains one, the CDK Toolkit knows you must mean that one\. **Tip** If you received an error like `--app is required...`, it's probably because you are running the command from a subdirectory\. Navigate to the main app directory and try again\. -The `cdk synth` command executes your app, which causes the resources defined in it to be translated to an AWS CloudFormation template\. The displayed output of `cdk synth` is a YAML\-format template; our app's output is shown below\. The template is also saved in the `cdk.out` directory in JSON format\. +The `cdk synth` command executes your app, which causes the resources defined in it to be translated into an AWS CloudFormation template\. The displayed output of `cdk synth` is a YAML\-format template; the beginning of our app's output is shown below\. The template is also saved in the `cdk.out` directory in JSON format\. ``` Resources: @@ -367,18 +361,15 @@ Resources: DeletionPolicy: Retain Metadata: aws:cdk:path: HelloCdkStack/MyFirstBucket/Resource - CDKMetadata: - Type: AWS::CDK::Metadata - Properties: - Modules: aws-cdk=1.XX.X,@aws-cdk/aws-events=1.XX.X,@aws-cdk/aws-iam=1.XX.X,@aws-cdk/aws-kms=1.XX.X,@aws-cdk/aws-s3=1.XX.X,@aws-cdk/cdk-assets-schema=1.XX.X,@aws-cdk/cloud-assembly-schema=1.XX.X,@aws-cdk/core=1.XX.X,@aws-cdk/cx-api=1.XX.X,@aws-cdk/region-info=1.XX.X,jsii-runtime=node.js/vXX.XX.X + CDKMetadata: ... ``` -Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for an `AWS::S3::Bucket` and see how the versioning configuration was translated\. +Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for the bucket and see how the `versioned` property was translated\. **Note** -Every generated template contains a `AWS::CDK::Metadata` resource by default\. The AWS CDK team uses this metadata to gain insight into how the AWS CDK is used, so we can continue to improve it\. For details, including how to opt out of version reporting, see [Version reporting](cli.md#version_reporting)\. +Every generated template contains a `AWS::CDK::Metadata` resource by default\. \(We haven't shown it here\.\) The AWS CDK team uses this metadata to gain insight into how the AWS CDK is used, so we can continue to improve it\. For details, including how to opt out of version reporting, see [Version reporting](cli.md#version_reporting)\. -The `cdk synth` generates a perfectly valid AWS CloudFormation template\. You could take it and deploy it using the AWS CloudFormation console\. But the AWS CDK Toolkit also has that feature built\-in\. +The `cdk synth` generates a perfectly valid AWS CloudFormation template\. You could take it and deploy it using the AWS CloudFormation console or another tool\. But the AWS CDK Toolkit can also do that\. ## Deploying the stack @@ -392,7 +383,7 @@ As with `cdk synth`, you don't need to specify the name of the stack since there It is optional \(though good practice\) to synthesize before deploying\. The AWS CDK synthesizes your stack before each deployment\. -If your code changes have security implications, you'll see a summary of these, and be asked to confirm them before deployment proceeds\. +If your code has security implications, you'll see a summary of these and need to confirm them before deployment proceeds\. This isn't the case in our stack\. `cdk deploy` displays progress information as your stack is deployed\. When it's done, the command prompt reappears\. You can go to the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home) and see that it now lists `HelloCdkStack`\. You'll also find `MyFirstBucket` in the Amazon S3 console\. @@ -400,7 +391,7 @@ You've deployed your first stack using the AWS CDK—congratulations\! But that' ## Modifying the app -The AWS CDK can update your deployed resources after you modify your app\. Let's make a couple of changes to our bucket\. First, we'll enable public read access, so people out in the world can access the files we store in the bucket\. We also want to be able to delete the bucket automatically when we delete the stack, so we'll change its `RemovalPolicy`\. Finally, because AWS CloudFormation won't delete Amazon S3 buckets that contain any objects, we'll ask the AWS CDK to delete the objects from our bucket before destroying the bucket\. +The AWS CDK can update your deployed resources after you modify your app\. Let's change our bucket so it can be automatically deleted when we delete the stack, which involves changing its `RemovalPolicy`\. Also, because AWS CloudFormation won't delete Amazon S3 buckets that contain any objects, we'll ask the AWS CDK to delete the objects from our bucket before destroying the bucket, via the `autoDeleteObjects` property\.\. ------ #### [ TypeScript ] @@ -410,7 +401,6 @@ Update `lib/hello-cdk-stack.ts`\. ``` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, - publicReadAccess: true, removalPolicy: cdk.RemovalPolicy.DESTROY, autoDeleteObjects: true }); @@ -424,7 +414,6 @@ Update `lib/hello-cdk-stack.js`\. ``` new s3.Bucket(this, 'MyFirstBucket', { versioned: true, - publicReadAccess: true, removalPolicy: cdk.RemovalPolicy.DESTROY, autoDeleteObjects: true }); @@ -436,10 +425,8 @@ new s3.Bucket(this, 'MyFirstBucket', { Update `hello_cdk/hello_cdk_stack.py`\. ``` -bucket = s3.Bucket(self, - "MyFirstBucket", +bucket = s3.Bucket(self, "MyFirstBucket", versioned=True, - public_read_access=True, removal_policy=core.RemovalPolicy.DESTROY, auto_delete_objects=True) ``` @@ -456,7 +443,6 @@ import software.amazon.awscdk.services.s3.BucketEncryption; ``` Bucket.Builder.create(this, "MyFirstBucket") .versioned(true) - .publicReadAccess(true) .removalPolicy(RemovalPolicy.DESTROY) .autoDeleteObjects(true) .build(); @@ -471,7 +457,6 @@ Update `HelloCdkStack.cs`\. new Bucket(this, "MyFirstBucket", new BucketProps { Versioned = true, - PublicReadAccess = true, RemovalPolicy = RemovalPolicy.DESTROY, AutoDeleteObjects = true }); @@ -479,26 +464,50 @@ new Bucket(this, "MyFirstBucket", new BucketProps ------ -Now we'll use the `cdk diff` command to see the differences between what's already been deployed, and the app as it stands right now\. +Here, we haven't written any code that, in itself, changes our Amazon S3 bucket\. Instead, our code defines the desired state of the bucket\. The AWS CDK synthesizes that state to a new AWS CloudFormation template and deploys a changeset that makes only the changes necessary to reach that state\. + +To see these changes, we'll use the `cdk diff` command \. ``` cdk diff ``` -The AWS CDK Toolkit queries your AWS account for the current AWS CloudFormation template for the `HelloCdkStack` and compares it with the template it just synthesized from your app\. The Resources section of the output should look like the following\. +The AWS CDK Toolkit queries your AWS account for the last\-deployed AWS CloudFormation template for the `HelloCdkStack` and compares it with the template it just synthesized from your app\. The output should look like the following\. ``` Stack HelloCdkStack IAM Statement Changes -┌───┬────────────────────────┬────────┬──────────────┬───────────┬───────────┐ -│ │ Resource │ Effect │ Action │ Principal │ Condition │ -├───┼────────────────────────┼────────┼──────────────┼───────────┼───────────┤ -│ + │ ${MyFirstBucket.Arn}/* │ Allow │ s3:GetObject │ * │ │ -└───┴────────────────────────┴────────┴──────────────┴───────────┴───────────┘ +┌───┬──────────────────────────────┬────────┬──────────────────────────────┬──────────────────────────────┬───────────┐ +│ │ Resource │ Effect │ Action │ Principal │ Condition │ +├───┼──────────────────────────────┼────────┼──────────────────────────────┼──────────────────────────────┼───────────┤ +│ + │ ${Custom::S3AutoDeleteObject │ Allow │ sts:AssumeRole │ Service:lambda.amazonaws.com │ │ +│ │ sCustomResourceProvider/Role │ │ │ │ │ +│ │ .Arn} │ │ │ │ │ +├───┼──────────────────────────────┼────────┼──────────────────────────────┼──────────────────────────────┼───────────┤ +│ + │ ${MyFirstBucket.Arn} │ Allow │ s3:DeleteObject* │ AWS:${Custom::S3AutoDeleteOb │ │ +│ │ ${MyFirstBucket.Arn}/* │ │ s3:GetBucket* │ jectsCustomResourceProvider/ │ │ +│ │ │ │ s3:GetObject* │ Role.Arn} │ │ +│ │ │ │ s3:List* │ │ │ +└───┴──────────────────────────────┴────────┴──────────────────────────────┴──────────────────────────────┴───────────┘ +IAM Policy Changes +┌───┬────────────────────────────────────────────────────────┬────────────────────────────────────────────────────────┐ +│ │ Resource │ Managed Policy ARN │ +├───┼────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤ +│ + │ ${Custom::S3AutoDeleteObjectsCustomResourceProvider/Ro │ {"Fn::Sub":"arn:${AWS::Partition}:iam::aws:policy/serv │ +│ │ le} │ ice-role/AWSLambdaBasicExecutionRole"} │ +└───┴────────────────────────────────────────────────────────┴────────────────────────────────────────────────────────┘ (NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299) +Parameters +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/S3Bucket AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3BucketBF7A7F3F: {"Type":"String","Description":"S3 bucket for asset \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/S3VersionKey AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3VersionKeyFAF93626: {"Type":"String","Description":"S3 key for asset version \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/ArtifactHash AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392ArtifactHashE56CD69A: {"Type":"String","Description":"Artifact hash for asset \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} + Resources [+] AWS::S3::BucketPolicy MyFirstBucket/Policy MyFirstBucketPolicy3243DEFD +[+] Custom::S3AutoDeleteObjects MyFirstBucket/AutoDeleteObjectsCustomResource MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E +[+] AWS::IAM::Role Custom::S3AutoDeleteObjectsCustomResourceProvider/Role CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092 +[+] AWS::Lambda::Function Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F [~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 ├─ [~] DeletionPolicy │ ├─ [-] Retain @@ -508,16 +517,21 @@ Resources └─ [+] Delete ``` -The diff indicates two things\. First, that the stack has a new IAM policy statement that grants everyone \(principal `*`\) read access \(`s3:GetObject` action\) to our bucket\. Note that we didn't need to create this statement; the AWS CDK did it for us\. All we needed to do was set the `publicReadAccess` property when instantiating the bucket\. +This diff has four sections\. ++ **IAM Statement Changes** and **IAM Policy Changes** \- These permission changes are there because we set the `AutoDeleteObjects` property on our Amazon S3 bucket\. The auto\-delete feature uses a custom resource to delete the objects in the bucket before the bucket itself is deleted\. The IAM objects grant the custom resource's code access to the bucket\. ++ **Parameters** \- The AWS CDK uses these entries to locate the Lambda function asset for the custom resource\. ++ **Resources** \- The new and changed resources in this stack\. We can see the aforementioned IAM objects, the custom resource ,and its associated Lambda function being added\. We can also see that the bucket's `DeletionPolicy` and `UpdateReplacePolicy` attributes are being updated\. These allow the bucket to be deleted along with the stack, and to be replaced with a new one\. -**Note** -It's informative to look at the output of cdk synth here and see the twenty additional lines of AWS CloudFormation template that the AWS CDK generated for us when we changed one property of our bucket\. +You may be curious about why we specified `RemovalPolicy` in our AWS CDK app but got a `DeletionPolicy` property in the resulting AWS CloudFormation template\. The AWS CDK uses a different name for the property because the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it\. See [Removal policies](resources.md#resources_removal) for further details\. -Besides the new policy, we can also see the `DeletionPolicy` property is set to `Delete`, enabling the bucket to be deleted when its stack is deleted\. The `UpdateReplacePolicy `is also changed to cause the bucket to be deleted if it were to be replaced with a new one\. +It's informative to compare the output of cdk synth here with the previous output and see the many additional lines of AWS CloudFormation template that the AWS CDK generated for us based on these relatively small changes\. -Don't be confused by the difference between `RemovalPolicy` in your AWS CDK app and `DeletionPolicy` in the resulting AWS CloudFormation template\. The AWS CDK calls it `RemovalPolicy` because its semantics are slightly different from AWS CloudFormation's `DeletionPolicy`: the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it\. See [Removal policies](resources.md#resources_removal) for further details\. +**Important** +Since the `autoDeleteObjects` property is implemented using a AWS CloudFormation custom resource, which is implemented using an AWS Lambda function, our stack contains an [asset](assets.md)\. This fact requires that our AWS account and region be [bootstrapped](bootstrapping.md) so that there's an Amazon S3 bucket to hold the asset during deployment\. If you haven't already bootstrapped, issue: -You can also see that the bucket isn't going to be replaced, but will be updated with the new properties\. +``` +cdk bootstrap +``` Now let's deploy\. @@ -525,19 +539,34 @@ Now let's deploy\. cdk deploy ``` -The AWS CDK warns you about the security policy change we previously saw in the diff\. Enter y to approve the changes and deploy the updated stack\. The Toolkit updates the bucket configuration as you requested\. +The AWS CDK warns you about the security policy changes we've already seen in the diff\. Enter y to approve the changes and deploy the updated stack\. The CDK Toolkit updates the bucket configuration as you requested\. ``` -HelloCdkStack: deploying... +HHelloCdkStack: deploying... +[0%] start: Publishing 4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392:current +[100%] success: Published 4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392:current HelloCdkStack: creating CloudFormation changeset... - 1/1 | 8:39:43 AM | UPDATE_COMPLETE | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketB8884501) - 1/1 | 8:39:44 AM | UPDATE_COMPLETE_CLEA | AWS::CloudFormation::Stack | HelloCdkStack - 2/1 | 8:39:45 AM | UPDATE_COMPLETE | AWS::CloudFormation::Stack | HelloCdkStack + 0/5 | 4:32:31 PM | UPDATE_IN_PROGRESS | AWS::CloudFormation::Stack | HelloCdkStack User Initiated + 0/5 | 4:32:36 PM | CREATE_IN_PROGRESS | AWS::IAM::Role | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092) + 1/5 | 4:32:36 PM | UPDATE_COMPLETE | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketB8884501) + 1/5 | 4:32:36 PM | CREATE_IN_PROGRESS | AWS::IAM::Role | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092) Resource creation Initiated + 3/5 | 4:32:54 PM | CREATE_COMPLETE | AWS::IAM::Role | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092) + 3/5 | 4:32:56 PM | CREATE_IN_PROGRESS | AWS::Lambda::Function | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F) + 3/5 | 4:32:56 PM | CREATE_IN_PROGRESS | AWS::S3::BucketPolicy | MyFirstBucket/Policy (MyFirstBucketPolicy3243DEFD) + 3/5 | 4:32:56 PM | CREATE_IN_PROGRESS | AWS::Lambda::Function | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F) Resource creation Initiated + 3/5 | 4:32:57 PM | CREATE_COMPLETE | AWS::Lambda::Function | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F) + 3/5 | 4:32:57 PM | CREATE_IN_PROGRESS | AWS::S3::BucketPolicy | MyFirstBucket/Policy (MyFirstBucketPolicy3243DEFD) Resource creation Initiated + 4/5 | 4:32:57 PM | CREATE_COMPLETE | AWS::S3::BucketPolicy | MyFirstBucket/Policy (MyFirstBucketPolicy3243DEFD) + 4/5 | 4:32:59 PM | CREATE_IN_PROGRESS | Custom::S3AutoDeleteObjects | MyFirstBucket/AutoDeleteObjectsCustomResource/Default (MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E) + 5/5 | 4:33:06 PM | CREATE_IN_PROGRESS | Custom::S3AutoDeleteObjects | MyFirstBucket/AutoDeleteObjectsCustomResource/Default (MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E) Resource creation Initiated + 5/5 | 4:33:06 PM | CREATE_COMPLETE | Custom::S3AutoDeleteObjects | MyFirstBucket/AutoDeleteObjectsCustomResource/Default (MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E) + 5/5 | 4:33:08 PM | UPDATE_COMPLETE_CLEA | AWS::CloudFormation::Stack | HelloCdkStack + 6/5 | 4:33:09 PM | UPDATE_COMPLETE | AWS::CloudFormation::Stack | HelloCdkStack ✅ HelloCdkStack Stack ARN: -arn:aws:cloudformation:REGION:ACCOUNT:stack/HelloCdkStack/ID +arn:aws:cloudformation:REGION:ACCOUNT:stack/HelloCdkStack/UNIQUE-ID ``` ## Destroying the app's resources @@ -551,10 +580,7 @@ cdk destroy Enter y to approve the changes and delete any stack resources\. **Note** -This wouldn't have worked if we hadn't changed the bucket's `RemovalPolicy`\! Instead, the stack deletion would complete successfully, and the bucket would become orphaned \(no longer associated with the stack\)\. - -**Tip** -If the bucket still exists after you delete the stack, it probably means you put something in it\. AWS CloudFormation won't delete buckets with files in them\. Delete the files and try again\. +If we hadn't changed the bucket's `RemovalPolicy`, the stack deletion would complete successfully, but the bucket would become orphaned \(no longer associated with the stack\)\. ## Next steps From 9f5fc66abd49671aa042ef599bce4d9816c4b2e5 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 1 Mar 2021 16:23:23 +0000 Subject: [PATCH 374/655] update Node.js version guidance, other tweaks --- doc_source/getting_started.md | 10 +++++----- doc_source/multiple_languages.md | 4 ++-- doc_source/troubleshooting.md | 2 +- doc_source/work-with-cdk-javascript.md | 5 +++-- doc_source/work-with.md | 2 +- 5 files changed, 12 insertions(+), 11 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index c4d35d48..e13c7e10 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -113,14 +113,14 @@ TypeScript was the first language supported by the AWS CDK, and much AWS CDK exa ## Prerequisites -With the concepts out of the way, here's what you need to have on your workstation before you install the AWS CDK and start developing\. +Here's what you need install to use the AWS CDK\. -All CDK developers need to [install Node\.js](https://nodejs.org/en/download/) 10\.3\.0 or later, even those working in languages other than TypeScript or JavaScript\. The AWS CDK Toolkit \(cdk command\-line tool\) and the AWS Construct Library run on Node\.js\. The bindings for other supported languages use this back end and tool set\. We suggest the latest LTS version\. +All AWS CDK developers, even those working in Python, Java, or C\#, need [Node\.js](https://nodejs.org/en/download/) 10\.13\.0 or later\. All supported languages use the same back end, which runs on Node\.js\. We recommend a version in [active long\-term support](https://nodejs.org/en/about/releases/), which, at this writing, is the latest 14\.x release\. Your organization may have a different recommendation\. **Important** -Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK\. +Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. -You must provide your credentials and an AWS Region to use AWS CDK, if you have not already done so\. If you have the AWS CLI installed, the easiest way to satisfy this requirement is to install the AWS CLI and issue the following command: +You must configure your workstation with your credentials and an AWS Region, if you have not already done so\. If you have the AWS CLI installed, the easiest way to satisfy this requirement is issue the following command: ``` aws configure @@ -143,7 +143,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY ``` -Finally, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. +Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. **Important** We strongly recommend against using your AWS root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. Best practices are to change this account's access key regularly and to use a least\-privileges role \(specifying `--role-arn`\) when deploying\. diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 9fa456dd..584dba1b 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -66,7 +66,7 @@ bucket = Bucket(...) ------ #### [ Java ] -Java's imports work differently from TypeScript's\. Each import statement imports either a single class name from a given package, or all classes defined in that package \(using `*`\)\. After importing, classes may be accessed using either the class name by itself or \(in case of name conflicts\) the *qualified* class name including its package\. +Java's imports work differently from TypeScript's\. Each import statement imports either a single class name from a given package, or all classes defined in that package \(using `*`\)\. Classes may be accessed using either the class name by itself if it has been imported, or the *qualified* class name including its package\. Packages are named like `software.amazon.awscdk.services.xxx` for AWS Construct Library packages \(the core module is `software.amazon.awscdk.core`\)\. The Maven group ID for AWS CDK packages is `software.amazon.awscdk`\. @@ -91,7 +91,7 @@ software.amazon.awscdk.services.s3.Bucket bucket = ------ #### [ C\# ] -In C\#, you import types with the `using` directive\. There are two styles, which give you access either all the types in the specified namespace using their plain names, or to refer to the namespace itself using an alias\. +In C\#, you import types with the `using` directive\. There are two styles, which give you access either all the types in the specified namespace using their plain names, or let you refer to the namespace itself using an alias\. Packages are named like `Amazon.CDK.AWS.xxx` for AWS Construct Library packages \(the core module is `Amazon.CDK`\)\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 36e797b9..04f666e4 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -218,7 +218,7 @@ Patterns, which represent a higher level of abstraction, let you define even mor Exceeding the AWS CloudFormation resource limit is an error during AWS CloudFormation synthesis\. The AWS CDK issues a warning if your stack exceeds 80% of the limit\. You can use a different limit by setting the `maxResources` property on your stack, or disable validation by setting `maxResources` to 0\. **Tip** -You can get an exact count of the resources in your synthesized output using the following utility script\. \(Since every AWS CDK user has Node\.js installed to run the CDK, the script is written in JavaScript\.\) +You can get an exact count of the resources in your synthesized output using the following utility script\. \(Since every AWS CDK developer needs Node\.js, the script is written in JavaScript\.\) ``` // rescount.js - count the resources defined in a stack diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 6af7a834..4064824f 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -102,7 +102,8 @@ However, if `a` could have some other "falsy" value besides `undefined`, it is b let c = a == null ? a : a.b; ``` -A version of the ECMAScript standard currently in development specifies new operators that will simplify the handling of undefined values\. Using them can simplify your code, but you will need a new version of Node\.js to use them\. For more information, see the [optional chaining](https://github.com/tc39/proposal-optional-chaining/blob/master/README.md) and [nullish coalescing](https://github.com/tc39/proposal-nullish-coalescing/blob/master/README.md) proposals\. +**Tip** +Node\.js 14\.0 and later support new operators that can simplify the handling of undefined values\. For more information, see the [optional chaining](https://github.com/tc39/proposal-optional-chaining/blob/master/README.md) and [nullish coalescing](https://github.com/tc39/proposal-nullish-coalescing/blob/master/README.md) proposals\. ## Synthesizing and deploying @@ -257,6 +258,6 @@ Many JavaScript developers move to [TypeScript](https://www.typescriptlang.org/) TypeScript's "shape\-based" interfaces, which define bundles of required and optional properties \(and their types\) within an object, allow common mistakes to be caught while you're writing the code, and make it easier for your IDE to provide robust autocomplete and other real\-time coding advice\. -Coding in TypeScript does involve an additional step: compiling your app with the TypeScript compiler, `tsc`\. This step can happen automatically whenever you save your source code, or before you run your app\. For typical AWS CDK apps, compilation requires a few seconds at most\. +Coding in TypeScript does involve an additional step: compiling your app with the TypeScript compiler, `tsc`\. For typical AWS CDK apps, compilation requires a few seconds at most\. The easiest way to migrate an existing JavaScript AWS CDK app to TypeScript is to create a new TypeScript project using `cdk init app --language typescript`, then copy your source files \(and any other necessary files, such as assets like AWS Lambda function source code\) to the new project\. Rename your JavaScript files to end in `.ts` and begin developing in TypeScript\. \ No newline at end of file diff --git a/doc_source/work-with.md b/doc_source/work-with.md index c6243475..8e9e7507 100644 --- a/doc_source/work-with.md +++ b/doc_source/work-with.md @@ -14,7 +14,7 @@ If you have the [AWS CLI](https://aws.amazon.com/cli/) installed, the simplest w aws configure ``` -All AWS CDK applications require Node\.js 10\.3 or later, even when your app is written in Python, Java, or C\#\. You may download a compatible version for your platform at [nodejs\.org](https://nodejs.org/)\. We recommend the [current LTS version](https://nodejs.org/en/about/releases/) \(at this writing, the latest 12\.x release\)\. +All AWS CDK applications require Node\.js 10\.13 or later, even if you work in Python, Java, or C\#\. You may download a compatible version at [nodejs\.org](https://nodejs.org/)\. We recommend the [active LTS version](https://nodejs.org/en/about/releases/) \(at this writing, the latest 14\.x release\)\. Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. After installing Node\.js, install the AWS CDK Toolkit \(the `cdk` command\): From adfad84949bf34891b2a6aed64f1c47433fc3faa Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 3 Mar 2021 04:04:09 +0000 Subject: [PATCH 375/655] update Java dependencies to edit pom.xml directly, add tip about NodejsFunction --- doc_source/cli.md | 26 ++++++++++++------------ doc_source/serverless_example.md | 35 ++++++++++++++++++++++++-------- doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- 4 files changed, 42 insertions(+), 23 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 3f00ddf5..691a1006 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -289,7 +289,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -308,7 +308,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -316,7 +316,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -340,7 +340,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -362,7 +362,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -579,7 +579,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -592,7 +592,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -608,7 +608,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -677,7 +677,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -727,7 +727,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -746,7 +746,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -766,7 +766,7 @@ Options: with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -788,7 +788,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 35f8e796..e62e1783 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -1,9 +1,9 @@ # Creating a serverless application using the AWS CDK -This example walks you through how to create the resources for a simple widget dispensing service\. \(For the purpose of this example, a widget is just a name or identifier that can be added to, retrieved from, and deleted from a collection\.\) The example includes: +This example walks you through creating the resources for a simple widget dispensing service\. \(For the purpose of this example, a widget is just a name or identifier that can be added to, retrieved from, and deleted from a collection\.\) The example includes: + An AWS Lambda function\. + An Amazon API Gateway API to call the Lambda function\. -+ An Amazon S3 bucket that contains the Lambda function code\. ++ An Amazon S3 bucket that holds the widgets\. This tutorial contains the following steps\. @@ -22,6 +22,8 @@ This tutorial contains the following steps\. + Get a widget by name with GET /\{name\} + Delete a widget by name with DELETE /\{name\} +1. Tear everything down when you're finished + ## Create a AWS CDK app Create the app **MyWidgetService** in the current folder\. @@ -114,14 +116,14 @@ Run the app and note that it synthesizes an empty stack\. cdk synth ``` -You should see output like the following, where *CDK\-VERSION* is the version of the AWS CDK\. +You should see output beginning with YAML code like the following\. ``` Resources: CDKMetadata: Type: AWS::CDK::Metadata Properties: - Modules: "@aws-cdk/cdk=CDK-VERSION,@aws-cdk/cx-api=CDK-VERSION,my_widget_service=0.1.0" + Modules: "..." ``` ## Create a Lambda function to list all widgets @@ -221,14 +223,28 @@ pip install aws_cdk.aws_apigateway aws_cdk.aws_lambda aws_cdk.aws_s3 ------ #### [ Java ] -Using your IDE's Maven integration \(e\.g\., in Eclipse, right\-click your project and choose **Maven** > **Add Dependency**\), install the following artifacts from the group `software.amazon.awscdk`: +Add the following dependencies in the `dependencies` element of your project's `pom.xml` file\. ``` -apigateway -lambda -s3 + + software.amazon.awscdk + apigateway + ${cdk.version} + + + software.amazon.awscdk + lambda + ${cdk.version} + + + software.amazon.awscdk + s3 + ${cdk.version} + ``` +We recommend editing `pom.xml` directory rather than using your IDE's dependency management tools to make sure the versions of all AWS CDK libraries are synchronized using the `$cdk.version` variable\. + ------ #### [ C\# ] @@ -479,6 +495,9 @@ namespace MyWidgetService ------ +**Tip** +We're using a `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)` in to deploy this function because it supports a wide variety of programming languages\. For JavaScript and TypeScript specifically, you might consider a `[lambda\-nodejs\.NodejsFunction](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda-nodejs.NodejsFunction.html)`\. The latter uses esbuild to bundle up the script and converts code written in TypeScript automatically\. + Save the app and make sure it still synthesizes an empty stack\. ``` diff --git a/doc_source/tagging.md b/doc_source/tagging.md index dddc9320..8119a2a3 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 20f46c05..45751a20 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 3cdafed83dde852f300221caa7613bed47dcda42 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 3 Mar 2021 04:12:44 +0000 Subject: [PATCH 376/655] use singular for steps --- doc_source/serverless_example.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index e62e1783..6738ce91 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -7,17 +7,17 @@ This example walks you through creating the resources for a simple widget dispen This tutorial contains the following steps\. -1. Creates a AWS CDK app +1. Create a AWS CDK app -1. Creates a Lambda function that gets a list of widgets with HTTP GET / +1. Create a Lambda function that gets a list of widgets with HTTP GET / -1. Creates the service that calls the Lambda function +1. Create the service that calls the Lambda function -1. Adds the service to the AWS CDK app +1. Add the service to the AWS CDK app -1. Tests the app +1. Test the app -1. Adds Lambda functions to do the following: +1. Add Lambda functions to do the following: + Create a widget with POST /\{name\} + Get a widget by name with GET /\{name\} + Delete a widget by name with DELETE /\{name\} From 5c4ae73bbe92c9000f50857d5a01241c0c970f99 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 16 Mar 2021 21:20:01 +0000 Subject: [PATCH 377/655] various changes --- doc_source/aspects.md | 11 +++++------ doc_source/bootstrapping.md | 2 +- doc_source/cdk_pipeline.md | 2 +- doc_source/codepipeline_example.md | 10 ++++++++-- doc_source/featureflags.md | 2 +- 5 files changed, 16 insertions(+), 11 deletions(-) diff --git a/doc_source/aspects.md b/doc_source/aspects.md index 2235199b..e7ef209d 100644 --- a/doc_source/aspects.md +++ b/doc_source/aspects.md @@ -131,7 +131,7 @@ class BucketVersioningChecker { // Check for versioning property, exclude the case where the property // can be a token (IResolvable). - if ( !node.versioningConfiguration + if (!node.versioningConfiguration || !Tokenization.isResolvable(node.versioningConfiguration) && node.versioningConfiguration.status !== 'Enabled') { Annotations.of(node).addError('Bucket versioning is not enabled'); @@ -157,11 +157,10 @@ class BucketVersioningChecker: # Check for versioning property, exclude the case where the property # can be a token (IResolvable). - if (!node.versioning_configuration or - !Tokenization.is_resolvable(node.versioning_configuration) - and node.versioning_configuration.status != "Enabled"): - - Annotations.of(node).add_error('Bucket versioning is not enabled') + if (not node.versioning_configuration or + not Tokenization.is_resolvable(node.versioning_configuration) + and node.versioning_configuration.status != "Enabled"): + Annotations.of(node).add_error('Bucket versioning is not enabled') # Later, apply to the stack Aspects.of(stack).add(BucketVersioningChecker()) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index cef2fa76..a8a5df86 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -130,7 +130,7 @@ The modern template is also selected when you issue cdk bootstrap in an AWS CDK { // ... "context": { - "@aws-cdk/core:newStyleStackSynthesis": "true" + "@aws-cdk/core:newStyleStackSynthesis": true } } ``` diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 41576d98..6efcb210 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -235,7 +235,7 @@ Finally, add the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featurefl ... "context": { ... - "@aws-cdk/core:newStyleStackSynthesis": "true" + "@aws-cdk/core:newStyleStackSynthesis": true } } ``` diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index fc31ec6e..c8bec92a 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -38,7 +38,7 @@ To set up a new AWS CDK project in CodeCommit; **Note** During cloning, Git will warn you that you appear to have cloned an empty repository; this is normal and expected\. -1. Change to the pipeline directory and initialize it as a new CDK project, then install the AWS Construct Libraries we'll use in our app\. +1. Change to the pipeline directory and initialize it as a new CDK project, then install the AWS Construct Libraries we'll use in our app\. Since AWS CodeCommit uses a default branch of "main," we'll also make sure we're working on that branch\. ------ #### [ TypeScript ] @@ -46,6 +46,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ``` cd pipeline cdk init --language typescript + git checkout main || git branch main npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions ``` @@ -56,6 +57,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ``` cd pipeline cdk init --language javascript + git checkout main || git branch main npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions ``` @@ -70,6 +72,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ``` cd pipeline cdk init --language python + git checkout main || git branch main source .venv/bin/activate git commit -m "project started" pip install -r requirements.txt @@ -83,6 +86,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ``` cd pipeline cdk init --language python + git checkout main || git branch main .venv\Scripts\activate.bat pip install -r requirements.txt pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline @@ -96,6 +100,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ``` cd pipeline cdk init --language java + git checkout main || git branch main ``` You can import the resulting Maven project into your Java IDE\. @@ -116,6 +121,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ``` cd pipeline cdk init --language csharp + git checkout main || git branch main ``` You can open the file `src/Pipeline.sln` in Visual Studio\. @@ -154,7 +160,7 @@ During cloning, Git will warn you that you appear to have cloned an empty reposi ------ -1. Stage all the files in the directory, commit them to your local repository, and push to CodeCommit\. +1. Stage all the files in the directory, commit them to your local repository, and push to CodeCommit\. ``` git add --all diff --git a/doc_source/featureflags.md b/doc_source/featureflags.md index aa34a875..52139603 100644 --- a/doc_source/featureflags.md +++ b/doc_source/featureflags.md @@ -6,7 +6,7 @@ The AWS CDK uses *feature flags* to enable potentially breaking behaviors in a r { "app": "npx ts-node bin/tscdk.ts", "context": { - "@aws-cdk/core:enableStackNameDuplicates": "true" + "@aws-cdk/core:enableStackNameDuplicates": true } } ``` From e1fb5cfe4edcd8a0de3f1391c7dc19e9b5caba5a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 16 Mar 2021 22:09:29 +0000 Subject: [PATCH 378/655] update Python instructions --- doc_source/hello_world.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 11cc072f..3bdecc16 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -251,13 +251,10 @@ module.exports = { HelloCdkStack } ------ #### [ Python ] -Replace the first import statement in `hello_cdk_stack.py` in the `hello_cdk` directory with the following code\. +Add the following import statement in `hello_cdk_stack.py` in the `hello_cdk` directory below the existing imports\. ``` -from aws_cdk import ( - aws_s3 as s3, - core -) +from aws_cdk import aws_s3 as s3 ``` Replace the comment with the following code\. From 1e6263c7ce0071d180f59402c515c18bc3b74e99 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 16 Mar 2021 22:09:56 +0000 Subject: [PATCH 379/655] update guidance re region-agnostic stacks with one AZs since Osaka is now full-fledged --- doc_source/environments.md | 2 +- doc_source/troubleshooting.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index bcd85cfd..c3b85e6d 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -7,7 +7,7 @@ For all but the simplest deployments, you will need to [bootstrap](bootstrapping If you don't specify an environment when you define a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availabilityZones` \(Python: `availability_zones`\)\. -In an environment\-agnostic stack, any constructs that use availability zones will see two of them\. This allows the stack to be deployed to almost any region, since nearly all regions have at least two availability zones\. The only exception is Osaka \(`ap-northeast-3`\), which has one\. +In an environment\-agnostic stack, any constructs that use availability zones will see two of them\. This allows the stack to be deployed to almost any region, since nearly all regions have at least two availability zones\. \(Some regions may launch with only one AZ, but this is rare\.\) When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Toolkit \(`cdk` command\)](cli.md) for details\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 04f666e4..07806a9c 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -245,7 +245,7 @@ AWS CloudFormation experts often suggest the use of nested stacks as a solution To get the number of Availability Zones you requested, specify the account and region in the stack's `env` property\. If you do not specify both, the AWS CDK, by default, synthesizes the stack as environment\-agnostic, such that it can be deployed to any region\. You can then deploy the stack to a specific region using AWS CloudFormation\. Because some regions have only two availability zones, an environment\-agnostic template never uses more than two\. **Note** -At this writing, there is one AWS region that has only one availability zone: ap\-northeast\-3 \(Osaka, Japan\)\. Environment\-agnostic AWS CDK stacks cannot be deployed to this region\. +Regions may occasionally launch with only one AZ\. Environment\-agnostic AWS CDK stacks cannot be deployed to such regions\. You can change this behavior by overriding your stack's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) \(Python: `availability_zones`\) property to explicitly specify the zones you want to use\. From a58f855f368b0c1f60c0625a4add5f588bbc645e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 17 Mar 2021 02:52:28 +0000 Subject: [PATCH 380/655] correct guidance on 1-AZ regions --- doc_source/environments.md | 2 +- doc_source/troubleshooting.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/environments.md b/doc_source/environments.md index c3b85e6d..88fd3eba 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -7,7 +7,7 @@ For all but the simplest deployments, you will need to [bootstrap](bootstrapping If you don't specify an environment when you define a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availabilityZones` \(Python: `availability_zones`\)\. -In an environment\-agnostic stack, any constructs that use availability zones will see two of them\. This allows the stack to be deployed to almost any region, since nearly all regions have at least two availability zones\. \(Some regions may launch with only one AZ, but this is rare\.\) +In an environment\-agnostic stack, any constructs that use availability zones will see two of them, allowing the stack to be deployed to any region\. When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Toolkit \(`cdk` command\)](cli.md) for details\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 07806a9c..3c106347 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -245,7 +245,7 @@ AWS CloudFormation experts often suggest the use of nested stacks as a solution To get the number of Availability Zones you requested, specify the account and region in the stack's `env` property\. If you do not specify both, the AWS CDK, by default, synthesizes the stack as environment\-agnostic, such that it can be deployed to any region\. You can then deploy the stack to a specific region using AWS CloudFormation\. Because some regions have only two availability zones, an environment\-agnostic template never uses more than two\. **Note** -Regions may occasionally launch with only one AZ\. Environment\-agnostic AWS CDK stacks cannot be deployed to such regions\. +In the past, regions have occasionally launched with only one availability zone\. Environment\-agnostic AWS CDK stacks cannot be deployed to such regions\. At this writing, however, all AWS regions have at least two AZs\. You can change this behavior by overriding your stack's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) \(Python: `availability_zones`\) property to explicitly specify the zones you want to use\. From f68f51501a2ea8993e1360a29cfd0d2c84063277 Mon Sep 17 00:00:00 2001 From: gowthamchandu <77114064+gowthamchandu@users.noreply.github.com> Date: Thu, 18 Mar 2021 14:20:08 +0530 Subject: [PATCH 381/655] Update tagging.md It should be Tags instead of Tag, just a small correction :) --- doc_source/tagging.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 8119a2a3..5a6bf6cb 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -298,7 +298,7 @@ Tags.of(theBestStack).remove('StackType', { #### [ JavaScript ] ``` -const { App , Stack , Tag } = require('@aws-cdk/core'); +const { App , Stack , Tags } = require('@aws-cdk/core'); const app = new App(); const theBestStack = new Stack(app, 'MarketingSystem'); @@ -316,7 +316,7 @@ Tags.of(theBestStack).remove'StackType', { #### [ Python ] ``` -from aws_cdk.core import App, Stack, Tag +from aws_cdk.core import App, Stack, Tags app = App(); the_best_stack = Stack(app, 'MarketingSystem') @@ -334,7 +334,7 @@ Tags.of(the_best_stack).remove("StackType", ``` import software.amazon.awscdk.core.App; -import software.amazon.awscdk.core.Tag; +import software.amazon.awscdk.core.Tags; // Add a tag to all constructs in the stack Tags.of(theBestStack).add("StackType", "TheBest"); @@ -410,4 +410,4 @@ Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps { }); ``` ------- \ No newline at end of file +------ From 60f4db12c6bad376bfe476f89cc6dc092bfc11fc Mon Sep 17 00:00:00 2001 From: Leigh Simpson Date: Sun, 21 Mar 2021 11:03:25 +0000 Subject: [PATCH 382/655] Producer classes expects `produce` method (not `producer`) ### Why? The paragraph describing `Lazy` values (within `tokens.md`) describes producer objects as follows: > These methods accept an object whose `producer` property is a [...] ... but both the code samples and API Reference describe a property called `produce` (without the `r`). ### What? * change `producer` to `produce` within text description * fixup indentation for TS and JS code examples ### References * API reference for [class `Lazy`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-number-valueproducer). Each method takes a particular `I*Producer` interface: * [`IAnyProducer`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.IAnyProducer.html) * [`IListProducer`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.IListProducer.html) * [`INumberProducer`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.INumberProducer.html) * [`IStableAnyProducer`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.IStableAnyProducer.html) * [`IStableListProducer`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.IStableListProducer.html) * [`IStableNumberProducer`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.IStableNumberProducer.html) * [`IStableStringProducer`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.IStableStringProducer.html) * [`IStringProducer`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.IStringProducer.html) ... all of which describe a `produce` property ### Contributor Grant of License By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. --- doc_source/tokens.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/doc_source/tokens.md b/doc_source/tokens.md index 01342ede..cf307049 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -260,7 +260,7 @@ As with list tokens, you cannot modify the number value, as doing so is likely t In addition to representing deploy\-time values, such as AWS CloudFormation [parameters](parameters.md), Tokens are also commonly used to represent synthesis\-time lazy values\. These are values for which the final value will be determined before synthesis has completed, just not at the point where the value is constructed\. Use tokens to pass a literal string or number value to another construct, while the actual value at synthesis time may depend on some calculation that has yet to occur\. -You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.stringValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-string-valueproducer-options) \(Python: `Lazy.string_value`\) and [Lazy\.numberValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-number-valueproducer) \(Python: `Lazy.number_value`\. These methods accept an object whose `producer` property is a function that accepts a context argument and returns the final value when called\. +You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.stringValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-string-valueproducer-options) \(Python: `Lazy.string_value`\) and [Lazy\.numberValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-number-valueproducer) \(Python: `Lazy.number_value`\. These methods accept an object whose `produce` property is a function that accepts a context argument and returns the final value when called\. The following example creates an Auto Scaling group whose capacity is determined after its creation\. @@ -272,9 +272,9 @@ let actualValue: number; new AutoScalingGroup(this, 'Group', { desiredCapacity: Lazy.numberValue({ - produce(context) { - return actualValue; - } + produce(context) { + return actualValue; + } }) }); @@ -290,9 +290,9 @@ let actualValue; new AutoScalingGroup(this, 'Group', { desiredCapacity: Lazy.numberValue({ - produce(context) { - return (actualValue); - } + produce(context) { + return (actualValue); + } }) }); @@ -424,4 +424,4 @@ var stringVal = stack.ToJsonString(new Dictionary }); ``` ------- \ No newline at end of file +------ From 6495e5b6853c19feb3cc3bd40f8a2bb7928a951a Mon Sep 17 00:00:00 2001 From: Leigh Simpson Date: Sun, 21 Mar 2021 11:10:08 +0000 Subject: [PATCH 383/655] Reverted newline change at end of file ### Why? Diff clutter --- doc_source/tokens.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/tokens.md b/doc_source/tokens.md index cf307049..61f5a70a 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -424,4 +424,4 @@ var stringVal = stack.ToJsonString(new Dictionary }); ``` ------- +------ \ No newline at end of file From 5e464e1c9eeb84956e639a0495e97387588ba395 Mon Sep 17 00:00:00 2001 From: gardnerjh Date: Fri, 26 Mar 2021 10:09:25 -0400 Subject: [PATCH 384/655] Fix Python example in How to Create CDK Pipeline guide Correct from `add_application` to `add_application_stage` --- doc_source/cdk_pipeline.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 6efcb210..bc5098e6 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -1142,10 +1142,10 @@ testingStage.addApplication(new MyApplication2(this, 'MyApp2', { ``` # Add two application stages to the same pipeline stage -testing_stage.add_application(MyApplication1(this, 'MyApp1', +testing_stage.add_application_stage(MyApplication1(this, 'MyApp1', env=Environment(account="111111111111", region="eu-west-1"))) -testing_stage.add_application(MyApplication2(this, 'MyApp2', +testing_stage.add_application_stage(MyApplication2(this, 'MyApp2', env=Environment(account="111111111111", region="eu-west-1"))) ``` @@ -1772,4 +1772,4 @@ We're currently aware of the following issues with CDK Pipelines\. + If a changeset failed to apply, the pipeline is not retried\. The pipeline must be restarted manually from the top by clicking **Release Change**\. + A stack that failed to deploy must be deleted manually using the CloudFormation console before starting the pipeline again by clicking **Release Change**\. -Please [report any other issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. \ No newline at end of file +Please [report any other issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. From 3df076c03d7361a25fff7f9438d890de1a6ed47f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 26 Mar 2021 18:38:00 +0000 Subject: [PATCH 385/655] fix AddApplicationStage method name --- doc_source/cdk_pipeline.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index bc5098e6..521f249a 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -1114,11 +1114,11 @@ You can also add more than one application stage to a pipeline stage\. For examp ``` // Add two application stages to the same pipeline stage -testingStage.addApplication(new MyApplication1(this, 'MyApp1', { +testingStage.addApplicationStage(new MyApplication1(this, 'MyApp1', { env: { account: '111111111111', region: 'eu-west-1' } })); -testingStage.addApplication(new MyApplication2(this, 'MyApp2', { +testingStage.addApplicationStage(new MyApplication2(this, 'MyApp2', { env: { account: '111111111111', region: 'eu-west-1' } })); ``` @@ -1128,11 +1128,11 @@ testingStage.addApplication(new MyApplication2(this, 'MyApp2', { ``` // Add two application stages to the same pipeline stage -testingStage.addApplication(new MyApplication1(this, 'MyApp1', { +testingStage.addApplicationStage(new MyApplication1(this, 'MyApp1', { env: { account: '111111111111', region: 'eu-west-1' } })); -testingStage.addApplication(new MyApplication2(this, 'MyApp2', { +testingStage.addApplicationStage(new MyApplication2(this, 'MyApp2', { env: { account: '111111111111', region: 'eu-west-1' } })); ``` @@ -1154,14 +1154,14 @@ testing_stage.add_application_stage(MyApplication2(this, 'MyApp2', ``` // Add two application stages to the same pipeline stage -testingStage.addApplication(new MyApplication1(this, "MyApp1", new StageProps.Builder() +testingStage.addApplicationStage(new MyApplication1(this, "MyApp1", new StageProps.Builder() .env(new Environment.Builder() .account("111111111111") .region("eu-west-1") .build()) .build())); -testingStage.addApplication(new MyApplication2(this, "MyApp2", new StageProps.Builder() +testingStage.addApplicationStage(new MyApplication2(this, "MyApp2", new StageProps.Builder() .env(new Environment.Builder() .account("111111111111") .region("eu-west-1") @@ -1175,7 +1175,7 @@ testingStage.addApplication(new MyApplication2(this, "MyApp2", new StageProps.Bu ``` // Add two application stages to the same pipeline stage -testingStage.AddApplication(new MyApplication1(this, "MyApp1", new Amazon.CDK.StageProps +testingStage.AddApplicationStage(new MyApplication1(this, "MyApp1", new Amazon.CDK.StageProps { Env = new Amazon.CDK.Environment { @@ -1184,7 +1184,7 @@ testingStage.AddApplication(new MyApplication1(this, "MyApp1", new Amazon.CDK.St } })); -testingStage.AddApplication(new MyApplication2(this, "MyApp1", new Amazon.CDK.StageProps +testingStage.AddApplicationStage(new MyApplication2(this, "MyApp1", new Amazon.CDK.StageProps { Env = new Amazon.CDK.Environment { @@ -1772,4 +1772,4 @@ We're currently aware of the following issues with CDK Pipelines\. + If a changeset failed to apply, the pipeline is not retried\. The pipeline must be restarted manually from the top by clicking **Release Change**\. + A stack that failed to deploy must be deleted manually using the CloudFormation console before starting the pipeline again by clicking **Release Change**\. -Please [report any other issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. +Please [report any other issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. \ No newline at end of file From 6f43cc7186eb8c53adfa156a86e008dc6a59aa01 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 26 Mar 2021 18:39:31 +0000 Subject: [PATCH 386/655] add info on authentication and pdate version reporting --- doc_source/cli.md | 41 +++++++++++++++++++--------------- doc_source/getting_started.md | 3 +++ doc_source/hello_world.md | 4 +--- doc_source/tagging.md | 4 ++-- doc_source/testing.md | 2 +- doc_source/use_cfn_template.md | 2 +- 6 files changed, 31 insertions(+), 25 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 691a1006..5414e3b4 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -78,9 +78,12 @@ Issue `cdk version` to display the version of the AWS CDK Toolkit\. Provide this ## Version reporting -To gain insight into how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information\. +To gain insight into how the AWS CDK is used, the constructs used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used by AWS to identify stacks using a construct with known security or reliability issues, and to contact their users with important information\. -By default, the AWS CDK reports the name and version of the following NPM modules that are loaded at synthesis time: +**Note** +Prior to version 1\.93\.0, the AWS CDK reported the names and versions of the modules loaded during synthesis, rather than the constructs used in te stack\. + +By default, the AWS CDK reports the use of constructs in the following NPM modules that are used in the stack: + AWS CDK core module + AWS Construct Library modules + AWS Solutions Constructs module @@ -92,9 +95,11 @@ The `AWS::CDK::Metadata` resource looks something like the following\. CDKMetadata: Type: "AWS::CDK::Metadata" Properties: - Modules: "@aws-cdk/core=X.YY.Z,@aws-cdk/s3=X.YY.Z,@aws-solutions-constrccts/aws-apigateway-lambda=X.YY.Z,aws-rfdk=X.YY.Z" + Analytics: "v2:deflate64:H4sIAND9SGAAAzXKSw5AMBAA0L1b2PdzBYnEAdio3RglglY60zQi7u6TWL/XKmNUlxeQSOKwaPTBqrNhwEWU3hGHiCzK0dWWfAxoL/Fd8mvk+QkS/0X6BdjnCdgmOOQKWz+AqqLDt2Y3YMnLYWwAAAA=" ``` +The `Analytics` property is a gzipped, base64\-encoded, prefix\-encoded list of the constructs present in the stack\. + To opt out of version reporting, use one of the following methods: + Use the cdk command with the \-\-no\-version\-reporting argument to opt out for a single command\. @@ -144,8 +149,8 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials Besides specifying AWS credentials and a region under the `[default]` section, you can also put them in a `[profile NAME]` section, where *NAME* is the name of the profile\. You can add any number of named profiles, with or without a `[default]` section\. Be sure to add the same profile sections to both the configuration and credentials files\. -**Tip** -Don't name a profile `default`\. That's just confusing\. +**Note** +Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. Use the `--profile` flag to choose a set of credentials and default region from these configuration files for a given command\. @@ -289,7 +294,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -308,7 +313,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -316,7 +321,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -340,7 +345,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -362,7 +367,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -579,7 +584,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -592,7 +597,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -608,7 +613,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -677,7 +682,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -727,7 +732,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -746,7 +751,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -766,7 +771,7 @@ Options: with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -788,7 +793,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index e13c7e10..fae60135 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -143,6 +143,9 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY ``` +**Note** +Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. + Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. **Important** diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 3bdecc16..132ef072 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -356,9 +356,7 @@ Resources: Status: Enabled UpdateReplacePolicy: Retain DeletionPolicy: Retain - Metadata: - aws:cdk:path: HelloCdkStack/MyFirstBucket/Resource - CDKMetadata: ... + Metadata:... ``` Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for the bucket and see how the `versioned` property was translated\. diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 5a6bf6cb..d9dc3718 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. @@ -410,4 +410,4 @@ Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps { }); ``` ------- +------ \ No newline at end of file diff --git a/doc_source/testing.md b/doc_source/testing.md index 8e8bea72..5521ffd8 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -131,7 +131,7 @@ Object { ### Testing the test -To make sure the test works, change the construct so that it generates different AWS CloudFormation output, then build and test again\. For example, add a `period` property of 1 minute to override the default of 5 minutes\. The boldface line below shows the code that needs to be added to `index.ts`\. +To make sure the test works, change the construct so that it generates different AWS CloudFormation output, then build and test again\. For example, add a `period` property of 1 minute to override the default of 5 minutes\. ``` this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 45751a20..b451547a 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 234fd6617f9a495dfaaf31e8bc78ba711a02d369 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 8 Apr 2021 18:45:09 +0000 Subject: [PATCH 387/655] update help reference --- doc_source/cli.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 5414e3b4..c9589bc3 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -715,6 +715,9 @@ Options: --execute Whether to execute ChangeSet (--no-execute will NOT execute the ChangeSet) [boolean] [default: true] + --change-set-name Name of the CloudFormation change set to create + [string] + -f, --force Always deploy stack even if templates are identical [boolean] [default: false] @@ -782,7 +785,7 @@ Options: -l, --language The language to be used for the new project (default can be configured in ~/.cdk.json) - [string] [choices: "csharp", "fsharp", "java", "javascript", "python", + [string] [choices: "csharp", "fsharp", "go", "java", "javascript", "python", "typescript"] --list List the available templates [boolean] From 60c93c9e126935a3a25feb91b33aee7a042cee74 Mon Sep 17 00:00:00 2001 From: Alejandro Alcalde Date: Fri, 9 Apr 2021 21:00:07 +0200 Subject: [PATCH 388/655] Fix incorrect import for RemovalPolicy In the example showing how to specify a RemovalPolicy the incorrect import was being specified: ```java import software.amazon.awscdk.core.RemovalPolicy; ``` instead of ```java import software.amazon.awscdk.services.s3.BucketEncryption; ``` --- doc_source/hello_world.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 132ef072..821c6825 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -432,7 +432,7 @@ bucket = s3.Bucket(self, "MyFirstBucket", Update `src/main/java/com/myorg/HelloCdkStack.java`, adding the new import and updating the bucket definition in the appropriate places\. ``` -import software.amazon.awscdk.services.s3.BucketEncryption; +import software.amazon.awscdk.core.RemovalPolicy; ``` ``` @@ -585,4 +585,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? From 10ae74e094e3e2caf35d1e7f137217eeab92d782 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 22 Apr 2021 16:08:58 +0000 Subject: [PATCH 389/655] Add "Working with the CDK in Go" and other Go changes --- doc_source/cli.md | 26 +++---- doc_source/doc-history.md | 1 + doc_source/getting_started.md | 3 + doc_source/hello_world.md | 3 + doc_source/home.md | 2 +- doc_source/index.md | 1 + doc_source/reference.md | 3 +- doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-go.md | 121 +++++++++++++++++++++++++++++++++ doc_source/work-with.md | 8 ++- 11 files changed, 153 insertions(+), 19 deletions(-) create mode 100644 doc_source/work-with-cdk-go.md diff --git a/doc_source/cli.md b/doc_source/cli.md index c9589bc3..b5954af6 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -294,7 +294,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -313,7 +313,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -321,7 +321,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -345,7 +345,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -367,7 +367,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -584,7 +584,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -597,7 +597,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -613,7 +613,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -682,7 +682,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -735,7 +735,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -754,7 +754,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -774,7 +774,7 @@ Options: with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -796,7 +796,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index db7baffd..b5f0f320 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -7,6 +7,7 @@ The table below represents significant documentation milestones\. We fix errors | Change | Description | Date | | --- |--- |--- | +| [Go developer preview](#doc-history) | Add information about Go language support \(in developer preview\) including a "Working with the CDK in Go" topic\. | April 19, 2021 | | [Import or migrate AWS CloudFormation template](#doc-history) | Add description of the new `cloudformation-include.CfnInclude` class, a powerful way to import and migrate AWS CloudFormation templates, or to vend them as AWS CDK constructs\. | October 15, 2020 | | [Add construct tree section](#doc-history) | Information about the construct tree and its relation to the constructs you define in your AWS CDK app\. | October 5, 2020 | | [Add Bootstrapping topic](#doc-history) | A complete explanation of why and how to bootstrap AWS environments for the CDK, including a comprehensive discussion of how to customize the process\. | September 8, 2020 | diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index fae60135..ad82b009 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -18,6 +18,9 @@ The AWS CDK is designed around a handful of important concepts\. We will introdu An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, Python, Java, or C\# that uses the AWS CDK to define AWS infrastructure\. An app defines one or more [stacks](stacks.md)\. Stacks \(equivalent to AWS CloudFormation stacks\) contain [constructs](constructs.md), each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on\. +**Note** +The AWS CDK also supports Go in a developer preview\. This Guide does not include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. + Constructs \(as well as stacks and apps\) are represented as types in your programming language of choice\. You instantiate constructs within a stack to declare them to AWS, and connect them to each other using well\-defined interfaces\. The AWS CDK includes the AWS CDK Toolkit \(also called the CLI\), a command\-line tool for working with your AWS CDK apps and stacks\. Among other functions, the Toolkit provides the ability to convert one or more AWS CDK stacks to AWS CloudFormation templates and related assets \(a process called *synthesis*\) and to deploy your stacks to an AWS account\. diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 132ef072..718cd4f1 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -2,6 +2,9 @@ You've read [Getting started with the AWS CDK](getting_started.md) and set up your development environment for writing AWS CDK apps? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. +**Note** +The AWS CDK supports Go in a developer preview\. This tutorial does not include instructions or code examples for Go\. + In this tutorial, you'll learn about the structure of a AWS CDK project, how to use the AWS Construct Library to define AWS resources using code, and how to synthesize, diff, and deploy collections of resources using the AWS CDK Toolkit command\-line tool\. The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps\. diff --git a/doc_source/home.md b/doc_source/home.md index 37161469..a6f0dfaa 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -8,7 +8,7 @@ AWS CloudFormation enables you to: + Build highly reliable, highly scalable, cost\-effective applications in the cloud without worrying about creating and configuring the underlying AWS infrastructure\. + Use a template file to create and delete a collection of resources together as a single unit \(a stack\)\. -Use the AWS CDK to define your cloud resources in a familiar programming language\. The AWS CDK supports TypeScript, JavaScript, Python, Java, and C\#/\.Net\. +Use the AWS CDK to define your cloud resources in a familiar programming language\. The AWS CDK supports TypeScript, JavaScript, Python, Java, C\#/\.Net, and \(in developer preview\) Go\. Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. diff --git a/doc_source/index.md b/doc_source/index.md index 29b3f553..079a017c 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -23,6 +23,7 @@ Amazon's trademarks and trade dress may not be used in + [Working with the AWS CDK in Python](work-with-cdk-python.md) + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Working with the AWS CDK in C#](work-with-cdk-csharp.md) + + [Working with the AWS CDK in Go](work-with-cdk-go.md) + [Translating TypeScript AWS CDK code to other languages](multiple_languages.md) + [Concepts](core_concepts.md) + [Constructs](constructs.md) diff --git a/doc_source/reference.md b/doc_source/reference.md index 54284567..15221912 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -65,4 +65,5 @@ From time to time, we may add support to the AWS CDK for additional programming | JavaScript | Stable | | Python | Stable | | Java | Stable | -| C\#/\.NET | Stable | \ No newline at end of file +| C\#/\.NET | Stable | +| Go | Experimental | \ No newline at end of file diff --git a/doc_source/tagging.md b/doc_source/tagging.md index d9dc3718..4989acbf 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index b451547a..4f3abf6a 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/doc_source/work-with-cdk-go.md b/doc_source/work-with-cdk-go.md new file mode 100644 index 00000000..6b8dc672 --- /dev/null +++ b/doc_source/work-with-cdk-go.md @@ -0,0 +1,121 @@ +# Working with the AWS CDK in Go + +The Go language binding for the AWS CDK is now available as a Developer Preview\. It is not suitable for production use and may undergo significant changes before being designated stable\. To follow development, see the [Project Board](https://github.com/aws/jsii/projects/3) on GitHub\. Please [report any issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. + +Unlike the other languages the CDK supports, Go is not a traditional object\-oriented programming language\. Go uses composition where other languages often leverage inheritance\. We have tried to employ idiomatic Go approaches as much as possible, but there are places where the CDK charts its own path\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +The Go bindings for the AWS CDK use the standard [Go toolchain](https://golang.org/dl/), v1\.16 or later\. You can use the editor of your choice\. + +## Creating a project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language go +``` + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +The resulting project includes a reference to the AWS CDK Go module, `github.com/aws/aws-cdk-go/awscdk`, in `go.mod`\. The CDK and its dependencies are automatically installed when you build your app\. + +## Managing AWS Construct Library modules + +In most AWS CDK documentation and examples, the word "module" is used primarily to refer to AWS Construct Library modules, one or more per AWS service, which differs from idiomatic Go usage of the term\. The CDK Construct Library is provided in one Go module with the individual Construct Library modules, which support the various AWS services, provided as Go packages within that module\. + +Some services' AWS Construct Library support is in more than one Construct Library module \(Go package\)\. For example, Amazon Route 53 has three Construct Library modules in addition to the main `awsroute53` package, named `awsroute53patterns`, `awsroute53resolver`, and `awsroute53targets`\. + +The AWS CDK's core package, which you'll need in most AWS CDK apps, is imported in Go code as `github.com/aws/aws-cdk-go/awscdk`\. Packages for the various services in the AWS Construct Library live under `github.com/aws/aws-cdk-go/awscdk`\. For example, the Amazon S3 module's namespace is `github.com/aws/aws-cdk-go/awscdk/awss3`\. + +``` +import ( + "github.com/aws/aws-cdk-go/awscdk/awss3" + // ... +) +``` + +Once you have imported the Construct Library modules \(Go packages\) for the services you want to use in your app, you access constructs in that module using, for example, `awss3.Bucket`\. + +## AWS CDK idioms in Go + +### Field and method names + +Field and method names use camel casing \(`likeThis`\) in TypeScript, the CDK's language of origin\. In Go, these follow Go conventions, so are Pascal\-cased \(`LikeThis`\)\. + +### Missing values and pointer conversion + +In Go, missing values in AWS CDK objects such as property bundles are represented by `nil`\. Go doesn't have nullable types; the only type that can contain `nil` is a pointer\. To allow values to be optional, then, all CDK properties, arguments, and return values are pointers, even for primitive types\. This applies to required values as well as optional ones, so if a required value later becomes optional, no breaking change in type is needed\. + +When passing literal values or expressions, you can use the following helper functions to create pointers to the values\. ++ `jsii.String` ++ `jsii.Number` ++ `jsii.Bool` ++ `jsii.Time` + +For consistency, we recommend that you use pointers similarly when defining your own constructs, even though it may seem more convenient to, for example, receive your construct's `id` as a string rather than a pointer to a string\. + +When dealing with optional AWS CDK values, including primitive values as well as complex types, you should explicitly test pointers to make sure they are not `nil` before doing anything with it\. Go does not have "syntactic sugar" to help handle empty or missing values as some other languages do\. However, required values in property bundles and similar structures are guaranteed to exist \(construction fails otherwise\), so these values need not be `nil`\-checked\. + +### Constructs and Props + +Constructs, which represent one or more AWS resources and their associated attributes, are represented in Go as interfaces\. For example, `awss3.Bucket` is an interface\. Every construct has a factory function, such as `awss3.NewBucket`, to return a struct that implements the corresponding interface\. + +All factory functions take three arguments: the `scope` in which the construct is being defined \(its parent in the construct tree\), an `id`, and `props`, a bundle of key/value pairs that the construct uses to configure the resources it creates\. The "bundle of attributes" pattern is also used elsewhere in the AWS CDK\. + +In Go, props are represented by a specific struct type for each construct\. For example, an `awss3.Bucket` takes a props argument of type `awss3.BucketProps`\. Use a struct literal to write props arguments\. + +``` +var bucket = awss3.NewBucket(stack, jsii.String("MyBucket"), &awss3.BucketProps{ + Versioned: jsii.Bool(true), +}) +``` + +### Generic structures + +In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Go, these objects are represented as slices and an empty interface, respectively\. + +The CDK provides variadic helper functions such as `jsii.Strings` for building slices containing primitive types\. + +``` +jsii.Strings("One", "Two", "Three") +``` + +### Developing custom constructs + +In Go, it is usually more straightforward to write a new construct than to extend an existing one\. First, define a new struct type, anonymously embedding one or more existing types if extension\-like semantics are desired\. Write methods for any new functionality you're adding and the fields necessary to hold the data they need\. Define a props interface if your construct needs one\. Finally, write a factory function `NewMyConstruct()` to return an instance of your construct\. + +If you are simply changing some default values on an existing construct or adding a simple behavior at instantiation, you don't need all that plumbing\. Instead, write a factory function that calls the factory function of the construct you're "extending\." In other CDK languages, for example, you might create a `TypedBucket` construct that enforces the type of objects in an Amazon S3 bucket by overriding the `s3.Bucket` type and, in your new type's initializer, adding a bucket policy that allows only specified filename extensions to be added to the bucket\. In Go, it is easier to simply write a `NewTypedBucket` that returns an `s3.Bucket` \(instantiated using `s3.NewBucket`\) to which you have added an appropriate bucket policy\. No new construct type is necessary because the functionality is already available in the standard bucket construct; the new "construct" just provides a simpler way to configure it\. + +## Building, synthesizing, and deploying + +The AWS CDK automatically compiles your app before running it\. However, it can be useful to build your app manually to check for errors and to run tests\. You can do this in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn compile` at a command prompt while in your project's root directory\. + +Run any tests you've written by running `mvn test` at a command prompt\. + +The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. + +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. + +``` +cdk synth "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. +``` + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file diff --git a/doc_source/work-with.md b/doc_source/work-with.md index 8e9e7507..c09a0abd 100644 --- a/doc_source/work-with.md +++ b/doc_source/work-with.md @@ -1,6 +1,9 @@ # Working with the AWS CDK -The AWS Cloud Development Kit \(AWS CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, and C\#\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. +The AWS Cloud Development Kit \(AWS CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and \(in developer preview\) Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. + +**Note** +This Guide does not include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. We develop the AWS CDK in TypeScript and use [JSII](https://github.com/aws/jsii) to provide a "native" experience in other supported languages\. For example, we distribute AWS Construct Library modules using your preferred language's standard repository, and you install them using the language's standard package manager\. Methods and properties are even named using your language's recommended naming patterns\. @@ -34,4 +37,5 @@ The specific language you work in also has its own prerequisites, described in t + [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) + [Working with the AWS CDK in Python](work-with-cdk-python.md) + [Working with the AWS CDK in Java](work-with-cdk-java.md) -+ [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) \ No newline at end of file ++ [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) ++ [Working with the AWS CDK in Go](work-with-cdk-go.md) \ No newline at end of file From 0986b3d8cb791302f76a5aff66d00f5d65666488 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 22 Apr 2021 17:59:32 +0000 Subject: [PATCH 390/655] clarify and update credentials --- doc_source/cli.md | 54 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 14 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index b5954af6..7718b991 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -117,22 +117,31 @@ To opt out of version reporting, use one of the following methods: } ``` -## Specifying the environment +## Specifying credentials and region - In AWS CDK terms, the [environment](environments.md) consists of a region and AWS credentials valid in that region\. The CDK Toolkit needs credentials in order to query your AWS account and to deploy CloudFormation templates\. +The CDK Toolkit needs to know your AWS credentials and the AWS region into which you are deploying, not only for deployment operations but also to retrieve context values during synthesis\. Together, your account and region make up the *environment*\. **Important** -We strongly recommend against using your AWS root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. +We strongly recommend against using your main AWS account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. -If you have the AWS CLI installed, the easiest way to satisfy this requirement is to install the AWS CLI and issue the following command: +Credentials and region may be specified using environment variables or configuration files\. These are the same variables and files used by other AWS tools such as the AWS CLI and the various AWS SDKs\. The CDK Toolkit looks for this information in the following order\. ++ The account and region specified on the stack in your AWS CDK app using its `env` property\. This also causes the stack to be synthesized as environment\-specific; see [Environments](environments.md) for further details\. ++ The `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` environment variables\. Alawys specify all three variables, not just one or two\. ++ A specific profile defined in the standard AWS `config` and `credentials` files, and specified using the `--profile` option on `cli` commands\. ++ The `[default]` section of the standard AWS `config` and `credentials` files, if the environment variables are not set and no profile is specified\. + +**Note** +The standard AWS `config` and `credentials` files are located at `~/.aws/config` and `~/.aws/credentials` \(macOS/Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\)\. + +If you have the AWS CLI installed, the easiest way to configure your account credentials and a default region is to issue the following command: ``` aws configure ``` -Provide your AWS access key ID, secret access key, and default region when prompted\. +Provide your AWS access key ID, secret access key, and default region when prompted\. These values are written to the `[default]` section of the `config` and `credentials` files\. -You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(macOS/Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. +If you don't have the AWS CLI installed, you can manually create or edit the `config` and `credentials` files to contain default credentials and a default region, in the following format\. + In `~/.aws/config` or `%USERPROFILE%\.aws\config` ``` @@ -147,18 +156,35 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY ``` -Besides specifying AWS credentials and a region under the `[default]` section, you can also put them in a `[profile NAME]` section, where *NAME* is the name of the profile\. You can add any number of named profiles, with or without a `[default]` section\. Be sure to add the same profile sections to both the configuration and credentials files\. +Besides specifying AWS credentials and a region in the `[default]` section, you can also add one or more `[profile NAME]` sections, where *NAME* is the name of the profile\. ++ In `~/.aws/config` or `%USERPROFILE%\.aws\config` -**Note** -Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. + ``` + [profile test] + region=us-east-1 + + [profile prod] + region=us-east-1 + ``` ++ In `~/.aws/credentials` or `%USERPROFILE%\.aws\credentials` -Use the `--profile` flag to choose a set of credentials and default region from these configuration files for a given command\. + ``` + [profile test] + aws_access_key_id=AKIAI44QH8DHBEXAMPLE + aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY + + [profile test] + aws_access_key_id=AKIAI44QH8DHBEXAMPLE + aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY + ``` -``` -cdk deploy --profile test PipelineStack -``` +Always add named profiles to both the `config` and `credentials` files\. The AWS CDK Toolkit does not fall back to using the region in the `[default]` section when the specified named profile is not found in the `config` file, as some other AWS tools do\. + +**Important** +Do not name a profile `default`: that is, do not use a `[profile default]` section in either `config` or `credentials`\. -Instead of using the configuration files, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. +**Note** +Although the AWS CDK uses credentials from the same sources files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. You may optionally use the `--role-arn` \(or `-r`\) option to specify the ARN of an IAM role that should be used for deployment\. This role must be assumable by the AWS account being used\. From 9f325f62c85d55175e9214d999d57d3b3700fbee Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 22 Apr 2021 18:11:32 +0000 Subject: [PATCH 391/655] tweaks --- doc_source/cli.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 7718b991..eb3e3e5e 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -124,11 +124,11 @@ The CDK Toolkit needs to know your AWS credentials and the AWS region into which **Important** We strongly recommend against using your main AWS account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. -Credentials and region may be specified using environment variables or configuration files\. These are the same variables and files used by other AWS tools such as the AWS CLI and the various AWS SDKs\. The CDK Toolkit looks for this information in the following order\. +Credentials and region may be specified directly in your AWS CDK app, using environment variables, or in configuration files\. These are the same variables and files used by other AWS tools such as the AWS CLI and the various AWS SDKs\. The CDK Toolkit looks for this information in the following order\. + The account and region specified on the stack in your AWS CDK app using its `env` property\. This also causes the stack to be synthesized as environment\-specific; see [Environments](environments.md) for further details\. + The `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` environment variables\. Alawys specify all three variables, not just one or two\. + A specific profile defined in the standard AWS `config` and `credentials` files, and specified using the `--profile` option on `cli` commands\. -+ The `[default]` section of the standard AWS `config` and `credentials` files, if the environment variables are not set and no profile is specified\. ++ The `[default]` section of the standard AWS `config` and `credentials` files\. **Note** The standard AWS `config` and `credentials` files are located at `~/.aws/config` and `~/.aws/credentials` \(macOS/Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\)\. From e84d742a963eb74bbbfa4d0e2d7074db3647b011 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 23 Apr 2021 03:51:57 +0000 Subject: [PATCH 392/655] correct info about env property --- doc_source/cli.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index eb3e3e5e..c254f5a4 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -124,10 +124,9 @@ The CDK Toolkit needs to know your AWS credentials and the AWS region into which **Important** We strongly recommend against using your main AWS account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. -Credentials and region may be specified directly in your AWS CDK app, using environment variables, or in configuration files\. These are the same variables and files used by other AWS tools such as the AWS CLI and the various AWS SDKs\. The CDK Toolkit looks for this information in the following order\. -+ The account and region specified on the stack in your AWS CDK app using its `env` property\. This also causes the stack to be synthesized as environment\-specific; see [Environments](environments.md) for further details\. +Credentials and region may be specified using environment variables or in configuration files\. These are the same variables and files used by other AWS tools such as the AWS CLI and the various AWS SDKs\. The CDK Toolkit looks for this information in the following order\. + The `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` environment variables\. Alawys specify all three variables, not just one or two\. -+ A specific profile defined in the standard AWS `config` and `credentials` files, and specified using the `--profile` option on `cli` commands\. ++ A specific profile defined in the standard AWS `config` and `credentials` files, and specified using the `--profile` option on `cdk` commands\. + The `[default]` section of the standard AWS `config` and `credentials` files\. **Note** @@ -164,7 +163,7 @@ Besides specifying AWS credentials and a region in the `[default]` section, you region=us-east-1 [profile prod] - region=us-east-1 + region=us-west-1 ``` + In `~/.aws/credentials` or `%USERPROFILE%\.aws\credentials` @@ -188,6 +187,8 @@ Although the AWS CDK uses credentials from the same sources files as other AWS t You may optionally use the `--role-arn` \(or `-r`\) option to specify the ARN of an IAM role that should be used for deployment\. This role must be assumable by the AWS account being used\. +The environment specified in your AWS CDK app using the stack's `env` property is used during synthesis to generate an environment\-specific AWS CloudFormation template\. It does not affect deployment\. For more information, see [Environments](environments.md)\. + ## Specifying the app command Many features of the CDK Toolkit require one or more AWS CloudFormation templates be synthesized, which in turn requires running your application\. Since the AWS CDK supports programs written in a variety of languages, it uses a configuration option to specify the exact command necessary to run your app\. This option can be specified in two ways\. From 203e5db8ea2a68d492fa96108243c59f1d51ac5b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 26 Apr 2021 22:24:50 +0000 Subject: [PATCH 393/655] update to how env works --- doc_source/cli.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index c254f5a4..e2d6576c 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -81,7 +81,7 @@ Issue `cdk version` to display the version of the AWS CDK Toolkit\. Provide this To gain insight into how the AWS CDK is used, the constructs used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used by AWS to identify stacks using a construct with known security or reliability issues, and to contact their users with important information\. **Note** -Prior to version 1\.93\.0, the AWS CDK reported the names and versions of the modules loaded during synthesis, rather than the constructs used in te stack\. +Prior to version 1\.93\.0, the AWS CDK reported the names and versions of the modules loaded during synthesis, rather than the constructs used in the stack\. By default, the AWS CDK reports the use of constructs in the following NPM modules that are used in the stack: + AWS CDK core module @@ -119,7 +119,7 @@ To opt out of version reporting, use one of the following methods: ## Specifying credentials and region -The CDK Toolkit needs to know your AWS credentials and the AWS region into which you are deploying, not only for deployment operations but also to retrieve context values during synthesis\. Together, your account and region make up the *environment*\. +The CDK Toolkit needs to know your AWS account credentials and the AWS region into which you are deploying, not only for deployment operations but also to retrieve context values during synthesis\. Together, your account and region make up the *environment*\. **Important** We strongly recommend against using your main AWS account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. @@ -132,6 +132,8 @@ Credentials and region may be specified using environment variables or in config **Note** The standard AWS `config` and `credentials` files are located at `~/.aws/config` and `~/.aws/credentials` \(macOS/Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\)\. +The environment specified in your AWS CDK app using the stack's `env` property is used during synthesis to generate an environment\-specific AWS CloudFormation template and during deployment to override the account or region specified by one of the above methods\. For more information, see [Environments](environments.md)\. + If you have the AWS CLI installed, the easiest way to configure your account credentials and a default region is to issue the following command: ``` @@ -187,8 +189,6 @@ Although the AWS CDK uses credentials from the same sources files as other AWS t You may optionally use the `--role-arn` \(or `-r`\) option to specify the ARN of an IAM role that should be used for deployment\. This role must be assumable by the AWS account being used\. -The environment specified in your AWS CDK app using the stack's `env` property is used during synthesis to generate an environment\-specific AWS CloudFormation template\. It does not affect deployment\. For more information, see [Environments](environments.md)\. - ## Specifying the app command Many features of the CDK Toolkit require one or more AWS CloudFormation templates be synthesized, which in turn requires running your application\. Since the AWS CDK supports programs written in a variety of languages, it uses a configuration option to specify the exact command necessary to run your app\. This option can be specified in two ways\. From 925ac8b19c03895c097852b448b16aa2534f0345 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 27 Apr 2021 16:50:01 +0000 Subject: [PATCH 394/655] correct build/test instructions --- doc_source/work-with-cdk-go.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/work-with-cdk-go.md b/doc_source/work-with-cdk-go.md index 6b8dc672..ad25e41a 100644 --- a/doc_source/work-with-cdk-go.md +++ b/doc_source/work-with-cdk-go.md @@ -93,9 +93,9 @@ If you are simply changing some default values on an existing construct or addin ## Building, synthesizing, and deploying -The AWS CDK automatically compiles your app before running it\. However, it can be useful to build your app manually to check for errors and to run tests\. You can do this in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn compile` at a command prompt while in your project's root directory\. +The AWS CDK automatically compiles your app before running it\. However, it can be useful to build your app manually to check for errors and to run tests\. You can do this by issuing `go build` at a command prompt while in your project's root directory\. -Run any tests you've written by running `mvn test` at a command prompt\. +Run any tests you've written by running `go test` at a command prompt\. The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. From cd10db35c3f6d42919f686ed7dd0445b608633c5 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 3 May 2021 17:18:43 +0000 Subject: [PATCH 395/655] add CDK v2 migration topic --- doc_source/work-with-cdk-v2.md | 239 +++++++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 doc_source/work-with-cdk-v2.md diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md new file mode 100644 index 00000000..ab149d66 --- /dev/null +++ b/doc_source/work-with-cdk-v2.md @@ -0,0 +1,239 @@ +# Migrating to AWS CDK v2 + +Version 2 of the AWS Cloud Development Kit \(AWS CDK\) is designed to make writing infrastructure as code in your preferred programming language even easier\. + +As a developer preview, CDK v2 is not intended for production use and may be subject to breaking API changes before it is finalized\. We are eager to hear your feedback on how CDK v2 works for you, and your suggestions for making it better, via [GitHub Issues](https://github.com/aws/aws-cdk/issues/new/choose)\. + +## Changes in AWS CDK v2 + +The main changes in CDK v2 are: ++ AWS CDK v2 consolidates the AWS Construct Library into a single package; developers no longer need to install one or more individual packages for each AWS service\. This change also eliminates the requirement to keep all CDK library versions in sync\. ++ Experimental L2/L3 constructs are no longer included in the AWS Construct Library; they will instead be distributed separately with an appropriate semantic version number\. Constructs will move into the main AWS Construct Library only after being designated stable, permitting the Construct Library to adhere to strict semantic versioning going forward\. We are still finalizing the details of how experimental constructs will be distributed for CDK v2, so initially, CDK v2 does not provide experimental constructs\. ++ The core `Construct` class has been extracted from the AWS CDK into a separate library, along with related types, to support efforts to apply the CDK programming model to other domains\. If you are writing your own constructs or using related APIs, you must declare the `construct` module as a dependency and make minor changes to your imports\. If you are using advanced features, such as hooking into the CDK app lifecycle, more changes are needed\. [See the RFC](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0192-remove-constructs-compat.md#release-notes) for full details\. ++ Deprecated properties, methods, and types in AWS CDK v1\.x and its Construct Library have been removed from the CDK v2 API\. In most supported languages, these APIs produce warnings under v1\.x, so you may have already migrated to the replacement APIs\. A complete [list of deprecated APIs](https://github.com/aws/aws-cdk/blob/master/DEPRECATED_APIs.md) in CDK v1\.x is available on GitHub\. ++ Behavior that was gated by feature flags in AWS CDK v1\.x is enabled by default in CDK v2, and the old feature flags are no longer needed or, in most cases, supported\. ++ CDK v2 requires that the environments you deploy into be boostrapped using the modern bootstrap stack; the legacy stack is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. Simply re\-bootstrap the affected environments to upgrade them\. It is not necessary to set any feature flags or environment variables to specify the modern bootstrap stack\. + +Aside from this topic, the AWS CDK Developer Guide describes CDK v1\.x\. Most of the information in the Guide still applies in CDK v2, or can be adapted with only minor changes\. A v2 Developer Guide will be available at General Availability \(GA\) of CDK v2\. A version of the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) is available for CDK v2\. + +## Prerequisites + +Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prerequisites](getting_started.md#getting_started_prerequisites)\. Additional requirements are listed here\. ++ For TypeScript developers, TypeScript 3\.8 or later is required\. ++ A new version of the CDK Toolkit is required for use with CDK v2\. To install it, issue `npm install -g aws-cdk@next`\. + +## Migrating to AWS CDK v2 + +To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. + +### Updating `cdk.json` + +Remove all feature flags from `cdk.json`\. You can add one or more of the three flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these are needed\. + +`@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId` +If your application uses multiple Amazon API Gateway API keys and associates them to usage plans + +`@aws-cdk/aws-rds:lowercaseDbIdentifier` +If your application uses Amazon RDS database instance or database clusters, and explicitly specifies the identifier for these + +`@aws-cdk/core:stackRelativeExports` +If your application uses multiple stacks and you refer to resources from one stack in another, this determines whether absolute or relative path is used to construct AWS CloudFormation exports + +The syntax for reverting these flags in `cdk.json` is shown here\. + +``` +{ + "context": { + "@aws-cdk/aws-rds:lowercaseDbIdentifier": false, + "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": false, + "@aws-cdk/core:stackRelativeExports": false, + } +} +``` + +### Updating dependencies and imports + +Update your app's dependencies in the appropriate configuration file, then install the new dependencies\. Finally, update the imports in your code\. + +------ +#### [ TypeScript ] + +For AWS CDK applications, update `package.json` as follows\. Note that `@aws-cdk/assert` must be updated to the same version as `aws-cdk-lib`\. + +``` +{ + "dependencies": { + "aws-cdk-lib": "^2.0.0-rc.1", + "@aws-cdk/assert": "^2.0.0-rc.1", + "constructs": "^10.0.0" + } +} +``` + +For construct libraries, establish the lowest version of `aws-cdk-lib` you require for your application \(2\.0\.0\-rc\.1 here\) and update `package.json` as follows\. Note that `aws-cdk-lib` appears both as a peer dependency and a dev dependency\. + +``` +{ + "peerDependencies": { + "aws-cdk-lib": "^2.0.0-rc.1", + "constructs": "^10.0.0" + }, + "devDependencies": { + "aws-cdk-lib": "2.0.0-rc.1", + "@aws-cdk/assert": "^2.0.0-rc.1", + "constructs": "^10.0.0", + "typescript": "~3.9.0" + } +} +``` + +Install the new dependencies by running `npm install` or `yarn install`\. + +Change your app's imports to import `Construct` from the new `constructs` module, core types such as `App` and `Stack` from the top level of `aws-cdk-lib`, and AWS Construct Library modules from namespaces under `aws-cdk-lib`\. + +``` +import { Construct } from 'constructs'; +import { App, Stack } from 'aws-cdk-lib'; +import { aws_s3 as s3 } from 'aws-cdk-lib'; +``` + +------ +#### [ JavaScript ] + +Update `package.json` as follows\. Note that `@aws-cdk/assert` must be updated to the same version as `aws-cdk-lib`\. + +``` +{ + "dependencies": { + "aws-cdk-lib": "^2.0.0-rc.1", + "@aws-cdk/assert": "^2.0.0-rc.1", + "constructs": "^10.0.0" + } +} +``` + +Install the new dependencies by running `npm install` or `yarn install`\. + +Change your app's imports to import `Construct` from the new `constructs` module, core types such as `App` and `Stack` from the top level of `aws-cdk-lib`, and AWS Construct Library modules from namespaces under `aws-cdk-lib`\. + +``` +const { Construct } = require('constructs'); +const { App, Stack } = require('aws-cdk-lib'); +const s3 = require('aws-cdk-lib').aws_s3; +``` + +------ +#### [ Python ] + +Update the `install_requires` definition in `setup.py` to look like this\. + +``` +install_requires=[ + "aws-cdk-lib>=2.0.0rc1", + "constructs>=10.0.0", + # ... +] +``` + +Install the new dependencies with `pip install -r requirements.txt`\. + +**Tip** +Uninstall any other versions of AWS CDK modules already installed in your app's virtual environment using `pip uninstall`\. + +Change your app's imports to import `Construct` from the new `constructs` module, core types such as `App` and `Stack` from the top level of `aws_cdk`, and AWS Construct Library modules from namespaces under `aws_cdk`\. + +``` +from constructs import Construct +from aws_cdk import App, Stack +from aws_cdk import aws_s3 as s3 + +# ... + +class MyConstruct(Construct): + # ... + +class MyStack(Stack): + # ... + +s3.Bucket(...) +``` + +Alternatively, you can import `constructs` and `aws_cdk`, then refer to classes through their namespace\. + +``` +import constructs +import aws_cdk as cdk +from aws_cdk import aws_s3 as s3 + +# ... + +class MyConstruct(constructs.Construct): + # ... + +class MyStack(cdk.Stack): + # ... + +s3.Bucket(...) +``` + +------ +#### [ Java ] + +In `pom.xml`, remove all `software.amazon.awscdk` dependencies and replace them with these dependencies on `software.constructs` and `software.amazon.awscdk`\. + +``` + + software.amazon.awscdk + aws-cdk-lib + 2.0.0-rc.1 + + + software.constructs + constructs + 10.0.0 + +``` + +Install the new dependencies by running `mvn package`\. + +Change your code to import `Construct` from the new `software.constructs` library, core classes like `Stack` and `App` from `software.amazon.awscdk`, and service constructs from `software.amazon.awscdk.services`\. + +``` +import software.constructs.Construct; +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.App; +import software.amazon.awscdk.services.s3.Bucket; +``` + +------ +#### [ C\# ] + +The most straightforward way to upgrade the dependencies of a C\# CDK application is to edit the `.csproj` file manually\. Remove all `Amazon.CDK.*` package references and replace them with references to the `Amazon.CDK.Lib` and `Constructs` packages\. + +``` + + +``` + +Install the new dependencies by running `dotnet restore`\. + +Change the imports in your source files as follows\. + +``` +using Constructs; // for Construct class +using Amazon.CDK; // for core classes like App and Stack +using Amazon.CDK.AWS.S3; // for service constructs like Bucket +``` + +------ + +## Troubleshooting + +**Unexpected infrastructure changes** +Before deploying your app, use `cdk diff` to check for unexpected changes to its resources\. Such changes are typically not caused by upgrading to AWS CDK v2, but are the result of deprecated behavior that was previously hidden by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd have the same problem upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, revising your code as necessary, deploying, and then upgrading to v2\. + +If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. + +**Typescript `'from' expected` or `';' expected` error in imports** +Upgrade to TypeScript 3\.8 or later\. \ No newline at end of file From f883df5a3bf0b7e21fd33ce4c551197b4d9eb422 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 3 May 2021 17:20:09 +0000 Subject: [PATCH 396/655] add link to CDK v2 topic --- doc_source/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc_source/index.md b/doc_source/index.md index 079a017c..fa14b210 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -24,6 +24,7 @@ Amazon's trademarks and trade dress may not be used in + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Working with the AWS CDK in C#](work-with-cdk-csharp.md) + [Working with the AWS CDK in Go](work-with-cdk-go.md) ++ [Migrating to AWS CDK v2](work-with-cdk-v2.md) + [Translating TypeScript AWS CDK code to other languages](multiple_languages.md) + [Concepts](core_concepts.md) + [Constructs](constructs.md) From 92d9d652d09bebc1e9a4b4940be82e01115f1c21 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 3 May 2021 17:20:26 +0000 Subject: [PATCH 397/655] churn of auto-generated anchor IDs --- doc_source/cli.md | 26 +++++++++++++------------- doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index e2d6576c..1c651b0d 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -321,7 +321,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -340,7 +340,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -348,7 +348,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -372,7 +372,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -394,7 +394,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -611,7 +611,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -624,7 +624,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -640,7 +640,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -709,7 +709,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -762,7 +762,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -781,7 +781,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -801,7 +801,7 @@ Options: with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -823,7 +823,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 4989acbf..f69a0690 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 4f3abf6a..f2490ea8 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From d0906ec7d8bbcde1b852e300dff6641be15ad0cf Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 6 May 2021 02:26:13 +0000 Subject: [PATCH 398/655] update build image and specify main branch --- doc_source/codepipeline_example.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index c8bec92a..e7a09cfb 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -490,7 +490,7 @@ export class PipelineStack extends Stack { }, }), environment: { - buildImage: codebuild.LinuxBuildImage.STANDARD_2_0, + buildImage: codebuild.LinuxBuildImage.STANDARD_5_0, }, }); const lambdaBuild = new codebuild.PipelineProject(this, 'LambdaBuild', { @@ -530,6 +530,7 @@ export class PipelineStack extends Stack { actions: [ new codepipeline_actions.CodeCommitSourceAction({ actionName: 'CodeCommit_Source', + branch: 'main', repository: code, output: sourceOutput, }), @@ -640,7 +641,7 @@ class PipelineStack extends Stack { } }), environment: { - buildImage: codebuild.LinuxBuildImage.STANDARD_2_0 + buildImage: codebuild.LinuxBuildImage.STANDARD_5_0 } }); @@ -654,6 +655,7 @@ class PipelineStack extends Stack { actions: [ new codepipeline_actions.CodeCommitSourceAction({ actionName: 'CodeCommit_Source', + branch: 'main', repository: code, output: sourceOutput }) @@ -757,7 +759,7 @@ class PipelineStack(core.Stack): "index.js", "node_modules/**/*"]}, environment=dict(buildImage= - codebuild.LinuxBuildImage.STANDARD_2_0)))) + codebuild.LinuxBuildImage.STANDARD_5_0)))) source_output = codepipeline.Artifact() cdk_build_output = codepipeline.Artifact("CdkBuildOutput") @@ -771,6 +773,7 @@ class PipelineStack(core.Stack): actions=[ codepipeline_actions.CodeCommitSourceAction( action_name="CodeCommit_Source", + branch="main", repository=code, output=source_output)]), codepipeline.StageProps(stage_name="Build", @@ -856,7 +859,7 @@ public class PipelineStack extends Stack { }}); }})) .environment(BuildEnvironment.builder().buildImage( - LinuxBuildImage.STANDARD_2_0).build()) + LinuxBuildImage.STANDARD_5_0).build()) .build(); PipelineProject lambdaBuild = PipelineProject.Builder.create(this, "LambdaBuild") @@ -891,6 +894,7 @@ public class PipelineStack extends Stack { .actions(Arrays.asList( CodeCommitSourceAction.Builder.create() .actionName("Source") + .branch('main') .repository(code) .output(sourceOutput) .build())) @@ -983,7 +987,7 @@ namespace Pipeline }), Environment = new BuildEnvironment { - BuildImage = WindowsBuildImage.WINDOWS_BASE_2_0 + BuildImage = LinuxBuildImage.STANDARD_5_0 } }); @@ -1040,6 +1044,7 @@ namespace Pipeline new CodeCommitSourceAction(new CodeCommitSourceActionProps { ActionName = "Source", + Branch = "main", Repository = code, Output = sourceOutput }) From 1d2d9491c546fc76f650b270c8f2b88360756c26 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 6 May 2021 02:26:28 +0000 Subject: [PATCH 399/655] fix links to Tags --- doc_source/tagging.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/tagging.md b/doc_source/tagging.md index f69a0690..3e2f343b 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -6,8 +6,8 @@ Tags are informational key\-value elements that you can add to constructs in you For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf)\. The [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-addscope-key-value-props) applies a new tag to the given construct and all of its children\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html#static-removescope-key-props) removes a tag from the given construct and any of its children, including tags a child construct may have applied to itself\. ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#removekey-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#removekey-props) applies a new tag to the given construct and all of its children\. ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#static-removescope-key-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#static-removescope-key-props) removes a tag from the given construct and any of its children, including tags a child construct may have applied to itself\. **Note** Tagging is implemented using [Aspects](aspects.md)\. Aspects are a way to apply an operation \(such as tagging\) to all constructs in a given scope\. From bb8d7e7a4654a98c1cfe2942f5b57f5bea58f72d Mon Sep 17 00:00:00 2001 From: Greg Cockburn Date: Fri, 7 May 2021 12:54:50 +1000 Subject: [PATCH 400/655] Correct python method is snake case, not camel. --- doc_source/assets.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/assets.md b/doc_source/assets.md index dc6eb5bd..9f6c5439 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -741,7 +741,7 @@ task_definition = ecs.FargateTaskDefinition(self, "TaskDef", memory_limit_mib=1024, cpu=512) task_definition.add_container("my-other-container", - image=ecs.ContainerImage.fromEcrRepository( + image=ecs.ContainerImage.from_ecr_repository( asset.repository, asset.image_uri.rpartition(":")[-1])) ``` @@ -880,4 +880,4 @@ To enable such use cases, external tools consult a set of metadata entries on AW Using these two metadata entries, tools can identify that assets are used by a certain resource, and enable advanced local experiences\. -To add these metadata entries to a resource, use the `asset.addResourceMetadata` \(Python: `add_resource_metadata`\) method\. \ No newline at end of file +To add these metadata entries to a resource, use the `asset.addResourceMetadata` \(Python: `add_resource_metadata`\) method\. From ce0fd47be5db96ad01c90ef28db19df0e240694f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 10 May 2021 18:52:39 +0000 Subject: [PATCH 401/655] copyright notice change --- doc_source/assets.md | 2 +- doc_source/hello_world.md | 2 +- doc_source/index.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/assets.md b/doc_source/assets.md index 9f6c5439..c202bc60 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -880,4 +880,4 @@ To enable such use cases, external tools consult a set of metadata entries on AW Using these two metadata entries, tools can identify that assets are used by a certain resource, and enable advanced local experiences\. -To add these metadata entries to a resource, use the `asset.addResourceMetadata` \(Python: `add_resource_metadata`\) method\. +To add these metadata entries to a resource, use the `asset.addResourceMetadata` \(Python: `add_resource_metadata`\) method\. \ No newline at end of file diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 715b35bf..1dce01e4 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -588,4 +588,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md index fa14b210..221b18b8 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -1,7 +1,7 @@ # AWS Cloud Development Kit (AWS CDK) Developer Guide ----- -*****Copyright © 2020 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** +*****Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** ----- Amazon's trademarks and trade dress may not be used in From f7d4a39a46c9a3e9a1b46eae32344cb8ab7d1927 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 10 May 2021 22:48:09 +0000 Subject: [PATCH 402/655] add info about new SAM CLI preview --- doc_source/sam.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/doc_source/sam.md b/doc_source/sam.md index ec64abf3..0d5ac967 100644 --- a/doc_source/sam.md +++ b/doc_source/sam.md @@ -2,6 +2,10 @@ This topic describes how to use the AWS SAM CLI with the AWS CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. +**Note** +Full AWS CDK integration with the AWS SAM CLI is currently in public preview\. This integration allows you to locally test and build serverless application defined using the CDK\. For more information, see [AWS Cloud Development Kit \(AWS CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. +The instructions here apply to the current \(non\-preview\) version of the AWS SAM CLI\. + 1. The first step is to create a AWS CDK application and add the Lambda package\. ``` From d16ac952aef8575ebacbf84534978d175530cbfc Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 10 May 2021 22:50:18 +0000 Subject: [PATCH 403/655] fix and improve wording --- doc_source/work-with-cdk-csharp.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index 376c8535..ebfc02a6 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -1,6 +1,6 @@ # Working with the AWS CDK in C\# -\.NET is a fully\-supported client platform for the AWS CDK and is considered stable\. C\# is the main \.NET language we for which provide examples and support\. You can choose to write AWS CDK applications in other \.NET languages, such as Visual Basic or F\#, but AWS offers limited support for these languages\. +\.NET is a fully\-supported client platform for the AWS CDK and is considered stable\. C\# is the main \.NET language for which we provide examples and support\. You can choose to write AWS CDK applications in other \.NET languages, such as Visual Basic or F\#, but AWS offers limited support for using these languages with the CDK\. You can develop AWS CDK applications in C\# using familiar tools including Visual Studio, Visual Studio Code, the `dotnet` command, and the NuGet package manager\. The modules comprising the AWS Construct Library are distributed via [nuget\.org](https://www.nuget.org/packages?q=amazon.cdk.aws)\. From ef0eb43455befc7ad7e9233fa7a6e3d3d4b0a162 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 10 May 2021 22:51:05 +0000 Subject: [PATCH 404/655] autogen, no text changes --- doc_source/cli.md | 26 +++++++++++++------------- doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-v2.md | 2 +- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 1c651b0d..e9336706 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -321,7 +321,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -340,7 +340,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -348,7 +348,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -372,7 +372,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -394,7 +394,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -611,7 +611,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -624,7 +624,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -640,7 +640,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -709,7 +709,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -762,7 +762,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -781,7 +781,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -801,7 +801,7 @@ Options: with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -823,7 +823,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 3e2f343b..0d21f033 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index f2490ea8..623c3383 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index ab149d66..81b0ebef 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -26,7 +26,7 @@ Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prereq To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. -### Updating `cdk.json` +### Updating `cdk.json` Remove all feature flags from `cdk.json`\. You can add one or more of the three flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these are needed\. From 41a2fc67a36e6641f292e7802f95cbaac6f6599e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 11 May 2021 01:28:31 +0000 Subject: [PATCH 405/655] add info about selection and listing in pipelines stacks --- doc_source/cli.md | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index e9336706..fc16d9db 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -222,15 +222,22 @@ cdk synth PipelineStack LambdaStack ``` You may also use wildcards to specify IDs that match a pattern\. -+ ? matches any single character -+ \* matches any number of characters ++ `?` matches any single character ++ `*` matches any number of characters \(`*` alone matches all stacks\) ++ `**` matches everything in a hierarchy -When using wildcards, enclose the pattern in quotes or escape the wildcards with `\`\. If you don't, your shell may try to expand the pattern to the names of files in the current directory\. At best, this won't do what you expect; at worst, you could deploy stacks you didn't intend to\. This isn't strictly necessary on Windows because `cmd.exe` does not expand wildcards, but is good practice regardless\. +You may also use the \-\-all option to specify all stacks\. + +If your app uses [CDK Pipelines](cdk_pipeline.md), the CDK Toolkit understands your stacks and stages as a hierorchy, and the \-\-all option and the `*` wildcard only match top\-level stacks\. To match all the stacks, use `**`\. Also use `**` to indicate all the stacks under a particular hierarchy\. + +When using wildcards, enclose the pattern in quotes, or escape the wildcards with `\`\. If you don't, your shell may try to expand the pattern to the names of files in the current directory\. At best, this won't do what you expect; at worst, you could deploy stacks you didn't intend to\. This isn't strictly necessary on Windows because `cmd.exe` does not expand wildcards, but is good practice nonetheless\. ``` cdk synth "*Stack" # PipelineStack, LambdaStack, etc. cdk synth 'Stack?' # StackA, StackB, Stack1, etc. -cdk synth \* # All stacks in the app +cdk synth \* # All stacks in the app, or all top-level stacks in a CDK Pipelines app +cdk synth '**' # All stacks in a CDK Pipelines app +cdk synth 'PipelineStack/Prod/**' # All stacks in Prod stage in a CDK Pipelines app ``` **Note** @@ -301,6 +308,8 @@ cdk list cdk ls ``` +If your application contains [CDK Pipelines](cdk_pipeline.md) stacks, the CDK Toolkit displays stack names as paths according to their location in the pipeline hierarchy \(e\.g\., `PipelineStack`, `PipelineStack/Prod`, `PipelineStack/Prod/MyService`, etc\)\. + If your app contains many stacks, you can specify full or partial stack IDs of the stacks to be listed; see [Specifying stacks](#cli-stacks)\. Add the `--long` flag to see more information about the stacks, including the stack names and their environments \(AWS account and region\)\. From 71e2134910ed463c2ed420bb759a0e0f2d444d6f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 11 May 2021 01:28:54 +0000 Subject: [PATCH 406/655] minor tweaks related to internal changes --- doc_source/apps.md | 2 +- doc_source/cfn_layer.md | 20 +++++++++---------- doc_source/codepipeline_example.md | 2 +- doc_source/context.md | 2 +- doc_source/environments.md | 6 +++--- doc_source/get_secrets_manager_value.md | 2 +- doc_source/getting_started.md | 2 +- doc_source/resources.md | 2 +- .../stack_how_to_create_multiple_stacks.md | 10 +++++----- 9 files changed, 24 insertions(+), 24 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index dff61448..ca565aa4 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -238,7 +238,7 @@ All constructs that have implemented the `validate` method can validate themselv This is the final stage of the execution of your AWS CDK app\. It's triggered by a call to `app.synth()`, and it traverses the construct tree and invokes the `synthesize` method on all constructs\. Constructs that implement `synthesize` can participate in synthesis and emit deployment artifacts to the resulting cloud assembly\. These artifacts include AWS CloudFormation templates, AWS Lambda application bundles, file and Docker image assets, and other deployment artifacts\. [Cloud assemblies](#apps_cloud_assembly) describes the output of this phase\. In most cases, you won't need to implement the `synthesize` method 5\. Deployment -In this phase, the AWS CDK CLI takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. +In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: + The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 4679bb50..3badc196 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -187,7 +187,7 @@ The basic approach to get access to the CFN Resource class is to use `construct. #### [ TypeScript ] ``` -// Get the AWS CloudFormation resource +// Get the CloudFormation resource const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; // Change its properties @@ -203,7 +203,7 @@ cfnBucket.analyticsConfiguration = [ #### [ JavaScript ] ``` -// Get the AWS CloudFormation resource +// Get the CloudFormation resource const cfnBucket = bucket.node.defaultChild; // Change its properties @@ -219,7 +219,7 @@ cfnBucket.analyticsConfiguration = [ #### [ Python ] ``` -# Get the AWS CloudFormation resource +# Get the CloudFormation resource cfn_bucket = bucket.node.default_child # Change its properties @@ -235,7 +235,7 @@ cfn_bucket.analytics_configuration = [ #### [ Java ] ``` -// Get the AWS CloudFormation resource +// Get the CloudFormation resource CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); cfnBucket.setAnalyticsConfigurations( @@ -249,7 +249,7 @@ cfnBucket.setAnalyticsConfigurations( #### [ C\# ] ``` -// Get the AWS CloudFormation resource +// Get the CloudFormation resource var cfnBucket = (CfnBucket)bucket.Node.DefaultChild; cfnBucket.AnalyticsConfigurations = new List { @@ -323,7 +323,7 @@ Use one of the `addOverride` methods \(Python: `add_override`\) methods, as show #### [ TypeScript ] ``` -// Get the AWS CloudFormation resource +// Get the CloudFormation resource const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; // Use dot notation to address inside the resource template fragment @@ -345,7 +345,7 @@ cfnBucket.addPropertyDeletionOverride('Tags.0'); #### [ JavaScript ] ``` -// Get the AWS CloudFormation resource +// Get the CloudFormation resource const cfnBucket = bucket.node.defaultChild ; // Use dot notation to address inside the resource template fragment @@ -367,7 +367,7 @@ cfnBucket.addPropertyDeletionOverride('Tags.0'); #### [ Python ] ``` -# Get the AWS CloudFormation resource +# Get the CloudFormation resource cfn_bucket = bucket.node.default_child # Use dot notation to address inside the resource template fragment @@ -389,7 +389,7 @@ cfn_bucket.add_property_deletion_override("Tags.0") #### [ Java ] ``` -// Get the AWS CloudFormation resource +// Get the CloudFormation resource CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); // Use dot notation to address inside the resource template fragment @@ -411,7 +411,7 @@ cfnBucket.addPropertyDeletionOverride("Tags.0"); #### [ C\# ] ``` -// Get the AWS CloudFormation resource +// Get the CloudFormation resource var cfnBucket = (CfnBucket)bucket.node.defaultChild; // Use dot notation to address inside the resource template fragment diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index e7a09cfb..7d4d4368 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -24,7 +24,7 @@ Also, make sure you have issued `cdk bootstrap`, as the Amazon S3 bucket in the To set up a new AWS CDK project in CodeCommit; -1. [Create a new CodeCommit repository](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html) named `pipeline` using the CodeCommit console or the AWS CLI\. +1. [Create a new CodeCommit repository](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html) named `pipeline` using the CodeCommit console or the CDK Toolkit\. if you already have a CodeCommit repository named `pipeline`, you can use another name\. Just make sure you clone it to a directory named pipeline on your local system\. diff --git a/doc_source/context.md b/doc_source/context.md index 145714e2..999b38f4 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -24,7 +24,7 @@ You can get a context value using the `construct.node.tryGetContext` method\. If ## Context methods -The AWS CDK supports several context methods that enable AWS CDK apps to get contextual information\. For example, you can get a list of Availability Zones that are available in a given AWS account and AWS Region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) method\. +The AWS CDK supports several context methods that enable AWS CDK apps to get contextual information\. For example, you can get a list of Availability Zones that are available in a given AWS account and region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) method\. The following are the context methods: diff --git a/doc_source/environments.md b/doc_source/environments.md index 88fd3eba..57ea64ac 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -9,7 +9,7 @@ If you don't specify an environment when you define a stack, the stack is said t In an environment\-agnostic stack, any constructs that use availability zones will see two of them, allowing the stack to be deployed to any region\. -When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations against your AWS account\. See [AWS CDK Toolkit \(`cdk` command\)](cli.md) for details\. +When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations in your AWS account\. See [AWS CDK Toolkit \(`cdk` command\)](cli.md) for details\. For production stacks, we recommend that you explicitly specify the environment for each stack in your app using the `env` property\. The following example specifies different environments for its two different stacks\. @@ -310,7 +310,7 @@ if [[ $# -ge 2 ]]; then npx cdk deploy "$@" exit $? else - echo 1>&2 "Provide AWS account and region as first two args." + echo 1>&2 "Provide account and region as first two args." echo 1>&2 "Additional args are passed through to cdk deploy." exit 1 fi @@ -330,7 +330,7 @@ if ($args.length -ge 2) { npx cdk deploy $args exit $lastExitCode } else { - [console]::error.writeline("Provide AWS account and region as first two args.") + [console]::error.writeline("Provide account and region as first two args.") [console]::error.writeline("Additional args are passed through to cdk deploy.") exit 1 } diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index 15a2a1b7..c6ebb676 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -1,6 +1,6 @@ # Get a value from AWS Secrets Manager -To use values from AWS Secrets Manager in your CDK app, use the [fromSecretAttributes](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-secretsmanager/secret.html#aws_secretsmanager_Secret_fromSecretAttributes) method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. +To use values from AWS Secrets Manager in your AWS CDK app, use the [fromSecretAttributes](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-secretsmanager/secret.html#aws_secretsmanager_Secret_fromSecretAttributes) method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. ------ #### [ TypeScript ] diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index ad82b009..dc610365 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -123,7 +123,7 @@ All AWS CDK developers, even those working in Python, Java, or C\#, need [Node\. **Important** Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. -You must configure your workstation with your credentials and an AWS Region, if you have not already done so\. If you have the AWS CLI installed, the easiest way to satisfy this requirement is issue the following command: +You must configure your workstation with your credentials and an AWS region, if you have not already done so\. If you have the AWS CLI installed, the easiest way to satisfy this requirement is issue the following command: ``` aws configure diff --git a/doc_source/resources.md b/doc_source/resources.md index 2ca8724d..0f176cad 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -490,7 +490,7 @@ new Function(this, "MyLambda", new FunctionProps ## Importing existing external resources -Sometimes you already have a resource in your AWS account and want to use it in your AWS CDK app, for example, a resource that was defined through the console, the AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into an AWS CDK object in the current stack by calling a static factory method on the resource's class\. +Sometimes you already have a resource in your AWS account and want to use it in your AWS CDK app, for example, a resource that was defined through the console, an AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into an AWS CDK object in the current stack by calling a static factory method on the resource's class\. The following example shows how to define a bucket based on an existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a Amazon Virtual Private Cloud based on an existing VPC having a specific ID\. diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md index 3bad0f86..7ab0aabb 100644 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ b/doc_source/stack_how_to_create_multiple_stacks.md @@ -272,7 +272,7 @@ export class MultistackStack extends cdk.Stack { // Add a Boolean property "encryptBucket" to the stack constructor. // If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. - // Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). + // Encrypted bucket uses KMS-managed keys (SSE-KMS). if (props && props.encryptBucket) { new s3.Bucket(this, "MyGroovyBucket", { encryption: s3.BucketEncryption.KMS_MANAGED, @@ -301,7 +301,7 @@ class MultistackStack extends cdk.Stack { // Add a Boolean property "encryptBucket" to the stack constructor. // If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. - // Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). + // Encrypted bucket uses KMS-managed keys (SSE-KMS). if ( props && props.encryptBucket) { new s3.Bucket(this, "MyGroovyBucket", { encryption: s3.BucketEncryption.KMS_MANAGED, @@ -336,7 +336,7 @@ class MultistackStack(core.Stack): # Add a Boolean property "encryptBucket" to the stack constructor. # If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. - # Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). + # Encrypted bucket uses KMS-managed keys (SSE-KMS). if encrypt_bucket: s3.Bucket(self, "MyGroovyBucket", encryption=s3.BucketEncryption.KMS_MANAGED, @@ -380,7 +380,7 @@ public class MultistackStack extends Stack { // Add a Boolean property "encryptBucket" to the stack constructor. // If true, creates an encrypted bucket. Otherwise, the bucket is - // unencrypted. Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). + // unencrypted. Encrypted bucket uses KMS-managed keys (SSE-KMS). if (encryptBucket) { Bucket.Builder.create(this, "MyGroovyBucket") .encryption(BucketEncryption.KMS_MANAGED) @@ -416,7 +416,7 @@ namespace Multistack { // Add a Boolean property "EncryptBucket" to the stack constructor. // If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. - // Encrypted bucket uses AWS KMS-managed keys (SSE-KMS). + // Encrypted bucket uses KMS-managed keys (SSE-KMS). if (props?.EncryptBucket ?? false) { new Bucket(this, "MyGroovyBucket", new BucketProps From 5a0534555a47990d7cbaf90d98d949cc1d24ca12 Mon Sep 17 00:00:00 2001 From: Tiago Barbosa Date: Wed, 12 May 2021 15:28:17 +0100 Subject: [PATCH 407/655] SecretArn is deprecated in latest C# CDK version Replace SecretArn with SecretCompleteArn --- doc_source/get_secrets_manager_value.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index c6ebb676..7026fdf3 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -94,7 +94,7 @@ public class SecretsManagerStack : Stack public SecretsManagerStack(App scope, string id, StackProps props) : base(scope, id, props) { var secret = Secret.FromSecretAttributes(this, "ImportedSecret", new SecretAttributes { - SecretArn = "arn:aws:secretsmanager:::secret:-" + SecretCompleteArn = "arn:aws:secretsmanager:::secret:-" // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: // encryptionKey = ..., }); @@ -109,4 +109,4 @@ Use the [create\-secret](https://docs.aws.amazon.com/cli/latest/reference/secret aws secretsmanager create-secret --name ImportedSecret --secret-string mygroovybucket ``` -The command returns an ARN you can use for the example\. \ No newline at end of file +The command returns an ARN you can use for the example\. From 28b59a08eaa96e22ed3c70be04b7740245734a4a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 18 May 2021 18:28:28 +0000 Subject: [PATCH 408/655] add security info for bootstrap template --- doc_source/bootstrapping.md | 8 +++++++- doc_source/cli.md | 5 +++++ doc_source/work-with-cdk-v2.md | 3 +++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index a8a5df86..a42ab8f2 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -11,6 +11,9 @@ The required resources are defined in a AWS CloudFormation stack, called the *bo The AWS CDK supports two bootstrap templates\. At this writing, the AWS CDK is transitioning from one of these templates to the other, but the original template \(dubbed "legacy"\) is still the default\. The newer template \("modern"\) is required by CDK Pipelines today, and will become the default at some point in the future\. For details, see [Bootstrapping templates](#bootstrapping-templates)\. +**Important** +The modern bootstrap template grants the bootstrapping account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. + Environments are independent, so if you want to deploy to multiple environments \(different AWS accounts or different regions in the same account\), each environment must be bootstrapped separately\. **Important** @@ -96,7 +99,7 @@ aws cloudformation create-stack ^ At this writing, the AWS CDK is transitioning from one set of bootstrap resources to another\. The original bootstrap template, which shipped with the very first version of the AWS CDK, is called the **legacy** template\. A newer version of the template with additional resources was added in version 1\.25\.0\. This newer template is called the **modern** template\. -The legacy template is fully supported by the AWS CDK and is in fact the template that is selected by default when you issue `cdk bootstrap`\. The modern template is required primarily by the CDK Pipelines module, which can be used to set up a continuous delivery pipeline for your CDK applications\. More precisely, the modern template is used by the `DefaultSynthesizer` \(see [Stack synthesizers](#bootstrapping-synthesizers)\), and CDK Pipelines requires this synthesizer, +The legacy template is still fully supported by the AWS CDK and is in fact the template that is selected by default when you issue `cdk bootstrap`\. The modern template is required primarily by the CDK Pipelines module, which can be used to set up a continuous delivery pipeline for your CDK applications\. More precisely, the modern template is used by the `DefaultSynthesizer` \(see [Stack synthesizers](#bootstrapping-synthesizers)\), and CDK Pipelines requires this synthesizer, The main differences between the templates are as follows\. @@ -104,6 +107,9 @@ The main differences between the templates are as follows\. \* *We will add additional resources to the modern template as needed\.* +**Important** +The modern bootstrap template grants the bootstrapping account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. + At some point in the future, the modern template will become the default bootstrapping template\. Until then, manually select the modern template when bootstrapping by setting the `CDK_NEW_BOOTSTRAP` environment variable\. ------ diff --git a/doc_source/cli.md b/doc_source/cli.md index fc16d9db..8d1763d0 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -268,6 +268,11 @@ You may incur AWS charges for what the AWS CDK stores in the bootstrapped resour **Note** Older versions of the modern template created a Customer Master Key by default\. To avoid charges, re\-bootstrap using `--no-bootstrap-customer-key`\. +The AWS CDK Toolkit supports two bootstrap templates: the modern template and the legacy template\. The legacy template is the default, but the modern template is required by CDK Pipelines\. For more inforamtion, see [Bootstrapping](bootstrapping.md)\. + +**Important** +The modern bootstrap template grants the bootstrapping account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](bootstrapping.md#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. + ## Creating a new app To create a new app, create a directory for it, then, inside the directory, issue `cdk init`\. diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index 81b0ebef..0871977d 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -14,6 +14,9 @@ The main changes in CDK v2 are: + Behavior that was gated by feature flags in AWS CDK v1\.x is enabled by default in CDK v2, and the old feature flags are no longer needed or, in most cases, supported\. + CDK v2 requires that the environments you deploy into be boostrapped using the modern bootstrap stack; the legacy stack is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. Simply re\-bootstrap the affected environments to upgrade them\. It is not necessary to set any feature flags or environment variables to specify the modern bootstrap stack\. +**Important** +The modern bootstrap template grants the bootstrapping account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](bootstrapping.md#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. + Aside from this topic, the AWS CDK Developer Guide describes CDK v1\.x\. Most of the information in the Guide still applies in CDK v2, or can be adapted with only minor changes\. A v2 Developer Guide will be available at General Availability \(GA\) of CDK v2\. A version of the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) is available for CDK v2\. ## Prerequisites From 4649b3799169f65a9ee6c9b028545dbbb814f8ba Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 24 May 2021 16:58:06 +0000 Subject: [PATCH 409/655] recommend passing scope and id positionally in Python --- doc_source/index.md | 2 +- doc_source/work-with-cdk-python.md | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/doc_source/index.md b/doc_source/index.md index 221b18b8..ed77e4a5 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -1,7 +1,7 @@ # AWS Cloud Development Kit (AWS CDK) Developer Guide ----- -*****Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** +*****Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** ----- Amazon's trademarks and trade dress may not be used in diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index da40925f..941700f2 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -122,11 +122,13 @@ In Python, `lambda` is a language keyword, so you cannot use it as a name for th By convention, the second argument to AWS CDK constructs is named `id`\. When writing your own stacks and constructs, calling a parameter `id` "shadows" the Python built\-in function `id()`, which returns an object's unique identifier\. This function isn't used very often, but if you should happen to need it in your construct, rename the argument, for example `id_`, or else call the built\-in function as `__builtins__.id()`\. -### Props +### Arguments and properties All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. -In Python, props are expressed as keyword arguments\. If an argument contains nested data structures, these are expressed using a class which takes its own keyword arguments at instantiation\. The same pattern is applied to other method calls that take a single structured argument\. +*scope* and *id* should always be passed as positional arguments, not keyword arguments, because their names change if the construct accepts a property named *scope* or *id*\. + +In Python, props are expressed as keyword arguments\. If an argument contains nested data structures, these are expressed using a class which takes its own keyword arguments at instantiation\. The same pattern is applied to other method calls that take a structured argument\. For example, in a Amazon S3 bucket's `add_lifecycle_rule` method, the `transitions` property is a list of `Transition` instances\. From 6953946ec2f45846ccb404216af389be31db18fa Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 24 May 2021 20:25:02 +0000 Subject: [PATCH 410/655] add link to Go announcement blog post --- doc_source/work-with-cdk-go.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc_source/work-with-cdk-go.md b/doc_source/work-with-cdk-go.md index ad25e41a..ca5a6b11 100644 --- a/doc_source/work-with-cdk-go.md +++ b/doc_source/work-with-cdk-go.md @@ -4,6 +4,8 @@ The Go language binding for the AWS CDK is now available as a Developer Preview\ Unlike the other languages the CDK supports, Go is not a traditional object\-oriented programming language\. Go uses composition where other languages often leverage inheritance\. We have tried to employ idiomatic Go approaches as much as possible, but there are places where the CDK charts its own path\. +This topic explains the ins and outs of working with the AWS CDK in Go\. See the [announcement blog post](https://aws.amazon.com/blogs/developer/getting-started-with-the-aws-cloud-development-kit-and-go/) for a walkthrough of a simple Go project for the AWS CDK\. + ## Prerequisites To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. From 0ceeedd42a03898d22eb59548812ac36564316aa Mon Sep 17 00:00:00 2001 From: Tom Fenton Date: Tue, 25 May 2021 15:54:09 +1200 Subject: [PATCH 411/655] Update cli.md, fix typo **Description of changes** Fix typo `Alawys` to `Always`. By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. --- doc_source/cli.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 8d1763d0..2513f164 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -125,7 +125,7 @@ The CDK Toolkit needs to know your AWS account credentials and the AWS region in We strongly recommend against using your main AWS account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. Credentials and region may be specified using environment variables or in configuration files\. These are the same variables and files used by other AWS tools such as the AWS CLI and the various AWS SDKs\. The CDK Toolkit looks for this information in the following order\. -+ The `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` environment variables\. Alawys specify all three variables, not just one or two\. ++ The `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` environment variables\. Always specify all three variables, not just one or two\. + A specific profile defined in the standard AWS `config` and `credentials` files, and specified using the `--profile` option on `cdk` commands\. + The `[default]` section of the standard AWS `config` and `credentials` files\. From 8b3e2c26d8a0ae8c741600773072ef8d3aba3a0a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 29 May 2021 02:40:52 +0000 Subject: [PATCH 412/655] update deprecated property --- doc_source/get_secrets_manager_value.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index 7026fdf3..03c80a69 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -13,7 +13,7 @@ export class SecretsManagerStack extends core.Stack { super(scope, id, props); const secret = sm.Secret.fromSecretAttributes(this, "ImportedSecret", { - secretArn: + secretCompleteArn: "arn:aws:secretsmanager:::secret:-" // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: // encryptionKey: ... @@ -31,7 +31,7 @@ class SecretsManagerStack extends core.Stack { super(scope, id, props); const secret = sm.Secret.fromSecretAttributes(this, "ImportedSecret", { - secretArn: + secretCompleteArn: "arn:aws:secretsmanager:::secret:-" // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: // encryptionKey: ... @@ -53,7 +53,7 @@ class SecretsManagerStack(core.Stack): super().__init__(scope, name, **kwargs) secret = sm.Secret.from_secret_attributes(self, "ImportedSecret", - secret_arn="arn:aws:secretsmanager:::secret:-", + secret_complete_arn="arn:aws:secretsmanager:::secret:-", # If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: # encryption_key=.... ) @@ -75,10 +75,10 @@ public class SecretsManagerStack extends Stack { super(scope, id, props); Secret secret = (Secret)Secret.fromSecretAttributes(this, "ImportedSecret", SecretAttributes.builder() - .secretArn("arn:aws:secretsmanager:::secret:-") - // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: - // .encryptionKey(...) - .build()); + .secretCompleteArn("arn:aws:secretsmanager:::secret:-") + // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: + // .encryptionKey(...) + .build()); } } ``` @@ -109,4 +109,4 @@ Use the [create\-secret](https://docs.aws.amazon.com/cli/latest/reference/secret aws secretsmanager create-secret --name ImportedSecret --secret-string mygroovybucket ``` -The command returns an ARN you can use for the example\. +The command returns an ARN you can use for the example\. \ No newline at end of file From 886790ed594afd5bf9a962bb1a9e6e2c7ff8cc53 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 10 Jun 2021 00:50:33 +0000 Subject: [PATCH 413/655] add best practices topic --- doc_source/best-practices.md | 150 +++++++++++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 doc_source/best-practices.md diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md new file mode 100644 index 00000000..08096218 --- /dev/null +++ b/doc_source/best-practices.md @@ -0,0 +1,150 @@ +# Best practices for developing and deploying cloud infrastructure with the AWS CDK + +The AWS CDK allows developers or administrators to define their cloud infrastructure using a supported programming language\. CDK applications are organized into stages, stacks, and constructs, providing modular design capabilities in both runtime components \(such as AWS Lambda code or containerized services\) and infrastructure components\. For a more detailed introduction to the concepts behind the CDK, see [Getting started with the AWS CDK](getting_started.md)\. + +The AWS CDK reflects careful consideration of the needs of our customers and internal teams and of the failure patterns that often arise during the deployment and ongoing maintenance of complex cloud applications\. We discovered that failures are often related to "out\-of\-band" changes to an application, such as configuration changes, that were not fully tested\. Therefore, we developed the AWS CDK around a model in which your entire application, not just business logic but also infrastructure and configuration, is defined in code\. That way, proposed changes can be carefully reviewed, comprehensively tested in environments resembling production to varying degrees, and fully rolled back if something goes wrong\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/all-in-one.jpg) + +At deployment time, the AWS CDK synthesizes a cloud assembly that contains not only AWS CloudFormation templates describing your infrastructure in all target environments, but file assets containing your code and their supporting files\. With the CDK, every commit in your application's main version control branch can represent a complete, consistent, deployable version of your application\. Your application can then be deployed automatically whenever a change is made\. + +The philosophy behind the AWS CDK leads to our recommended best practices, which we have divided into broad categories\. ++ [Organization best practices](#best-practices-organization) ++ [Coding best practices](#best-practices-code) ++ [Construct best practices](#best-practices-constructs) ++ [Application best practices](#best-practices-apps) + +## Organization best practices + +In the beginning stages of AWS CDK adoption, it's important to consider how to set up your organization for success\. It's a best practice to have a team of experts responsible for training and guiding the rest of the company as they adopt the CDK The size of this team may vary, from one or two people at a small company to a full\-fledged Cloud Center of Excellence \(CCoE\) at a larger company\. This team is responsible for setting standards and policies for how cloud infrastructure will be done at your company, as well as for training and mentoring developers\. + +The CCoE also creates a "landing zone" that defines your organizational units within AWS\. A landing zone is a pre\-configured, secure, scalable, multi\-account AWS environment based on best practice blueprints\. You can tie together the services that make up your landing zone with [AWS Control Tower](https://aws.amazon.com/controltower/), a high\-level service configures and manages your entire multi\-account system from a single user interface\. + +Development teams should be able use their own accounts for testing and have the ability to deploy new resources in these accounts as needed\. Individual developers can treat these resources as extensions of their own development workstation\. Using [CDK Pipelines](cdk_pipeline.md), the AWS CDK applications can then be deployed via a shared services account to testing, integration, and production environments \(each isolated in its own AWS region and/or account\) by merging the developers' code into your organization's canonical repository\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/best-practice-deploy-to-multiple-accounts.jpg) + +## Coding best practices + + This section presents best practices for organizing your AWS CDK code\. The diagram below shows the relationship between a team and that team's code repositories, packages, applications, and construct libraries\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/code-organization.jpg) + +### Start simple and add complexity only when you need it + +The guiding principle for most of our best practices is to keep things simple as possible—but no simpler\. Add complexity only when your requirements dictate a more complicated solution\. With the AWS CDK, you can always refactor your code as necessary to support new requirements, so it doesn't make sense to architect for all possible scenarios up front\. + +### Every application starts with a single package in a single repository + + The entry point of your AWS CDK app should be a single package where you define the different components of your application \(infrastructure, code, and configuration\), as well as the CI/CD pipeline to deploy the application\. Use additional packages for constructs that you use in more than one application\. \(Shared constructs should also have their own lifecycle and testing strategy\.\) Dependencies between packages in the same repository are managed by your repo's build tooling\. + +Though it is possible, it is not recommended to put multiple applications in the same repository, especially when using automated deployment pipelines, because this increases the "blast radius" of changes during deployment\. With multiple applications in a repository, not only do changes to one application trigger deployment of the others \(even if they have not changed\), but a break in one application prevents the other applications from being deployed\. + +### Move code into repositories based on code lifecycle or team ownership + +When packages begin to be used in multiple applications, move them to their own repository, so they can be referenced by the build systems of the applications that use them, but updated on cadences independent of the lifecycles of those applications\. It may make sense to put all shared constructs in one repository at first\. + +Also move packages to their own repo when different teams are working on them, to help enforce access control\. + +To consume packages across repository boundaries, you now need a private package repository—similar to NPM, PyPi, or Maven Central, but internal to your organization, and a release process that builds, tests, and publishes the package to the private package repository\. [CodeArtifact](%url-aca-user) can host packages for most popular programming languages\. + +Dependencies on packages in the package repository are managed by your language's package manager, for example NPM for TypeScript or JavaScript applications\. Your package manager helps to make sure builds are repeatable by recording the specific versions of every package your application depends on and allows you to upgrade those dependencies in a controlled manner\. + +Shared packages need a different testing strategy: although for a single application it might be good enough to deploy the application to a testing environment and confirm that it still works, shared packages need to be tested independently of the consuming application, as if they were being released to the public\. \(Your organization might in fact choose to actually release some shared packages to the public\.\) + +Keep in mind that a construct can be arbitrary simple or complex\. A `Bucket` is a construct, but `CameraShopWebsite` could be a construct, too\. + +### Infrastructure and application code live in the same package + +The AWS CDK not only generates AWS CloudFormation templates for deploying infrastructure, it also bundles assets like Lambda functions and Docker images and deploys them alongside your infrastructure\. So it's not only possible to combine the code that defines your infrastructure and the code that implements your business logic into a single construct— it's a best practice\. These two kinds of code don't need to live in separate repositories or even in separate packages\. + +A construct that is self\-contained, in other words that completely describes a piece of functionality including its infrastructure and logic, makes it easy to evolve the two kinds of code together, test them in isolation, share and reuse the code across projects, and version all the code in sync\. + +## Construct best practices + + This section contains best practices for developing constructs\. Constructs are reusable, composable modules that encapsulate resources, and the building blocks of AWS CDK apps\. + +### Model your app through constructs, not stacks + +When breaking down your application into units, represent each unit as a descendant of [https://docs.aws.amazon.com/cdk/api/latest/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/latest/docs/constructs.Construct.html) and not of [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html)\. Stacks are a unit of deployment, and so tend to be oriented to specific applications\. By using constructs instead of stacks, you give yourself and your users the flexibility to build stacks in the way that makes the most sense for each deployment scenario\. For example, you could compose multiple constructs into a `DevStack` with some configuration for development environments and then have a different composition for production\. + +### Configure with properties and methods, not environment variables + + Environment variable lookups inside constructs and stacks are a common anti\-pattern\. Both constructs and stacks should accept a properties object to allow for full configurability completely in code\. To do otherwise is to introduce a dependency on the machine that the code will run on, which becomes another bit of configuration information you have to keep track of and manage\. + +In general, environment variable lookups should be limited to the top level of an AWS CDK app, and should be used to pass in information needed for running in a development environment; see [Environments](environments.md)\. + +### Unit test your infrastructure + +If you avoid network lookups during synthesis and model all your production stages in code \(best practices we cover later\), you can run a full suite of unit tests at build time, consistently, in all environments\. If any single commit always results in the same generated template, you can trust the unit tests that you write to confirm that the generated templates look how you expect them to\. See [Testing constructs](testing.md)\. + +### Don't change the logical ID of stateful resources + +Changing the logical ID of a resource results in the resource being replaced with a new one at the next deployment\. For stateful resources like databases and buckets, or persistent infrastructure like an Amazon VPC, this is almost never what you want\. Be careful about any refactor of your AWS CDK code that could cause the ID to change, and write unit tests that assert that the logical IDs of your stateful resources remain static\. The logical ID is derived from the `id` you specify when you instantiate the construct, and the construct's position in the construct tree; see [Logical IDs](identifiers.md#identifiers_logical_ids)\. + +### Constructs aren't enough for compliance + +Many enterprise customers are writing their own wrappers for L2 constructs \(the "curated" constructs that represent individual AWS resources with built\-in sane defaults and best practices\) to enforce security best practices such as static encryption and specific IAM policies\. For example, you might create a `MyCompanyBucket` that you then use in your applications in place of the usual Amazon S3 `Bucket` construct\. This pattern is useful for surfacing security guidance early in the software development lifecycle, but it cannot be relied on as the sole means of enforcement\. + +Instead, use AWS features such as [service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) and [permission boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to enforce your security guardrails at the organization level\. Use [Aspects](aspects.md) or tools like [CloudFormation Guard](https://github.com/aws-cloudformation/cloudformation-guard) to make assertions about the security properties of infrastructure elements before deployment\. Use AWS CDK for what it does best\. + +Finally, keep in mind that writing your own "L2\+" constructs like these may prevent your developers from taking advantage of the growing ecosystems of AWS CDK packages, such as [AWS Solutions Constructs](https://docs.aws.amazon.com/https://docs.aws.amazon.com/solutions/latest/constructs/welcome.html), as these are typically based on standard AWS CDK constructs and won't be able to use your custom versions\. + +## Application best practices + +In this section we discuss how best to write your AWS CDK applications, combining constructs to define how your AWS resources are connected\. + +### Make decisions at synthesis time + +Although AWS CloudFormation lets you make decisions at deployment time \(using `Conditions`, `{ Fn::If }`, and `Parameters`\), and the AWS CDK gives you some access to these mechanisms, we recommend against using them\. The types of values you can use, and the types of operations you can perform on them, are quite limited\. + +Instead, try to make all decisions, such as which construct to instantiate, in your AWS CDK application, using your programming language's `if` statements and other features\. For example, a common CDK idiom, iterating over a list and instantiating a construct with values from each item in the list, simply isn't possible using AWS CloudFormation expressions\. + +Treat AWS CloudFormation as an implementation detail that the AWS CDK uses for robust cloud deployments, not as a language target\. You're not writing AWS CloudFormation templates in TypeScript or Python, you're writing CDK code that happens to use CloudFormation for deployment\. + +### Use generated resource names, not physical names + +Names are a precious resource\. Every name can only be used once, so if you hard\-code a table name or bucket name into your infrastructure and application, you can't deploy that piece of infrastructure twice in the same account\. \(The name we're talking about here is the name specified by, for example, the `bucketName` property on an Amazon S3 bucket construct\.\) + +What's worse, you can't make changes to the resource that require it to be replaced\. If a property can only be set at resource creation, for example the `KeySchema` of an Amazon DynamoDB table, that property is immutable, and changing it requires a new resource\. But the new resource must have the same name in order to be a true replacement, and it can't, because the existing resource is still using that name\. + +A better approach is to specify as few names as possible\. If you leave out resource names, the AWS CDK will generate them for you, and it'll do so in a way that won't cause these problems\. You then, for example, pass the generated table name \(which you can reference as `table.tableName` in your AWS CDK application\) as an environment variable into your AWS Lambda function, or you generate a configuration file on your Amazon EC2 instance on startup, or you write the actual table name to AWS Systems Manager Parameter Store and your application reads it from there\. It's like dependency injection, but for resources\. + +### Separate your application into multiple stacks as dictated by deployment requirements + +There is no hard and fast rule to how many stacks your application needs\. You'll usually end up basing the decision on your deployment patterns\. Keep in mind the following guidelines: ++ It's typically easier to keep as many resources in the same stack as possible, so keep them together unless you know you want them separated\. ++ Consider keeping stateful resources \(like databases\) in a separate stack from stateless resources\. You can then turn on termination protection on the stateful stack, and can freely destroy or create multiple copies of the stateless stack without risk of data loss\. ++ Stateful resources are more sensitive to construct renaming—renaming leads to resource replacement—so it makes sense not to nest them inside constructs that are likely to be moved around or renamed \(unless the state can be rebuilt if lost, like a cache\)\. This is another good reason to put stateful resources in their own stack\. + +### Keep synthesis deterministic and commit `cdk.context.json` + +In general, don't put network access code, or any other code that is sensitive to the synthesis environment, in your AWS CDK app\. Apart from the possibility of that call failing at an inopportune time, what's worse is that it's non\-deterministic—it may return a different answer every time\. This means your stack could be different every time you synthesize it, which makes it harder to test your code and to roll your infrastructure back to a previous state\. + +The AWS CDK includes features that use network access to look up information during synthesis\. The AWS CDK caches the results of these lookups in the file `cdk.context.json`, which you should commit to version control along with the rest of your app\. The result of that lookup is thereby "locked in" until you explicitly change it, allowing you to get exactly the same result each time you synthesize\. \(See [Runtime context](context.md)\.\) A couple of examples of where this happens \(and the possible consequences of not committing the cache\) are: ++ If you provision an Amazon VPC to all available Availability Zones in a specified region, which is two on deployment day, your IP space gets split in two\. If AWS launches a new Availability Zone the next day, the next deployment tries to split your IP space in three, requiring all subnets to be recreated; this probably won't be possible because instances are still running, and you'll have to clean up manually\. ++ If you query for the latest Amazon Linux machine image and deploy an Amazon EC2 instance, and the next day a new image is released, the deployment the day after picks up the new AMI and replaces all your instances\. This may not be what you expected to happen\. + + Use the same approach if you must use information from outside your app\. For example, write an external script to gather the information and write it to a file, execute the script once, and commit the resulting file \(and the script that created it\)\. Then read that file in your AWS CDK app\. When you want to update this information, do so explicitly by running the script again\. + +### Let the AWS CDK manage roles and security groups + +One of the great features of the AWS CDK construct library is the `grant()` convenience methods that allow quick and simple creation of AWS Identity and Access Management roles granting access to one resource by another using minimally\-scoped permissions\. For example, consider a line like the following: + +``` +myBucket.grantRead(myLambda) +``` + +This single line results in a policy being added to the Lambda function's role \(which is also created for you\)\. That role and its policies are more than a dozen lines of CloudFormation that you don't have to write, and the AWS CDK grants only the minimal permissions required for the function to read from the bucket\. + +If you require developers to always use predefined roles that were created by a security team, AWS CDK coding becomes much more complicated, and your teams lose a lot of flexibility in how they design their applications\. A better alternative is to use [service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) and [permission boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to ensure that developers stay within the guardrails\. + +### Model all production stages in code + + In traditional AWS CloudFormation scenarios, your goal is to produce a single artifact that is parameterized so that it can be deployed to various target environments after applying configuration values specific to those environments\. In the CDK, you can, and should, build that configuration right into your source code\. Create a stack for your production environment, and a separate one for each of your other stages, and put the configuration values for each right there in the code\. Use services like [Secrets Manager](https://aws.amazon.com/secrets-manager/) and [Systems Manager](https://aws.amazon.com/systems-manager/) Parameter Store for sensitive values that you don't want to check in to source control, using the names or ARNs of those resources\. + + When you synthesize your application, the cloud assembly created in the `cdk.out` folder contains a separate template for each environment\. Your entire build is deterministic: there are no out\-of\-band changes to your application, and any given commit always yields the exact same AWS CloudFormation template and accompanying assets, which makes unit testing much more reliable\. + +### Measure everything + +Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html) class\. \ No newline at end of file From be24b0c6e8e84800955517f94896cc4e279b5f5a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 10 Jun 2021 00:51:58 +0000 Subject: [PATCH 414/655] various minor updates and some churn --- doc_source/bootstrapping.md | 4 ++-- doc_source/cli.md | 28 ++++++++++++++-------------- doc_source/index.md | 1 + doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-v2.md | 4 ++-- 6 files changed, 21 insertions(+), 20 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index a42ab8f2..8b26164b 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -12,7 +12,7 @@ The required resources are defined in a AWS CloudFormation stack, called the *bo The AWS CDK supports two bootstrap templates\. At this writing, the AWS CDK is transitioning from one of these templates to the other, but the original template \(dubbed "legacy"\) is still the default\. The newer template \("modern"\) is required by CDK Pipelines today, and will become the default at some point in the future\. For details, see [Bootstrapping templates](#bootstrapping-templates)\. **Important** -The modern bootstrap template grants the bootstrapping account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. +The modern bootstrap template grants the bootstrapped account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. Environments are independent, so if you want to deploy to multiple environments \(different AWS accounts or different regions in the same account\), each environment must be bootstrapped separately\. @@ -108,7 +108,7 @@ The main differences between the templates are as follows\. \* *We will add additional resources to the modern template as needed\.* **Important** -The modern bootstrap template grants the bootstrapping account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. +The modern bootstrap template grants the bootstrapped account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. At some point in the future, the modern template will become the default bootstrapping template\. Until then, manually select the modern template when bootstrapping by setting the `CDK_NEW_BOOTSTRAP` environment variable\. diff --git a/doc_source/cli.md b/doc_source/cli.md index 2513f164..8346d808 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -271,7 +271,7 @@ Older versions of the modern template created a Customer Master Key by default\. The AWS CDK Toolkit supports two bootstrap templates: the modern template and the legacy template\. The legacy template is the default, but the modern template is required by CDK Pipelines\. For more inforamtion, see [Bootstrapping](bootstrapping.md)\. **Important** -The modern bootstrap template grants the bootstrapping account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](bootstrapping.md#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. +The modern bootstrap template grants the bootstrapped account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](bootstrapping.md#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. ## Creating a new app @@ -335,7 +335,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -354,7 +354,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -362,7 +362,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -386,7 +386,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -408,7 +408,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -625,7 +625,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -638,7 +638,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -654,7 +654,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -723,7 +723,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -776,7 +776,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -795,7 +795,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -815,7 +815,7 @@ Options: with [string] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -837,7 +837,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/index.md b/doc_source/index.md index ed77e4a5..71e1d412 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -43,6 +43,7 @@ Amazon's trademarks and trade dress may not be used in + [Aspects](aspects.md) + [Escape hatches](cfn_layer.md) + [Bootstrapping](bootstrapping.md) ++ [Best practices for developing and deploying cloud infrastructure with the AWS CDK](best-practices.md) + [API reference](reference.md) + [Examples](examples.md) + [Creating a serverless application using the AWS CDK](serverless_example.md) diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 0d21f033..3b353160 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 623c3383..d949ab19 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index 0871977d..d6aad29d 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -15,7 +15,7 @@ The main changes in CDK v2 are: + CDK v2 requires that the environments you deploy into be boostrapped using the modern bootstrap stack; the legacy stack is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. Simply re\-bootstrap the affected environments to upgrade them\. It is not necessary to set any feature flags or environment variables to specify the modern bootstrap stack\. **Important** -The modern bootstrap template grants the bootstrapping account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](bootstrapping.md#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. +The modern bootstrap template grants the bootstrapped account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](bootstrapping.md#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. Aside from this topic, the AWS CDK Developer Guide describes CDK v1\.x\. Most of the information in the Guide still applies in CDK v2, or can be adapted with only minor changes\. A v2 Developer Guide will be available at General Availability \(GA\) of CDK v2\. A version of the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) is available for CDK v2\. @@ -29,7 +29,7 @@ Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prereq To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. -### Updating `cdk.json` +### Updating `cdk.json` Remove all feature flags from `cdk.json`\. You can add one or more of the three flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these are needed\. From 5e80de776c97d924e050b122e766aea6bb03263b Mon Sep 17 00:00:00 2001 From: John Culkin Date: Sat, 12 Jun 2021 09:35:51 -0400 Subject: [PATCH 415/655] Comma added to install_requires A Comma needed to be added to the end of the install_requires list. This allows for easy copy/pasting --- doc_source/work-with-cdk-v2.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index d6aad29d..39f16763 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -135,7 +135,7 @@ install_requires=[ "aws-cdk-lib>=2.0.0rc1", "constructs>=10.0.0", # ... -] +], ``` Install the new dependencies with `pip install -r requirements.txt`\. @@ -239,4 +239,4 @@ Before deploying your app, use `cdk diff` to check for unexpected changes to its If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. **Typescript `'from' expected` or `';' expected` error in imports** -Upgrade to TypeScript 3\.8 or later\. \ No newline at end of file +Upgrade to TypeScript 3\.8 or later\. From a69bc5ffd5db72747926522c144ebdc1180e29bc Mon Sep 17 00:00:00 2001 From: Ben McCown <78867981+ben-mccown@users.noreply.github.com> Date: Mon, 21 Jun 2021 15:12:15 -0500 Subject: [PATCH 416/655] Resolving Windows file encoding issues --- doc_source/bootstrapping.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 8b26164b..88cf696f 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -67,10 +67,22 @@ cdk bootstrap --profile prod AWS CDK bootstrapping is performed by an AWS CloudFormation template\. To get a copy of this template in the file `bootstrap-template.yaml`, run the following command\. +------ +#### [ macOS/Linux ] + ``` cdk bootstrap --show-template > bootstrap-template.yaml ``` +------ +#### [ Windows ] + +``` +cdk bootstrap --show-template | Out-File -encoding utf8 bootstrap-template.yaml +``` + +------ + The template is also available in the [AWS CDK GitHub repository](https://github.com/aws/aws-cdk/blob/master/packages/aws-cdk/lib/api/bootstrap/bootstrap-template.yaml)\. Deploy this template using your preferred deployment mechanism for AWS CloudFormation templates\. For example, the following command deploys the template using the AWS CLI: @@ -547,4 +559,4 @@ The `DefaultStackSynthesizer` requires four IAM roles for four different purpose The AWS CDK Toolkit requires that the following CloudFormation outputs exist on the bootstrap stack\. + `BucketName`: the name of the file asset bucket + `BucketDomainName`: the file asset bucket in domain name format -+ `BootstrapVersion`: the current version of the bootstrap stack \ No newline at end of file ++ `BootstrapVersion`: the current version of the bootstrap stack From 3ec827c05d3f34abb6699d09cd787a99cdfb621d Mon Sep 17 00:00:00 2001 From: Ben McCown <78867981+ben-mccown@users.noreply.github.com> Date: Mon, 28 Jun 2021 16:48:23 -0500 Subject: [PATCH 417/655] Allowing compatibility with regular cmd.exe --- doc_source/bootstrapping.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 88cf696f..95abd5db 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -78,7 +78,7 @@ cdk bootstrap --show-template > bootstrap-template.yaml #### [ Windows ] ``` -cdk bootstrap --show-template | Out-File -encoding utf8 bootstrap-template.yaml +powershell "cdk bootstrap --show-template | Out-File -encoding utf8 bootstrap-template.yaml" ``` ------ From 928da3208543830bf9dd20db9ae3260d2a90538d Mon Sep 17 00:00:00 2001 From: James Date: Tue, 6 Jul 2021 21:59:55 +0100 Subject: [PATCH 418/655] Core construct does not take a third parameter Corrected examples in line with: - https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html - https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.core/Construct.html --- doc_source/constructs.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 9f91d4de..48917055 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -832,7 +832,7 @@ export class NotifyingBucket extends Construct { public readonly topic: sns.Topic; constructor(scope: Construct, id: string, props: NotifyingBucketProps) { - super(scope, id, props); + super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); this.topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(new s3notify.SnsDestination(this.topic), { prefix: props.prefix }); @@ -847,7 +847,7 @@ export class NotifyingBucket extends Construct { class NotifyingBucket extends Construct { constructor(scope, id, props) { - super(scope, id, props); + super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); this.topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(new s3notify.SnsDestination(this.topic), { prefix: props.prefix }); @@ -864,7 +864,7 @@ module.exports = { NotifyingBucket } class NotifyingBucket(core.Construct): def __init__(self, scope: core.Construct, id: str, *, prefix=None, **kwargs): - super().__init__(scope, id, **kwargs) + super().__init__(scope, id) bucket = s3.Bucket(self, "bucket") self.topic = sns.Topic(self, "topic") bucket.add_object_created_notification(s3notify.SnsDestination(self.topic), @@ -1002,4 +1002,4 @@ The construct tree is separate from the constructs you define in your AWS CDK co The construct tree defines an implicit order in which constructs are synthesized to resources in the final AWS CloudFormation template\. Where one resource must be created before another, AWS CloudFormation or the AWS Construct Library will generally infer the dependency and make sure the resources are created in the right order\. You can also add an explicit dependency between two nodes using `node.addDependency()`; see [Dependencies](https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html#dependencies) in the AWS CDK API Reference\. -The AWS CDK provides a simple way to visit every node in the construct tree and perform an operation on each one\. See [Aspects](aspects.md)\. \ No newline at end of file +The AWS CDK provides a simple way to visit every node in the construct tree and perform an operation on each one\. See [Aspects](aspects.md)\. From 24d69f350e9a5ef2b70462576170ea034a3a41db Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 15 Jul 2021 18:29:37 +0000 Subject: [PATCH 419/655] bootstrapping updates, cfn public registry, tweaks --- doc_source/bootstrapping.md | 8 +- doc_source/cdk_pipeline.md | 8 +- doc_source/cli.md | 57 ++++++++----- doc_source/codepipeline_example.md | 2 +- doc_source/getting_started.md | 20 ++++- doc_source/hello_world.md | 2 +- doc_source/index.md | 1 + doc_source/serverless_example.md | 2 +- doc_source/stacks.md | 2 +- doc_source/tagging.md | 2 +- doc_source/troubleshooting.md | 6 +- doc_source/use_cfn_public_registry.md | 112 ++++++++++++++++++++++++++ doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-v2.md | 4 +- 14 files changed, 187 insertions(+), 41 deletions(-) create mode 100644 doc_source/use_cfn_public_registry.md diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 8b26164b..b90ef8ea 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -117,7 +117,7 @@ At some point in the future, the modern template will become the default bootstr ``` export CDK_NEW_BOOTSTRAP=1 -cdk bootstrap +cdk bootstrap aws://ACCOUNT-NUMBER/REGION ``` ------ @@ -125,7 +125,7 @@ cdk bootstrap ``` set CDK_NEW_BOOTSTRAP=1 -cdk bootstrap +cdk bootstrap aws://ACCOUNT-NUMBER/REGION ``` ------ @@ -144,7 +144,7 @@ The modern template is also selected when you issue cdk bootstrap in an AWS CDK **Tip** We recommend always setting `CDK_NEW_BOOTSTRAP` when you want to bootstrap using the modern template\. The context key is supported to make sure you bootstrap correctly if your app uses the `DefaultStackSynthesizer`, but relies on you being in an app's directory when bootstrapping\. -These two ways to specify the modern template also apply to `cdk bootstrap --show-template`, which will display the modern template if one or the other of these flags is present\. +These two ways to specify the modern template also apply to `cdk bootstrap --show-template`, which will display the modern template if either of these flags is present\. If the environment you are bootstrapping with the modern template has already been bootstrapped with the legacy template, the environment is upgraded to the modern template\. The Amazon S3 bucket from the legacy stack is orphaned in the process\. Re\-deploy all AWS CDK applications in the environment at least once before deleting the legacy bucket\. @@ -154,7 +154,7 @@ There are two ways to customize the bootstrapping resources\. + Use command\-line parameters with the `cdk bootstrap` command\. This lets you modify a few aspects of the template\. + Modify the default bootstrap template and deploy it yourself\. This gives you unlimited control over the bootstrap resources\. -The following command\-line options, when used with CDK Toolkit's cdk bootstrap, provide commonly\-needed adjustments to the bootstrapping template\.\. +The following command\-line options, when used with CDK Toolkit's cdk bootstrap, provide commonly\-needed adjustments to the bootstrapping template\. + \-\-bootstrap\-bucket\-name overrides the name of the Amazon S3 bucket\. May require changes to your CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + \-\-bootstrap\-kms\-key\-id overrides the AWS KMS key used to encrypt the S3 bucket\. + \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 521f249a..44bcbe47 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -31,7 +31,7 @@ You may omit the \-\-profile option if your default AWS profile contains the nec ``` export CDK_NEW_BOOTSTRAP=1 -npx cdk bootstrap --profile ADMIN-PROFILE \ +npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ aws://ACCOUNT-ID/REGION ``` @@ -41,7 +41,7 @@ npx cdk bootstrap --profile ADMIN-PROFILE \ ``` set CDK_NEW_BOOTSTRAP=1 -npx cdk bootstrap --profile ADMIN-PROFILE ^ +npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ aws://ACCOUNT-ID/REGION ``` @@ -57,7 +57,7 @@ Again, you may omit the \-\-profile option if your default AWS profile contains ``` export CDK_NEW_BOOTSTRAP=1 -npx cdk bootstrap --profile ADMIN-PROFILE \ +npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ --trust PIPELINE-ACCOUNT-ID \ aws://ACCOUNT-ID/REGION @@ -68,7 +68,7 @@ npx cdk bootstrap --profile ADMIN-PROFILE \ ``` set CDK_NEW_BOOTSTRAP=1 -npx cdk bootstrap --profile ADMIN-PROFILE ^ +npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ --trust PIPELINE-ACCOUNT-ID ^ aws://ACCOUNT-ID/REGION diff --git a/doc_source/cli.md b/doc_source/cli.md index 8346d808..5ae81de7 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -21,7 +21,7 @@ All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(` | --- | --- | | `cdk list` \(`ls`\) | Lists the stacks in the app | | `cdk synthesize` \(`synth`\) | Synthesizes and prints the CloudFormation template for the specified stack\(s\) | -| `cdk bootstrap` | Deploys the CDK Toolkit stack; see [Bootstrapping](bootstrapping.md) | +| `cdk bootstrap` | Deploys the CDK Toolkit staging stack; see [Bootstrapping](bootstrapping.md) | | `cdk deploy` | Deploys the specified stack\(s\) | | `cdk destroy` | Destroys the specified stack\(s\) | | `cdk diff` | Compares the specified stack with the deployed stack or a local CloudFormation template | @@ -228,7 +228,7 @@ You may also use wildcards to specify IDs that match a pattern\. You may also use the \-\-all option to specify all stacks\. -If your app uses [CDK Pipelines](cdk_pipeline.md), the CDK Toolkit understands your stacks and stages as a hierorchy, and the \-\-all option and the `*` wildcard only match top\-level stacks\. To match all the stacks, use `**`\. Also use `**` to indicate all the stacks under a particular hierarchy\. +If your app uses [CDK Pipelines](cdk_pipeline.md), the CDK Toolkit understands your stacks and stages as a hierarchy, and the \-\-all option and the `*` wildcard only match top\-level stacks\. To match all the stacks, use `**`\. Also use `**` to indicate all the stacks under a particular hierarchy\. When using wildcards, enclose the pattern in quotes, or escape the wildcards with `\`\. If you don't, your shell may try to expand the pattern to the names of files in the current directory\. At best, this won't do what you expect; at worst, you could deploy stacks you didn't intend to\. This isn't strictly necessary on Windows because `cmd.exe` does not expand wildcards, but is good practice nonetheless\. @@ -248,11 +248,12 @@ The order in which you specify the stacks is not necessarily the order in which Deploying stacks that contain [assets](assets.md), synthesize to large templates, or use [CDK Pipelines](cdk_pipeline.md) require special dedicated AWS CDK resources to be provisioned\. The `cdk bootstrap` command creates the necessary resources for you\. You only need to bootstrap if you are deploying a stack that requires these dedicated resources\. See [Bootstrapping](bootstrapping.md) for details\. ``` -cdk bootstrap # bootstraps default account/region -cdk bootstrap --profile test # bootstraps test environment +cdk bootstrap ``` -You may also bootstrap a specific environment\. Credentials must be configured \(e\.g\. in `~/.aws/credentials`\) for the specified account and region\. You may specify a profile that contains the required credentials\. +If issued with no arguments, as shown here, the `cdk bootstrap` command synthesizes the current app and bootstraps the environments its stacks will be deployed to\. If the app contains environment\-agnostic stacks, which do not explicitly specify an environment so they can be deployed anywhere, the default account and region are bootstrapped, or the environment specified using `--profile`\. + +Outside of an app, you must explicitly specify the environment to be bootstrapped\. You may also do so to bootstrap an environment that's not specified in your app or local AWS profile\. Credentials must be configured \(e\.g\. in `~/.aws/credentials`\) for the specified account and region\. You may specify a profile that contains the required credentials\. ``` cdk bootstrap ACCOUNT-NUMBER/REGION # e.g. @@ -268,7 +269,7 @@ You may incur AWS charges for what the AWS CDK stores in the bootstrapped resour **Note** Older versions of the modern template created a Customer Master Key by default\. To avoid charges, re\-bootstrap using `--no-bootstrap-customer-key`\. -The AWS CDK Toolkit supports two bootstrap templates: the modern template and the legacy template\. The legacy template is the default, but the modern template is required by CDK Pipelines\. For more inforamtion, see [Bootstrapping](bootstrapping.md)\. +The AWS CDK Toolkit supports two bootstrap templates: the modern template and the legacy template\. The legacy template is the default, but the modern template is required by CDK Pipelines\. For more information, see [Bootstrapping](bootstrapping.md)\. **Important** The modern bootstrap template grants the bootstrapped account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](bootstrapping.md#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. @@ -335,7 +336,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -354,7 +355,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -362,7 +363,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -386,7 +387,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -408,7 +409,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -593,7 +594,7 @@ Options: [boolean] [default: true] --asset-metadata Include "aws:asset:*" CloudFormation metadata for - resources that user assets (enabled by default) + resources that uses assets (enabled by default) [boolean] [default: true] -r, --role-arn ARN of Role to use when invoking CloudFormation @@ -625,7 +626,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -638,7 +639,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -650,11 +651,16 @@ Options: -e, --exclusively Only synthesize requested stacks, don't include dependencies [boolean] + --validation After synthesis, validate stacks with the + "validateOnSynth" attribute set (can also be + controlled with CDK_VALIDATION) + [boolean] [default: true] + -q, --quiet Do not output CloudFormation Template to stdout [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -696,6 +702,12 @@ Options: modern bootstrapping only) [array] [default: []] + --trust-for-lookup The AWS account IDs that should be + trusted to look up values in this + environment (may be repeated, modern + bootstrapping only) + [array] [default: []] + --cloudformation-execution-policies The Managed Policy ARNs that should be attached to the role performing deployments into this environment @@ -723,7 +735,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -776,7 +788,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -795,7 +807,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -812,10 +824,13 @@ Options: diff rendering [number] [default: 3] --template The path to the CloudFormation template to compare - with [string] + with [string] + + --security-only Only diff for broadened security changes + [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -837,7 +852,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md index 7d4d4368..d245aaee 100644 --- a/doc_source/codepipeline_example.md +++ b/doc_source/codepipeline_example.md @@ -18,7 +18,7 @@ Beyond having the AWS CDK set up and configured, your workstation needs to be ab You can also use the `git-remote-codecommit` Git add\-on or other methods of connecting and authenticating [supported by CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up.html)\. -Also, make sure you have issued `cdk bootstrap`, as the Amazon S3 bucket in the bootstrap stack is required to deploy a Lambda function with the AWS CDK\. +Also, make sure you have issued `cdk bootstrap aws://ACCOUNT-NUMBER/REGION`, as the Amazon S3 bucket in the bootstrap stack is required to deploy a Lambda function with the AWS CDK\. ## Setting up the project diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index dc610365..ca5c8cf0 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -204,7 +204,25 @@ cdk --version Many AWS CDK stacks that you write will include [assets](assets.md): external files that are deployed with the stack, such as AWS Lambda functions Docker images\. The AWS CDK uploads these to an Amazon S3 bucket or other container so they are available to AWS CloudFormation during deployment\. Deployment requires that these containers already exist in the account and region you are deploying into\. Creating them is called [bootstrapping](bootstrapping.md)\. To bootstrap, issue: ``` -cdk bootstrap +cdk bootstrap aws://ACCOUNT-NUMBER/REGION +``` + +**Tip** +If you don't have your AWS account number handy, you can get it from the AWS Management Console\. Or, if you have the AWS CLI installed, the following command displays your default account information, including the account number\. + +``` +aws sts get-caller-identity +``` +If you have created named profiles in your local AWS configuration, you can use the `--profile` option to display the account information for a specific profile's account, such as the *prod* profile as shown here\. + +``` +aws sts get-caller-identity --profile prod +``` +To display the default region, use `aws configure get`\. + +``` +aws configure get region +aws configure get region --profile prod ``` ## AWS CDK tools diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 1dce01e4..1d298982 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -528,7 +528,7 @@ It's informative to compare the output of cdk synth here with the previous outpu Since the `autoDeleteObjects` property is implemented using a AWS CloudFormation custom resource, which is implemented using an AWS Lambda function, our stack contains an [asset](assets.md)\. This fact requires that our AWS account and region be [bootstrapped](bootstrapping.md) so that there's an Amazon S3 bucket to hold the asset during deployment\. If you haven't already bootstrapped, issue: ``` -cdk bootstrap +cdk bootstrap aws://ACCOUNT-NUMBER/REGION ``` Now let's deploy\. diff --git a/doc_source/index.md b/doc_source/index.md index 71e1d412..412f1d2a 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -54,6 +54,7 @@ Amazon's trademarks and trade dress may not be used in + [Get a value from an environment variable](get_env_var.md) + [Use an AWS CloudFormation parameter](get_cfn_param.md) + [Import or migrate an existing AWS CloudFormation template](use_cfn_template.md) + + [Using resources from the AWS CloudFormation Public Registry](use_cfn_public_registry.md) + [Get a value from the Systems Manager Parameter Store](get_ssm_value.md) + [Get a value from AWS Secrets Manager](get_secrets_manager_value.md) + [Create an app with multiple stacks](stack_how_to_create_multiple_stacks.md) diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 6738ce91..86902758 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -594,7 +594,7 @@ cdk synth Before you can deploy your first AWS CDK app containing a lambda function, you must bootstrap your AWS environment\. This creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see [Bootstrapping your AWS environment](cli.md#cli-bootstrap)\. If you've already bootstrapped, you'll get a warning and nothing will change\. ``` -cdk bootstrap +cdk bootstrap aws://ACCOUNT-NUMBER/REGION ``` Now we're ready to deploy the app as follows\. diff --git a/doc_source/stacks.md b/doc_source/stacks.md index 6eb5308d..e3e51146 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -361,7 +361,7 @@ The [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack ## Nested stacks -The [NestedStack](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudformation.NestedStack.html) construct offers a way around the AWS CloudFormation 500\-resource limit for stacks\. A nested stack counts as only one resource in the stack that contains it, but can itself contain up to 500 resources, including additional nested stacks\. +The [NestedStack](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.NestedStack.html) construct offers a way around the AWS CloudFormation 500\-resource limit for stacks\. A nested stack counts as only one resource in the stack that contains it, but can itself contain up to 500 resources, including additional nested stacks\. The scope of a nested stack must be a `Stack` or `NestedStack` construct\. The nested stack needn't be declared lexically inside its parent stack; it is necessary only to pass the parent stack as the first parameter \(`scope`\) when instantiating the nested stack\. Aside from this restriction, defining constructs in a nested stack works exactly the same as in an ordinary stack\. diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 3b353160..fa44cd66 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index 3c106347..d2971700 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -158,15 +158,15 @@ alias cdk=npx cdk Your AWS environment does not have a staging bucket, which the AWS CDK uses to hold resources during deployment\. Stacks require this bucket if they contain [Assets](assets.md) or synthesize to AWS CloudFormation templates larger than 50 kilobytes\. You can create the staging bucket with the following command: ``` -cdk bootstrap +cdk bootstrap aws://ACCOUNT-NUMBER/REGION ``` To avoid generating unexpected AWS charges, the AWS CDK does not automatically create a staging bucket\. You must bootstrap your environment explicitly\. -By default, the staging bucket is created in the region specified by the default AWS profile \(set by `aws configure`\), using that profile's account\. You can specify a different account and region on the command line as follows\. +By default, the staging bucket is created in the region\(s\) used by stacks in the current AWS CDK application, or the region specified in your local AWS profile \(set by `aws configure`\), using that profile's account\. You can specify a different account and region on the command line as follows\. \(You must specify the account and region if you are not in an app's directory\.\) ``` -cdk bootstrap aws://123456789/us-east-1 +cdk bootstrap aws://ACCOUNT-NUMBER/REGION ``` You must bootstrap in every region where you will deploy stacks that require a staging bucket\. diff --git a/doc_source/use_cfn_public_registry.md b/doc_source/use_cfn_public_registry.md new file mode 100644 index 00000000..297197d1 --- /dev/null +++ b/doc_source/use_cfn_public_registry.md @@ -0,0 +1,112 @@ +# Using resources from the AWS CloudFormation Public Registry + + The AWS CloudFormation Public Registry is a collection of AWS CloudFormation extensions from both AWS and third parties that are available for use by all AWS customers\. You can also publish your own extension for others to use\. Extensions are of two types: resources and modules\. You can use public resource extensions in your AWS CDK app using the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html) construct\. + +All public extensions published by AWS are available to all accounts in all regions without any action on your part\. On the other hand, you must activate each third\-party extension you want to use, in each account and region where you want to use it\. + +**Note** +When you use AWS CloudFormation with third\-party resource types, you will incur charges based on the number of handler operations you run per month and handler operation duration\. See [CloudFormation pricing](http://aws.amazon.com/cloudformation/pricing/) for complete details\. + +See [Using public extensions in CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry-public.html) for complete documentation of this feature from the AWS CloudFormation side\. + +## Activating a third\-party resource in your account and region + +Extensions published by AWS do not require activation; they are always available in every account and region\. You can activate a third\-party extension through the AWS Management Console, via the AWS Command Line Interface, or by deploying a special AWS CloudFormation resource\. + +To activate a third\-party extension through the AWS Management Console, or to simply see what resources are available, follow these steps\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/activate-cfn-extension.png) + +1. Log in to the AWS account in which you want to use the extension, then switch to the region where you want to use it\. + +1. Navigate to the CloudFormation console via the **Services** menu\. + +1. Click **Public extensions** on the navigation bar, then activate the **Third party** radio button under **Publisher**\. A list of the available third\-party public extensions appears\. \(You may also choose **AWS** to see a list of the public extensions published by AWS, though you don't need to activate them\.\) + +1. Browse the list and find the extension you want to activate, or search for it, then activate the radio button in the upper right corner of the extension's card\. + +1. Click the **Activate** button at the top of the list to activate the selected extension\. The extension's **Activate** page appears\. + +1. In the **Activate** page, you may override the extension's default name, specify an execution role and logging configuration, and choose whether to automatically update the extension when a new version is released\. When you have set these options as you like, click **Activate extension** at the bottom of the page\. + +To activate a third\-party extension using the AWS CLI, use the `activate-type `command, substituting the ARN of the custom type you want to use for the one given\. + +``` +aws cloudformation activate-type --public-type-arn public_extension_ARN --auto-update-activated +``` + +To activate an extension through CloudFormation or the CDK, deploy a resource of type `AWS::CloudFormation::TypeActivation`, specifying the following properties\. ++ `TypeName` \- The name of the type, such as `AWSQS::EKS::Cluster`\. ++ `MajorVersion` \- The major version number of the extension that you want; omit if you want the latest version\. ++ `AutoUpdate` \- Whether to automatically update this extension when a new minor version is released by the publisher\. \(Major version updates require explicitly changing the `MajorVersion` property\.\) ++ `ExecutionRoleArn` \- The ARN of the IAM role under which this extension will run\. ++ `LoggingConfig` \- The logging configuration for the extension\. + +The `TypeActivation` resource can be deployed by the CDK using the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html) construct, as shown below for the actual etxensions\. + +## Adding a resource from the AWS CloudFormation Public Registry to your CDK app + + Use the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html) construct to include a resource from the AWS CloudFormation Public Registry in your application\. This construct is in the CDK's `core` module\. + +For example, suppose there is a public resource named `MY::S5::UltimateBucket` that you want to use in your AWS CDK application\. This resource takes one property: the bucket name\. The corresponding `CfnResource` instantiation looks like this\. + +------ +#### [ TypeScript ] + +``` +const ubucket = new CfnResource(this, 'MyUltimateBucket', { + type: 'MY::S5::UltimateBucket::MODULE', + properties: { + BucketName: 'UltimateBucket' + } +}); +``` + +------ +#### [ JavaScript ] + +``` +const ubucket = new CfnResource(this, 'MyUltimateBucket', { + type: 'MY::S5::UltimateBucket::MODULE', + properties: { + BucketName: 'UltimateBucket' + } +}); +``` + +------ +#### [ Python ] + +``` +ubucket = CfnResource(self, "MyUltimateBucket", + type="MY::S5::UltimateBucket::MODULE", + properties=dict( + BucketName="UltimateBucket")) +``` + +------ +#### [ Java ] + +``` +CfnResource.Builder.create(this, "MyUltimateBucket") + .type("MY::S5::UltimateBucket::MODULE") + .properties(new HashMap() {{ + put("BucketName", "UltimateBucket"); + }}); +``` + +------ +#### [ C\# ] + +``` +new CfnResource(this, "MyUltimateBucket", new CfnResourceProps +{ + Type = "MY::S5::UltimateBucket::MODULE", + Properties = new Dictionary + { + ["BucketName"] = "UltimateBucket" + } +}); +``` + +------ \ No newline at end of file diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index d949ab19..103022a9 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index 39f16763..eca04a79 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -29,7 +29,7 @@ Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prereq To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. -### Updating `cdk.json` +### Updating `cdk.json` Remove all feature flags from `cdk.json`\. You can add one or more of the three flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these are needed\. @@ -239,4 +239,4 @@ Before deploying your app, use `cdk diff` to check for unexpected changes to its If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. **Typescript `'from' expected` or `';' expected` error in imports** -Upgrade to TypeScript 3\.8 or later\. +Upgrade to TypeScript 3\.8 or later\. \ No newline at end of file From 0db68239bbfc386961eb8da5f927c28f936be941 Mon Sep 17 00:00:00 2001 From: Gurkan Nisanci Date: Mon, 19 Jul 2021 12:25:02 +0100 Subject: [PATCH 420/655] fix URL --- doc_source/best-practices.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md index 08096218..269ce8cc 100644 --- a/doc_source/best-practices.md +++ b/doc_source/best-practices.md @@ -88,7 +88,7 @@ Many enterprise customers are writing their own wrappers for L2 constructs \(the Instead, use AWS features such as [service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) and [permission boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to enforce your security guardrails at the organization level\. Use [Aspects](aspects.md) or tools like [CloudFormation Guard](https://github.com/aws-cloudformation/cloudformation-guard) to make assertions about the security properties of infrastructure elements before deployment\. Use AWS CDK for what it does best\. -Finally, keep in mind that writing your own "L2\+" constructs like these may prevent your developers from taking advantage of the growing ecosystems of AWS CDK packages, such as [AWS Solutions Constructs](https://docs.aws.amazon.com/https://docs.aws.amazon.com/solutions/latest/constructs/welcome.html), as these are typically based on standard AWS CDK constructs and won't be able to use your custom versions\. +Finally, keep in mind that writing your own "L2\+" constructs like these may prevent your developers from taking advantage of the growing ecosystems of AWS CDK packages, such as [AWS Solutions Constructs](https://docs.aws.amazon.com/solutions/latest/constructs/welcome.html), as these are typically based on standard AWS CDK constructs and won't be able to use your custom versions\. ## Application best practices @@ -147,4 +147,4 @@ If you require developers to always use predefined roles that were created by a ### Measure everything -Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html) class\. \ No newline at end of file +Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html) class\. From 666eb454e3a714f2bea4033ca16a281cf4112925 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Jul 2021 19:38:19 +0000 Subject: [PATCH 421/655] minor improvements --- doc_source/context.md | 12 ++++++------ doc_source/environments.md | 10 +++++++++- doc_source/resources.md | 2 +- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/doc_source/context.md b/doc_source/context.md index 999b38f4..1df30ae8 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -2,21 +2,21 @@ Context values are key\-value pairs that can be associated with a stack or construct\. The AWS CDK uses context to cache information from your AWS account, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs used to start your instances\. [Feature flags](featureflags.md) are also context values\. You can create your own context values for use by your apps or constructs\. -Context keys and values are strings\. If you want to pass other types of value, such as numbers but also including structured data such as JSON, it must be passed as a string\. Code that consumes such a context value will need to convert or parse the data as appropriate\. +Context keys are strings, and values may be any type supported by JSON: numbers, strings, arrays, or objects\. ## Construct context -Context values are made available to your AWS CDK app in six different ways: +Context values can be provided to your AWS CDK app in six different ways: + Automatically from the current AWS account\. -+ Through the \-\-context option to the cdk command\. ++ Through the \-\-context option to the cdk command\. \(These values are always strings\.\) + In the project's `cdk.context.json` file\. -+ In the project's `cdk.json` file\. ++ In the `context` key of the project's `cdk.json` file\. + In the `context` key of your `~/.cdk.json` file\. -+ In your AWS CDK app using the `construct.node.setContext` method\. ++ In your AWS CDK app using the `construct.node.setContext()` method\. The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, changing your Auto Scaling group\. The AWS CDK does not write context data to any of the other files listed\. -We recommend that your project's context files be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. It is also critical to successful automated deployment of stacks that rely on context values \(for example, using [CDK Pipelines](cdk_pipeline.md)\): since the deployment system won't have access to your AWS account, it will rely on the cached values in the context files\. +We recommend that your project's context files be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. It is also critical to successful automated deployment of stacks that rely on context values \(for example, using [CDK Pipelines](cdk_pipeline.md)\)\. Context values are scoped to the construct that created them; they are visible to child constructs, but not to siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), whether automatically, from a file, or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in the app\. diff --git a/doc_source/environments.md b/doc_source/environments.md index 57ea64ac..6c672ae6 100644 --- a/doc_source/environments.md +++ b/doc_source/environments.md @@ -5,7 +5,15 @@ Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated **Note** For all but the simplest deployments, you will need to [bootstrap](bootstrapping.md) each environment you will deploy into\. Deployment requires certain AWS resources to be available, and these resources are provisioned by bootstrapping\. -If you don't specify an environment when you define a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availabilityZones` \(Python: `availability_zones`\)\. +If you don't specify an environment when you instantiate a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availabilityZones` \(Python: `availability_zones`\)\. + +**Tip** +If you're using the standard AWS CDK development template, your stacks are instantiated in the same file where you instantiate the `App` object\. +The file named after your project \(for example, `hello-cdk.ts`\) in your project's `bin` folder\. +The file named after your project \(for example, `hello-cdk.js`\) in your project's `bin` folder\. +The file `app.py` in your project's main directory\. +The file named `ProjectNameApp.java`, for example `HelloCdkApp.java`, nested deep under the `src/main` directory\. +The file named `Program.cs` under `src\ProjectName`, for example `src\HelloCdk\Program.cs`\. In an environment\-agnostic stack, any constructs that use availability zones will see two of them, allowing the stack to be deployed to any region\. diff --git a/doc_source/resources.md b/doc_source/resources.md index 0f176cad..d764591f 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -531,7 +531,7 @@ ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { ``` # Construct a resource (bucket) just by its name (must be same account) -s3.Bucket.from__bucket_name(self, "MyBucket", "my-bucket-name") +s3.Bucket.from_bucket_name(self, "MyBucket", "my-bucket-name") # Construct a resource (bucket) by its full ARN (can be cross account) s3.Bucket.from_arn(self, "MyBucket", "arn:aws:s3:::my-bucket-name") From 3c1c904014776818383736900098dcea4f93ffac Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 22 Jul 2021 16:40:41 +0000 Subject: [PATCH 422/655] update windows template saving --- doc_source/bootstrapping.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 57aa43cf..fd2571ab 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -77,6 +77,8 @@ cdk bootstrap --show-template > bootstrap-template.yaml ------ #### [ Windows ] +On Windows, PowerShell must be used to preserve the encoding of the template\. + ``` powershell "cdk bootstrap --show-template | Out-File -encoding utf8 bootstrap-template.yaml" ``` @@ -85,7 +87,7 @@ powershell "cdk bootstrap --show-template | Out-File -encoding utf8 bootstrap-te The template is also available in the [AWS CDK GitHub repository](https://github.com/aws/aws-cdk/blob/master/packages/aws-cdk/lib/api/bootstrap/bootstrap-template.yaml)\. - Deploy this template using your preferred deployment mechanism for AWS CloudFormation templates\. For example, the following command deploys the template using the AWS CLI: +Deploy this template using your preferred deployment mechanism for AWS CloudFormation templates\. For example, the following command deploys the template using the AWS CLI: ------ #### [ macOS/Linux ] @@ -559,4 +561,4 @@ The `DefaultStackSynthesizer` requires four IAM roles for four different purpose The AWS CDK Toolkit requires that the following CloudFormation outputs exist on the bootstrap stack\. + `BucketName`: the name of the file asset bucket + `BucketDomainName`: the file asset bucket in domain name format -+ `BootstrapVersion`: the current version of the bootstrap stack ++ `BootstrapVersion`: the current version of the bootstrap stack \ No newline at end of file From f9445dc16aa67a9e8e0111ebdea8f438c2aca771 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 22 Jul 2021 16:41:03 +0000 Subject: [PATCH 423/655] update best practices to align with Well-Architected framework, and some noise --- doc_source/best-practices.md | 38 +++++++++++++++++++++++++--------- doc_source/cli.md | 26 +++++++++++------------ doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-v2.md | 2 +- 5 files changed, 44 insertions(+), 26 deletions(-) diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md index 269ce8cc..cc9b9eb2 100644 --- a/doc_source/best-practices.md +++ b/doc_source/best-practices.md @@ -1,14 +1,16 @@ # Best practices for developing and deploying cloud infrastructure with the AWS CDK -The AWS CDK allows developers or administrators to define their cloud infrastructure using a supported programming language\. CDK applications are organized into stages, stacks, and constructs, providing modular design capabilities in both runtime components \(such as AWS Lambda code or containerized services\) and infrastructure components\. For a more detailed introduction to the concepts behind the CDK, see [Getting started with the AWS CDK](getting_started.md)\. +The AWS CDK allows developers or administrators to define their cloud infrastructure using a supported programming language\. CDK applications should be organized into logical units, such as API, database, and monitoring resources, and optionally have a pipeline for automated deployments\. The logical units should be implemented as constructs including the infrastructure \(e\.g\. Amazon S3 buckets, Amazon RDS databases, Amazon VPC network\), runtime code \(e\.g\. AWS Lambda functions\), and configuration code\. Stacks define the deployment model of these logical units\. For a more detailed introduction to the concepts behind the CDK, see [Getting started with the AWS CDK](getting_started.md)\. The AWS CDK reflects careful consideration of the needs of our customers and internal teams and of the failure patterns that often arise during the deployment and ongoing maintenance of complex cloud applications\. We discovered that failures are often related to "out\-of\-band" changes to an application, such as configuration changes, that were not fully tested\. Therefore, we developed the AWS CDK around a model in which your entire application, not just business logic but also infrastructure and configuration, is defined in code\. That way, proposed changes can be carefully reviewed, comprehensively tested in environments resembling production to varying degrees, and fully rolled back if something goes wrong\. +In addition to the guidance in this document, you should also consider [best practices for AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html) as well as for the individual AWS services you use, where they are obviously applicable to CDK\-defined infrastructure\. + ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/all-in-one.jpg) -At deployment time, the AWS CDK synthesizes a cloud assembly that contains not only AWS CloudFormation templates describing your infrastructure in all target environments, but file assets containing your code and their supporting files\. With the CDK, every commit in your application's main version control branch can represent a complete, consistent, deployable version of your application\. Your application can then be deployed automatically whenever a change is made\. +At deployment time, the AWS CDK synthesizes a cloud assembly that contains not only AWS CloudFormation templates describing your infrastructure in all target environments, but file assets containing your runtime code and their supporting files\. With the CDK, every commit in your application's main version control branch can represent a complete, consistent, deployable version of your application\. Your application can then be deployed automatically whenever a change is made\. -The philosophy behind the AWS CDK leads to our recommended best practices, which we have divided into broad categories\. +The philosophy behind the AWS CDK leads to our recommended best practices, which we have divided into four broad categories\. + [Organization best practices](#best-practices-organization) + [Coding best practices](#best-practices-code) + [Construct best practices](#best-practices-constructs) @@ -18,9 +20,11 @@ The philosophy behind the AWS CDK leads to our recommended best practices, which In the beginning stages of AWS CDK adoption, it's important to consider how to set up your organization for success\. It's a best practice to have a team of experts responsible for training and guiding the rest of the company as they adopt the CDK The size of this team may vary, from one or two people at a small company to a full\-fledged Cloud Center of Excellence \(CCoE\) at a larger company\. This team is responsible for setting standards and policies for how cloud infrastructure will be done at your company, as well as for training and mentoring developers\. +The CCoE may provide guidance on what programming languages should be used for cloud infrastructure\. The details will vary from one organization to the next, but a good policy helps make sure developers can easily understand and maintain all cloud infrastructure throughout the company\. + The CCoE also creates a "landing zone" that defines your organizational units within AWS\. A landing zone is a pre\-configured, secure, scalable, multi\-account AWS environment based on best practice blueprints\. You can tie together the services that make up your landing zone with [AWS Control Tower](https://aws.amazon.com/controltower/), a high\-level service configures and manages your entire multi\-account system from a single user interface\. -Development teams should be able use their own accounts for testing and have the ability to deploy new resources in these accounts as needed\. Individual developers can treat these resources as extensions of their own development workstation\. Using [CDK Pipelines](cdk_pipeline.md), the AWS CDK applications can then be deployed via a shared services account to testing, integration, and production environments \(each isolated in its own AWS region and/or account\) by merging the developers' code into your organization's canonical repository\. +Development teams should be able use their own accounts for testing and have the ability to deploy new resources in these accounts as needed\. Individual developers can treat these resources as extensions of their own development workstation\. Using [CDK Pipelines](cdk_pipeline.md), the AWS CDK applications can then be deployed via a CI/CD account to testing, integration, and production environments \(each isolated in its own AWS region and/or account\) by merging the developers' code into your organization's canonical repository\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/best-practice-deploy-to-multiple-accounts.jpg) @@ -34,9 +38,17 @@ Development teams should be able use their own accounts for testing and have the The guiding principle for most of our best practices is to keep things simple as possible—but no simpler\. Add complexity only when your requirements dictate a more complicated solution\. With the AWS CDK, you can always refactor your code as necessary to support new requirements, so it doesn't make sense to architect for all possible scenarios up front\. +### Align with the AWS Well Architected Framework + +The [AWS Well\-Architected](http://aws.amazon.com/https://aws.amazon.com/architecture/well-architected/) framework defines a *component* as the code, configuration, and AWS resources that together deliver against a requirement\. A component is often the unit of technical ownership, and is decoupled from other components\. The term *workload* is used to identify a set of components that together deliver business value\. A workload is usually the level of detail that business and technology leaders communicate about\. + +An AWS CDK application maps to a component as defined by the AWS Well\-Architected Framework\. AWS CDK apps are a mechanism to codify and deliver Well\-Architected cloud application best practices\. You can also create and share components as reusable code libraries through artifact repositories, such as AWS CodeArtifact\. + ### Every application starts with a single package in a single repository - The entry point of your AWS CDK app should be a single package where you define the different components of your application \(infrastructure, code, and configuration\), as well as the CI/CD pipeline to deploy the application\. Use additional packages for constructs that you use in more than one application\. \(Shared constructs should also have their own lifecycle and testing strategy\.\) Dependencies between packages in the same repository are managed by your repo's build tooling\. +A single package is the entry point of your AWS CDK app\. This is where you define how and where the different logical units of your application are deployed, as well as the CI/CD pipeline to deploy the application\. The app's constructs define the logical units of your solution\. + +Use additional packages for constructs that you use in more than one application\. \(Shared constructs should also have their own lifecycle and testing strategy\.\) Dependencies between packages in the same repository are managed by your repo's build tooling\. Though it is possible, it is not recommended to put multiple applications in the same repository, especially when using automated deployment pipelines, because this increases the "blast radius" of changes during deployment\. With multiple applications in a repository, not only do changes to one application trigger deployment of the others \(even if they have not changed\), but a break in one application prevents the other applications from being deployed\. @@ -54,9 +66,9 @@ Shared packages need a different testing strategy: although for a single applica Keep in mind that a construct can be arbitrary simple or complex\. A `Bucket` is a construct, but `CameraShopWebsite` could be a construct, too\. -### Infrastructure and application code live in the same package +### Infrastructure and runtime code live in the same package -The AWS CDK not only generates AWS CloudFormation templates for deploying infrastructure, it also bundles assets like Lambda functions and Docker images and deploys them alongside your infrastructure\. So it's not only possible to combine the code that defines your infrastructure and the code that implements your business logic into a single construct— it's a best practice\. These two kinds of code don't need to live in separate repositories or even in separate packages\. +The AWS CDK not only generates AWS CloudFormation templates for deploying infrastructure, it also bundles runtime assets like Lambda functions and Docker images and deploys them alongside your infrastructure\. So it's not only possible to combine the code that defines your infrastructure and the code that implements your runtime logic into a single construct— it's a best practice\. These two kinds of code don't need to live in separate repositories or even in separate packages\. A construct that is self\-contained, in other words that completely describes a piece of functionality including its infrastructure and logic, makes it easy to evolve the two kinds of code together, test them in isolation, share and reuse the code across projects, and version all the code in sync\. @@ -66,11 +78,11 @@ A construct that is self\-contained, in other words that completely describes a ### Model your app through constructs, not stacks -When breaking down your application into units, represent each unit as a descendant of [https://docs.aws.amazon.com/cdk/api/latest/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/latest/docs/constructs.Construct.html) and not of [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html)\. Stacks are a unit of deployment, and so tend to be oriented to specific applications\. By using constructs instead of stacks, you give yourself and your users the flexibility to build stacks in the way that makes the most sense for each deployment scenario\. For example, you could compose multiple constructs into a `DevStack` with some configuration for development environments and then have a different composition for production\. +When breaking down your application into logical units, represent each unit as a descendant of [https://docs.aws.amazon.com/cdk/api/latest/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/latest/docs/constructs.Construct.html) and not of [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html)\. Stacks are a unit of deployment, and so tend to be oriented to specific applications\. By using constructs instead of stacks, you give yourself and your users the flexibility to build stacks in the way that makes the most sense for each deployment scenario\. For example, you could compose multiple constructs into a `DevStack` with some configuration for development environments and then have a different composition for your `ProdStack`\. ### Configure with properties and methods, not environment variables - Environment variable lookups inside constructs and stacks are a common anti\-pattern\. Both constructs and stacks should accept a properties object to allow for full configurability completely in code\. To do otherwise is to introduce a dependency on the machine that the code will run on, which becomes another bit of configuration information you have to keep track of and manage\. +Environment variable lookups inside constructs and stacks are a common anti\-pattern\. Both constructs and stacks should accept a properties object to allow for full configurability completely in code\. To do otherwise is to introduce a dependency on the machine that the code will run on, which becomes another bit of configuration information you have to keep track of and manage\. In general, environment variable lookups should be limited to the top level of an AWS CDK app, and should be used to pass in information needed for running in a development environment; see [Environments](environments.md)\. @@ -110,6 +122,12 @@ What's worse, you can't make changes to the resource that require it to be repla A better approach is to specify as few names as possible\. If you leave out resource names, the AWS CDK will generate them for you, and it'll do so in a way that won't cause these problems\. You then, for example, pass the generated table name \(which you can reference as `table.tableName` in your AWS CDK application\) as an environment variable into your AWS Lambda function, or you generate a configuration file on your Amazon EC2 instance on startup, or you write the actual table name to AWS Systems Manager Parameter Store and your application reads it from there\. It's like dependency injection, but for resources\. +### Define removal policies and log retention + +The AWS CDK does its best to keep you from losing data by defaulting to policies that retain everything you create\. For example, the default removal policy on resources that contain data \(such as Amazon S3 buckets and database tables\) is to never delete the resource when it is removed from the stack, but rather orphan the resource from the stack\. Similarly, the CDK's default is to retain all logs forever\. In production environments, these defaults can quickly result in the storage of large amounts of data you don't actually need, and a corresponding AWS bill\. + +Consider carefully what you want these policies to actually be for each production resource and specify them accordingly\. Use an [Aspects](aspects.md) to validate the removal and logging policies in your stack\. + ### Separate your application into multiple stacks as dictated by deployment requirements There is no hard and fast rule to how many stacks your application needs\. You'll usually end up basing the decision on your deployment patterns\. Keep in mind the following guidelines: @@ -147,4 +165,4 @@ If you require developers to always use predefined roles that were created by a ### Measure everything -Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html) class\. +Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html) class\. \ No newline at end of file diff --git a/doc_source/cli.md b/doc_source/cli.md index 5ae81de7..5f34b526 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -336,7 +336,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -355,7 +355,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -363,7 +363,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -387,7 +387,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -409,7 +409,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -626,7 +626,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -639,7 +639,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -660,7 +660,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -735,7 +735,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -788,7 +788,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -807,7 +807,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -830,7 +830,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -852,7 +852,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/tagging.md b/doc_source/tagging.md index fa44cd66..286527ad 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 103022a9..90060fa5 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index eca04a79..c587ff19 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -29,7 +29,7 @@ Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prereq To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. -### Updating `cdk.json` +### Updating `cdk.json` Remove all feature flags from `cdk.json`\. You can add one or more of the three flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these are needed\. From 37b29692d3f17be40421e5f00252adfae878d945 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 26 Jul 2021 18:23:47 +0000 Subject: [PATCH 424/655] bootstrapping roles and versions info, other changes --- doc_source/bootstrapping.md | 135 +++++++++++++++++++++++---------- doc_source/cli.md | 2 +- doc_source/work-with-cdk-v2.md | 2 +- 3 files changed, 99 insertions(+), 40 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index fd2571ab..337f000f 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -11,9 +11,6 @@ The required resources are defined in a AWS CloudFormation stack, called the *bo The AWS CDK supports two bootstrap templates\. At this writing, the AWS CDK is transitioning from one of these templates to the other, but the original template \(dubbed "legacy"\) is still the default\. The newer template \("modern"\) is required by CDK Pipelines today, and will become the default at some point in the future\. For details, see [Bootstrapping templates](#bootstrapping-templates)\. -**Important** -The modern bootstrap template grants the bootstrapped account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. - Environments are independent, so if you want to deploy to multiple environments \(different AWS accounts or different regions in the same account\), each environment must be bootstrapped separately\. **Important** @@ -32,6 +29,9 @@ Policy contains a statement with one or more invalid principals This error message means that the appropriate IAM roles do not exist in the other environment, which is most likely caused by a lack of bootstrapping\. +**Note** +Do not delete and recreate an account's bootstrap stack if you are using CDK Pipelines to deploy into that account\. The pipeline will stop working\. To update the bootstrap stack to a new version, instead re\-run `cdk bootstrap` to update the bootstrap stack in place\. + ## How to bootstrap Bootstrapping is the deployment of a AWS CloudFormation template to a specific AWS environment \(account and region\)\. The bootstrapping template accepts parameters that customize some aspects of the bootstrapped resources \(see [Customizing bootstrapping](#bootstrapping-customizing)\)\. Thus, you can bootstrap in one of two ways\. @@ -121,10 +121,7 @@ The main differences between the templates are as follows\. \* *We will add additional resources to the modern template as needed\.* -**Important** -The modern bootstrap template grants the bootstrapped account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. - -At some point in the future, the modern template will become the default bootstrapping template\. Until then, manually select the modern template when bootstrapping by setting the `CDK_NEW_BOOTSTRAP` environment variable\. +In AWS CDK version 2, the modern template will be the default bootstrapping template\. In version 1, manually select the modern template when bootstrapping by setting the `CDK_NEW_BOOTSTRAP` environment variable\. ------ #### [ macOS/Linux ] @@ -177,8 +174,12 @@ The following command\-line options, when used with CDK Toolkit's cdk bootstrap, The following additional switches are available only with the modern bootstrapping template\. + \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. ++ \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. +**Important** +The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. + ### Customizing the template When you need more customization than the AWS CDK Toolkit switches can provide, you can modify the bootstrap template to suit your needs\. Remember that you can obtain the template by using the \-\-show\-template flag\. Optionally, set the CDK\_NEW\_BOOTSTRAP environment variable to get the modern template \(otherwise, you'll get the legacy template\)\. @@ -196,7 +197,7 @@ cdk bootstrap --show-template ``` set CDK_NEW_BOOTSTRAP=1 -cdk bootstrap --show-template +powershell "cdk bootstrap --show-template | Out-File -encoding utf8 bootstrap-template.yaml" ``` ------ @@ -247,7 +248,7 @@ new MyStack(this, 'MyStack', { #### [ Python ] ``` -MyStack(self, "MyStack", +MyStack(self, "MyStack", # stack properties synthesizer=DefaultStackSynthesizer( # synthesizer properties @@ -337,7 +338,7 @@ new MyStack(this, 'MyStack', { #### [ Python ] ``` -MyStack(self, "MyStack", +MyStack(self, "MyStack", synthesizer=DefaultStackSynthesizer( qualifier="MYQUALIFIER" )) @@ -395,23 +396,31 @@ The following example shows all the available properties for `DefaultStackSynthe new DefaultStackSynthesizer({ // Name of the S3 bucket for file assets fileAssetsBucketName: 'cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}', - + bucketPrefix: '', + // Name of the ECR repository for Docker image assets imageAssetsRepositoryName: 'cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}', // ARN of the role assumed by the CLI and Pipeline to deploy here - deployRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}', - + deployRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}', + deployRoleExternalId: '', + // ARN of the role used for file asset publishing (assumed from the deploy role) fileAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}', fileAssetPublishingExternalId: '', - + // ARN of the role used for Docker asset publishing (assumed from the deploy role) imageAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}', imageAssetPublishingExternalId: '', - + // ARN of the role passed to CloudFormation to execute the deployments cloudFormationExecutionRole: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}', + + // Name of the SSM parameter which describes the bootstrap stack version number + bootstrapStackVersionSsmParameter: '/cdk-bootstrap/${Qualifier}/version', + + // Add a rule to every template which verifies the required bootstrap stack version + generateBootstrapVersionRule: true, }) ``` @@ -422,23 +431,31 @@ new DefaultStackSynthesizer({ new DefaultStackSynthesizer({ // Name of the S3 bucket for file assets fileAssetsBucketName: 'cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}', - + bucketPrefix: '', + // Name of the ECR repository for Docker image assets imageAssetsRepositoryName: 'cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}', // ARN of the role assumed by the CLI and Pipeline to deploy here - deployRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}', - + deployRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}', + deployRoleExternalId: '', + // ARN of the role used for file asset publishing (assumed from the deploy role) fileAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}', fileAssetPublishingExternalId: '', - + // ARN of the role used for Docker asset publishing (assumed from the deploy role) imageAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}', imageAssetPublishingExternalId: '', - + // ARN of the role passed to CloudFormation to execute the deployments cloudFormationExecutionRole: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}', + + // Name of the SSM parameter which describes the bootstrap stack version number + bootstrapStackVersionSsmParameter: '/cdk-bootstrap/${Qualifier}/version', + + // Add a rule to every template which verifies the required bootstrap stack version + generateBootstrapVersionRule: true, }) ``` @@ -449,23 +466,31 @@ new DefaultStackSynthesizer({ DefaultStackSynthesizer( # Name of the S3 bucket for file assets file_assets_bucket_name="cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}", - + bucket_prefix="", + # Name of the ECR repository for Docker image assets image_assets_repository_name="cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}", # ARN of the role assumed by the CLI and Pipeline to deploy here - deploy_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}", - + deploy_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}", + deploy_role_external_id="", + # ARN of the role used for file asset publishing (assumed from the deploy role) file_sset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", file_asset_publishing_external_id="", - + # ARN of the role used for Docker asset publishing (assumed from the deploy role) image_asset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}", image_asset_publishing_external_id="", - + # ARN of the role passed to CloudFormation to execute the deployments cloud_formation_execution_role="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" + + // Name of the SSM parameter which describes the bootstrap stack version number + bootstrap_stack_version_ssm_parameter="/cdk-bootstrap/${Qualifier}/version", + + // Add a rule to every template which verifies the required bootstrap stack version + generate_bootstrap_version_rule=True, ) ``` @@ -476,23 +501,31 @@ DefaultStackSynthesizer( DefaultStackSynthesizer.Builder.create() // Name of the S3 bucket for file assets .fileAssetsBucketName("cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}") - + .bucketPrefix('') + // Name of the ECR repository for Docker image assets .imageAssetsRepositoryName("cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}") // ARN of the role assumed by the CLI and Pipeline to deploy here .deployRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}") - + .deployRoleExternalId("") + // ARN of the role used for file asset publishing (assumed from the deploy role) .fileAssetPublishingRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}") .fileAssetPublishingExternalId("") - + // ARN of the role used for Docker asset publishing (assumed from the deploy role) - .imageAssetPublishingRoleArn: "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}", - .imageAssetPublishingExternalId: "", - + .imageAssetPublishingRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}") + .imageAssetPublishingExternalId("") + // ARN of the role passed to CloudFormation to execute the deployments .cloudFormationExecutionRole("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}") + + // Name of the SSM parameter which describes the bootstrap stack version number + .bootstrapStackVersionSsmParameter("/cdk-bootstrap/${Qualifier}/version") + + // Add a rule to every template which verifies the required bootstrap stack version + .generateBootstrapVersionRule(true) .build() ``` @@ -504,23 +537,31 @@ new DefaultStackSynthesizer(new DefaultStackSynthesizerProps { // Name of the S3 bucket for file assets FileAssetsBucketName = "cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}", - + BucketPrefix = "", + // Name of the ECR repository for Docker image assets ImageAssetsRepositoryName = "cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}", // ARN of the role assumed by the CLI and Pipeline to deploy here - DeployRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}", - + DeployRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}", + DeployRoleExternalId = "", + // ARN of the role used for file asset publishing (assumed from the deploy role) FileAssetPublishingRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", FileAssetPublishingExternalId = "", - + // ARN of the role used for Docker asset publishing (assumed from the deploy role) ImageAssetPublishingRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}", ImageAssetPublishingExternalId = "", - + // ARN of the role passed to CloudFormation to execute the deployments CloudFormationExecutionRole = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" + + // Name of the SSM parameter which describes the bootstrap stack version number + BootstrapStackVersionSsmParameter = "/cdk-bootstrap/${Qualifier}/version", + + // Add a rule to every template which verifies the required bootstrap stack version + GenerateBootstrapVersionRule = true, }) ``` @@ -551,8 +592,9 @@ Outputs: ### Roles -The `DefaultStackSynthesizer` requires four IAM roles for four different purposes\. If you are not using the default roles, the synthesizer needs to be told the ARNs for the roles you want to use\. The roles are: +The `DefaultStackSynthesizer` requires five IAM roles for five different purposes\. If you are not using the default roles, the synthesizer needs to be told the ARNs for the roles you want to use\. The roles are: + The *deployment role* is assumed by the AWS CDK Toolkit and by AWS CodePipeline to deploy into an environment\. Its `AssumeRolePolicy` controls who can deploy into the environment\. The permissions this role needs can be seen in the template\. ++ The *lookup role* is assumed by the AWS CDK Toolkit to perform context lookups in an environment\. Its `AssumeRolePolicy` controls who can deploy into the environment\. The permissions this role needs can be seen in the template\. + The *file publishing role* and the *image publishing role* are assumed by the AWS CDK Toolkit and by AWS CodeBuild projects to publish assets into an environment: that is, to write to the S3 bucket and the ECR repository, respectively\. These roles require write access to these resources\. + *The AWS CloudFormation execution role* is passed to AWS CloudFormation to perform the actual deployment\. Its permissions are the permissions that the deployment will execute under\. The permissions are passed to the stack as a parameter that lists managed policy ARNs\. @@ -561,4 +603,21 @@ The `DefaultStackSynthesizer` requires four IAM roles for four different purpose The AWS CDK Toolkit requires that the following CloudFormation outputs exist on the bootstrap stack\. + `BucketName`: the name of the file asset bucket + `BucketDomainName`: the file asset bucket in domain name format -+ `BootstrapVersion`: the current version of the bootstrap stack \ No newline at end of file ++ `BootstrapVersion`: the current version of the bootstrap stack + +### Template history + +The bootstrap template is versioned and evolves over time with the AWS CDK itself\. If you provide your own bootstrap template, keep it up\-to\-date with the canonical default template to ensure that yours continues to work with all CDK features\. This section contains a list of the changes made in each version\. + + +| Template version | AWS CDK version | Changes | +| --- | --- | --- | +| 1 | 1\.40\.0 | Initial version of template with Bucket, Key, Repository and Roles\. | +| 2 | 1\.45\.0 | Split asset publishing role into separate file and image publishing roles\. | +| 3 | 1\.46\.0 | Add FileAssetKeyArn export to be able to add decrypt permissions to asset consumers\. | +| 4 | 1\.61\.0 | KMS permissions are now implicit via S3 and no longer require FileAsetKeyArn, Add CdkBootstrapVersion SSM parameter so the bootstrap stack version can be verified without knowing the stack name\. | +| 5 | 1\.87\.0 | Deployment role can read SSM parameter\. | +| 6 | 1\.108\.0 | Add lookup role separate from deployment role\. | +| 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | +| 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | +| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | \ No newline at end of file diff --git a/doc_source/cli.md b/doc_source/cli.md index 5f34b526..2a39aed7 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -272,7 +272,7 @@ Older versions of the modern template created a Customer Master Key by default\. The AWS CDK Toolkit supports two bootstrap templates: the modern template and the legacy template\. The legacy template is the default, but the modern template is required by CDK Pipelines\. For more information, see [Bootstrapping](bootstrapping.md)\. **Important** -The modern bootstrap template grants the bootstrapped account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](bootstrapping.md#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. +The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. ## Creating a new app diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index c587ff19..d4f63c94 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -15,7 +15,7 @@ The main changes in CDK v2 are: + CDK v2 requires that the environments you deploy into be boostrapped using the modern bootstrap stack; the legacy stack is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. Simply re\-bootstrap the affected environments to upgrade them\. It is not necessary to set any feature flags or environment variables to specify the modern bootstrap stack\. **Important** -The modern bootstrap template grants the bootstrapped account read and write access to any Amazon S3 bucket in the same environment, as well as the ability to read secrets from AWS KMS\. All accounts trusted in the bootstrapped environment can perform the same actions\. If this is not what you want, use a [custom template](bootstrapping.md#bootstrapping-customizing-extended)\. These permissions are only required by [CDK Pipelines](cdk_pipeline.md)\. +The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. Aside from this topic, the AWS CDK Developer Guide describes CDK v1\.x\. Most of the information in the Guide still applies in CDK v2, or can be adapted with only minor changes\. A v2 Developer Guide will be available at General Availability \(GA\) of CDK v2\. A version of the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) is available for CDK v2\. From 33c6c3bf3825630ae10849b491b9dd916a86e60c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 27 Jul 2021 20:56:26 +0000 Subject: [PATCH 425/655] tweaks to best practices --- doc_source/best-practices.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md index cc9b9eb2..e7a947bb 100644 --- a/doc_source/best-practices.md +++ b/doc_source/best-practices.md @@ -26,7 +26,7 @@ The CCoE also creates a "landing zone" that defines your organizational units wi Development teams should be able use their own accounts for testing and have the ability to deploy new resources in these accounts as needed\. Individual developers can treat these resources as extensions of their own development workstation\. Using [CDK Pipelines](cdk_pipeline.md), the AWS CDK applications can then be deployed via a CI/CD account to testing, integration, and production environments \(each isolated in its own AWS region and/or account\) by merging the developers' code into your organization's canonical repository\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/best-practice-deploy-to-multiple-accounts.jpg) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/best-practice-deploy-to-multiple-accounts.png) ## Coding best practices @@ -38,7 +38,7 @@ Development teams should be able use their own accounts for testing and have the The guiding principle for most of our best practices is to keep things simple as possible—but no simpler\. Add complexity only when your requirements dictate a more complicated solution\. With the AWS CDK, you can always refactor your code as necessary to support new requirements, so it doesn't make sense to architect for all possible scenarios up front\. -### Align with the AWS Well Architected Framework +### Align with the AWS Well\-Architected framework The [AWS Well\-Architected](http://aws.amazon.com/https://aws.amazon.com/architecture/well-architected/) framework defines a *component* as the code, configuration, and AWS resources that together deliver against a requirement\. A component is often the unit of technical ownership, and is decoupled from other components\. The term *workload* is used to identify a set of components that together deliver business value\. A workload is usually the level of detail that business and technology leaders communicate about\. From 94e5946858bb90913dfd387c4698be397b88bfa6 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 29 Jul 2021 00:07:38 +0000 Subject: [PATCH 426/655] fix broken link --- doc_source/best-practices.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md index e7a947bb..44ea16a1 100644 --- a/doc_source/best-practices.md +++ b/doc_source/best-practices.md @@ -40,7 +40,7 @@ The guiding principle for most of our best practices is to keep things simple as ### Align with the AWS Well\-Architected framework -The [AWS Well\-Architected](http://aws.amazon.com/https://aws.amazon.com/architecture/well-architected/) framework defines a *component* as the code, configuration, and AWS resources that together deliver against a requirement\. A component is often the unit of technical ownership, and is decoupled from other components\. The term *workload* is used to identify a set of components that together deliver business value\. A workload is usually the level of detail that business and technology leaders communicate about\. +The [AWS Well\-Architected](http://aws.amazon.com/architecture/well-architected/) framework defines a *component* as the code, configuration, and AWS resources that together deliver against a requirement\. A component is often the unit of technical ownership, and is decoupled from other components\. The term *workload* is used to identify a set of components that together deliver business value\. A workload is usually the level of detail that business and technology leaders communicate about\. An AWS CDK application maps to a component as defined by the AWS Well\-Architected Framework\. AWS CDK apps are a mechanism to codify and deliver Well\-Architected cloud application best practices\. You can also create and share components as reusable code libraries through artifact repositories, such as AWS CodeArtifact\. From 6d0c9e7b7f5fa42655895222b7922fd4ea50be29 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 29 Jul 2021 00:08:33 +0000 Subject: [PATCH 427/655] update CDK Pipelines for GA --- doc_source/cdk_pipeline.md | 22 +++++----------------- 1 file changed, 5 insertions(+), 17 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 44bcbe47..84c15ecc 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -2,12 +2,10 @@ [CDK Pipelines](https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html) is a construct library module for painless continuous delivery of AWS CDK applications\. Whenever you check your AWS CDK app's source code in to AWS CodeCommit, GitHub, or BitBucket, CDK Pipelines can automatically build, test, and deploy your new version\. -CDK Pipelines are self\-updating: if you add new application stages or new stacks, the pipeline automatically reconfigures itself to deploy those new stages and/or stacks\. - -If you've looked at our [AWS CodePipeline example](codepipeline_example.md), CDK Pipelines can do everything that example does, and more, with less code\. Going forward, we anticipate widespread adoption of CDK Pipelines by AWS CDK developers\. +CDK Pipelines are self\-updating: if you add application stages or stacks, the pipeline automatically reconfigures itself to deploy those new stages and/or stacks\. **Note** -CDK Pipelines is currently in developer preview, and its API is subject to change\. Breaking API changes will be announced in the AWS CDK [Release Notes](https://github.com/aws/aws-cdk/releases)\. +CDK Pipelines supports two APIs: the original API that was made available in the Developer Preview release, and a modern one that incorporates feedback from CDK customers received during the preview phase\. The examples in this topic use the original API; we are preparing examples that use the modern API\. For more details on the differences between the two supported APIs, see [CDK Pipelines original API](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/pipelines/ORIGINAL_API.md)\. ## Bootstrap your AWS environments @@ -604,7 +602,7 @@ Now that you've done the initial deployment, you no longer need AWS administrati ## Sources and synth actions -As we've seen in the preceding example, the basic pieces of CDK pipelines are *sources* and *synth actions*\. +As we've seen in the preceding example, the basic pieces of CDK Pipelines are *sources* and *synth actions*\. Sources are places where your code lives\. Any source from the [codepipeline\-actions](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-codepipeline-actions-readme.html) module can be used\. @@ -1735,7 +1733,7 @@ In particular, keep in mind the following\. + Use dependency locking to prevent accidental upgrades\. The default `CdkSynth` that come with CDK Pipelines respect `package-lock.json` and `yarn.lock` to ensure your dependencies are the ones you expect\. + Credentials for production environments should be short\-lived\. After bootstrapping and initial provisioning, there is no need for developers to have account credentials; all changes can be deployed through the pipeline\. Eliminate the possibility of credentials leaking by not needing them in the first place\! -## Troubleshooting tips +## Troubleshooting The following issues are commonly encountered while getting started with CDK Pipelines\. @@ -1762,14 +1760,4 @@ Stack STACK_NAME is in ROLLBACK_COMPLETE state and can not be updated. (Service: AmazonCloudFormation; Status Code: 400; Error Code: ValidationError; Request ID: ...) ``` -The stack failed its previous deployment and is in a non\-retryable state\. Delete the stack from the AWS CloudFormation console and retry the deployment\. - -## Known issues and limitations - -We're currently aware of the following issues with CDK Pipelines\. -+ Context queries are not supported; `Vpc.fromLookup()` and similar functions do not work\. -+ Console links to other accounts will not work\. The AWS CodePipeline console assumes links are relative to the current account\. You cannot click through to a AWS CloudFormation stack in a different account\. -+ If a changeset failed to apply, the pipeline is not retried\. The pipeline must be restarted manually from the top by clicking **Release Change**\. -+ A stack that failed to deploy must be deleted manually using the CloudFormation console before starting the pipeline again by clicking **Release Change**\. - -Please [report any other issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. \ No newline at end of file +The stack failed its previous deployment and is in a non\-retryable state\. Delete the stack from the AWS CloudFormation console and retry the deployment\. \ No newline at end of file From fea89253443e97e1d3a20821a7aa064001f2f99b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 29 Jul 2021 00:09:28 +0000 Subject: [PATCH 428/655] remove CodePipeline example since CDK Pipelines is better and GA --- doc_source/examples.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/doc_source/examples.md b/doc_source/examples.md index 40557422..873931c2 100644 --- a/doc_source/examples.md +++ b/doc_source/examples.md @@ -2,5 +2,4 @@ This topic contains the following examples: + [Creating a serverless application using the AWS CDK](serverless_example.md) Creates a serverless application using Lambda, API Gateway, and Amazon S3\. -+ [Creating an AWS Fargate service using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. -+ [Creating a pipeline using the AWS CDK](codepipeline_example.md) Creates a CI/CD pipeline\. \ No newline at end of file ++ [Creating an AWS Fargate service using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. \ No newline at end of file From b8c1d7e6f7ae0b1435477705bd690bde6ae3cefc Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 29 Jul 2021 00:10:05 +0000 Subject: [PATCH 429/655] minor fixes and churn --- doc_source/cli.md | 26 +++++++++++++------------- doc_source/getting_started.md | 4 ++-- doc_source/index.md | 1 - doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-v2.md | 2 +- 6 files changed, 18 insertions(+), 19 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 2a39aed7..7694ac7e 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -336,7 +336,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -355,7 +355,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -363,7 +363,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -387,7 +387,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -409,7 +409,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -626,7 +626,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -639,7 +639,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -660,7 +660,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -735,7 +735,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -788,7 +788,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -807,7 +807,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -830,7 +830,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -852,7 +852,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index ca5c8cf0..3e1a4064 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -116,7 +116,7 @@ TypeScript was the first language supported by the AWS CDK, and much AWS CDK exa ## Prerequisites -Here's what you need install to use the AWS CDK\. +Here's what you need to install to use the AWS CDK\. All AWS CDK developers, even those working in Python, Java, or C\#, need [Node\.js](https://nodejs.org/en/download/) 10\.13\.0 or later\. All supported languages use the same back end, which runs on Node\.js\. We recommend a version in [active long\-term support](https://nodejs.org/en/about/releases/), which, at this writing, is the latest 14\.x release\. Your organization may have a different recommendation\. @@ -201,7 +201,7 @@ cdk --version ## Bootstrapping -Many AWS CDK stacks that you write will include [assets](assets.md): external files that are deployed with the stack, such as AWS Lambda functions Docker images\. The AWS CDK uploads these to an Amazon S3 bucket or other container so they are available to AWS CloudFormation during deployment\. Deployment requires that these containers already exist in the account and region you are deploying into\. Creating them is called [bootstrapping](bootstrapping.md)\. To bootstrap, issue: +Many AWS CDK stacks that you write will include [assets](assets.md): external files that are deployed with the stack, such as AWS Lambda functions or Docker images\. The AWS CDK uploads these to an Amazon S3 bucket or other container so they are available to AWS CloudFormation during deployment\. Deployment requires that these containers already exist in the account and region you are deploying into\. Creating them is called [bootstrapping](bootstrapping.md)\. To bootstrap, issue: ``` cdk bootstrap aws://ACCOUNT-NUMBER/REGION diff --git a/doc_source/index.md b/doc_source/index.md index 412f1d2a..e6e53181 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -48,7 +48,6 @@ Amazon's trademarks and trade dress may not be used in + [Examples](examples.md) + [Creating a serverless application using the AWS CDK](serverless_example.md) + [Creating an AWS Fargate service using the AWS CDK](ecs_example.md) - + [Creating a pipeline using the AWS CDK](codepipeline_example.md) + [AWS CDK examples](about_examples.md) + [AWS CDK how-tos](how_tos.md) + [Get a value from an environment variable](get_env_var.md) diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 286527ad..08ef26f6 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 90060fa5..2e6a072c 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index d4f63c94..b242d6c5 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -29,7 +29,7 @@ Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prereq To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. -### Updating `cdk.json` +### Updating `cdk.json` Remove all feature flags from `cdk.json`\. You can add one or more of the three flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these are needed\. From 7caf55cc6d2d53b85cc6154ef6ba02a832a5f2c3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 29 Jul 2021 00:11:02 +0000 Subject: [PATCH 430/655] remove CodePipeline example since CDK Pipelines is better and GA --- doc_source/codepipeline_example.md | 1289 ---------------------------- 1 file changed, 1289 deletions(-) delete mode 100644 doc_source/codepipeline_example.md diff --git a/doc_source/codepipeline_example.md b/doc_source/codepipeline_example.md deleted file mode 100644 index d245aaee..00000000 --- a/doc_source/codepipeline_example.md +++ /dev/null @@ -1,1289 +0,0 @@ -# Creating a pipeline using the AWS CDK - -The AWS CDK lets you easily define applications in the AWS Cloud using your programming language of choice\. But creating an application is just the start of the journey\. You also want to make changes to it and deploy them\. You can do this through the **Code** suite of tools: AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline\. Together, they allow you to build what's called a [deployment pipeline](https://aws.amazon.com/getting-started/tutorials/continuous-deployment-pipeline/) for your application\. This example shows how to deploy an AWS Lambda function using such a pipeline\. - -## How it works - -Our application contains two AWS CDK stacks\. The first stack, `PipelineStack`, defines the pipeline itself\. The second, `LambdaStack`, is used to deploy the Lambda function\. - -The key to this example is that you deploy `PipelineStack` from your own workstation, but `LambdaStack` is deployed by the pipeline; you never deploy it yourself\. - -Since the `LambdaStack` is deployed by the pipeline, it must be available to the pipeline \(along with the Lambda code\)\. Therefore, this app and the Lambda function are stored in a CodeCommit repository\. - -The `PipelineStack` contains the definitions of the pipeline, which includes build steps for both the Lambda function and the `LambdaStack`\. - -## Prerequisites - -Beyond having the AWS CDK set up and configured, your workstation needs to be able to push to AWS CodeCommit using Git, which means you need some way of identifying yourself to CodeCommit\. The easiest way to do this is to configure Git credentials for an IAM user, as described in [Setup for HTTPS users using Git credentials](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html)\. - -You can also use the `git-remote-codecommit` Git add\-on or other methods of connecting and authenticating [supported by CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up.html)\. - -Also, make sure you have issued `cdk bootstrap aws://ACCOUNT-NUMBER/REGION`, as the Amazon S3 bucket in the bootstrap stack is required to deploy a Lambda function with the AWS CDK\. - -## Setting up the project - -To set up a new AWS CDK project in CodeCommit; - -1. [Create a new CodeCommit repository](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html) named `pipeline` using the CodeCommit console or the CDK Toolkit\. - - if you already have a CodeCommit repository named `pipeline`, you can use another name\. Just make sure you clone it to a directory named pipeline on your local system\. - -1. Clone this new repository to your local computer in a directory named pipeline\. If you are authenticating with an IAM user with Git credentials, copy the HTTPS URL from the CodeCommit console\. \(Other authentication methods require a different URL\.\) - - ``` - git clone CODECOMMIT-REPO-URL pipeline - ``` - - Enter your credentials if prompted for them\. -**Note** -During cloning, Git will warn you that you appear to have cloned an empty repository; this is normal and expected\. - -1. Change to the pipeline directory and initialize it as a new CDK project, then install the AWS Construct Libraries we'll use in our app\. Since AWS CodeCommit uses a default branch of "main," we'll also make sure we're working on that branch\. - ------- -#### [ TypeScript ] - - ``` - cd pipeline - cdk init --language typescript - git checkout main || git branch main - npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline - npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions - ``` - ------- -#### [ JavaScript ] - - ``` - cd pipeline - cdk init --language javascript - git checkout main || git branch main - npm install @aws-cdk/aws-codedeploy @aws-cdk/aws-lambda @aws-cdk/aws-codebuild @aws-cdk/aws-codepipeline - npm install @aws-cdk/aws-codecommit @aws-cdk/aws-codepipeline-actions - ``` - ------- -#### [ Python ] - - A couple of commands differ between Windows and macOS/Linux\. - - **macOS/Linux** - - ``` - cd pipeline - cdk init --language python - git checkout main || git branch main - source .venv/bin/activate - git commit -m "project started" - pip install -r requirements.txt - pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline - pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions - pip freeze | grep -v '-e git' > requirements.txt - ``` - - **Windows** - - ``` - cd pipeline - cdk init --language python - git checkout main || git branch main - .venv\Scripts\activate.bat - pip install -r requirements.txt - pip install aws_cdk.aws_codedeploy aws_cdk.aws_lambda aws_cdk.aws_codebuild aws_cdk.aws_codepipeline - pip install aws_cdk.aws_codecommit aws_cdk.aws_codepipeline_actions - pip freeze | find /V "-e git" > requirements.txt - ``` - ------- -#### [ Java ] - - ``` - cd pipeline - cdk init --language java - git checkout main || git branch main - ``` - - You can import the resulting Maven project into your Java IDE\. - - Add `` elements like the following to `pom.xml`\. You can copy the existing dependency for the AWS CDK core module and modify it\. For example, a dependency for the AWS Lambda module looks like this\. - - ``` - - software.amazon.awscdk - lambda - ${cdk.version} - - ``` - ------- -#### [ C\# ] - - ``` - cd pipeline - cdk init --language csharp - git checkout main || git branch main - ``` - - You can open the file `src/Pipeline.sln` in Visual Studio\. - - Choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio and add the following packages\. - - ``` - Amazon.CDK.AWS.CodeDeploy - Amazon.CDK.AWS.CodeBuild - Amazon.CDK.AWS.CodeCommit - Amazon.CDK.AWS.CodePipeline - Amazon.CDK.AWS.CodePipeline.Actions - Amazon.CDK.AWS.Lambda - ``` - ------- - -1. If a directory named `test` exists, delete it\. We won't be using it in this example, and some of the code in the tests will cause errors because of other changes we'll be making\. - ------- -#### [ macOS/Linux ] - - ``` - rm -rf test - ``` - ------- -#### [ Windows ] - - ``` - cd test - del /f /q /s *.* - cd .. - rmdir test - ``` - ------- - -1. Stage all the files in the directory, commit them to your local repository, and push to CodeCommit\. - - ``` - git add --all - git commit -m "initial commit" - git push - ``` - -## Add Lambda code - -1. Create a directory for your AWS Lambda code\. - - ``` - mkdir lambda - ``` - -1. Place your AWS Lambda function in the new directory\. Our CDK app expects a Lambda function written in TypeScript, with a main file of `index.ts` and a main function named `main()`, regardless of what language the rest of the app is written in\. The function will be built \(transpiled to JavaScript\) by the TypeScript compiler as part of the pipeline\. Some changes will be needed in the Lambda build process if your function is written in another language\. - - If you don't have a function handy to play with, this one will do: - - ``` - // index.ts - const GREETING = "Hello, AWS!"; - export async function main(event: any, context: any) { - console.log(GREETING); - return GREETING; - } - ``` - -1. Commit your changes and push\. - - ``` - git add --all - git commit -m "add lambda function" - git push - ``` - -## Define Lambda stack - -Let's define the AWS CloudFormation stack that will create the Lambda function, the stack that we'll deploy in our pipeline\. We'll create a new file to hold this stack\. - -We need some way to get a reference to the Lambda function we'll be deploying\. This code is built by the pipeline, and the pipeline passes us a reference to it as AWS CloudFormation parameters\. We get it using the `fromCfnParameters()` method and store it as an attribute named `lambdaCode`, where it can be picked up by the deployment stage of the pipeline\. - -The example also uses the CodeDeploy support for blue\-green deployments to Lambda, transferring traffic to the new version in 10\-percent increments every minute\. As blue\-green deployment can only operate on aliases, not on the function directly, we create an alias for our function, named `Prod`\. - -The alias uses a Lambda version obtained using the function's `currentVersion` property\. This ensures that every invocation of the AWS CDK code publishes a new version of the function\. - -If the Lambda function needs any other resources when executing, such as an Amazon S3 bucket, Amazon DynamoDB table, or Amazon API Gateway, you'd declare those resources here\. - ------- -#### [ TypeScript ] - -File: `lib/lambda-stack.ts` - -``` -import * as codedeploy from '@aws-cdk/aws-codedeploy'; -import * as lambda from '@aws-cdk/aws-lambda'; -import { App, Stack, StackProps } from '@aws-cdk/core'; - -export class LambdaStack extends Stack { - public readonly lambdaCode: lambda.CfnParametersCode; - - constructor(app: App, id: string, props?: StackProps) { - super(app, id, props); - - this.lambdaCode = lambda.Code.fromCfnParameters(); - - const func = new lambda.Function(this, 'Lambda', { - code: this.lambdaCode, - handler: 'index.main', - runtime: lambda.Runtime.NODEJS_10_X, - description: `Function generated on: ${new Date().toISOString()}`, - }); - - const alias = new lambda.Alias(this, 'LambdaAlias', { - aliasName: 'Prod', - version: func.currentVersion, - }); - - new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', { - alias, - deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE, - }); - } -} -``` - ------- -#### [ JavaScript ] - -File: `lib/lambda-stack.js` - -``` -const codedeploy = require('@aws-cdk/aws-codedeploy'); -const lambda = require('@aws-cdk/aws-lambda'); -const { Stack } = require('@aws-cdk/core'); - -class LambdaStack extends Stack { - - constructor(app, id, props) { - super(app, id, props); - - this.lambdaCode = lambda.Code.fromCfnParameters(); - - const func = new lambda.Function(this, 'Lambda', { - code: this.lambdaCode, - handler: 'index.main', - runtime: lambda.Runtime.NODEJS_10_X, - description: `Function generated on: ${new Date().toISOString()}`, - }); - - const alias = new lambda.Alias(this, 'LambdaAlias', { - aliasName: 'Prod', - version: func.currentVersion - }); - - new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', { - alias, - deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE - }); - } -} - -module.exports = { LambdaStack } -``` - ------- -#### [ Python ] - -File: `pipeline/lambda_stack.py` - -``` -from aws_cdk import core, aws_codedeploy as codedeploy, aws_lambda as lambda_ -import datetime - -class LambdaStack(core.Stack): - def __init__(self, app: core.App, id: str, **kwargs): - super().__init__(app, id, **kwargs) - - self.lambda_code = lambda_.Code.from_cfn_parameters() - - func = lambda_.Function(self, "Lambda", - code=self.lambda_code, - handler="index.main", - runtime=lambda_.Runtime.NODEJS_10_X, - description="Function generated on {}".format(datetime.datetime.now()), - ) - - alias = lambda_.Alias(self, "LambdaAlias", alias_name="Prod", - version=func.current_version) - - codedeploy.LambdaDeploymentGroup(self, "DeploymentGroup", - alias=alias, - deployment_config= - codedeploy.LambdaDeploymentConfig.LINEAR_10_PERCENT_EVERY_1_MINUTE - ) -``` - ------- -#### [ Java ] - -File: `src/main/java/com/myorg/LambdaStack.java` - -``` -package com.myorg; - -import software.amazon.awscdk.core.App; -import software.amazon.awscdk.core.Stack; -import software.amazon.awscdk.core.StackProps; - -import software.amazon.awscdk.services.codedeploy.*; -import software.amazon.awscdk.services.lambda.*; -import software.amazon.awscdk.services.lambda.Runtime; - -import java.time.Instant; - -public class LambdaStack extends Stack { - - // private attribute to hold our Lambda's code, with public getters - private CfnParametersCode lambdaCode; - - public CfnParametersCode getLambdaCode() { - return lambdaCode; - } - - // Constructor without props argument - public LambdaStack(final App scope, final String id) { - this(scope, id, null); - } - - public LambdaStack(final App scope, final String id, final StackProps props) { - super(scope, id, props); - - lambdaCode = CfnParametersCode.fromCfnParameters(); - - Function func = Function.Builder.create(this, "Lambda") - .code(lambdaCode) - .handler("index.main") - .runtime(Runtime.NODEJS_10_X) - .description(String.format("Function generated on %s", Instant.now())) - .build(); - - Version version = func.getCurrentVersion(); - Alias alias = Alias.Builder.create(this, "LambdaAlias") - .aliasName("LambdaAlias") - .version(version).build(); - - LambdaDeploymentGroup.Builder.create(this, "DeploymentGroup") - .alias(alias) - .deploymentConfig(LambdaDeploymentConfig.LINEAR_10_PERCENT_EVERY_1_MINUTE).build(); - } -} -``` - ------- -#### [ C\# ] - -File: `src/Pipeline/LambdaStack.cs` - -``` -using Amazon.CDK; -using Amazon.CDK.AWS.CodeDeploy; -using Amazon.CDK.AWS.Lambda; - -using System; - -namespace Pipeline -{ - public class LambdaStack : Stack - { - public readonly CfnParametersCode lambdaCode; - - public LambdaStack(Construct scope, string id, StackProps props = null) : - base(scope, id, props) - { - lambdaCode = Code.FromCfnParameters(); - - var func = new Function(this, "Lambda", new FunctionProps - { - Code = lambdaCode, - Handler = "index.main", - Runtime = Runtime.NODEJS_10_X, - Description = "Function generated at " + DateTime.Now.ToString("s") - }); - - var version = func.currentVersion; - var alias = new Alias(this, "LambdaAlias", new AliasProps - { - AliasName = "Prod", - Version = version - }); - - new LambdaDeploymentGroup(this, "DeploymentGroup", new LambdaDeploymentGroupProps - { - Alias = alias, - DeploymentConfig = LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE - }); - } - } -} -``` - ------- - -## Define pipeline stack - -Our second stack, `PipelineStack`, contains the code that defines our pipeline\. - -First it needs a reference to the Lambda code it's deploying\. For that, we define a new props interface for it, `PipelineStackProps`\. This extends the standard `StackProps` and is how clients of this class \(including ourselves\) pass the Lambda code that the class needs\. - -The name of the CodeCommit repo hosting our source code is also passed in the stack's props\. The `Repository.fromRepositoryName` method is a standard AWS CDK idiom for referencing a resource, such as a CodeCommit repository, that lives outside the AWS CDK code\. - -The pipeline has two CodeBuild projects\. The first project synthesizes the AWS CloudFormation template to deploy the Lambda function from the AWS CDK code\. To do that, it installs the AWS CDK Toolkit using `npm`, then any dependencies, and then issues cdk synth command to produce AWS CloudFormation templates in the target directory `dist`\. The `dist/LambdaStack.template.json` file is this step's output\. - -The second project builds the Lambda code\. It begins by changing the current directory to `lambda`, which is where the Lambda code lives\. It then installs any dependencies and the TypeScript compiler, then builds the code\. The output is the contents of the `node_modules` directory, plus the `index.js` file\. The Lambda runtime will call the `handler\(\)` function in this file to handle requests\. - -**Tip** -This is where you'll need some changes if you use a Lambda function written in a language other than TypeScript\. - -Finally, we define our pipeline\. It has a source Action targeting the CodeCommit repository, two build Actions using the previously defined projects, and finally a deploy Action that uses AWS CloudFormation\. It takes the template generated by the AWS CDK build Project \(stored in the `LambdaStack.template.json` file\), passes it to AWS CloudFormation for deployment\. To make the Lambda build output is an input to the AWS CloudFormation action, we pass it in the `extraInputs` property\. - -We also change the name of the stack that will be deployed, from `LambdaStack` to `LambdaDeploymentStack`\. This isn't required; it's just an example of how you'd do this if you wanted\. - ------- -#### [ TypeScript ] - -File: `lib/pipeline-stack.ts` - -``` -import * as codebuild from '@aws-cdk/aws-codebuild'; -import * as codecommit from '@aws-cdk/aws-codecommit'; -import * as codepipeline from '@aws-cdk/aws-codepipeline'; -import * as codepipeline_actions from '@aws-cdk/aws-codepipeline-actions'; -import * as lambda from '@aws-cdk/aws-lambda'; -import { App, Stack, StackProps } from '@aws-cdk/core'; - -export interface PipelineStackProps extends StackProps { - readonly lambdaCode: lambda.CfnParametersCode; - readonly repoName: string -} - -export class PipelineStack extends Stack { - constructor(app: App, id: string, props: PipelineStackProps) { - super(app, id, props); - - const code = codecommit.Repository.fromRepositoryName(this, 'ImportedRepo', - props.repoName); - - const cdkBuild = new codebuild.PipelineProject(this, 'CdkBuild', { - buildSpec: codebuild.BuildSpec.fromObject({ - version: '0.2', - phases: { - install: { - commands: 'npm install', - }, - build: { - commands: [ - 'npm run build', - 'npm run cdk synth -- -o dist' - ], - }, - }, - artifacts: { - 'base-directory': 'dist', - files: [ - 'LambdaStack.template.json', - ], - }, - }), - environment: { - buildImage: codebuild.LinuxBuildImage.STANDARD_5_0, - }, - }); - const lambdaBuild = new codebuild.PipelineProject(this, 'LambdaBuild', { - buildSpec: codebuild.BuildSpec.fromObject({ - version: '0.2', - phases: { - install: { - commands: [ - 'cd lambda', - 'npm install', - ], - }, - build: { - commands: 'npm run build', - }, - }, - artifacts: { - 'base-directory': 'lambda', - files: [ - 'index.js', - 'node_modules/**/*', - ], - }, - }), - environment: { - buildImage: codebuild.LinuxBuildImage.STANDARD_2_0, - }, - }); - - const sourceOutput = new codepipeline.Artifact(); - const cdkBuildOutput = new codepipeline.Artifact('CdkBuildOutput'); - const lambdaBuildOutput = new codepipeline.Artifact('LambdaBuildOutput'); - new codepipeline.Pipeline(this, 'Pipeline', { - stages: [ - { - stageName: 'Source', - actions: [ - new codepipeline_actions.CodeCommitSourceAction({ - actionName: 'CodeCommit_Source', - branch: 'main', - repository: code, - output: sourceOutput, - }), - ], - }, - { - stageName: 'Build', - actions: [ - new codepipeline_actions.CodeBuildAction({ - actionName: 'Lambda_Build', - project: lambdaBuild, - input: sourceOutput, - outputs: [lambdaBuildOutput], - }), - new codepipeline_actions.CodeBuildAction({ - actionName: 'CDK_Build', - project: cdkBuild, - input: sourceOutput, - outputs: [cdkBuildOutput], - }), - ], - }, - { - stageName: 'Deploy', - actions: [ - new codepipeline_actions.CloudFormationCreateUpdateStackAction({ - actionName: 'Lambda_CFN_Deploy', - templatePath: cdkBuildOutput.atPath('LambdaStack.template.json'), - stackName: 'LambdaDeploymentStack', - adminPermissions: true, - parameterOverrides: { - ...props.lambdaCode.assign(lambdaBuildOutput.s3Location), - }, - extraInputs: [lambdaBuildOutput], - }), - ], - }, - ], - }); - } -} -``` - ------- -#### [ JavaScript ] - -File: `lib/pipeline-stack.js` - -``` -const codebuild = require('@aws-cdk/aws-codebuild'); -const codecommit = require('@aws-cdk/aws-codecommit'); -const codepipeline = require('@aws-cdk/aws-codepipeline'); -const codepipeline_actions = require('@aws-cdk/aws-codepipeline-actions'); - -const { Stack } = require('@aws-cdk/core'); - -class PipelineStack extends Stack { - constructor(app, id, props) { - super(app, id, props); - - const code = codecommit.Repository.fromRepositoryName(this, 'ImportedRepo', - props.repoName); - - const cdkBuild = new codebuild.PipelineProject(this, 'CdkBuild', { - buildSpec: codebuild.BuildSpec.fromObject({ - version: '0.2', - phases: { - install: { - commands: 'npm install' - }, - build: { - commands: 'npm run cdk synth -- -o dist' - } - }, - artifacts: { - 'base-directory': 'dist', - files: [ - 'LambdaStack.template.json' - ] - } - }), - environment: { - buildImage: codebuild.LinuxBuildImage.STANDARD_2_0 - } - }); - - const lambdaBuild = new codebuild.PipelineProject(this, 'LambdaBuild', { - buildSpec: codebuild.BuildSpec.fromObject({ - version: '0.2', - phases: { - install: { - commands: [ - 'cd lambda', - 'npm install', - 'npm install typescript' - ] - }, - build: { - commands: 'npx tsc index.ts' - } - }, - artifacts: { - 'base-directory': 'lambda', - files: [ - 'index.js', - 'node_modules/**/*' - ] - } - }), - environment: { - buildImage: codebuild.LinuxBuildImage.STANDARD_5_0 - } - }); - - const sourceOutput = new codepipeline.Artifact(); - const cdkBuildOutput = new codepipeline.Artifact('CdkBuildOutput'); - const lambdaBuildOutput = new codepipeline.Artifact('LambdaBuildOutput'); - new codepipeline.Pipeline(this, 'Pipeline', { - stages: [ - { - stageName: 'Source', - actions: [ - new codepipeline_actions.CodeCommitSourceAction({ - actionName: 'CodeCommit_Source', - branch: 'main', - repository: code, - output: sourceOutput - }) - ] - }, - { - stageName: 'Build', - actions: [ - new codepipeline_actions.CodeBuildAction({ - actionName: 'Lambda_Build', - project: lambdaBuild, - input: sourceOutput, - outputs: [lambdaBuildOutput] - }), - new codepipeline_actions.CodeBuildAction({ - actionName: 'CDK_Build', - project: cdkBuild, - input: sourceOutput, - outputs: [cdkBuildOutput] - }) - ] - }, - { - stageName: 'Deploy', - actions: [ - new codepipeline_actions.CloudFormationCreateUpdateStackAction({ - actionName: 'Lambda_CFN_Deploy', - templatePath: cdkBuildOutput.atPath('LambdaStack.template.json'), - stackName: 'LambdaDeploymentStack', - adminPermissions: true, - parameterOverrides: { - ...props.lambdaCode.assign(lambdaBuildOutput.s3Location) - }, - extraInputs: [lambdaBuildOutput] - }) - ] - } - ] - }); - } -} - -module.exports = { PipelineStack } -``` - ------- -#### [ Python ] - -File: `pipeline/pipeline_stack.py` - -``` -from aws_cdk import (core, aws_codebuild as codebuild, - aws_codecommit as codecommit, - aws_codepipeline as codepipeline, - aws_codepipeline_actions as codepipeline_actions, - aws_lambda as lambda_) - -class PipelineStack(core.Stack): - - def __init__(self, scope: core.Construct, id: str, *, repo_name: str=None, - lambda_code: lambda_.CfnParametersCode=None, **kwargs) -> None: - super().__init__(scope, id, **kwargs) - - code = codecommit.Repository.from_repository_name(self, "ImportedRepo", - repo_name) - - cdk_build = codebuild.PipelineProject(self, "CdkBuild", - build_spec=codebuild.BuildSpec.from_object(dict( - version="0.2", - phases=dict( - install=dict( - commands=[ - "npm install aws-cdk", - "npm update", - "python -m pip install -r requirements.txt" - ]), - build=dict(commands=[ - "npx cdk synth -o dist"])), - artifacts={ - "base-directory": "dist", - "files": [ - "LambdaStack.template.json"]}, - environment=dict(buildImage= - codebuild.LinuxBuildImage.STANDARD_2_0)))) - - lambda_build = codebuild.PipelineProject(self, 'LambdaBuild', - build_spec=codebuild.BuildSpec.from_object(dict( - version="0.2", - phases=dict( - install=dict( - commands=[ - "cd lambda", - "npm install", - "npm install typescript"]), - build=dict( - commands=[ - "npx tsc index.ts"])), - artifacts={ - "base-directory": "lambda", - "files": [ - "index.js", - "node_modules/**/*"]}, - environment=dict(buildImage= - codebuild.LinuxBuildImage.STANDARD_5_0)))) - - source_output = codepipeline.Artifact() - cdk_build_output = codepipeline.Artifact("CdkBuildOutput") - lambda_build_output = codepipeline.Artifact("LambdaBuildOutput") - - lambda_location = lambda_build_output.s3_location - - codepipeline.Pipeline(self, "Pipeline", - stages=[ - codepipeline.StageProps(stage_name="Source", - actions=[ - codepipeline_actions.CodeCommitSourceAction( - action_name="CodeCommit_Source", - branch="main", - repository=code, - output=source_output)]), - codepipeline.StageProps(stage_name="Build", - actions=[ - codepipeline_actions.CodeBuildAction( - action_name="Lambda_Build", - project=lambda_build, - input=source_output, - outputs=[lambda_build_output]), - codepipeline_actions.CodeBuildAction( - action_name="CDK_Build", - project=cdk_build, - input=source_output, - outputs=[cdk_build_output])]), - codepipeline.StageProps(stage_name="Deploy", - actions=[ - codepipeline_actions.CloudFormationCreateUpdateStackAction( - action_name="Lambda_CFN_Deploy", - template_path=cdk_build_output.at_path( - "LambdaStack.template.json"), - stack_name="LambdaDeploymentStack", - admin_permissions=True, - parameter_overrides=dict( - lambda_code.assign( - bucket_name=lambda_location.bucket_name, - object_key=lambda_location.object_key, - object_version=lambda_location.object_version)), - extra_inputs=[lambda_build_output])]) - ] - ) -``` - ------- -#### [ Java ] - -File: `src/main/java/com/myorg/PipelineStack.java` - -``` -package com.myorg; - -import java.util.Arrays; -import java.util.List; -import java.util.HashMap; - -import software.amazon.awscdk.core.*; -import software.amazon.awscdk.services.codebuild.*; -import software.amazon.awscdk.services.codecommit.*; -import software.amazon.awscdk.services.codepipeline.*; -import software.amazon.awscdk.services.codepipeline.StageProps; -import software.amazon.awscdk.services.codepipeline.actions.*; -import software.amazon.awscdk.services.lambda.*; - -public class PipelineStack extends Stack { - // alternate constructor for calls without props. - // lambdaCode and repoName are both required. - public PipelineStack(final App scope, final String id, - final CfnParametersCode lambdaCode, final String repoName) { - this(scope, id, null, lambdaCode, repoName); - } - - @SuppressWarnings("serial") - public PipelineStack(final App scope, final String id, final StackProps props, - final CfnParametersCode lambdaCode, final String repoName) { - super(scope, id, props); - - IRepository code = Repository.fromRepositoryName(this, "ImportedRepo", repoName); - - PipelineProject cdkBuild = PipelineProject.Builder.create(this, "CDKBuild") - .buildSpec(BuildSpec.fromObject(new HashMap() {{ - put("version", "0.2"); - put("phases", new HashMap() {{ - put("install", new HashMap() {{ - put("commands", "npm install aws-cdk"); - }}); - put("build", new HashMap() {{ - put("commands", Arrays.asList("mvn compile -q -DskipTests", - "npx cdk synth -o dist")); - }}); - }}); - put("artifacts", new HashMap() {{ - put("base-directory", "dist"); - put("files", Arrays.asList("LambdaStack.template.json")); - }}); - }})) - .environment(BuildEnvironment.builder().buildImage( - LinuxBuildImage.STANDARD_5_0).build()) - .build(); - - PipelineProject lambdaBuild = PipelineProject.Builder.create(this, "LambdaBuild") - .buildSpec(BuildSpec.fromObject(new HashMap() {{ - put("version", "0.2"); - put("phases", new HashMap() {{ - put("install", new HashMap>() {{ - put("commands", Arrays.asList("cd lambda", "npm install", - "npm install typescript")); - }}); - put("build", new HashMap>() {{ - put("commands", Arrays.asList("npx tsc index.ts")); - }}); - }}); - put("artifacts", new HashMap() {{ - put("base-directory", "lambda"); - put("files", Arrays.asList("index.js", "node_modules/**/*")); - }}); - }})) - .environment(BuildEnvironment.builder().buildImage( - LinuxBuildImage.STANDARD_2_0).build()) - .build(); - - Artifact sourceOutput = new Artifact(); - Artifact cdkBuildOutput = new Artifact("CdkBuildOutput"); - Artifact lambdaBuildOutput = new Artifact("LambdaBuildOutput"); - - Pipeline.Builder.create(this, "Pipeline") - .stages(Arrays.asList( - StageProps.builder() - .stageName("Source") - .actions(Arrays.asList( - CodeCommitSourceAction.Builder.create() - .actionName("Source") - .branch('main') - .repository(code) - .output(sourceOutput) - .build())) - .build(), - StageProps.builder() - .stageName("Build") - .actions(Arrays.asList( - CodeBuildAction.Builder.create() - .actionName("Lambda_Build") - .project(lambdaBuild) - .input(sourceOutput) - .outputs(Arrays.asList(lambdaBuildOutput)).build(), - CodeBuildAction.Builder.create() - .actionName("CDK_Build") - .project(cdkBuild) - .input(sourceOutput) - .outputs(Arrays.asList(cdkBuildOutput)) - .build())) - .build(), - StageProps.builder() - .stageName("Deploy") - .actions(Arrays.asList( - CloudFormationCreateUpdateStackAction.Builder.create() - .actionName("Lambda_CFN_Deploy") - .templatePath(cdkBuildOutput.atPath("LambdaStack.template.json")) - .adminPermissions(true) - .parameterOverrides(lambdaCode.assign(lambdaBuildOutput.getS3Location())) - .extraInputs(Arrays.asList(lambdaBuildOutput)) - .stackName("LambdaDeploymentStack") - .build())) - .build())) - .build(); - } -} -``` - ------- -#### [ C\# ] - -File: `src/Pipeline/PipelineStack.cs` - -``` -using Amazon.CDK; -using Amazon.CDK.AWS.CodeBuild; -using Amazon.CDK.AWS.CodeCommit; -using Amazon.CDK.AWS.CodePipeline; -using Amazon.CDK.AWS.CodePipeline.Actions; -using Amazon.CDK.AWS.Lambda; -using System.Collections.Generic; - -namespace Pipeline -{ - public class PipelineStackProps : StackProps - { - public CfnParametersCode LambdaCode { get; set; } - public string RepoName { get; set; } - } - - public class PipelineStack : Stack - { - public PipelineStack(Construct scope, string id, PipelineStackProps props = null) : - base(scope, id, props) - { - var code = Repository.FromRepositoryName(this, "ImportedRepo", props.RepoName); - - var cdkBuild = new PipelineProject(this, "CDKBuild", new PipelineProjectProps - { - BuildSpec = BuildSpec.FromObject(new Dictionary - { - ["version"] = "0.2", - ["phases"] = new Dictionary - { - ["install"] = new Dictionary - { - ["commands"] = "npm install aws-cdk" - }, - ["build"] = new Dictionary - { - ["commands"] = "npx cdk synth -o dist" - } - }, - ["artifacts"] = new Dictionary - { - ["base-directory"] = "dist", - ["files"] = new string[] - { - "LambdaStack.template.json" - } - } - }), - Environment = new BuildEnvironment - { - BuildImage = LinuxBuildImage.STANDARD_5_0 - } - }); - - var lambdaBuild = new PipelineProject(this, "LambdaBuild", new PipelineProjectProps - { - BuildSpec = BuildSpec.FromObject(new Dictionary - { - ["version"] = "0.2", - ["phases"] = new Dictionary - { - ["install"] = new Dictionary - { - ["commands"] = new string[] - { - "cd lambda", - "npm install", - "npm install typescript" - } - }, - ["build"] = new Dictionary - { - ["commands"] = "npx tsc index.ts" - } - }, - ["artifacts"] = new Dictionary - { - ["base-directory"] = "lambda", - ["files"] = new string[] - { - "index.js", - "node_modules/**/*" - } - } - }), - Environment = new BuildEnvironment - { - BuildImage = LinuxBuildImage.STANDARD_2_0 - } - }); - - var sourceOutput = new Artifact_(); - var cdkBuildOutput = new Artifact_("CdkBuildOutput"); - var lambdaBuildOutput = new Artifact_("LambdaBuildOutput"); - - new Amazon.CDK.AWS.CodePipeline.Pipeline(this, "Pipeline", new PipelineProps - { - Stages = new[] - { - new Amazon.CDK.AWS.CodePipeline.StageProps - { - StageName = "Source", - Actions = new [] - { - new CodeCommitSourceAction(new CodeCommitSourceActionProps - { - ActionName = "Source", - Branch = "main", - Repository = code, - Output = sourceOutput - }) - } - }, - new Amazon.CDK.AWS.CodePipeline.StageProps - { - StageName = "Build", - Actions = new [] - { - new CodeBuildAction(new CodeBuildActionProps - { - ActionName = "Lambda_Build", - Project = lambdaBuild, - Input = sourceOutput, - Outputs = new [] { lambdaBuildOutput } - }), - new CodeBuildAction(new CodeBuildActionProps - { - ActionName = "CDK_Build", - Project = cdkBuild, - Input = sourceOutput, - Outputs = new [] { cdkBuildOutput } - }) - } - }, - new Amazon.CDK.AWS.CodePipeline.StageProps - { - StageName = "Deploy", - Actions = new [] - { - new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps { - ActionName = "Lambda_CFN_Deploy", - TemplatePath = cdkBuildOutput.AtPath("LambdaStack.template.json"), - StackName = "LambdaDeploymentStack", - AdminPermissions = true, - ParameterOverrides = props.LambdaCode.Assign(lambdaBuildOutput.S3Location), - ExtraInputs = new [] { lambdaBuildOutput } - }) - } - } - } - }); - } - } -} -``` - ------- - -## Main program - -Finally, we have our main AWS CDK application file\. - -**Note** -If you didn't name your new CodeCommit repository `pipeline`, here's where you'd change it\. Just edit the value of `CODECOMMIT_REPO_NAME`\. - -This code is straightforward: it first instantiates the `LambdaStack` class as `LambdaStack`, which is what the AWS CDK build in the pipeline expects\. Then it instantiates the `PipelineStack` class, passing the Lambda code from the `LambdaStack` object\. - ------- -#### [ TypeScript ] - -File: `bin/pipeline.ts` - -``` -#!/usr/bin/env node - -const CODECOMMIT_REPO_NAME = "pipeline"; - -import { App } from '@aws-cdk/core'; -import { LambdaStack } from '../lib/lambda-stack'; -import { PipelineStack } from '../lib/pipeline-stack'; - -const app = new App(); - -const lambdaStack = new LambdaStack(app, 'LambdaStack'); -new PipelineStack(app, 'PipelineDeployingLambdaStack', { - lambdaCode: lambdaStack.lambdaCode, - repoName: CODECOMMIT_REPO_NAME -}); - -app.synth(); -``` - ------- -#### [ JavaScript ] - -File: `bin/pipeline.js` - -``` -#!/usr/bin/env node - -const CODECOMMIT_REPO_NAME = "pipeline"; - -const { App } = require('@aws-cdk/core'); -const { LambdaStack } = require('../lib/lambda-stack'); -const { PipelineStack } = require('../lib/pipeline-stack'); - -const app = new App(); - -const lambdaStack = new LambdaStack(app, 'LambdaStack'); -new PipelineStack(app, 'PipelineDeployingLambdaStack', { - lambdaCode: lambdaStack.lambdaCode, - repoName: CODECOMMIT_REPO_NAME -}); - -app.synth(); -``` - ------- -#### [ Python ] - -File: `app.py` - -``` -#!/usr/bin/env python3 - -CODECOMMIT_REPO_NAME = "pipeline" - -from aws_cdk import core - -from pipeline.pipeline_stack import PipelineStack -from pipeline.lambda_stack import LambdaStack - -app = core.App() - -lambda_stack = LambdaStack(app, "LambdaStack") - -PipelineStack(app, "PipelineDeployingLambdaStack", - lambda_code=lambda_stack.lambda_code, - repo_name=CODECOMMIT_REPO_NAME) - -app.synth() -``` - ------- -#### [ Java ] - -File: `src/main/java/com/myorg/PipelineApp.java` - -``` -package com.myorg; - -import software.amazon.awscdk.core.*; - -public class PipelineApp { - static final String CODECOMMIT_REPO_NAME = "pipeline"; - - public static void main(final String[] argv) { - App app = new App(); - - LambdaStack lambdaStack = new LambdaStack(app, "LambdaStack"); - new PipelineStack(app, "PipelineStack", - lambdaStack.getLambdaCode(), CODECOMMIT_REPO_NAME); - - app.synth(); - } -} -``` - ------- -#### [ C\# ] - -File: `src/Pipeline/Program.cs` - -``` -using Amazon.CDK; - -namespace Pipeline -{ - class Program - { - const string CODECOMMIT_REPO_NAME = "pipeline"; - - static void Main(string[] args) - { - var app = new App(); - - var lambdaStack = new LambdaStack(app, "LambdaStack"); - new PipelineStack(app, "PipelineDeployingLambdaStack", new PipelineStackProps - { - LambdaCode = lambdaStack.lambdaCode, - RepoName = CODECOMMIT_REPO_NAME - }); - - app.Synth(); - } - } -} -``` - ------- - -Now check this code in to Git and push it to AWS CodeCommit\. - -``` -git add --all -git commit -m "add CDK app" -git push -``` - -## Deploying the pipeline - -Now we can deploy the pipeline\. - -``` -cdk deploy PipelineDeployingLambdaStack -``` - -The name, `PipelineDeployingLambdaStack`, is the name we used when we instantiated `PipelineStack`\. - -**Tip** -Rather than typing that whole name out, this is a good place to use a wildcard\! Put quotes around the name pattern to prevent the shell from tyring to expand it\. - -``` -cdk deploy "Pipe*" -``` - -You'll be asked to approve your stack's security changes\. Type **y** to accept them and continue with deployment\. - -Don't deploy `LambdaStack`\. This stack is deployed by the pipeline, and it won't deploy without values provided by the pipeline\. - -After the deployment finishes, you should have a three\-stage pipeline that looks something like the following\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/pipeline.jpg) - -Try making a change to your Lambda function code and push it to the repository\. The pipeline should pick up your change, build it, and deploy it automatically, without any other action from you\. - -## Cleaning up - -To avoid unexpected AWS charges, destroy your AWS CDK stacks after you're done with this exercise\. - -Delete the `LambdaStack` first using the AWS CloudFormation console\. The IAM role needed to delete `LambdaStack` is provided by `PipelineDeployingLambdaStack`, so if you delete it first, you no longer have permission to destroy `LambdaStack`\. - -Then you may delete the `PipelineDeployingLambdaStack`\. - -``` -cdk destroy LambdaStack -cdk destroy PipelineDeployingLambdaStack -``` - -Finally, delete your AWS CodeCommit repository from the AWS Console\. \ No newline at end of file From 67da255ff477cb91e0025ecd2c785529011261e8 Mon Sep 17 00:00:00 2001 From: Dmitry Balabanov Date: Mon, 2 Aug 2021 12:19:21 +0200 Subject: [PATCH 431/655] Fix typo in NuGet package name The correct package name is Amazon.CDK.AWS.ECS.Patterns --- doc_source/ecs_example.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index bcd86cdf..7f45e6f0 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -144,7 +144,7 @@ Choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solut ``` Amazon.CDK.AWS.EC2 Amazon.CDK.AWS.ECS -AMazon.CDK.AWS.ECS.Patterns +Amazon.CDK.AWS.ECS.Patterns ``` **Tip** @@ -366,4 +366,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` \ No newline at end of file +``` From 090393e1ed834d87f73c16543506d5d0839c038e Mon Sep 17 00:00:00 2001 From: chefren Date: Wed, 4 Aug 2021 10:51:52 +1000 Subject: [PATCH 432/655] Explain correct use of lists in policies parameter --- doc_source/bootstrapping.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 337f000f..7391588c 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -172,7 +172,7 @@ The following command\-line options, when used with CDK Toolkit's cdk bootstrap, + \-\-termination\-protection prevents the bootstrap stack from being deleted \(see [Protecting a stack from being deleted](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html) in the AWS CloudFormation User Guide\) The following additional switches are available only with the modern bootstrapping template\. -+ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. ++ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. Note that this is passed as a CFN CommaDelimitedList Parameter, so the value must represent a single comma separated list string, eg: `--cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess"`.\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. + \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. From 000f1a4fd23dfe39d24b3b80647c325af51ca214 Mon Sep 17 00:00:00 2001 From: chefren Date: Wed, 4 Aug 2021 12:42:49 +1000 Subject: [PATCH 433/655] Remove extra dot --- doc_source/bootstrapping.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 7391588c..5cbcde04 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -172,7 +172,7 @@ The following command\-line options, when used with CDK Toolkit's cdk bootstrap, + \-\-termination\-protection prevents the bootstrap stack from being deleted \(see [Protecting a stack from being deleted](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html) in the AWS CloudFormation User Guide\) The following additional switches are available only with the modern bootstrapping template\. -+ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. Note that this is passed as a CFN CommaDelimitedList Parameter, so the value must represent a single comma separated list string, eg: `--cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess"`.\. ++ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. Note that this is passed as a CFN CommaDelimitedList Parameter, so the value must represent a single comma separated list string, eg: `--cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess"`\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. + \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. From 71c849cf3400fcd9ef5768cd1cd0b9e142c0ff7a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 5 Aug 2021 15:25:27 +0000 Subject: [PATCH 434/655] correct fromArn to fromBucketArn --- doc_source/resources.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index d764591f..31c1053c 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -502,7 +502,7 @@ The following example shows how to define a bucket based on an existing bucket w s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); // Construct a resource (bucket) by its full ARN (can be cross account) -s3.Bucket.fromArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); +s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); // Construct a resource by giving attribute(s) (complex resources) ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { @@ -518,7 +518,7 @@ ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); // Construct a resource (bucket) by its full ARN (can be cross account) -s3.Bucket.fromArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); +s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); // Construct a resource by giving attribute(s) (complex resources) ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { @@ -534,7 +534,7 @@ ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { s3.Bucket.from_bucket_name(self, "MyBucket", "my-bucket-name") # Construct a resource (bucket) by its full ARN (can be cross account) -s3.Bucket.from_arn(self, "MyBucket", "arn:aws:s3:::my-bucket-name") +s3.Bucket.from_bucket_arn(self, "MyBucket", "arn:aws:s3:::my-bucket-name") # Construct a resource by giving attribute(s) (complex resources) ec2.Vpc.from_vpc_attributes(self, "MyVpc", vpc_id="vpc-1234567890abcdef") From dc1da93cd4ec4157d3de61b6f81b44a39a53c873 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 5 Aug 2021 22:40:43 +0000 Subject: [PATCH 435/655] update code snippet to not pass props to Construct --- doc_source/constructs.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 48917055..43abe66a 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -741,7 +741,7 @@ public class NotifyingBucket : Construct ------ -The `NotifyingBucket` constructor has a signature compatible with the base `Construct` class: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. This means that you could define an instance of this construct in your app without `props`, for example: +The `NotifyingBucket` constructor has a typical construct signature: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. \(The base `Construct` class does not take a `props`argument\.\) You could define an instance of this construct in your app without `props`, for example: ------ #### [ TypeScript ] @@ -892,7 +892,7 @@ public class NotifyingBucket extends Bucket { } public NotifyingBucket(final Construct scope, final String id, final BucketProps props, final String prefix) { - super(scope, id, props); + super(scope, id); Bucket bucket = new Bucket(this, "bucket"); topic = new Topic(this, "topic"); @@ -911,7 +911,7 @@ public class NotifyingBucket : Construct { public readonly Topic topic; - public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id, props) + public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id) { var bucket = new Bucket(this, "bucket"); topic = new Topic(this, "topic"); @@ -1002,4 +1002,4 @@ The construct tree is separate from the constructs you define in your AWS CDK co The construct tree defines an implicit order in which constructs are synthesized to resources in the final AWS CloudFormation template\. Where one resource must be created before another, AWS CloudFormation or the AWS Construct Library will generally infer the dependency and make sure the resources are created in the right order\. You can also add an explicit dependency between two nodes using `node.addDependency()`; see [Dependencies](https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html#dependencies) in the AWS CDK API Reference\. -The AWS CDK provides a simple way to visit every node in the construct tree and perform an operation on each one\. See [Aspects](aspects.md)\. +The AWS CDK provides a simple way to visit every node in the construct tree and perform an operation on each one\. See [Aspects](aspects.md)\. \ No newline at end of file From e26dd327f635c4a9f4f59e9804fc86f1094bc236 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 5 Aug 2021 23:19:45 +0000 Subject: [PATCH 436/655] add tip about role argument --- doc_source/bootstrapping.md | 9 ++++++++- doc_source/ecs_example.md | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 5cbcde04..a509e642 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -172,7 +172,14 @@ The following command\-line options, when used with CDK Toolkit's cdk bootstrap, + \-\-termination\-protection prevents the bootstrap stack from being deleted \(see [Protecting a stack from being deleted](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html) in the AWS CloudFormation User Guide\) The following additional switches are available only with the modern bootstrapping template\. -+ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. Note that this is passed as a CFN CommaDelimitedList Parameter, so the value must represent a single comma separated list string, eg: `--cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess"`\. ++ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. +**Tip** + The policies must be passed as a single string argument, with the policy ARNs separated by commas, like this: + + ``` + --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCo + deDeployFullAccess". + ``` + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. + \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. diff --git a/doc_source/ecs_example.md b/doc_source/ecs_example.md index 7f45e6f0..fa7c774f 100644 --- a/doc_source/ecs_example.md +++ b/doc_source/ecs_example.md @@ -366,4 +366,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` +``` \ No newline at end of file From 95d3f795638c0a176264db34b10bb40e10042a7e Mon Sep 17 00:00:00 2001 From: Mohamed Ali Jamaoui Date: Tue, 10 Aug 2021 07:39:41 +0100 Subject: [PATCH 437/655] Correct typo Correct typo --- doc_source/getting_started.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 3e1a4064..6365b931 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -8,7 +8,7 @@ The AWS Cloud Development Kit \(AWS CDK\) lets you define your cloud infrastruct Ideally, you already have experience with popular AWS services, particularly [AWS Identity and Access Management](https://aws.amazon.com/iam/) \(IAM\)\. You might already have AWS credentials on your workstation for use with an AWS SDK or the AWS CLI and experience working with AWS resources programmatically\. -Familiarity with [AWS CloudFormation](https://aws.amazon.com/cloudformation/) is also useful, as the output of an AWS CDK program is a AWS CloudFormation template\. +Familiarity with [AWS CloudFormation](https://aws.amazon.com/cloudformation/) is also useful, as the output of an AWS CDK program is an AWS CloudFormation template\. Finally, you should be proficient in the programming language you intend to use with the AWS CDK\. @@ -240,4 +240,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? From b0906d5ec76f0eac9518afdec99a77d9ca806fe8 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 18 Aug 2021 23:27:17 +0000 Subject: [PATCH 438/655] update CDK Pipelines topic to use new API --- doc_source/cdk_pipeline.md | 1576 +++++++++++++++--------------------- 1 file changed, 651 insertions(+), 925 deletions(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 84c15ecc..10326b08 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -1,11 +1,11 @@ # Continuous integration and delivery \(CI/CD\) using CDK Pipelines -[CDK Pipelines](https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html) is a construct library module for painless continuous delivery of AWS CDK applications\. Whenever you check your AWS CDK app's source code in to AWS CodeCommit, GitHub, or BitBucket, CDK Pipelines can automatically build, test, and deploy your new version\. +[CDK Pipelines](https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html) is a construct library module for painless continuous delivery of AWS CDK applications\. Whenever you check your AWS CDK app's source code in to AWS CodeCommit, GitHub, or CodeStar, CDK Pipelines can automatically build, test, and deploy your new version\. CDK Pipelines are self\-updating: if you add application stages or stacks, the pipeline automatically reconfigures itself to deploy those new stages and/or stacks\. **Note** -CDK Pipelines supports two APIs: the original API that was made available in the Developer Preview release, and a modern one that incorporates feedback from CDK customers received during the preview phase\. The examples in this topic use the original API; we are preparing examples that use the modern API\. For more details on the differences between the two supported APIs, see [CDK Pipelines original API](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/pipelines/ORIGINAL_API.md)\. +CDK Pipelines supports two APIs: the original API that was made available in the Developer Preview release, and a modern one that incorporates feedback from CDK customers received during the preview phase\. The examples in this topic use the modern API\. For details on the differences between the two supported APIs, see [CDK Pipelines original API](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/pipelines/ORIGINAL_API.md)\. ## Bootstrap your AWS environments @@ -46,7 +46,7 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ ------ -To bootstrap additional environments into which AWS CDK applications will be deployed by the pipeline, use the commands below instead\. The `--trust` option indicates which other account should have permissions to deploy AWS CDK applications into this environment; specify the pipeline's AWS account ID\. +To bootstrap additional environments into which AWS CDK applications will be deployed by the pipeline, use the commands below instead\. The \-\-trust option indicates which other account should have permissions to deploy AWS CDK applications into this environment; specify the pipeline's AWS account ID\. Again, you may omit the \-\-profile option if your default AWS profile contains the necessary credentials or if you are using the `AWS_*` environment variables to provide your AWS account credentials\. @@ -75,13 +75,13 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ ------ **Tip** -Use administrative credentials only to bootstrap and to provision the initial pipeline\. Drop administrative credentials as soon as possible\. +Use administrative credentials only to bootstrap and to provision the initial pipeline\. Afterward, use the pipeline itself, not your local machine, to deploy changes\. -If you are upgrading an existing bootstrapped environment, the old Amazon S3 bucket is orphaned when the new bucket is created\. Delete it manually using the Amazon S3 console\. +If you are upgrading a legacy\-bootstrapped environment, the old Amazon S3 bucket is orphaned when the new bucket is created\. Delete it manually using the Amazon S3 console\. ## Initialize project -Create a new, empty GitHub project and clone it to your workstation in the `my-pipeline` directory\. \(Our code examples in this topic use GitHub; you can also use BitBucket or AWS CodeCommit\.\) +Create a new, empty GitHub project and clone it to your workstation in the `my-pipeline` directory\. \(Our code examples in this topic use GitHub; you can also use CodeStar or AWS CodeCommit\.\) ``` git clone GITHUB-CLONE-URL my-pipeline @@ -114,7 +114,7 @@ cdk init app --language javascript cdk init app --language python ``` -After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install its dependencies\. +After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install the AWS CDK core dependencies\. ``` source .venv/bin/activate @@ -141,36 +141,33 @@ If you are using Visual Studio, open the solution file in the `src` directory\. ------ -Install the CDK Pipelines module along with others you'll be using\. +Install the CDK Pipelines module along with any others you'll be using\. **Tip** -Be sure to commit your `cdk.json` and `cdk.context.json` files in source control\. The context information \(such as feature flags and cached values retrieved from your AWS account\) are part of your project's state\. In particular, any cached values are critical to successful deployment, since your app won't be able to retrieve such values from your AWS account while running in the CI/CD environment\. +Be sure to commit your `cdk.json` and `cdk.context.json` files in source control\. The context information \(such as feature flags and cached values retrieved from your AWS account\) are part of your project's state\. By design, cached values cannot be retrieved in a CI/CD environment, so having them in `cdk.context.json` is critical to successful deployment\. ------ #### [ TypeScript ] ``` -npm install @aws-cdk/pipelines @aws-cdk/aws-codebuild -npm install @aws-cdk/aws-codepipeline @aws-cdk/aws-codepipeline-actions +npm install @aws-cdk/pipelines @aws-cdk/aws-lambda ``` ------ #### [ JavaScript ] ``` -npm install @aws-cdk/pipelines @aws-cdk/aws-codebuild -npm install @aws-cdk/aws-codepipeline @aws-cdk/aws-codepipeline-actions +npm install @aws-cdk/pipelines @aws-cdk/aws-lambda ``` ------ #### [ Python ] ``` -python -m pip install aws_cdk.pipelines aws_cdk.aws_codebuild -python -m pip install aws_cdk.aws_codepipeline aws_cdk.aws_codepipeline_actions +python -m pip install aws_cdk.pipelines aws_cdk.aws_lambda ``` -Freeze your dependencies in `requirements.txt`\. +Add the project's dependencies to `requirements.txt` so they can be installed in the CI/CD environment\. It is convenient to use `pip freeze` for this\. **macOS/Linux** @@ -187,7 +184,7 @@ python -m pip freeze | findstr /R /B /V "[-#]" > requirements.txt ------ #### [ Java ] -Edit your project's `pom.xml` and add a `` element for the `pipeline` module and a few others you'll need\. Follow the template below for each module, placing each inside the existing `` container\. +Edit your project's `pom.xml` and add a `` element for the `pipeline` module and the others you'll need\. Follow the template below for each module, placing each inside the existing `` container\. ``` @@ -197,36 +194,26 @@ Edit your project's `pom.xml` and add a `` element for the `pipeline software.amazon.awscdk - codebuild - ${cdk.version} - - - software.amazon.awscdk - codepipeline - ${cdk.version} - - - software.amazon.awscdk - codepipeline-actions + lambda ${cdk.version} ``` +After updating `pom.xml`, issue `mvn package` to install the new modules\. + ------ #### [ C\# ] -In Visual Studio, choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio and add the following packages\. Make sure the **Include prerelease** checkbox is marked, since the CDK Pipelines module is in developer preview\. +In Visual Studio, choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** in Visual Studio and add the following packages\. ``` Amazon.CDK.Pipelines -Amazon.CDK.AWS.CodeBuild -Amazon.CDK.AWS.CodePipeline -Amazon.CDK.AWS.CodePipeline.Actions +Amazon.CDK.AWS.Lambda ``` ------ -Finally, add the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featureflags.md) to the new project's `cdk.json` file\. The file will already contain some context values; add this new one inside the `context` object\. +Finally, add the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featureflags.md) to the new project's `cdk.json` file\. The file will already contain some context values; add this new one inside the `context` object if it's not already there\. ``` { @@ -240,9 +227,16 @@ Finally, add the `@aws-cdk/core:newStyleStackSynthesis` [feature flag](featurefl In a future release of the AWS CDK, "new style" stack synthesis will become the default, but for now we need to opt in using the feature flag\. -## Define pipelines +## Define a pipeline + +Your CDK Pipelines application will include at least two stacks: one that represents the pipeline itself, and one or more stacks that represent the application deployed through it\. Stacks can also be grouped into *stages*, which you can use to deploy copies of infrastructure stacks to different environments\. For now, we'll consider the pipeline, and later delve into the application it will deploy\. + +The construct [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CodePipeline.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CodePipeline.html) is the construct that represents a CDK Pipeline that uses AWS CodePipeline as its deployment engine\. When you instantiate `CodePipeline` in a stack, you define the source location for the pipeline \(e\.g\. a GitHub repository\) and the commands to build the app\. For example, the following defines a pipeline whose source is stored in a GitHub repository, and includes a build step for a TypeScript CDK application\. Fill in the information about your GitHub repo where indicated\. + +**Note** +By default, the pipeline authenticates to GitHub using a personal access token stored in Secrets Manager under the name `github-token`\. -The construct [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CdkPipeline.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CdkPipeline.html) is the construct that represents a CDK Pipeline\. When you instantiate `CdkPipeline` in a stack, you define the source location for the pipeline as well as the build commands\. For example, the following defines a pipeline whose source is stored in a GitHub repository, and includes a build step for a TypeScript application\. The Pipeline will be provisioned in account `111111111111` and region `eu-west-1`\. +You'll also need to update the instantiation of the pipeline stack to specify the AWS account and region\. ------ #### [ TypeScript ] @@ -250,41 +244,19 @@ The construct [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipeline In `lib/my-pipeline-stack.ts` \(may vary if your project folder isn't named `my-pipeline`\): ``` -import { Stack, StackProps, Construct, SecretValue } from '@aws-cdk/core'; -import { CdkPipeline, SimpleSynthAction } from '@aws-cdk/pipelines'; - -import * as codepipeline from '@aws-cdk/aws-codepipeline'; -import * as codepipeline_actions from '@aws-cdk/aws-codepipeline-actions'; +import * as cdk from '@aws-cdk/core'; +import { CodePipeline, CodePipelineSource, ShellStep } from '@aws-cdk/pipelines'; -export class MyPipelineStack extends Stack { - constructor(scope: Construct, id: string, props?: StackProps) { +export class MyPipelineStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); - const sourceArtifact = new codepipeline.Artifact(); - const cloudAssemblyArtifact = new codepipeline.Artifact(); - - const pipeline = new CdkPipeline(this, 'Pipeline', { - pipelineName: 'MyAppPipeline', - cloudAssemblyArtifact, - - sourceAction: new codepipeline_actions.GitHubSourceAction({ - actionName: 'GitHub', - output: sourceArtifact, - oauthToken: SecretValue.secretsManager('GITHUB_TOKEN_NAME'), - trigger: codepipeline_actions.GitHubTrigger.POLL, - // Replace these with your actual GitHub project info - owner: 'GITHUB-OWNER', - repo: 'GITHUB-REPO', - }), - - synthAction: SimpleSynthAction.standardNpmSynth({ - sourceArtifact, - cloudAssemblyArtifact, - - // Use this if you need a build step (if you're not using ts-node - // or if you have TypeScript Lambdas that need to be compiled). - buildCommand: 'npm run build', - }), + const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'] + }) }); } } @@ -299,7 +271,7 @@ import * as cdk from '@aws-cdk/core'; import { MyPipelineStack } from '../lib/my-pipeline-stack'; const app = new cdk.App(); -new MyPipelineStack(app, 'PipelineStack', { +new MyPipelineStack(app, 'MyPipelineStack', { env: { account: '111111111111', region: 'eu-west-1', @@ -315,40 +287,18 @@ app.synth(); In `lib/my-pipeline-stack.js` \(may vary if your project folder isn't named `my-pipeline`\): ``` -const { Stack, SecretValue } = require('@aws-cdk/core'); -const { CdkPipeline, SimpleSynthAction } = require('@aws-cdk/pipelines'); - -const codepipeline = require('@aws-cdk/aws-codepipeline'); -const codepipeline_actions = require('@aws-cdk/aws-codepipeline-actions'); +const cdk = require('@aws-cdk/core'); +const { CodePipeline, CodePipelineSource, ShellStep } = require('@aws-cdk/pipelines'); -class MyPipelineStack extends Stack { + class MyPipelineStack extends cdk.Stack { constructor(scope, id, props) { super(scope, id, props); - const sourceArtifact = new codepipeline.Artifact(); - const cloudAssemblyArtifact = new codepipeline.Artifact(); - - const pipeline = new CdkPipeline(this, 'Pipeline', { - pipelineName: 'MyAppPipeline', - cloudAssemblyArtifact, - - sourceAction: new codepipeline_actions.GitHubSourceAction({ - actionName: 'GitHub', - output: sourceArtifact, - oauthToken: SecretValue.secretsManager('GITHUB_TOKEN_NAME'), - trigger: codepipeline_actions.GitHubTrigger.POLL, - // Replace these with your actual GitHub project info - owner: 'GITHUB-OWNER', - repo: 'GITHUB-REPO' - }), - - synthAction: SimpleSynthAction.standardNpmSynth({ - sourceArtifact, - cloudAssemblyArtifact, - - // Use this if you need a build step (if you're not using ts-node - // or if you have TypeScript Lambdas that need to be compiled). - buildCommand: 'npm run build' + const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'] }) }); } @@ -366,10 +316,10 @@ const cdk = require('@aws-cdk/core'); const { MyPipelineStack } = require('../lib/my-pipeline-stack'); const app = new cdk.App(); -new MyPipelineStack(app, 'PipelineStack', { +new MyPipelineStack(app, 'MyPipelineStack', { env: { account: '111111111111', - region: 'eu-west-1' + region: 'eu-west-1', } }); @@ -382,52 +332,35 @@ app.synth(); In `my-pipeline/my-pipeline-stack.py` \(may vary if your project folder isn't named `my-pipeline`\): ``` -from aws_cdk.core import Stack, StackProps, Construct, SecretValue -from aws_cdk.pipelines import CdkPipeline, SimpleSynthAction - -import aws_cdk.aws_codepipeline as codepipeline -import aws_cdk.aws_codepipeline_actions as codepipeline_actions - -class MyPipelineStack(Stack): - - def __init__(self, scope: Construct, id: str, **kwargs) -> None: - super().__init__(scope, id, **kwargs) - - source_artifact = codepipeline.Artifact() - cloud_assembly_artifact = codepipeline.Artifact() - - pipeline = CdkPipeline(self, "Pipeline", - pipeline_name="MyAppPipeline", - cloud_assembly_artifact=cloud_assembly_artifact, - source_action=codepipeline_actions.GitHubSourceAction( - action_name="GitHub", - output=source_artifact, - oauth_token=SecretValue.secrets_manager("GITHUB_TOKEN_NAME"), - trigger=codepipeline_actions.GitHubTrigger.POLL, - # Replace these with your actual GitHub project info - owner="GITHUB-OWNER", - repo="GITHUB-REPO"), - synth_action=SimpleSynthAction.standard_npm_synth( - source_artifact=source_artifact, - cloud_assembly_artifact=cloud_assembly_artifact, - # Use this if you need a build step (if you're not using ts-node - # or if you have TypeScript Lambdas that need to be compiled). - build_command="npm run build" - ) - ) +from aws_cdk import core as cdk +from aws_cdk.pipelines import CodePipeline, CodePipelineSource, ShellStep + +class MyPipelineStack(cdk.Stack): + + def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + pipeline = CodePipeline(self, "Pipeline", + pipeline_name="MyPipeline", + synth=ShellStep("Synth", + input=CodePipelineSource.git_hub("OWNER/REPO", "main"), + commands=["npm ci", "npm run build", "npx cdk synth"] + ) + ) ``` In `app.py`: ``` #!/usr/bin/env python3 - -from aws_cdk import core +from aws_cdk import core as cdk from my_pipeline.my_pipeline_stack import MyPipelineStack -app = core.App() -MyPipelineStack(app, "my-pipeline", - env=core.Environment(account="111111111111", region="eu-west-1")) +app = cdk.App() +MyPipelineStack(app, "MyPipelineStack", + env=cdk.Environment(account="111111111111", region="eu-west-1") +) + app.synth() ``` @@ -439,16 +372,13 @@ In `src/main/java/com/myorg/MyPipelineStack.java` \(may vary if your project fol ``` package com.myorg; +import java.util.Arrays; import software.amazon.awscdk.core.Construct; -import software.amazon.awscdk.core.SecretValue; import software.amazon.awscdk.core.Stack; import software.amazon.awscdk.core.StackProps; -import software.amazon.awscdk.pipelines.CdkPipeline; -import software.amazon.awscdk.pipelines.SimpleSynthAction; -import software.amazon.awscdk.pipelines.StandardNpmSynthOptions; -import software.amazon.awscdk.services.codepipeline.Artifact; -import software.amazon.awscdk.services.codepipeline.actions.GitHubSourceAction; -import software.amazon.awscdk.services.codepipeline.actions.GitHubTrigger; +import software.amazon.awscdk.pipelines.CodePipeline; +import software.amazon.awscdk.pipelines.CodePipelineSource; +import software.amazon.awscdk.pipelines.ShellStep; public class MyPipelineStack extends Stack { public MyPipelineStack(final Construct scope, final String id) { @@ -458,27 +388,13 @@ public class MyPipelineStack extends Stack { public MyPipelineStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); - final Artifact sourceArtifact = new Artifact(); - final Artifact cloudAssemblyArtifact = new Artifact(); - - final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") - .pipelineName("MyAppPipeline") - .cloudAssemblyArtifact(cloudAssemblyArtifact) - .sourceAction(GitHubSourceAction.Builder.create() - .actionName("GitHub") - .output(sourceArtifact) - .oauthToken(SecretValue.secretsManager("GITHUB_TOKEN_NAME")) - .trigger(GitHubTrigger.POLL) - .owner("GITHUB-OWNER") - .repo("GITHUB-REPO") - .build()) - .synthAction(SimpleSynthAction.standardNpmSynth( - StandardNpmSynthOptions.builder() - .sourceArtifact(sourceArtifact) - .cloudAssemblyArtifact(cloudAssemblyArtifact) - .buildCommand("npm run build") - .build())) - .build(); + CodePipeline pipeline = CodePipeline.Builder.create(this, "pipeline") + .pipelineName("MyPipeline") + .synth(ShellStep.Builder.create("Synth") + .input(CodePipelineSource.gitHub("OWNER/REPO", "main")) + .commands(Arrays.asList)"npm ci", "npm run build", "npx cdk synth")) + .build()) + .build(); } } ``` @@ -490,17 +406,18 @@ package com.myorg; import software.amazon.awscdk.core.App; import software.amazon.awscdk.core.Environment; +import software.amazon.awscdk.core.StackProps; public class MyPipelineApp { public static void main(final String[] args) { App app = new App(); - MyPipelineStack.Builder.create(app, "PipelineStack") + new MyPipelineStack(app, "PipelineStack", StackProps.builder() .env(new Environment.Builder() .account("111111111111") .region("eu-west-1") .build()) - .build(); + .build()); app.synth(); } @@ -515,36 +432,20 @@ In `src/MyPipeline/MyPipelineStack.cs` \(may vary if your project folder isn't n ``` using Amazon.CDK; using Amazon.CDK.Pipelines; -using Amazon.CDK.AWS.CodePipeline; -using Amazon.CDK.AWS.CodePipeline.Actions; namespace MyPipeline { public class MyPipelineStack : Stack { - internal MyPipelineStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) + internal MyPipelineStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { - var sourceArtifact = new Artifact_(); - var cloudAssemblyArtifact = new Artifact_(); - - var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps + var pipeline = new CodePipeline(this, "pipeline", new CodePipelineProps { - PipelineName = "MyAppPipeline", - CloudAssemblyArtifact = cloudAssemblyArtifact, - SourceAction = new GitHubSourceAction(new GitHubSourceActionProps - { - ActionName = "GitHub", - Output = sourceArtifact, - OauthToken = SecretValue.SecretsManager("GITHUB TOKEN_NAME"), - Trigger = GitHubTrigger.POLL, - Owner = "GITHUB-OWNER", - Repo = "GITHUB-REPO" - }), - SynthAction = SimpleSynthAction.StandardNpmSynth(new StandardNpmSynthOptions + PipelineName = "MyPipeline", + Synth = new ShellStep("Synth", new ShellStepProps { - SourceArtifact = sourceArtifact, - CloudAssemblyArtifact = cloudAssemblyArtifact, - BuildCommand = "npm run build" + Input = CodePipelineSource.GitHub("OWNER/REPO", "main"), + Commands = new string[] { "npm ci", "npm run build", "npx cdk synth" } }) }); } @@ -556,9 +457,6 @@ In `src/MyPipeline/Program.cs` \(may vary if your project folder isn't named `my ``` using Amazon.CDK; -using System; -using System.Collections.Generic; -using System.Linq; namespace MyPipeline { @@ -569,12 +467,10 @@ namespace MyPipeline var app = new App(); new MyPipelineStack(app, "MyPipelineStack", new StackProps { - Env = new Amazon.CDK.Environment - { - Account = "111111111111", - Region = "eu-west-1" - } + Env = new Amazon.CDK.Environment { + Account = "111111111111", Region = "eu-west-1" } }); + app.Synth(); } } @@ -583,12 +479,7 @@ namespace MyPipeline ------ -Note the following in this example: -+ The source code is stored in a GitHub repository\. -+ The GitHub access token needed to access the repo is retrieved from AWS Secrets Manager\. Provide the name of the secret where indicated\. -+ Specify the owner of the repository and the repo name where indicated\. - -You must deploy a CDK Pipeline manually once\. After that, the pipeline will keep itself up to date from the source code repository\. To perform the initial deployment: +You must deploy a pipeline manually once\. After that, the pipeline will keep itself up to date from the source code repository, so make sure the code in the repo is the code you want deployed\. Check in your changes and push to GitHub, then deploy: ``` git add --all @@ -598,314 +489,284 @@ cdk deploy ``` **Tip** -Now that you've done the initial deployment, you no longer need AWS administrative access\. +Now that you've done the initial deployment, your local AWS account no longer needs administrative access, because all changes to your app will be deployed via the pipeline\. All you need to be able to do is push to GitHub\. -## Sources and synth actions +## Application stages + +To define a multi\-stack AWS application that can be added to the pipeline all at once, define a subclass of `[Stage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stage.html)` \(not to be confused with `CdkStage` in the CDK Pipelines module\)\. -As we've seen in the preceding example, the basic pieces of CDK Pipelines are *sources* and *synth actions*\. +The stage contains the stacks that make up your application\. If there are dependencies between the stacks, the stacks are automatically added to the pipeline in the right order\. Stacks that don't depend on each other are deployed in parallel\. You can add a dependency relationship between stacks by calling `stack1.addDependency(stack2)`\. -Sources are places where your code lives\. Any source from the [codepipeline\-actions](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-codepipeline-actions-readme.html) module can be used\. +Stages accept a default `env` argument, which becomes the default environment for the stacks inside it\. \(Stacks can still have their own environment specified\.\)\. -Synth actions \(`synthAction`\) define how to build and synth the project\. A synth action can be any AWS CodePipeline action that produces an artifact containing an AWS CDK Cloud Assembly \(the `cdk.out` directory created by `cdk synth`\)\. Pass the output artifact of the synth operation in the Pipeline's `cloudAssemblyArtifact` property\. +An application is added to the pipeline by calling `[addStage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CodePipeline.html#addwbrstagestage-options)()` with instances of `Stage`\. A stage can be instantiated and added to the pipeline multiple times to define different stages of your DTAP or multi\-region application pipeline: -`SimpleSynthAction` is available for synths that can be performed by running a couple of simple shell commands \(install, build, and synth\) using AWS CodeBuild\. When using these, the source repository does not require a `buildspec.yml`\. Here's an example of using `[SimpleSynthAction](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.SimpleSynthAction.html)` to run a Maven \(Java\) build followed by a `cdk synth`: +We will create a stack containing a simple Lambda function and place that stack in a stage\. Then we will add the stage to the pipeline so it can be deployed\. ------ #### [ TypeScript ] -``` -const pipeline = new CdkPipeline(this, 'Pipeline', { - // ... - synthAction: new SimpleSynthAction({ - sourceArtifact, - cloudAssemblyArtifact, - installCommand: 'npm install -g aws-cdk', - buildCommand: 'mvn package', - synthCommand: 'cdk synth', - }) -}); -``` - ------- -#### [ JavaScript ] +Create the new file `lib/my-pipeline-lambda-stack.ts` to hold our application stack containing a Lambda function\. ``` -const pipeline = new CdkPipeline(this, 'Pipeline', { - // ... - synthAction: new SimpleSynthAction({ - sourceArtifact, - cloudAssemblyArtifact, - installCommand: 'npm install -g aws-cdk', - buildCommand: 'mvn package', - synthCommand: 'cdk synth' - }) -}); +import * as cdk from '@aws-cdk/core'; +import { Function, InlineCode, Runtime } from '@aws-cdk/aws-lambda'; + +export class MyLambdaStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + new Function(this, 'LambdaFunction', { + runtime: Runtime.NODEJS_12_X, + handler: 'index.handler', + code: new InlineCode('exports.handler = _ => "Hello, CDK";') + }); + } +} ``` ------- -#### [ Python ] +Create the new file `lib/my-pipeline-app-stage.ts` to hold our stage\. ``` -class MyPipeline(Stack): - def __init__(self, scope: Construct, id: str, **kwargs) -> None: - super().__init__(scope, id, **kwargs) +import * as cdk from '@aws-cdk/core'; +import { MyLambdaStack } from './my-pipeline-lambda-stack'; - pipeline = CdkPipeline(self, "Pipeline", - # ... - synth_action=SimpleSynthAction( - source_artifact=source_artifact, - cloud_assembly_artifact=cloud_assembly_artifact, - install_command="npm install -g aws-cdk", - build_command="mvn package", - synth_command="cdk synth" - )) +export class MyPipelineAppStage extends cdk.Stage { + + constructor(scope: cdk.Construct, id: string, props?: cdk.StageProps) { + super(scope, id, props); + + const lambdaStack = new MyLambdaStack(this, 'LambdaStack'); + } +} ``` ------- -#### [ Java ] +Edit `lib/my-pipeline-stack.ts` to add the stage to our pipeline\. ``` -final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") - // ... - .synthAction(SimpleSynthAction.Builder.create() - .sourceArtifact(sourceArtifact) - .cloudAssemblyArtifact(cloudAssemblyArtifact) - .installCommand("npm install -g aws-cdk") - .buildCommand("mvn package") - .synthCommand("cdk synth") - .build()) - .build(); -``` +import * as cdk from '@aws-cdk/core'; +import { CodePipeline, CodePipelineSource, ShellStep } from '@aws-cdk/pipelines'; +import { MyPipelineAppStage } from './my-pipeline-app-stage'; ------- -#### [ C\# ] +export class MyPipelineStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); -``` -var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps -{ - SynthAction = new SimpleSynthAction(new SimpleSynthActionProps - { - SourceArtifact = sourceArtifact, - CloudAssemblyArtifact = cloudAssemblyArtifact, - InstallCommand = "npm install -g aws-cdk", - BuildCommand = "mvn package", - SynthCommand = "cdk synth" - }) -}); + const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'] + }) + }); + + pipeline.addStage(new MyPipelineAppStage(this, "test", { + env: { account: "111111111111", region: "eu-west-1" } + })); + } +} ``` ------ +#### [ JavaScript ] -A couple of convention\-based synth operations for TypeScript or JavaScript projects are available as class methods of `SimpleSynthAction`: -+ `[standardNpmSynth](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.SimpleSynthAction.html#static-standard-wbr-npm-wbr-synthoptions-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span)()` builds using NPM conventions\. Expects a `package-lock.json`, a `cdk.json`, and expects the CDK Toolkit to be a versioned dependency in `package.json`\. Does not perform a build step by default\. -+ `[standardYarnSynth](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.SimpleSynthAction.html#static-standard-wbr-yarn-wbr-synthoptions-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span)()` builds using Yarn conventions\. Expects a `yarn.lock`, a `cdk.json`, and expects the CDK Toolkit to be a versioned dependency in `package.json`\. Does not perform a build step by default\. - -If your needs are not covered by `SimpleSynthAction`, you can add a custom build/synth step by creating a custom AWS CodeBuild project and passing a corresponding `CodeBuildAction` to the pipeline\. - -## Application stages - -To define a multi\-stack AWS application that can be added to the pipeline all at once, define a subclass of `[Stage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stage.html)` \(not to be confused with `CdkStage` in the CDK Pipelines module\)\. +Create the new file `lib/my-pipeline-lambda-stack.js` to hold our application stack containing a Lambda function\. -The stage contains the stacks that make up your application\. If there are dependencies between the stacks, the stacks are automatically added to the pipeline in the right order\. Stacks that don't depend on each other are deployed in parallel\. You can add a dependency relationship between stacks by calling `stack1.addDependency(stack2)`\. +``` +const cdk = require('@aws-cdk/core'); +const { Function, InlineCode, Runtime } = require('@aws-cdk/aws-lambda'); -Stages accept a default `env` argument, which the `Stack`s inside the `Stage` will use if no environment is specified for them\. +class MyLambdaStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new Function(this, 'LambdaFunction', { + runtime: Runtime.NODEJS_12_X, + handler: 'index.handler', + code: new InlineCode('exports.handler = _ => "Hello, CDK";') + }); + } +} -An application is added to the pipeline by calling `[addApplicationStage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CdkPipeline.html#add-wbr-application-wbr-stageappstage-options-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span)()` with instances of the Stage\. A stage can be instantiated and added to the pipeline multiple times to define different stages of your DTAP or multi\-region application pipeline: +module.exports = { MyLambdaStack } +``` ------- -#### [ TypeScript ] +Create the new file `lib/my-pipeline-app-stage.js` to hold our stage\. ``` -import { Construct, Stack, StackProps, Stage, StageProps } from '@aws-cdk/core'; -import * as codepipeline from '@aws-cdk/aws-codepipeline'; -import { CdkPipeline } from '@aws-cdk/pipelines'; +const cdk = require('@aws-cdk/core'); +const { MyLambdaStack } = require('./my-pipeline-lambda-stack'); -export class DatabaseStack extends Stack { - // ... +class MyPipelineAppStage extends cdk.Stage { + + constructor(scope, id, props) { + super(scope, id, props); + + const lambdaStack = new MyLambdaStack(this, 'LambdaStack'); + } } -export class ComputeStack extends Stack { - // ... -} +module.exports = { MyPipelineAppStage }; +``` -// Your application -// May consist of one or more Stacks -// -export class MyApplication extends Stage { - constructor(scope: Construct, id: string, props?: StageProps) { - super(scope, id, props); +Edit `lib/my-pipeline-stack.ts` to add the stage to our pipeline\. - const dbStack = new DatabaseStack(this, 'Database'); - new ComputeStack(this, 'Compute', { - table: dbStack.table, - }); - } -} +``` +const cdk = require('@aws-cdk/core'); +const { CodePipeline, CodePipelineSource, ShellStep } = require('@aws-cdk/pipelines'); +const { MyPipelineAppStage } = require('./my-pipeline-app-stage'); -// Stack to hold the pipeline -// -export class MyPipelineStack extends Stack { - constructor(scope: Construct, id: string, props?: StackProps) { + class MyPipelineStack extends cdk.Stack { + constructor(scope, id, props) { super(scope, id, props); - const sourceArtifact = new codepipeline.Artifact(); - const cloudAssemblyArtifact = new codepipeline.Artifact(); - - const pipeline = new CdkPipeline(this, 'Pipeline', { - // ...source and build information here + const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'] + }) }); - // Do this as many times as necessary with any account and region - // Account and region may be different from the pipeline's. - pipeline.addApplicationStage(new MyApplication(this, 'Prod', { - env: { - account: '123456789012', - region: 'eu-west-1', - } + pipeline.addStage(new MyPipelineAppStage(this, "test", { + env: { account: "111111111111", region: "eu-west-1" } })); + } } + +module.exports = { MyPipelineStack } ``` ------ -#### [ JavaScript ] +#### [ Python ] + +Create the new file `my_pipeline/my_pipeline_lambda_stack.py` to hold our application stack containing a Lambda function\. ``` -const { Stack, Stage } = require('@aws-cdk/core'); -const codepipeline = require('@aws-cdk/aws-codepipeline'); -const { CdkPipeline } = require('@aws-cdk/pipelines'); +from aws_cdk import core as cdk +from aws_cdk.aws_lambda import Function, InlieCode, Runtime -class DatabaseStack extends Stack { - // ... -} +class MyLambdaStack(cdk.Stack): + def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) -class ComputeStack extends Stack { - // ... -} + Function(self, "LambdaFunction", + runtime=Runtime.NODEJS_12_X, + handler="index.handler", + code=InlineCode("exports.handler = _ => 'Hello, CDK';") + ) +``` -// Your application -// May consist of one or more Stacks -// -class MyApplication extends Stage { - constructor(scope, id, props) { - super(scope, id, props); +Create the new file `my_pipeline/my_pipeline_app_stage.py` to hold our stage\. - const dbStack = new DatabaseStack(this, 'Database'); - new ComputeStack(this, 'Compute', { - table: dbStack.table - }); - } -} +``` +from aws_cdk import core as cdk +from my_pipeline.my_pipeline_lambda_stack import MyLambdaStack -// Stack to hold the pipeline -// -class MyPipelineStack extends Stack { - constructor(scope, id, props) { - super(scope, id, props); +class MyPipelineAppStage(cdk.Stage): + def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) - const sourceArtifact = new codepipeline.Artifact(); - const cloudAssemblyArtifact = new codepipeline.Artifact(); + lambdaStack = MyLambdaStack(self, "LambdaStack") +``` - const pipeline = new CdkPipeline(this, 'Pipeline', { - // ...source and build information here - }); +Edit `my_pipeline/my_pipeline_stack.py` to add the stage to our pipeline\. - // Do this as many times as necessary with any account and region - // Account and region may be different from the pipeline's. - pipeline.addApplicationStage(new MyApplication(this, 'Prod', { - env: { - account: '123456789012', - region: 'eu-west-1' - } - })); - } -} +``` +from aws_cdk import core as cdk +from aws_cdk.pipelines import CodePipeline, CodePipelineSource, ShellStep +from my_pipeline.my_pipeline_app_stage import MyPipelineAppStage + +class MyPipelineStack(cdk.Stack): -module.exports = { MyApplication, MyPipelineStack, ComputeStack, DatabaseStack } + def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + pipeline = CodePipeline(self, "Pipeline", + pipeline_name="MyPipeline", + synth=ShellStep("Synth", + input=CodePipelineSource.git_hub("OWNER/REPO", "main"), + commands=["npm ci", "npm run build", "npx cdk synth"])) + + pipeline.add_stage(MyPipelineAppStage(self, "test", + env=cdk.Environment(account="111111111111", region="eu-west-1"))) ``` ------ -#### [ Python ] +#### [ Java ] -``` -from my_pipeline.my_pipeline_stack import source_artifact -from aws_cdk.core import Construct, Stack, Stage, Environment -from aws_cdk.pipelines import CdkPipeline -import aws_cdk.aws_codepipeline as code_pipeline +Create the new file `src/main/java/com.myorg/MyPipelineLambdaStack.java` to hold our application stack containing a Lambda function\. -class DatabaseStack(Stack): - pass # ... +``` +package com.myorg; -class ComputeStack(Stack): - pass # ... +import software.amazon.awscdk.core.Construct; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; -# Your application -# May consist of one or more Stacks -# -class MyApplication(Stage): - def __init__(self, scope: Construct, id: str, **kwargs): - super().__init__(scope, id, **kwargs) +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.lambda.Runtime; +import software.amazon.awscdk.services.lambda.InlineCode; - db_stack = DatabaseStack(self, "Database") - ComputeStack(self, "Compute", table=db_stack.table) +public class MyPipelineLambdaStack extends Stack { + public MyPipelineLambdaStack(final Construct scope, final String id) { + this(scope, id, null); + } -# Stack to hold the pipeline -# -class MyPipelineStack(Stack): - def __init__(self, scope: Construct, id: str, **kwargs): - super().__init__(scope, id, **kwargs) + public MyPipelineLambdaStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); - source_artifact = code_pipeline.Artifact() - cloud_assembly_artifact = code_pipeline.Artifact() + Function.Builder.create(this, "LambdaFunction") + .runtime(Runtime.NODEJS_12_X) + .handler("index.handler") + .code(new InlineCode("exports.handler = _ => 'Hello, CDK';")) + .build(); - pipeline = CdkPipeline(self, "Pipeline", - # ...source and build information here - ) + } - # Do this as many times as necessary with any account and region - # Account and region may be different from the pipeline's. - pipeline.add_application_stage(MyApplication(self, 'Prod', - env=Environment(account="123456789012", region="eu-west-1"))) +} ``` ------- -#### [ Java ] +Create the new file `src/main/java/com.myorg/MyPipelineAppStage.java` to hold our stage\. ``` -class DatabaseStack extends Stack { - Table table; - - public DatabaseStack(Construct scope, String id) { - super(scope, id); - // ... - } - - public Table getTable() { - return table; - } -} +package com.myorg; + +import software.amazon.awscdk.core.Construct; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.Stage; +import software.amazon.awscdk.core.StageProps; -class ComputeStack extends Stack { - public ComputeStack(Construct scope, String id, Table table) { - // ... +public class MyPipelineAppStage extends Stage { + public MyPipelineAppStage(final Construct scope, final String id) { + this(scope, id, null); } -} -// Your application -// May consist of one or more Stacks -// -class MyApplication extends Stage { - public MyApplication(Construct scope, String id, StageProps props) { + public MyPipelineAppStage(final Construct scope, final String id, final StageProps props) { super(scope, id, props); - DatabaseStack dbStack = new DatabaseStack(this, "Database"); - new ComputeStack(this, "Compute", dbStack.getTable()); + Stack lambdaStack = new MyPipelineLambdaStack(this, "LambdaStack"); } - + } +``` + +Edit `src/main/java/com.myorg/MyPipelineStack.java` to add the stage to our pipeline\. + +``` +package com.myorg; + +import java.util.Arrays; +import software.amazon.awscdk.core.Construct; +import software.amazon.awscdk.core.Environment; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; +import software.amazon.awscdk.core.StageProps; +import software.amazon.awscdk.pipelines.CodePipeline; +import software.amazon.awscdk.pipelines.CodePipelineSource; +import software.amazon.awscdk.pipelines.ShellStep; -// Stack to hold the pipeline -// public class MyPipelineStack extends Stack { public MyPipelineStack(final Construct scope, final String id) { this(scope, id, null); @@ -914,18 +775,17 @@ public class MyPipelineStack extends Stack { public MyPipelineStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); - final Artifact sourceArtifact = new Artifact(); - final Artifact cloudAssemblyArtifact = new Artifact(); - - final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") - // ...source and build information here - .build(); - - // Do this as many times as necessary with any account and region - // Account and region may be different from the pipeline's. - pipeline.addApplicationStage(new MyApplication(this, "Prod", new StackProps.Builder() - .env(new Environment.Builder() - .account("123456789012") + final CodePipeline pipeline = CodePipeline.Builder.create(this, "pipeline") + .pipelineName("MyPipeline") + .synth(ShellStep.Builder.create("Synth") + .input(CodePipelineSource.gitHub("OWNER/REPO", "main")) + .commands(Arrays.asList("npm ci", "npm run build", "npx cdk synth")) + .build()) + .build(); + + pipeline.addStage(new MyPipelineAppStage(this, "test", StageProps.builder() + .env(Environment.builder() + .account("111111111111") .region("eu-west-1") .build()) .build())); @@ -936,188 +796,169 @@ public class MyPipelineStack extends Stack { ------ #### [ C\# ] -``` -public class DatabaseStack : Stack -{ - public Table Table { get; set; } - - public DatabaseStack(Construct scope, string id) : base(scope, id) - { - // ... - } +Create the new file `src/MyPipeline/MyPipelineLambdaStack.cs` to hold our application stack containing a Lambda function\. -} +``` +using Amazon.CDK; +using Amazon.CDK.AWS.Lambda; -public class ComputeStack : Stack +namespace MyPipeline { - public ComputeStack(Construct scope, string id, Table table) : base(scope, id) + class MyPipelineLambdaStack : Stack { - // ... + public MyPipelineLambdaStack(Construct scope, string id, StackProps props=null) : base(scope, id, props) + { + new Function(this, "LambdaFunction", new FunctionProps + { + Runtime = Runtime.NODEJS_12_X, + Handler = "index.handler", + Code = new InlineCode("exports.handler = _ => 'Hello, CDK';") + }); + } } } +``` + +Create the new file `src/MyPipeline/MyPipelineAppStage.cs` to hold our stage\. + +``` +using Amazon.CDK; -// Your application -// May consist of one or more Stacks -// -public class MyApplication : Stage +namespace MyPipeline { - public MyApplication(Construct scope, string id, Amazon.CDK.StageProps props) : base(scope, id, props) + class MyPipelineAppStage : Stage { - var dbStack = new DatabaseStack(this, "Database"); - new ComputeStack(this, "Compute", dbStack.Table); + public MyPipelineAppStage(Construct scope, string id, StageProps props=null) : base(scope, id, props) + { + Stack lambdaStack = new MyPipelineLambdaStack(this, "LambdaStack"); + } } - } +``` -// Stack to hold the pipeline -// -public class MyPipelineStack : Stack +Edit `src/MyPipeline/MyPipelineStack.cs` to add the stage to our pipeline\. + +``` +using Amazon.CDK; +using Amazon.CDK.Pipelines; + +namespace MyPipeline { - public MyPipelineStack(Construct scope, string id, StackProps props) : base(scope, id, props) + public class MyPipelineStack : Stack { - var sourceArtifact = new Artifact_(); - var cloudAssemblyArtifact = new Artifact_(); - - var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps + internal MyPipelineStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { - // ... source and build information here - }); + var pipeline = new CodePipeline(this, "pipeline", new CodePipelineProps + { + PipelineName = "MyPipeline", + Synth = new ShellStep("Synth", new ShellStepProps + { + Input = CodePipelineSource.GitHub("OWNER/REPO", "main"), + Commands = new string[] { "npm ci", "npm run build", "npx cdk synth" } + }) + }); - // Do this as many times as necessary with any account and region - // Account and region may be different from the pipeline's. - pipeline.AddApplicationStage(new MyApplication(this, "Prod", new Amazon.CDK.StageProps - { - Env = new Amazon.CDK.Environment + pipeline.AddStage(new MyPipelineAppStage(this, "test", new StageProps { - Account = "123456789012", - Region = "eu-west-1" - } - })); + Env = new Environment + { + Account = "111111111111", Region = "eu-west-1" + } + })); + } } } ``` ------ -Every application stage added by `addApplicationStage()` leads to the addition of an individual pipeline stage, which is returned by the `addApplicationStage()` call\. This stage is represented by the [CdkStage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CdkStage.html) construct\. You can add more actions to the stage by calling its `[addActions](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CdkStage.html#add-wbr-actionsactions-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span)()` method\. For example: - -**Note** -`core.Stage` is a stage in an AWS CDK app containing stacks\. `pipelines.CdkStage` is a stage in a CDK pipeline\. +Every application stage added by `addStage()` results in the addition of a corresponding pipeline stage, represented by a [StageDeployment](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.StageDeployment.html) instance returned by the `addStage()` call\. You can add pre\-deployment or post\-deployment actions to the stage by calling its `addPre()` or `addPost()` method\. ------ #### [ TypeScript ] ``` -// import { ManualApprovalAction } from '@aws-cdk/aws-codepipeline-actions'; +// import { ManualApprovalStep } from '@aws-cdk/pipelines'; -const testingStage = pipeline.addApplicationStage(new MyApplication(this, 'Testing', { +const testingStage = pipeline.addStage(new MyPipelineAppStage(this, 'testing', { env: { account: '111111111111', region: 'eu-west-1' } })); -// Add an action -- in this case, a Manual Approval action -// (testingStage.addManualApprovalAction() is an equivalent convenience method) -testingStage.addActions(new ManualApprovalAction({ - actionName: 'ManualApproval', - runOrder: testingStage.nextSequentialRunOrder(), -})); + testingStage.addPost(new ManualApprovalStep('approval')); ``` ------ #### [ JavaScript ] ``` -// const { ManualApprovalAction } = require('@aws-cdk/aws-codepipeline-actions'); +// const { ManualApprovalStep } = require('@aws-cdk/pipelines'); -const testingStage = pipeline.addApplicationStage(new MyApplication(this, 'Testing', { +const testingStage = pipeline.addStage(new MyPipelineAppStage(this, 'testing', { env: { account: '111111111111', region: 'eu-west-1' } })); -// Add an action -- in this case, a Manual Approval action -// (testingStage.addManualApprovalAction() is an equivalent convenience method) -testingStage.addActions(new ManualApprovalAction({ - actionName: 'ManualApproval', - runOrder: testingStage.nextSequentialRunOrder() -})); +testingStage.addPost(new ManualApprovalStep('approval')); ``` ------ #### [ Python ] ``` -# from aws_cdk.aws_codepipeline_actions import ManualApprovalAction +# from aws_cdk.pipelines import ManualApprovalStep -testing_stage = pipeline.add_application_stage(MyApplication(self, "Testing", - env=Environment(account="111111111111", region="eu-west-1"))) +testing_stage = pipeline.add_stage(MyPipelineAppStage(self, "testing", + env=cdk.Environment(account="111111111111", region="eu-west-1"))) -# Add an action -- in this case, a Manual Approval action -# (testingStage.addManualApprovalAction() is an equivalent convenience method) -testing_stage.add_actions(ManualApprovalAction( - action_name="ManualApproval", - run_order=testing_stage.next_sequential_run_order() -)) +testing_stage.add_post(ManualApprovalStep('approval')) ``` ------ #### [ Java ] ``` -// import software.amazon.awscdk.services.codepipeline.actions.ManualApprovalAction; +// import software.amazon.awscdk.pipelines.StageDeployment; +// import software.amazon.awscdk.pipelines.ManualApprovalStep; -final CdkStage testingStage = pipeline.addApplicationStage(new MyApplication(this, "Testing", - new StageProps.Builder() - .env(new Environment.Builder() - .account("111111111111") - .region("eu-west-1") - .build()) - .build())); +StageDeployment testingStage = + pipeline.addStage(new MyPipelineAppStage(this, "test", StageProps.builder() + .env(Environment.builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); -// Add an action -- in this case, a Manual Approval action -// (testingStage.addManualApprovalAction() is an equivalent convenience method) -testingStage.addActions(ManualApprovalAction.Builder.create() - .actionName("ManualApproval") - .runOrder(testingStage.nextSequentialRunOrder()) - .build()); +testingStage.addPost(new ManualApprovalStep("approval")); ``` ------ #### [ C\# ] ``` -// using Amazon.CDK.AWS.CodePipeline.Actions; - -var testingStage = pipeline.AddApplicationStage(new MyApplication(this, "Testing", - new Amazon.CDK.StageProps - { - Env = new Amazon.CDK.Environment - { - Account = "111111111111", - Region = "eu-west-1" - } - })); - -// Add an action -- in this case, a Manual Approval action -// (testingStage.AddManualApprovalAction() is an equivalent convenience method) -testingStage.AddActions(new ManualApprovalAction(new ManualApprovalActionProps { - ActionName = "ManualApproval", - RunOrder = testingStage.NextSequentialRunOrder() +var testingStage = pipeline.AddStage(new MyPipelineAppStage(this, "test", new StageProps +{ + Env = new Environment + { + Account = "111111111111", Region = "eu-west-1" + } })); + +testingStage.AddPost(new ManualApprovalStep("approval")); ``` ------ -You can also add more than one application stage to a pipeline stage\. For example: +You can add stages to a [Wave](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.Wave.html) to deploy them in parallel, for example when deploying a stage to multiple accounts or regions\. ------ #### [ TypeScript ] ``` -// Add two application stages to the same pipeline stage -testingStage.addApplicationStage(new MyApplication1(this, 'MyApp1', { +const wave = pipeline.addWave('wave'); +wave.addStage(new MyApplicationStage(this, 'MyAppEU', { env: { account: '111111111111', region: 'eu-west-1' } })); - -testingStage.addApplicationStage(new MyApplication2(this, 'MyApp2', { - env: { account: '111111111111', region: 'eu-west-1' } +wave.addStage(new MyApplicationStage(this, 'MyAppUS', { + env: { account: '111111111111', region: 'us-west-1' } })); ``` @@ -1125,13 +966,12 @@ testingStage.addApplicationStage(new MyApplication2(this, 'MyApp2', { #### [ JavaScript ] ``` -// Add two application stages to the same pipeline stage -testingStage.addApplicationStage(new MyApplication1(this, 'MyApp1', { +const wave = pipeline.addWave('wave'); +wave.addStage(new MyApplicationStage(this, 'MyAppEU', { env: { account: '111111111111', region: 'eu-west-1' } })); - -testingStage.addApplicationStage(new MyApplication2(this, 'MyApp2', { - env: { account: '111111111111', region: 'eu-west-1' } +wave.addStage(new MyApplicationStage(this, 'MyAppUS', { + env: { account: '111111111111', region: 'us-west-1' } })); ``` @@ -1139,55 +979,50 @@ testingStage.addApplicationStage(new MyApplication2(this, 'MyApp2', { #### [ Python ] ``` -# Add two application stages to the same pipeline stage -testing_stage.add_application_stage(MyApplication1(this, 'MyApp1', - env=Environment(account="111111111111", region="eu-west-1"))) - -testing_stage.add_application_stage(MyApplication2(this, 'MyApp2', - env=Environment(account="111111111111", region="eu-west-1"))) +wave = pipeline.add_wave("wave") +wave.add_stage(MyApplicationStage(self, "MyAppEU", + env=cdk.Environment(account="111111111111", region="eu-west-1"))) +wave.add_stage(MyApplicationStage(self, "MyAppUS", + env=cdk.Environment(account="111111111111", region="us-west-1"))) ``` ------ #### [ Java ] ``` -// Add two application stages to the same pipeline stage -testingStage.addApplicationStage(new MyApplication1(this, "MyApp1", new StageProps.Builder() - .env(new Environment.Builder() - .account("111111111111") - .region("eu-west-1") - .build()) - .build())); - -testingStage.addApplicationStage(new MyApplication2(this, "MyApp2", new StageProps.Builder() - .env(new Environment.Builder() - .account("111111111111") - .region("eu-west-1") - .build()) - .build())); +// import software.amazon.awscdk.pipelines.Wave; +final Wave wave = pipeline.addWave("wave"); +wave.addStage(new MyPipelineAppStage(this, "MyAppEU", StageProps.builder() + .env(Environment.builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); +wave.addStage(new MyPipelineAppStage(this, "MyAppUS", StageProps.builder() + .env(Environment.builder() + .account("111111111111") + .region("us-west-1") + .build()) + .build())); ``` ------ #### [ C\# ] ``` -// Add two application stages to the same pipeline stage - -testingStage.AddApplicationStage(new MyApplication1(this, "MyApp1", new Amazon.CDK.StageProps +var wave = pipeline.AddWave("wave"); +wave.AddStage(new MyPipelineAppStage(this, "MyAppEU", new StageProps { - Env = new Amazon.CDK.Environment + Env = new Environment { - Account = "111111111111", - Region = "eu-west-1" + Account = "111111111111", Region = "eu-west-1" } })); - -testingStage.AddApplicationStage(new MyApplication2(this, "MyApp1", new Amazon.CDK.StageProps +wave.AddStage(new MyPipelineAppStage(this, "MyAppUS", new StageProps { - Env = new Amazon.CDK.Environment + Env = new Environment { - Account = "111111111111", - Region = "eu-west-1" + Account = "111111111111", Region = "us-west-1" } })); ``` @@ -1196,7 +1031,7 @@ testingStage.AddApplicationStage(new MyApplication2(this, "MyApp1", new Amazon.C ## Testing deployments -You can add any type of AWS CodePipeline action to a CDK Pipeline to validate the deployments you are performing\. Using the CDK Pipeline library's `[ShellScriptAction](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.ShellScriptAction.html)`, you can try to access a just\-deployed Amazon API Gateway backed by a Lambda function, for example, or issue an AWS CLI command to check some setting of a deployed resource\. +You can add steps to a CDK Pipeline to validate the deployments you are performing\. Using the CDK Pipeline library's `[ShellStep](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.ShellStep.html)`, you can try to access a just\-deployed Amazon API Gateway backed by a Lambda function, for example, or issue an AWS CLI command to check some setting of a deployed resource\. In its simplest form, adding validation actions looks like this: @@ -1204,12 +1039,10 @@ In its simplest form, adding validation actions looks like this: #### [ TypeScript ] ``` -// stage is a CdkStage returned by pipeline.addApplicationStage +// stage was returned by pipeline.addStage -stage.addActions(new ShellScriptAction({ - name: 'MyValidation', +stage.addPost(new ShellStep("validate", { commands: ['curl -Ssf https://my.webservice.com/'], - // ... more configuration ... })); ``` @@ -1217,12 +1050,10 @@ stage.addActions(new ShellScriptAction({ #### [ JavaScript ] ``` -// stage is a CdkStage returned by pipeline.addApplicationStage +// stage was returned by pipeline.addStage -stage.addActions(new ShellScriptAction({ - name: 'MyValidation', - commands: ['curl -Ssf https://my.webservice.com/'] - // ... more configuration ... +stage.addPost(new ShellStep("validate", { + commands: ['curl -Ssf https://my.webservice.com/'], })); ``` @@ -1230,11 +1061,10 @@ stage.addActions(new ShellScriptAction({ #### [ Python ] ``` -# stage is a CdkStage returned by pipeline.addApplicationStage +# stage was returned by pipeline.add_stage -stage.add_actions(ShellScriptAction(name="MyValidation", - commands=['curl -Ssf https://my.webservice.com/'], - # ... more configuration ... +stage.add_post(ShellStep("validate", + commands=['curl -Ssf https://my.webservice.com/'] )) ``` @@ -1242,12 +1072,10 @@ stage.add_actions(ShellScriptAction(name="MyValidation", #### [ Java ] ``` -// stage is a CdkStage returned by pipeline.addApplicationStage +// stage was returned by pipeline.addStage -stage.addActions(ShellScriptAction.Builder.create() - .actionName("MyValidation") +stage.addPost(ShellStep.Builder.create("validate") .commands(Arrays.asList("curl -Ssf https://my.webservice.com/")) - // ... more configuration ... .build()); ``` @@ -1255,15 +1083,11 @@ stage.addActions(ShellScriptAction.Builder.create() #### [ C\# ] ``` -// stage is a CdkStage returned by pipeline.addApplicationStage -stage.AddActions(new ShellScriptAction(new ShellScriptActionProps +// stage was returned by pipeline.addStage + +stage.AddPost(new ShellStep("validate", new ShellStepProps { - ActionName = "MyValidation", - Commands = new string[] - { - "curl -Ssf https://my.webservice.com/" - // ... more configuration ... - } + Commands = new string[] { "curl -Ssf https://my.webservice.com/" } })); ``` @@ -1271,39 +1095,21 @@ stage.AddActions(new ShellScriptAction(new ShellScriptActionProps Because many AWS CloudFormation deployments result in the generation of resources with unpredictable names, CDK Pipelines provide a way to read AWS CloudFormation outputs after a deployment\. This makes it possible to pass \(for example\) the generated URL of a load balancer to a test action\. -To use outputs, expose the `CfnOutput` object you're interested in and pass it `pipeline.stackOutput()`\. +To use outputs, expose the `CfnOutput` object you're interested in and pass it in a step's `envFromCfnOutputs` property to make it available as an environment variable within that step\. ------ #### [ TypeScript ] ``` -export class MyLbApplication extends Stage { - public readonly loadBalancerAddress: CfnOutput; - - constructor(scope: Construct, id: string, props?: StageProps) { - super(scope, id, props); - - const lbStack = new LoadBalancerStack(this, 'Stack'); - - // Or create this in `LoadBalancerStack` directly - this.loadBalancerAddress = new CfnOutput(lbStack, 'LbAddress', { - value: `https://${lbStack.loadBalancer.loadBalancerDnsName}/` - }); - } -} - -const lbApp = new MyLbApplication(this, 'MyApp', { - env: { /* ... */ } +// given a stack lbStack that exposes a load balancer construct as loadBalancer +this.loadBalancerAddress = new cdk.CfnOutput(lbStack, 'LbAddress', { + value: `https://${lbStack.loadBalancer.loadBalancerDnsName}/` }); -const stage = pipeline.addApplicationStage(lbApp); -stage.addActions(new ShellScriptAction({ - // ... - useOutputs: { - // When the test is executed, this will make $URL contain the - // load balancer address. - URL: pipeline.stackOutput(lbApp.loadBalancerAddress), - } +// pass the load balancer address to a shell step +stage.addPost(new ShellStep("lbaddr", { + envFromCfnOutputs: {lb_addr: lbStack.loadBalancerAddress}, + commands: ['echo $lb_addr'] })); ``` @@ -1311,32 +1117,15 @@ stage.addActions(new ShellScriptAction({ #### [ JavaScript ] ``` -class MyLbApplication extends Stage { - - constructor(scope, id, props) { - super(scope, id, props); - - const lbStack = new LoadBalancerStack(this, 'Stack'); - - // Or create this in `LoadBalancerStack` directly - this.loadBalancerAddress = new CfnOutput(lbStack, 'LbAddress', { - value: `https://${lbStack.loadBalancer.loadBalancerDnsName}/` - }); - } -} - -const lbApp = new MyLbApplication(this, 'MyApp', { - env: { /* ... */ } +// given a stack lbStack that exposes a load balancer construct as loadBalancer +this.loadBalancerAddress = new cdk.CfnOutput(lbStack, 'LbAddress', { + value: `https://${lbStack.loadBalancer.loadBalancerDnsName}/` }); -const stage = pipeline.addApplicationStage(lbApp); -stage.addActions(new ShellScriptAction({ - // ... - useOutputs: { - // When the test is executed, this will make $URL contain the - // load balancer address. - URL: pipeline.stackOutput(lbApp.loadBalancerAddress) - } +// pass the load balancer address to a shell step +stage.addPost(new ShellStep("lbaddr", { + envFromCfnOutputs: {lb_addr: lbStack.loadBalancerAddress}, + commands: ['echo $lb_addr'] })); ``` @@ -1344,382 +1133,319 @@ stage.addActions(new ShellScriptAction({ #### [ Python ] ``` -class MyLbApplication(Stage): - load_balancer_address: CfnOutput = None +# given a stack lb_stack that exposes a load balancer construct as load_balancer +self.load_balancer_address = cdk.CfnOutput(lb_stack, "LbAddress", + value=f"https://{lb_stack.load_balancer.load_balancer_dns_name}/") - def __init__(self, scope: Construct, id: str, **kwargs): - super().__init__(scope, str, **kwargs) - - lb_stack = LoadBalancerStack(self, "Stack") - - # Or create this in `LoadBalancerStack` directly - self.load_balancer_address = CfnOutput(lb_stack, "LbAddress", - value=f"https://{lb_stack.load_balancer_dns_name}") - -lb_app = MyLbApplication(self, "Myapp", - env=Environment(...)) - -stage = pipeline.add_application_stage(lb_app) -stage.add_actions(ShellScriptAction( - # ... - use_outputs=pipeline.stack_output( - # When the test is executed, this will make $URL contain the - # load balancer address. - URL=lb_app.load_balancer_address) -)) +# pass the load balancer address to a shell step +stage.add_post(ShellStep("lbaddr", + env_from_cfn_outputs={"lb_addr": lb_stack.load_balancer_address} + commands=["echo $lb_addr"])) ``` ------ #### [ Java ] ``` -class MyLbApplication extends Stage { - CfnOutput loadBalancerAddress; - - public MyLbApplication(Construct scope, String id, StageProps props) { - super(scope, id, props); - - LoadBalancerStack lbStack = new LoadBalancerStack(this, "Stack"); +// given a stack lbStack that exposes a load balancer construct as loadBalancer +loadBalancerAddress = CfnOutput.Builder.create(lbStack, "LbAddress") + .value(String.format("https://%s/", + lbStack.loadBalancer.loadBalancerDnsName)) + .build(); - // Or create this in `LoadBalancerStack` directly - loadBalancerAddress = CfnOutput.Builder.create(lbStack, "LbAddress") - .value(String.format("https://%s/", lbStack.getLoadBalancer().getDnsName())) - .build(); - } - - public CfnOutput getLoadBalancerAddress() { - return loadBalancerAddress; - } -} - -// some time later... -public class MyPipelineStack extends Stack { - public MyPipelineStack(final Construct scope, final String id) { - super(scope, id, null); - } - - @SuppressWarnings("serial") - public MyPipelineStack(final Construct scope, final String id, final StackProps props) { - super(scope, id, props); - - final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") - // ...source and build information here - .build(); - - final MyLbApplication lbApp = // ... - - final CdkStage stage = pipeline.addApplicationStage(lbApp); - stage.addActions(ShellScriptAction.Builder.create() - // ... - .useOutputs(new HashMap() {{ - put("URL", pipeline.stackOutput(lbApp.getLoadBalancerAddress())); - }}) - .build()); - } -} +stage.addPost(ShellStep.Builder.create("lbaddr") + .envFromCfnOutputs(new HashMap() {{ + put("lbAddr", loadBalancerAddress); }}) + .commands(Arrays.asList("echo $lbAddr")) + .build()); ``` ------ #### [ C\# ] ``` -public class MyLbApplication : Stage +// given a stack lbStack that exposes a load balancer construct as loadBalancer +loadBalancerAddress = new CfnOutput(lbStack, "LbAddress", new CfnOutputProps { - public CfnOutput LoadBalancerAddress { get; set; } - - public MyLbApplication(Construct scope, string id, Amazon.CDK.StageProps props) : - base(scope, id, props) - { - - LoadBalancerStack LbStack = new LoadBalancerStack(this, "Stack"); - - // Or create this in `LoadBalancerStack` directly - var loadBalancerAddress = new CfnOutput(LbStack, "LbAddress", new CfnOutputProps - { - Value = $"https://{LbStack.LoadBalancer}/" - }); - } -} + Value = string.Format("https://{0}/", lbStack.loadBalancer.LoadBalancerDnsName) +}); -public class MyPipelineStack : Stack +stage.AddPost(new ShellStep("lbaddr", new ShellStepProps { - public MyPipelineStack(Construct scope, string id, StackProps props = null) : base(scope, id) + EnvFromCfnOutputs = new Dictionary { - var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps - { - // ... source and build information here - }); - - MyLbApplication LbApp = new MyLbApplication(this, "App", new Amazon.CDK.StageProps - { - // set up your application stage - }); - - CdkStage stage = pipeline.AddApplicationStage(LbApp); - stage.AddActions(new ShellScriptAction(new ShellScriptActionProps - { - // ... - UseOutputs = new Dictionary - { - ["URL"] = pipeline.StackOutput(LbApp.LoadBalancerAddress) - } - })); - } -} + { "lbAddr", loadBalancerAddress } + }, + Commands = new string[] { "echo $lbAddr" } +})); ``` ------ -The `ShellScriptAction` limits you to rather small validation tests—basically whatever you can write in a few lines of shell script\. You can bring additional files \(such as complete shell scripts, or scripts in other languages\) into the test via the `additionalArtifacts` property\. +You can write simple validation tests right in the `ShellStep`, but this approach becomes unwieldy when the test is more than a few lines\. For more complex tests, you can bring additional files \(such as complete shell scripts, or programs in other languages\) into the `ShellStep` via the `inputs` property\. The inputs can be any step that has an output, including a source \(such as a GitHub repo\) or another `ShellStep`\. -Bringing in files from the source repository is appropriate if the files are directly usable in the test \(for example, if they are themselves executable\)\. Pass the `sourceArtifact`: +Bringing in files from the source repository is appropriate if the files are directly usable in the test \(for example, if they are themselves executable\)\. In this example, we declare our GitHub repo as `source` \(rather than instantiating it inline as part of the `CodePipeline`\), then pass this fileset to both the pipeline and the validation test\. ------ #### [ TypeScript ] ``` -const sourceArtifact = new codepipeline.Artifact(); +const source = CodePipelineSource.gitHub('OWNER/REPO', 'main'); -const pipeline = new CdkPipeline(this, 'Pipeline', { - // ... +const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: source, + commands: ['npm ci', 'npm run build', 'npx cdk synth'] + }) }); -const validationAction = new ShellScriptAction({ - name: 'TestUsingSourceArtifact', - additionalArtifacts: [sourceArtifact], +const stage = pipeline.addStage(new MyPipelineAppStage(this, 'test', { + env: { account: '111111111111', region: 'eu-west-1' } +})); - // 'test.sh' comes from the source repository - commands: ['./test.sh'], -}); +stage.addPost(new ShellStep('validate', { + input: source, + commands: ['sh ./tests/validate.sh'] +})); ``` ------ #### [ JavaScript ] ``` -const sourceArtifact = new codepipeline.Artifact(); +const source = CodePipelineSource.gitHub('OWNER/REPO', 'main'); -const pipeline = new CdkPipeline(this, 'Pipeline', { - // ... +const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: source, + commands: ['npm ci', 'npm run build', 'npx cdk synth'] + }) }); -const validationAction = new ShellScriptAction({ - name: 'TestUsingSourceArtifact', - additionalArtifacts: [sourceArtifact], +const stage = pipeline.addStage(new MyPipelineAppStage(this, 'test', { + env: { account: '111111111111', region: 'eu-west-1' } +})); - // 'test.sh' comes from the source repository - commands: ['./test.sh'] -}); +stage.addPost(new ShellStep('validate', { + input: source, + commands: ['sh ./tests/validate.sh'] +})); ``` ------ #### [ Python ] ``` -source_artifact = code_pipeline.Artifact() +source = CodePipelineSource.git_hub("OWNER/REPO", "main") -pipeline = CdkPipeline(self, "Pipeline", ...) +pipeline = CodePipeline(self, "Pipeline", + pipeline_name="MyPipeline", + synth=ShellStep("Synth", + input=source, + commands=["npm ci", "npm run build", "npx cdk synth"])) -validation_action = ShellScriptAction( - name="TestUsingSourceArtifact", - additional_artifacts=[source_artifact], - # 'test.sh' comes from the source repository - commands=["./test'sh"] -) +stage = pipeline.add_stage(MyApplicationStage(self, "test", + env=cdk.Environment(account="111111111111", region="eu-west-1"))) + +stage.add_post(ShellStep("validate", input=source, + commands=["curl -Ssf https://my.webservice.com/"], +)) ``` ------ #### [ Java ] ``` -final Artifact sourceArtifact = new Artifact(); - -final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") - // ...source and build information here - .build(); +final CodePipelineSource source = CodePipelineSource.gitHub("OWNER/REPO", "main"); -ShellScriptAction validationAction = ShellScriptAction.Builder.create() - .actionName("TestUsingSourceArtifact") - .additionalArtifacts(Arrays.asList(sourceArtifact)) - // 'test.sh' comes from the source repository - .commands(Arrays.asList("./test.sh")) +final CodePipeline pipeline = CodePipeline.Builder.create(this, "pipeline") + .pipelineName("MyPipeline") + .synth(ShellStep.Builder.create("Synth") + .input(source) + .commands(Arrays.asList("npm ci", "npm run build", "npx cdk synth")) + .build()) .build(); + +final StageDeployment stage = + pipeline.addStage(new MyPipelineAppStage(this, "test", StageProps.builder() + .env(Environment.builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); + +stage.addPost(ShellStep.Builder.create("validate") + .input(source) + .commands(Arrays.asList("sh ./tests/validate.sh")) + .build()); ``` ------ #### [ C\# ] ``` -Artifact_ sourceArtifact = new Artifact_(); +var source = CodePipelineSource.GitHub("OWNER/REPO", "main"); -var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps +var pipeline = new CodePipeline(this, "pipeline", new CodePipelineProps { - // define your pipeline + PipelineName = "MyPipeline", + Synth = new ShellStep("Synth", new ShellStepProps + { + Input = source, + Commands = new string[] { "npm ci", "npm run build", "npx cdk synth" } + }) }); -var validationAction = new ShellScriptAction(new ShellScriptActionProps { - ActionName = "TestUsingSourceArtifact", - AdditionalArtifacts = new Artifact_[] { sourceArtifact }, - Commands = new string[] { "./test.sh" } -}); +var stage = pipeline.AddStage(new MyPipelineAppStage(this, "test", new StageProps +{ + Env = new Environment + { + Account = "111111111111", Region = "eu-west-1" + } +})); + +stage.AddPost(new ShellStep("validate", new ShellStepProps +{ + Input = source, + Commands = new string[] { "sh ./tests/validate.sh" } +})); ``` ------ -Getting the additional files from the synth step is appropriate if your tests need the compilation step that is done as part of synthesis\. On the synthesis step, specify `additionalArtifacts` to package additional subdirectories into artifacts, and use the same artifact in the `ShellScriptAction`'s `additionalArtifacts`: +Getting the additional files from the synth step is appropriate if your tests need to be compiled, which is done as part of synthesis\. ------ #### [ TypeScript ] ``` -// If you are using additional output artifacts from the synth step, -// they must be named. -const cloudAssemblyArtifact = new codepipeline.Artifact('CloudAsm'); -const integTestsArtifact = new codepipeline.Artifact('IntegTests'); - -const pipeline = new CdkPipeline(this, 'Pipeline', { - synthAction: SimpleSynthAction.standardNpmSynth({ - sourceArtifact, - cloudAssemblyArtifact, - buildCommand: 'npm run build', - additionalArtifacts: [ - { - directory: 'test', - artifact: integTestsArtifact, - } - ], - }), - // ... +const synthStep = new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'], }); -const validationAction = new ShellScriptAction({ - actionName: 'TestUsingBuildArtifact', - additionalArtifacts: [integTestsArtifact], - // 'test.js' was produced from 'test/test.ts' during the synth step - commands: ['node ./test.js'], +const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: synthStep }); + +const stage = pipeline.addStage(new MyPipelineAppStage(this, 'test', { + env: { account: '111111111111', region: 'eu-west-1' } +})); + +// run a script that was transpiled from TypeScript during synthesis +stage.addPost(new ShellStep('validate', { + input: synthStep, + commands: ['node tests/validate.js'] +})); ``` ------ #### [ JavaScript ] ``` -// If you are using additional output artifacts from the synth step, -// they must be named. -const cloudAssemblyArtifact = new codepipeline.Artifact('CloudAsm'); -const integTestsArtifact = new codepipeline.Artifact('IntegTests'); - -const pipeline = new CdkPipeline(this, 'Pipeline', { - synthAction: SimpleSynthAction.standardNpmSynth({ - sourceArtifact, - cloudAssemblyArtifact, - buildCommand: 'npm run build', - additionalArtifacts: [ - { - directory: 'test', - artifact: integTestsArtifact - } - ] - }) - // ... +const synthStep = new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'], }); -const validationAction = new ShellScriptAction({ - actionName: 'TestUsingBuildArtifact', - additionalArtifacts: [integTestsArtifact], - // 'test.js' was produced from 'test/test.ts' during the synth step - commands: ['node ./test.js'] +const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: synthStep }); + +const stage = pipeline.addStage(new MyPipelineAppStage(this, "test", { + env: { account: "111111111111", region: "eu-west-1" } +})); + +// run a script that was transpiled from TypeScript during synthesis +stage.addPost(new ShellStep('validate', { + input: synthStep, + commands: ['node tests/validate.js'] +})); ``` ------ #### [ Python ] ``` -# If you are using additional output artifacts from the synth step, -# they must be named. -cloud_assembly_artifact = code_pipeline.Artifact("CloudAsm") -integ_tests_artifact = code_pipeline.Artifact("IntegTests") - -pipeline = CdkPipeline(self, "Pipeline", - synth_action=SimpleSynthAction.standard_npm_synth( - source_artifact=source_artifact, - cloud_assembly_artifact=cloud_assembly_artifact, - build_command="tsc", - additional_artifacts=[dict(directory='test', - artifact=integ_tests_artifact)] - # ... - )) - -validation_action = ShellScriptAction( - action_name="TestUsingBuildArtifact", - additional_artifacts=[integ_tests_artifact], - # 'test.js' was produced from "test/test.ts" during the synth step - commands=["node ./test.js"] -) +synth_step = ShellStep("Synth", + input=CodePipelineSource.git_hub("OWNER/REPO", "main"), + commands=["npm ci", "npm run build", "npx cdk synth"]) + +pipeline = CodePipeline(self, "Pipeline", + pipeline_name="MyPipeline", + synth=synth_step) + +stage = pipeline.add_stage(MyApplicationStage(self, "test", + env=cdk.Environment(account="111111111111", region="eu-west-1"))) + +# run a script that was compiled during synthesis +stage.add_post(ShellStep("validate", + input=synth_step, + commands=["node test/validate.js"], +)) ``` ------ #### [ Java ] ``` -// If you are using additional output artifacts from the synth step, -// they must be named. -final Artifact cloudAssemblyArtifact = new Artifact("IntegTests"); -final Artifact integTestsArtifact = new Artifact("IntegTests"); - -final CdkPipeline pipeline = CdkPipeline.Builder.create(this, "Pipeline") - .synthAction(SimpleSynthAction.standardNpmSynth(new StandardNpmSynthOptions.Builder() - .sourceArtifact(sourceArtifact) - .cloudAssemblyArtifact(cloudAssemblyArtifact) - .buildCommand("npm run build") - .additionalArtifacts(Arrays.asList(new AdditionalArtifact.Builder() - .directory("test").artifact(integTestsArtifact).build())) - .build())) - .build(); +final ShellStep synth = ShellStep.Builder.create("Synth") + .input(CodePipelineSource.gitHub("OWNER/REPO", "main")) + .commands(Arrays.asList("npm ci", "npm run build", "npx cdk synth")) + .build(); + +final CodePipeline pipeline = CodePipeline.Builder.create(this, "pipeline") + .pipelineName("MyPipeline") + .synth(synth) + .build(); + +final StageDeployment stage = + pipeline.addStage(new MyPipelineAppStage(this, "test", StageProps.builder() + .env(Environment.builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); -final ShellScriptAction validationAction = ShellScriptAction.Builder.create() - .actionName("TestUsingBuildArtifact") - .additionalArtifacts(Arrays.asList(integTestsArtifact)) - // 'test.js' was produced from 'test/test.ts' during the synth step - .commands(Arrays.asList("node ./test.js")) - .build(); +stage.addPost(ShellStep.Builder.create("validate") + .input(synth) + .commands(Arrays.asList("node ./tests/validate.js")) + .build()); ``` ------ #### [ C\# ] ``` -// If you are using additional output artifacts from the synth step, -// they must be named. -var sourceArtifact = new Artifact_("Source"); -var cloudAssemblyArtifact = new Artifact_("CloudAssembly"); -var integTestsArtifact = new Artifact_("IntegTests"); - -var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps +var synth = new ShellStep("Synth", new ShellStepProps { - SynthAction = SimpleSynthAction.StandardNpmSynth(new StandardNpmSynthOptions - { - SourceArtifact = sourceArtifact, - CloudAssemblyArtifact = cloudAssemblyArtifact, - BuildCommand = "npm run build", - AdditionalArtifacts = new AdditionalArtifact[] - { - new AdditionalArtifact - { - Directory = "test", - Artifact = integTestsArtifact - } - } - }), + Input = CodePipelineSource.GitHub("OWNER/REPO", "main"), + Commands = new string[] { "npm ci", "npm run build", "npx cdk synth" } }); -var validationAction = new ShellScriptAction(new ShellScriptActionProps +var pipeline = new CodePipeline(this, "pipeline", new CodePipelineProps { - ActionName = "TestUsingBuildArtifact", - AdditionalArtifacts = new Artifact_[] { integTestsArtifact }, - Commands = new string[] { "node./test.js" } + PipelineName = "MyPipeline", + Synth = synth }); + +var stage = pipeline.AddStage(new MyPipelineAppStage(this, "test", new StageProps +{ + Env = new Environment + { + Account = "111111111111", Region = "eu-west-1" + } +})); + +stage.AddPost(new ShellStep("validate", new ShellStepProps +{ + Input = synth, + Commands = new string[] { "node ./tests/validate.js" } +})); ``` ------ @@ -1729,9 +1455,9 @@ var validationAction = new ShellScriptAction(new ShellScriptActionProps Any form of continuous delivery has inherent security risks\. Under the AWS [Shared Responsibility Model](https://aws.amazon.com/compliance/shared-responsibility-model/), you are responsible for the security of your information in the AWS cloud\. The CDK Pipelines library gives you a head start by incorporating secure defaults and modeling best practices, but by its very nature a library that needs a high level of access to fulfill its intended purpose cannot assure complete security\. There are many attack vectors outside of AWS and your organization\. In particular, keep in mind the following\. -+ Be mindful of the software you depend on\. Vet all third\-party software you run on your build machine, as it has the ability to change the infrastructure that gets deployed\. -+ Use dependency locking to prevent accidental upgrades\. The default `CdkSynth` that come with CDK Pipelines respect `package-lock.json` and `yarn.lock` to ensure your dependencies are the ones you expect\. -+ Credentials for production environments should be short\-lived\. After bootstrapping and initial provisioning, there is no need for developers to have account credentials; all changes can be deployed through the pipeline\. Eliminate the possibility of credentials leaking by not needing them in the first place\! ++ Be mindful of the software you depend on\. Vet all third\-party software you run in your pipeline, as it has the ability to change the infrastructure that gets deployed\. ++ Use dependency locking to prevent accidental upgrades\. CDK Pipelines respects `package-lock.json` and `yarn.lock` to ensure your dependencies are the ones you expect\. ++ Credentials for production environments should be short\-lived\. After bootstrapping and initial provisioning, there is no need for developers to have account credentials at all; changes can be deployed through the pipeline\. Eliminate the possibility of credentials leaking by not needing them in the first place\! ## Troubleshooting From 87f2fb04f8d43adad7334f40b3184bb04fd8dd0b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 18 Aug 2021 23:28:12 +0000 Subject: [PATCH 439/655] autogenerated ID churn --- doc_source/cli.md | 26 +++++++++++++------------- doc_source/getting_started.md | 2 +- doc_source/hello_world.md | 2 +- doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-v2.md | 2 +- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 7694ac7e..2f8c989b 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -336,7 +336,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -355,7 +355,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -363,7 +363,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -387,7 +387,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -409,7 +409,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -626,7 +626,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -639,7 +639,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -660,7 +660,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -735,7 +735,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -788,7 +788,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -807,7 +807,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -830,7 +830,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -852,7 +852,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 6365b931..602cb2a0 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -240,4 +240,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 1d298982..bf00a7fe 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -63,7 +63,7 @@ cdk init app --language javascript cdk init app --language python ``` -After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install its dependencies\. +After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install the AWS CDK core dependencies\. ``` source .venv/bin/activate diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 08ef26f6..3b353160 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 2e6a072c..d949ab19 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index b242d6c5..60e81b5d 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -29,7 +29,7 @@ Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prereq To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. -### Updating `cdk.json` +### Updating `cdk.json` Remove all feature flags from `cdk.json`\. You can add one or more of the three flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these are needed\. From 256e5f822aa57459b0f7950c4ecdf5d0e3fb97be Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 24 Aug 2021 23:58:19 +0000 Subject: [PATCH 440/655] update guidance around context values --- doc_source/best-practices.md | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md index 44ea16a1..b996f917 100644 --- a/doc_source/best-practices.md +++ b/doc_source/best-practices.md @@ -100,7 +100,7 @@ Many enterprise customers are writing their own wrappers for L2 constructs \(the Instead, use AWS features such as [service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) and [permission boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to enforce your security guardrails at the organization level\. Use [Aspects](aspects.md) or tools like [CloudFormation Guard](https://github.com/aws-cloudformation/cloudformation-guard) to make assertions about the security properties of infrastructure elements before deployment\. Use AWS CDK for what it does best\. -Finally, keep in mind that writing your own "L2\+" constructs like these may prevent your developers from taking advantage of the growing ecosystems of AWS CDK packages, such as [AWS Solutions Constructs](https://docs.aws.amazon.com/solutions/latest/constructs/welcome.html), as these are typically based on standard AWS CDK constructs and won't be able to use your custom versions\. +Finally, keep in mind that writing your own "L2\+" constructs like these may prevent your developers from taking advantage of the growing ecosystems of AWS CDK packages, such as [AWS Solutions Constructs](https://docs.aws.amazon.com/solutions/latest/constructs/welcome.html), as these are typically built upon standard AWS CDK constructs and won't be able to use your custom versions\. ## Application best practices @@ -108,7 +108,7 @@ In this section we discuss how best to write your AWS CDK applications, combinin ### Make decisions at synthesis time -Although AWS CloudFormation lets you make decisions at deployment time \(using `Conditions`, `{ Fn::If }`, and `Parameters`\), and the AWS CDK gives you some access to these mechanisms, we recommend against using them\. The types of values you can use, and the types of operations you can perform on them, are quite limited\. +Although AWS CloudFormation lets you make decisions at deployment time \(using `Conditions`, `{ Fn::If }`, and `Parameters`\), and the AWS CDK gives you some access to these mechanisms, we recommend against using them\. The types of values you can use, and the types of operations you can perform on them, are quite limited compared to those available in a general\-purpose programming language\. Instead, try to make all decisions, such as which construct to instantiate, in your AWS CDK application, using your programming language's `if` statements and other features\. For example, a common CDK idiom, iterating over a list and instantiating a construct with values from each item in the list, simply isn't possible using AWS CloudFormation expressions\. @@ -135,15 +135,23 @@ There is no hard and fast rule to how many stacks your application needs\. You'l + Consider keeping stateful resources \(like databases\) in a separate stack from stateless resources\. You can then turn on termination protection on the stateful stack, and can freely destroy or create multiple copies of the stateless stack without risk of data loss\. + Stateful resources are more sensitive to construct renaming—renaming leads to resource replacement—so it makes sense not to nest them inside constructs that are likely to be moved around or renamed \(unless the state can be rebuilt if lost, like a cache\)\. This is another good reason to put stateful resources in their own stack\. -### Keep synthesis deterministic and commit `cdk.context.json` +### Commit `cdk.context.json` to avoid non\-deterministic behavior -In general, don't put network access code, or any other code that is sensitive to the synthesis environment, in your AWS CDK app\. Apart from the possibility of that call failing at an inopportune time, what's worse is that it's non\-deterministic—it may return a different answer every time\. This means your stack could be different every time you synthesize it, which makes it harder to test your code and to roll your infrastructure back to a previous state\. +Determinism is key to successful AWS CDK deployments\. A AWS CDK app should have essentially the same result whenever it is deployed \(notwithstanding necessary differences based on the environment where it's deployed\)\. -The AWS CDK includes features that use network access to look up information during synthesis\. The AWS CDK caches the results of these lookups in the file `cdk.context.json`, which you should commit to version control along with the rest of your app\. The result of that lookup is thereby "locked in" until you explicitly change it, allowing you to get exactly the same result each time you synthesize\. \(See [Runtime context](context.md)\.\) A couple of examples of where this happens \(and the possible consequences of not committing the cache\) are: -+ If you provision an Amazon VPC to all available Availability Zones in a specified region, which is two on deployment day, your IP space gets split in two\. If AWS launches a new Availability Zone the next day, the next deployment tries to split your IP space in three, requiring all subnets to be recreated; this probably won't be possible because instances are still running, and you'll have to clean up manually\. -+ If you query for the latest Amazon Linux machine image and deploy an Amazon EC2 instance, and the next day a new image is released, the deployment the day after picks up the new AMI and replaces all your instances\. This may not be what you expected to happen\. +Since your AWS CDK app is written in a a general\-purpose programming language, it can execute arbitrary code, use arbitrary libraries, and make arbitrary network calls\. For example, you could use an AWS SDK to retrieve some information from your AWS account while synthesizing your app\. Recognize that doing so will result in additional credential setup requirements, increased latency, and a chance, however small, of failure every time you run `cdk synth`\. - Use the same approach if you must use information from outside your app\. For example, write an external script to gather the information and write it to a file, execute the script once, and commit the resulting file \(and the script that created it\)\. Then read that file in your AWS CDK app\. When you want to update this information, do so explicitly by running the script again\. +You should never modify your AWS account or resources during synthesis; synthesizing an app should not have side effects\. Changes to your infrastructure should happen only in the deployment phase, after the AWS CloudFormation template has been generated\. This way, if there's a problem, AWS CloudFormation will automatically roll back the change\. To make changes that can't be easily made within the AWS CDK framework, use [custom resources](https://docs.aws.amazon.com/https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html) to execute arbitrary code at deployment time\. + +But even strictly read\-only calls are not necessarily safe\. Consider what happens if the value returned by a network call changes\. What part of your infrastructure will that impact? What will happen to already\-deployed resources? Here are just two of the situations in which a sudden change in values might cause a problem\. ++ If you provision an Amazon VPC to all available Availability Zones in a specified region, and the number of AZs is two on deployment day, your IP space gets split in half\. If AWS launches a new Availability Zone the next day, the next deployment after that tries to split your IP space into thirds, requiring all subnets to be recreated\. This probably won't be possible because your Amazon EC2 instances are still running, and you'll have to clean this up manually\. ++ If you query for the latest Amazon Linux machine image and deploy an Amazon EC2 instance, and the next day a new image is released, a subsequent deployment picks up the new AMI and replaces all your instances\. This may not be what you expected to happen\. + +These situations can be particularly pernicious because the AWS\-side change may occur after months or years of successful deployments\. Suddenly your deployments are failing "for no reason" and you have long ago forgotten what you originally did and why\. + +Fortunately, the AWS CDK includes a mechanism called *context providers* to record a snapshot of non\-deterministic values, allowing future synthesis operations produce the same template\. The only changes in the synthesized template are the changes *you* made in your code\. When you use a construct's `.fromLookup()` method, the result of the call is cached in `cdk.context.json`, which you should commit to version control along with the rest of your code to ensure future executions of your CDK app use the same value\. The AWS CDK Toolkit includes commands to manage the context cache, so you can refresh specific entries when you need to\. For more information, see [Runtime context](context.md) + +If you need some value \(from AWS or elsewhere\) for which there is no native CDK context provider, we recommend writing a separate script to retrieve the value and write it to a file, then consume that file in your CDK app\. Do not run the script as part of your regular build process, but only when you want to refresh the stored value\. ### Let the AWS CDK manage roles and security groups From 7dafb3ec9ce84fd2aaaf1e62cd64c803d10e1857 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 24 Aug 2021 23:58:47 +0000 Subject: [PATCH 441/655] generated ID changes --- doc_source/cli.md | 26 +++++++++++++------------- doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-v2.md | 2 +- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 2f8c989b..d588fd6a 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -336,7 +336,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -355,7 +355,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -363,7 +363,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -387,7 +387,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -409,7 +409,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -626,7 +626,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -639,7 +639,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -660,7 +660,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -735,7 +735,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -788,7 +788,7 @@ Options: [string] [choices: "bar", "events"] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -807,7 +807,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -830,7 +830,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -852,7 +852,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 3b353160..d7a83a98 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index d949ab19..c7740f00 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -4,7 +4,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index 60e81b5d..e23b76f2 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -29,7 +29,7 @@ Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prereq To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. -### Updating `cdk.json` +### Updating `cdk.json` Remove all feature flags from `cdk.json`\. You can add one or more of the three flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these are needed\. From d556f804799edc03e545d1e9cf2a860f33379b22 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 26 Aug 2021 14:31:44 +0000 Subject: [PATCH 442/655] tweaks --- doc_source/best-practices.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md index b996f917..4fda798f 100644 --- a/doc_source/best-practices.md +++ b/doc_source/best-practices.md @@ -126,7 +126,7 @@ A better approach is to specify as few names as possible\. If you leave out reso The AWS CDK does its best to keep you from losing data by defaulting to policies that retain everything you create\. For example, the default removal policy on resources that contain data \(such as Amazon S3 buckets and database tables\) is to never delete the resource when it is removed from the stack, but rather orphan the resource from the stack\. Similarly, the CDK's default is to retain all logs forever\. In production environments, these defaults can quickly result in the storage of large amounts of data you don't actually need, and a corresponding AWS bill\. -Consider carefully what you want these policies to actually be for each production resource and specify them accordingly\. Use an [Aspects](aspects.md) to validate the removal and logging policies in your stack\. +Consider carefully what you want these policies to actually be for each production resource and specify them accordingly\. Use [Aspects](aspects.md) to validate the removal and logging policies in your stack\. ### Separate your application into multiple stacks as dictated by deployment requirements @@ -141,17 +141,17 @@ Determinism is key to successful AWS CDK deployments\. A AWS CDK app should have Since your AWS CDK app is written in a a general\-purpose programming language, it can execute arbitrary code, use arbitrary libraries, and make arbitrary network calls\. For example, you could use an AWS SDK to retrieve some information from your AWS account while synthesizing your app\. Recognize that doing so will result in additional credential setup requirements, increased latency, and a chance, however small, of failure every time you run `cdk synth`\. -You should never modify your AWS account or resources during synthesis; synthesizing an app should not have side effects\. Changes to your infrastructure should happen only in the deployment phase, after the AWS CloudFormation template has been generated\. This way, if there's a problem, AWS CloudFormation will automatically roll back the change\. To make changes that can't be easily made within the AWS CDK framework, use [custom resources](https://docs.aws.amazon.com/https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html) to execute arbitrary code at deployment time\. +You should never modify your AWS account or resources during synthesis; synthesizing an app should not have side effects\. Changes to your infrastructure should happen only in the deployment phase, after the AWS CloudFormation template has been generated\. This way, if there's a problem, AWS CloudFormation will automatically roll back the change\. To make changes that can't be easily made within the AWS CDK framework, use [custom resources](https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html) to execute arbitrary code at deployment time\. -But even strictly read\-only calls are not necessarily safe\. Consider what happens if the value returned by a network call changes\. What part of your infrastructure will that impact? What will happen to already\-deployed resources? Here are just two of the situations in which a sudden change in values might cause a problem\. +Even strictly read\-only calls are not necessarily safe\. Consider what happens if the value returned by a network call changes\. What part of your infrastructure will that impact? What will happen to already\-deployed resources? Here are just two of the situations in which a sudden change in values might cause a problem\. + If you provision an Amazon VPC to all available Availability Zones in a specified region, and the number of AZs is two on deployment day, your IP space gets split in half\. If AWS launches a new Availability Zone the next day, the next deployment after that tries to split your IP space into thirds, requiring all subnets to be recreated\. This probably won't be possible because your Amazon EC2 instances are still running, and you'll have to clean this up manually\. + If you query for the latest Amazon Linux machine image and deploy an Amazon EC2 instance, and the next day a new image is released, a subsequent deployment picks up the new AMI and replaces all your instances\. This may not be what you expected to happen\. -These situations can be particularly pernicious because the AWS\-side change may occur after months or years of successful deployments\. Suddenly your deployments are failing "for no reason" and you have long ago forgotten what you originally did and why\. +These situations can be particularly pernicious because the AWS\-side change may occur after months or years of successful deployments\. Suddenly your deployments are failing "for no reason" and you long ago forgot what you did and why\. -Fortunately, the AWS CDK includes a mechanism called *context providers* to record a snapshot of non\-deterministic values, allowing future synthesis operations produce the same template\. The only changes in the synthesized template are the changes *you* made in your code\. When you use a construct's `.fromLookup()` method, the result of the call is cached in `cdk.context.json`, which you should commit to version control along with the rest of your code to ensure future executions of your CDK app use the same value\. The AWS CDK Toolkit includes commands to manage the context cache, so you can refresh specific entries when you need to\. For more information, see [Runtime context](context.md) +Fortunately, the AWS CDK includes a mechanism called *context providers* to record a snapshot of non\-deterministic values, allowing future synthesis operations produce exactly the same template\. The only changes in the new template are the changes *you* made in your code\. When you use a construct's `.fromLookup()` method, the result of the call is cached in `cdk.context.json`, which you should commit to version control along with the rest of your code to ensure future executions of your CDK app use the same value\. The AWS CDK Toolkit includes commands to manage the context cache, so you can refresh specific entries when you need to\. For more information, see [Runtime context](context.md)\. -If you need some value \(from AWS or elsewhere\) for which there is no native CDK context provider, we recommend writing a separate script to retrieve the value and write it to a file, then consume that file in your CDK app\. Do not run the script as part of your regular build process, but only when you want to refresh the stored value\. +If you need some value \(from AWS or elsewhere\) for which there is no native CDK context provider, we recommend writing a separate script to retrieve the value and write it to a file, then read that file in your CDK app\. Run the script only when you want to refresh the stored value, not as part of your regular build process\. ### Let the AWS CDK manage roles and security groups From 65415261e5f77e09b6bbbc8e2a566aec599e346c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 4 Sep 2021 15:51:11 +0000 Subject: [PATCH 443/655] updates --- doc_source/best-practices.md | 5 +++-- doc_source/cdk_pipeline.md | 2 +- doc_source/cli.md | 12 ++++++++---- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md index 4fda798f..0fadb39a 100644 --- a/doc_source/best-practices.md +++ b/doc_source/best-practices.md @@ -4,13 +4,14 @@ The AWS CDK allows developers or administrators to define their cloud infrastruc The AWS CDK reflects careful consideration of the needs of our customers and internal teams and of the failure patterns that often arise during the deployment and ongoing maintenance of complex cloud applications\. We discovered that failures are often related to "out\-of\-band" changes to an application, such as configuration changes, that were not fully tested\. Therefore, we developed the AWS CDK around a model in which your entire application, not just business logic but also infrastructure and configuration, is defined in code\. That way, proposed changes can be carefully reviewed, comprehensively tested in environments resembling production to varying degrees, and fully rolled back if something goes wrong\. -In addition to the guidance in this document, you should also consider [best practices for AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html) as well as for the individual AWS services you use, where they are obviously applicable to CDK\-defined infrastructure\. - ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/all-in-one.jpg) At deployment time, the AWS CDK synthesizes a cloud assembly that contains not only AWS CloudFormation templates describing your infrastructure in all target environments, but file assets containing your runtime code and their supporting files\. With the CDK, every commit in your application's main version control branch can represent a complete, consistent, deployable version of your application\. Your application can then be deployed automatically whenever a change is made\. The philosophy behind the AWS CDK leads to our recommended best practices, which we have divided into four broad categories\. + +**Tip** +In addition to the guidance in this document, you should also consider [best practices for AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html) as well as for the individual AWS services you use, where they are obviously applicable to CDK\-defined infrastructure\. + [Organization best practices](#best-practices-organization) + [Coding best practices](#best-practices-code) + [Construct best practices](#best-practices-constructs) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 10326b08..33b15b30 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -5,7 +5,7 @@ CDK Pipelines are self\-updating: if you add application stages or stacks, the pipeline automatically reconfigures itself to deploy those new stages and/or stacks\. **Note** -CDK Pipelines supports two APIs: the original API that was made available in the Developer Preview release, and a modern one that incorporates feedback from CDK customers received during the preview phase\. The examples in this topic use the modern API\. For details on the differences between the two supported APIs, see [CDK Pipelines original API](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/pipelines/ORIGINAL_API.md)\. +CDK Pipelines supports two APIs: the original API that was made available in the Developer Preview, and a modern one that incorporates feedback from CDK customers received during the preview phase\. The examples in this topic use the modern API\. For details on the differences between the two supported APIs, see [CDK Pipelines original API](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/pipelines/ORIGINAL_API.md)\. ## Bootstrap your AWS environments diff --git a/doc_source/cli.md b/doc_source/cli.md index d588fd6a..2e1d66a1 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -613,9 +613,6 @@ Options: --no-color Removes colors and other style from console output [boolean] [default: false] - --fail Fail with exit code 1 in case of diff - [boolean] [default: false] - --version Show version number [boolean] -h, --help Show help [boolean] @@ -785,7 +782,11 @@ Options: this is disabled) [boolean] [default: true] --progress Display mode for stack activity events - [string] [choices: "bar", "events"] + [string] [choices: "bar", "events"] + + --rollback Rollback stack to stable state on failure (iterate + more rapidly with --no-rollback or -R) + [boolean] [default: true] ``` ### `cdk destroy` @@ -827,6 +828,9 @@ Options: with [string] --security-only Only diff for broadened security changes + [boolean] [default: false] + + --fail Fail with exit code 1 in case of diff [boolean] [default: false] ``` From 112ce920bee57b48786decbe5cf1e17342136d51 Mon Sep 17 00:00:00 2001 From: aws-farrdoug Date: Thu, 9 Sep 2021 13:20:07 +0100 Subject: [PATCH 444/655] [bugfix] Removed erroneous link to SDK rather than CDK --- doc_source/about_examples.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/doc_source/about_examples.md b/doc_source/about_examples.md index ccf624e9..3c156277 100644 --- a/doc_source/about_examples.md +++ b/doc_source/about_examples.md @@ -1,5 +1,3 @@ # AWS CDK examples -For more examples of AWS CDK stacks and apps in your favorite supported programming language, see: -+ The [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repository on GitHub -+ The [AWS Code Example Repository](https://github.com/awsdocs/aws-doc-sdk-examples)\. \ No newline at end of file +For more examples of AWS CDK stacks and apps in your favorite supported programming language, see the [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repository on GitHub. \ No newline at end of file From 213cab7de814f3a6b17d13e73b8d34ee30fe3dca Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 13 Sep 2021 22:45:04 +0000 Subject: [PATCH 445/655] autoformat --- doc_source/about_examples.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/about_examples.md b/doc_source/about_examples.md index 3c156277..eea1ebeb 100644 --- a/doc_source/about_examples.md +++ b/doc_source/about_examples.md @@ -1,3 +1,3 @@ # AWS CDK examples -For more examples of AWS CDK stacks and apps in your favorite supported programming language, see the [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repository on GitHub. \ No newline at end of file +For more examples of AWS CDK stacks and apps in your favorite supported programming language, see the [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repository on GitHub\. \ No newline at end of file From 73c3529ebc84d16e3ec4307239fa40403115e462 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 28 Sep 2021 22:27:21 +0000 Subject: [PATCH 446/655] remove AWS from CDK Toolkit text --- doc_source/best-practices.md | 2 +- doc_source/cli.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md index 0fadb39a..6acf194e 100644 --- a/doc_source/best-practices.md +++ b/doc_source/best-practices.md @@ -150,7 +150,7 @@ Even strictly read\-only calls are not necessarily safe\. Consider what happens These situations can be particularly pernicious because the AWS\-side change may occur after months or years of successful deployments\. Suddenly your deployments are failing "for no reason" and you long ago forgot what you did and why\. -Fortunately, the AWS CDK includes a mechanism called *context providers* to record a snapshot of non\-deterministic values, allowing future synthesis operations produce exactly the same template\. The only changes in the new template are the changes *you* made in your code\. When you use a construct's `.fromLookup()` method, the result of the call is cached in `cdk.context.json`, which you should commit to version control along with the rest of your code to ensure future executions of your CDK app use the same value\. The AWS CDK Toolkit includes commands to manage the context cache, so you can refresh specific entries when you need to\. For more information, see [Runtime context](context.md)\. +Fortunately, the AWS CDK includes a mechanism called *context providers* to record a snapshot of non\-deterministic values, allowing future synthesis operations produce exactly the same template\. The only changes in the new template are the changes *you* made in your code\. When you use a construct's `.fromLookup()` method, the result of the call is cached in `cdk.context.json`, which you should commit to version control along with the rest of your code to ensure future executions of your CDK app use the same value\. The CDK Toolkit includes commands to manage the context cache, so you can refresh specific entries when you need to\. For more information, see [Runtime context](context.md)\. If you need some value \(from AWS or elsewhere\) for which there is no native CDK context provider, we recommend writing a separate script to retrieve the value and write it to a file, then read that file in your CDK app\. Run the script only when you want to refresh the stored value, not as part of your regular build process\. diff --git a/doc_source/cli.md b/doc_source/cli.md index 2e1d66a1..ff8de4c0 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -269,7 +269,7 @@ You may incur AWS charges for what the AWS CDK stores in the bootstrapped resour **Note** Older versions of the modern template created a Customer Master Key by default\. To avoid charges, re\-bootstrap using `--no-bootstrap-customer-key`\. -The AWS CDK Toolkit supports two bootstrap templates: the modern template and the legacy template\. The legacy template is the default, but the modern template is required by CDK Pipelines\. For more information, see [Bootstrapping](bootstrapping.md)\. +The CDK Toolkit supports two bootstrap templates: the modern template and the legacy template\. The legacy template is the default, but the modern template is required by CDK Pipelines\. For more information, see [Bootstrapping](bootstrapping.md)\. **Important** The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. From 248daa5773c30b84961576c0cb68b95ad7122e2b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 28 Sep 2021 22:27:44 +0000 Subject: [PATCH 447/655] add info on using CDK Toolkit (and tsc) locally --- doc_source/work-with-cdk-javascript.md | 30 +++++++++++++++++++++++- doc_source/work-with-cdk-typescript.md | 32 +++++++++++++++++++++++++- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 4064824f..23075407 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -24,9 +24,37 @@ Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest `cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +## Using local `cdk` + +For the most part, this guide assumes you install the CDK Toolkit globally \(`npm install -g aws-cdk`\), and the provided command examples \(such as `cdk synth`\) follow this assumption\. This approach makes it easy to keep the CDK Toolkit up to date, and since the CDK takes a strict approach to backward compatibility, there is generally little risk in always using the latest version\. + +Some teams prefer to specify all dependencies within each project, including tools like the CDK Toolkit\. This practice lets you pin such components to specific versions and ensure that all developers on your team \(and your CI/CD environment\) use exactly those versions\. This eliminates a possible source of change, helping to make builds and deployments more consistent nand repeatable\. + +The CDK includes a dependency for the CDK Toolkit in the JavaScript project template's `package.json`, so if you want to use this approach, you don't need to make any changes to your project\. All you need to do is use slightly different commands for building your app and for issunig `cdk` commands\. + +| Operation | Use global CDK Toolkit | Use local CDK Toolkit | +| --- |--- |--- | +| Initialize project | `cdk init --language javascript` | `npx aws-cdk init --language javascript` | +| --- |--- |--- | +| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx aws-cdk ...` | +| --- |--- |--- | + +`npx aws-cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@1.120 --version` prints `1.120.0`\. + +**Tip** +Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. + +``` +alias cdk=npx aws-cdk +``` + +``` +doskey cdk=npx aws-cdk +``` + ## Managing AWS Construct Library modules -Use the Node Package Manager \(`npm`\), included with Node\.js, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. +Use the Node Package Manager \(`npm`\) to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an *aws\-* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index c80574f2..04b52fe0 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -33,9 +33,39 @@ Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest `cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +## Using local `tsc` and `cdk` + +For the most part, this guide assumes you install TypeScript and the CDK Toolkit globally \(`npm install -g typescript aws-cdk`\), and the provided command examples \(such as `cdk synth`\) follow this assumption\. This approach makes it easy to keep both components up to date, and since both take a strict approach to backward compatibility, there is generally little risk in always using the latest versions\. + +Some teams prefer to specify all dependencies within each project, including tools like the TypeScript compiler and the CDK Toolkit\. This practice lets you pin these components to specific versions and ensure that all developers on your team \(and your CI/CD environment\) use exactly those versions\. This eliminates a possible source of change, helping to make builds and deployments more consistent nand repeatable\. + +The CDK includes dependencies for both TypeScript and the CDK Toolkit in the TypeScript project template's `package.json`, so if you want to use this approach, you don't need to make any changes to your project\. All you need to do is use slightly different commands for building your app and for issunig `cdk` commands\. + +| Operation | Use global tools | Use local tools | +| --- |--- |--- | +| Initialize project | `cdk init --language typescript` | `npx aws-cdk init --language typescript` | +| --- |--- |--- | +| Build | `tsc` | `npm run build` | +| --- |--- |--- | +| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx aws-cdk ...` | +| --- |--- |--- | + +`npx aws-cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@1.120 --version` prints `1.120.0`\. + +**Tip** +Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. + +``` +alias cdk=npx aws-cdk +``` + +``` +doskey cdk=npx aws-cdk +``` + ## Managing AWS Construct Library modules -Use the Node Package Manager \(`npm`\), included with Node\.js, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. +Use the Node Package Manager \(`npm`\) to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an * a* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. From 23dac5c5dc6fc463a703d9b89b0b3bb6695042bf Mon Sep 17 00:00:00 2001 From: Georgios Goniotakis Date: Thu, 30 Sep 2021 01:34:08 +0200 Subject: [PATCH 448/655] Fixed error (#356) --- doc_source/bootstrapping.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index a509e642..e1891b41 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -584,7 +584,7 @@ The template should contain a resource to create an SSM parameter with a well\-k ``` Resources: - CdkBootstrapVersion:` + CdkBootstrapVersion: Type: AWS::SSM::Parameter Properties: Type: String @@ -627,4 +627,4 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 6 | 1\.108\.0 | Add lookup role separate from deployment role\. | | 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | -| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | \ No newline at end of file +| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | From 600dca9bd56b36c2b0d48450d02d874138449e5a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 29 Sep 2021 23:54:12 +0000 Subject: [PATCH 449/655] fix build commands for Python, Java, C# examples --- doc_source/bootstrapping.md | 2 +- doc_source/cdk_pipeline.md | 24 ++++++++++++------------ 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index e1891b41..636d6f80 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -627,4 +627,4 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 6 | 1\.108\.0 | Add lookup role separate from deployment role\. | | 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | -| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | +| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | \ No newline at end of file diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 33b15b30..13470756 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -344,7 +344,7 @@ class MyPipelineStack(cdk.Stack): pipeline_name="MyPipeline", synth=ShellStep("Synth", input=CodePipelineSource.git_hub("OWNER/REPO", "main"), - commands=["npm ci", "npm run build", "npx cdk synth"] + commands=["npm install -g aws-cdk", "cdk synth"] ) ) ``` @@ -392,7 +392,7 @@ public class MyPipelineStack extends Stack { .pipelineName("MyPipeline") .synth(ShellStep.Builder.create("Synth") .input(CodePipelineSource.gitHub("OWNER/REPO", "main")) - .commands(Arrays.asList)"npm ci", "npm run build", "npx cdk synth")) + .commands(Arrays.asList)"npm install -g aws-cdk", "cdk synth")) .build()) .build(); } @@ -445,7 +445,7 @@ namespace MyPipeline Synth = new ShellStep("Synth", new ShellStepProps { Input = CodePipelineSource.GitHub("OWNER/REPO", "main"), - Commands = new string[] { "npm ci", "npm run build", "npx cdk synth" } + Commands = new string[] { "npm install -g aws-cdk", "cdk synth" } }) }); } @@ -687,7 +687,7 @@ class MyPipelineStack(cdk.Stack): pipeline_name="MyPipeline", synth=ShellStep("Synth", input=CodePipelineSource.git_hub("OWNER/REPO", "main"), - commands=["npm ci", "npm run build", "npx cdk synth"])) + commands=["npm install -g aws-cdk", "cdk synth"])) pipeline.add_stage(MyPipelineAppStage(self, "test", env=cdk.Environment(account="111111111111", region="eu-west-1"))) @@ -779,7 +779,7 @@ public class MyPipelineStack extends Stack { .pipelineName("MyPipeline") .synth(ShellStep.Builder.create("Synth") .input(CodePipelineSource.gitHub("OWNER/REPO", "main")) - .commands(Arrays.asList("npm ci", "npm run build", "npx cdk synth")) + .commands(Arrays.asList("npm install -g aws-cdk", "cdk synth")) .build()) .build(); @@ -854,7 +854,7 @@ namespace MyPipeline Synth = new ShellStep("Synth", new ShellStepProps { Input = CodePipelineSource.GitHub("OWNER/REPO", "main"), - Commands = new string[] { "npm ci", "npm run build", "npx cdk synth" } + Commands = new string[] { "npm install -g aws-cdk", "cdk synth" } }) }); @@ -1244,7 +1244,7 @@ pipeline = CodePipeline(self, "Pipeline", pipeline_name="MyPipeline", synth=ShellStep("Synth", input=source, - commands=["npm ci", "npm run build", "npx cdk synth"])) + commands=["npm install -g aws-cdk", "cdk synth"])) stage = pipeline.add_stage(MyApplicationStage(self, "test", env=cdk.Environment(account="111111111111", region="eu-west-1"))) @@ -1264,7 +1264,7 @@ final CodePipeline pipeline = CodePipeline.Builder.create(this, "pipeline") .pipelineName("MyPipeline") .synth(ShellStep.Builder.create("Synth") .input(source) - .commands(Arrays.asList("npm ci", "npm run build", "npx cdk synth")) + .commands(Arrays.asList("npm install -g aws-cdk", "cdk synth")) .build()) .build(); @@ -1294,7 +1294,7 @@ var pipeline = new CodePipeline(this, "pipeline", new CodePipelineProps Synth = new ShellStep("Synth", new ShellStepProps { Input = source, - Commands = new string[] { "npm ci", "npm run build", "npx cdk synth" } + Commands = new string[] { "npm install -g aws-cdk", "cdk synth" } }) }); @@ -1373,7 +1373,7 @@ stage.addPost(new ShellStep('validate', { ``` synth_step = ShellStep("Synth", input=CodePipelineSource.git_hub("OWNER/REPO", "main"), - commands=["npm ci", "npm run build", "npx cdk synth"]) + commands=["npm install -g aws-cdk", "cdk synth"]) pipeline = CodePipeline(self, "Pipeline", pipeline_name="MyPipeline", @@ -1395,7 +1395,7 @@ stage.add_post(ShellStep("validate", ``` final ShellStep synth = ShellStep.Builder.create("Synth") .input(CodePipelineSource.gitHub("OWNER/REPO", "main")) - .commands(Arrays.asList("npm ci", "npm run build", "npx cdk synth")) + .commands(Arrays.asList("npm install -g aws-cdk", "cdk synth")) .build(); final CodePipeline pipeline = CodePipeline.Builder.create(this, "pipeline") @@ -1424,7 +1424,7 @@ stage.addPost(ShellStep.Builder.create("validate") var synth = new ShellStep("Synth", new ShellStepProps { Input = CodePipelineSource.GitHub("OWNER/REPO", "main"), - Commands = new string[] { "npm ci", "npm run build", "npx cdk synth" } + Commands = new string[] { "npm install -g aws-cdk", "cdk synth" } }); var pipeline = new CodePipeline(this, "pipeline", new CodePipelineProps From 4af63421f803e451a9ec39e5eff24be56331a950 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 29 Sep 2021 23:57:01 +0000 Subject: [PATCH 450/655] fix parenthesis --- doc_source/cdk_pipeline.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 13470756..79b953c0 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -392,7 +392,7 @@ public class MyPipelineStack extends Stack { .pipelineName("MyPipeline") .synth(ShellStep.Builder.create("Synth") .input(CodePipelineSource.gitHub("OWNER/REPO", "main")) - .commands(Arrays.asList)"npm install -g aws-cdk", "cdk synth")) + .commands(Arrays.asList("npm install -g aws-cdk", "cdk synth")) .build()) .build(); } From 7d563cbbd76564a2818803271c1913e30da3635f Mon Sep 17 00:00:00 2001 From: Lucas Shanley Date: Wed, 29 Sep 2021 18:57:41 -0500 Subject: [PATCH 451/655] Fix error in Java MyPipelineStack (#354) Overview - For Java projects there is no `package.json` to install AWS-CDK. This causes errors when attempting to deploy the pipeline as the `npm ci` step depends on this file. - Fixed the commands to `Arrays.asList("npm install -g aws-sdk", "cdk synth")` to correct this behavior. Testing - Created new pipeline following the updated steps and was successful in pipeline creation and deployment. Relevant links - https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html - In the `Synth and sources` section this behavior is described. From 5e119e0702482434fe519a834addd0ab0510f4ab Mon Sep 17 00:00:00 2001 From: Philipp <6516667+psperber@users.noreply.github.com> Date: Thu, 30 Sep 2021 02:00:57 +0200 Subject: [PATCH 452/655] Add missing bracket (#353) --- doc_source/tagging.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/tagging.md b/doc_source/tagging.md index d7a83a98..aebebaf8 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -307,7 +307,7 @@ const theBestStack = new Stack(app, 'MarketingSystem'); Tags.of(theBestStack).add('StackType', 'TheBest'); // Remove the tag from all resources except subnet resources -Tags.of(theBestStack).remove'StackType', { +Tags.of(theBestStack).remove('StackType', { excludeResourceTypes: ['AWS::EC2::Subnet'] }); ``` @@ -410,4 +410,4 @@ Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps { }); ``` ------- \ No newline at end of file +------ From 57a2f857bf804c015a2efefe748db3973e22ffa2 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 30 Sep 2021 00:01:39 +0000 Subject: [PATCH 453/655] newline churn --- doc_source/tagging.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/tagging.md b/doc_source/tagging.md index aebebaf8..0fb295c0 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -410,4 +410,4 @@ Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps { }); ``` ------- +------ \ No newline at end of file From bd567743b045a8d744c6976b29ec95b094322af3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 6 Oct 2021 23:36:28 +0000 Subject: [PATCH 454/655] sync changes from awsdocs --- doc_source/assets.md | 2 +- doc_source/best-practices.md | 12 ++++-- doc_source/cdk_pipeline.md | 20 ++++++--- doc_source/cli.md | 26 +++++------ doc_source/context.md | 7 +-- doc_source/get_ssm_value.md | 11 +++-- doc_source/getting_started.md | 4 +- doc_source/hello_world.md | 6 +-- doc_source/home.md | 6 +++ doc_source/how_to_set_cw_alarm.md | 4 +- doc_source/serverless_example.md | 3 ++ doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 60 ++++++++++++++++++++++++-- doc_source/work-with-cdk-typescript.md | 4 +- doc_source/work-with-cdk-v2.md | 2 +- doc_source/work-with.md | 4 +- 16 files changed, 128 insertions(+), 45 deletions(-) diff --git a/doc_source/assets.md b/doc_source/assets.md index c202bc60..aefd9f9c 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -274,7 +274,7 @@ The `Function` method uses assets to bundle the contents of the directory and us Amazon S3 asset types also expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. -The following example uses deploy\-time attributes to pass the location of an image asset into a Lambda function as environment variables\. +The following example uses deploy\-time attributes to pass the location of an image asset into a Lambda function as environment variables\. \(The kind of file doesn't matter; the PNG image used here is just an example\.\) ------ #### [ TypeScript ] diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md index 6acf194e..62dd19bd 100644 --- a/doc_source/best-practices.md +++ b/doc_source/best-practices.md @@ -65,7 +65,7 @@ Dependencies on packages in the package repository are managed by your language' Shared packages need a different testing strategy: although for a single application it might be good enough to deploy the application to a testing environment and confirm that it still works, shared packages need to be tested independently of the consuming application, as if they were being released to the public\. \(Your organization might in fact choose to actually release some shared packages to the public\.\) -Keep in mind that a construct can be arbitrary simple or complex\. A `Bucket` is a construct, but `CameraShopWebsite` could be a construct, too\. +Keep in mind that a construct can be arbitrarily simple or complex\. A `Bucket` is a construct, but `CameraShopWebsite` could be a construct, too\. ### Infrastructure and runtime code live in the same package @@ -119,9 +119,13 @@ Treat AWS CloudFormation as an implementation detail that the AWS CDK uses for r Names are a precious resource\. Every name can only be used once, so if you hard\-code a table name or bucket name into your infrastructure and application, you can't deploy that piece of infrastructure twice in the same account\. \(The name we're talking about here is the name specified by, for example, the `bucketName` property on an Amazon S3 bucket construct\.\) -What's worse, you can't make changes to the resource that require it to be replaced\. If a property can only be set at resource creation, for example the `KeySchema` of an Amazon DynamoDB table, that property is immutable, and changing it requires a new resource\. But the new resource must have the same name in order to be a true replacement, and it can't, because the existing resource is still using that name\. +What's worse, you can't make changes to the resource that require it to be replaced\. If a property can only be set at resource creation, for example the `KeySchema` of an Amazon DynamoDB table, that property is immutable, and changing it requires a new resource\. But the new resource must have the same name in order to be a true replacement, and it can't while the existing resource is still using that name\. -A better approach is to specify as few names as possible\. If you leave out resource names, the AWS CDK will generate them for you, and it'll do so in a way that won't cause these problems\. You then, for example, pass the generated table name \(which you can reference as `table.tableName` in your AWS CDK application\) as an environment variable into your AWS Lambda function, or you generate a configuration file on your Amazon EC2 instance on startup, or you write the actual table name to AWS Systems Manager Parameter Store and your application reads it from there\. It's like dependency injection, but for resources\. +A better approach is to specify as few names as possible\. If you leave out resource names, the AWS CDK will generate them for you, and it'll do so in a way that won't cause these problems\. You then, for example, pass the generated table name \(which you can reference as `table.tableName` in your AWS CDK application\) as an environment variable into your AWS Lambda function, or you generate a configuration file on your Amazon EC2 instance on startup, or you write the actual table name to AWS Systems Manager Parameter Store and your application reads it from there\. + +If the place you need it is another AWS CDK stack, that's even easier\. Given one stack that defines the resource and another than needs to use it: ++ If the two stacks are in the same AWS CDK app, just pass a reference between the two stacks\. For example, save a reference to the resource's construct as an attribute of the defining stack \(`this.stack.uploadBucket = myBucket`\), then pass that attribute to the constructor of the stack that needs the resource\. ++ When the two stacks are in different AWS CDK apps, use a static `from` method to import an externally\-defined resource based on its ARN, name, or other attributes \(for example, `Table.fromarn()` for a DynamoDB table\)\. Use the `CfnOutput` consturct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS console\. Or the second app can parse the CloudFormation template generated by the first app and retrieve that value from the Outputs section\. ### Define removal policies and log retention @@ -138,7 +142,7 @@ There is no hard and fast rule to how many stacks your application needs\. You'l ### Commit `cdk.context.json` to avoid non\-deterministic behavior -Determinism is key to successful AWS CDK deployments\. A AWS CDK app should have essentially the same result whenever it is deployed \(notwithstanding necessary differences based on the environment where it's deployed\)\. +Determinism is key to successful AWS CDK deployments\. A AWS CDK app should have essentially the same result whenever it is deployed to a given environment\. Since your AWS CDK app is written in a a general\-purpose programming language, it can execute arbitrary code, use arbitrary libraries, and make arbitrary network calls\. For example, you could use an AWS SDK to retrieve some information from your AWS account while synthesizing your app\. Recognize that doing so will result in additional credential setup requirements, increased latency, and a chance, however small, of failure every time you run `cdk synth`\. diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index 79b953c0..f5a5d964 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -144,7 +144,7 @@ If you are using Visual Studio, open the solution file in the `src` directory\. Install the CDK Pipelines module along with any others you'll be using\. **Tip** -Be sure to commit your `cdk.json` and `cdk.context.json` files in source control\. The context information \(such as feature flags and cached values retrieved from your AWS account\) are part of your project's state\. By design, cached values cannot be retrieved in a CI/CD environment, so having them in `cdk.context.json` is critical to successful deployment\. +Be sure to commit your `cdk.json` and `cdk.context.json` files in source control\. The context information \(such as feature flags and cached values retrieved from your AWS account\) are part of your project's state\. The values may be different in another environment, which can cause instability \(unexpected changes\) in your results\. ------ #### [ TypeScript ] @@ -344,7 +344,9 @@ class MyPipelineStack(cdk.Stack): pipeline_name="MyPipeline", synth=ShellStep("Synth", input=CodePipelineSource.git_hub("OWNER/REPO", "main"), - commands=["npm install -g aws-cdk", "cdk synth"] + commands=["npm install -g aws-cdk", + "python -m pip install -r requirements.txt", + "cdk synth"] ) ) ``` @@ -413,7 +415,7 @@ public class MyPipelineApp { App app = new App(); new MyPipelineStack(app, "PipelineStack", StackProps.builder() - .env(new Environment.Builder() + .env(new Environment.builder() .account("111111111111") .region("eu-west-1") .build()) @@ -687,7 +689,9 @@ class MyPipelineStack(cdk.Stack): pipeline_name="MyPipeline", synth=ShellStep("Synth", input=CodePipelineSource.git_hub("OWNER/REPO", "main"), - commands=["npm install -g aws-cdk", "cdk synth"])) + commands=["npm install -g aws-cdk", + "python -m pip install -r requirements.txt", + "cdk synth"])) pipeline.add_stage(MyPipelineAppStage(self, "test", env=cdk.Environment(account="111111111111", region="eu-west-1"))) @@ -1244,7 +1248,9 @@ pipeline = CodePipeline(self, "Pipeline", pipeline_name="MyPipeline", synth=ShellStep("Synth", input=source, - commands=["npm install -g aws-cdk", "cdk synth"])) + commands=["npm install -g aws-cdk", + "python -m pip install -r requirements.txt", + "cdk synth"])) stage = pipeline.add_stage(MyApplicationStage(self, "test", env=cdk.Environment(account="111111111111", region="eu-west-1"))) @@ -1373,7 +1379,9 @@ stage.addPost(new ShellStep('validate', { ``` synth_step = ShellStep("Synth", input=CodePipelineSource.git_hub("OWNER/REPO", "main"), - commands=["npm install -g aws-cdk", "cdk synth"]) + commands=["npm install -g aws-cdk", + "python -m pip install -r requirements.txt", + "cdk synth"]) pipeline = CodePipeline(self, "Pipeline", pipeline_name="MyPipeline", diff --git a/doc_source/cli.md b/doc_source/cli.md index ff8de4c0..80e65df4 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -336,7 +336,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -355,7 +355,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -363,7 +363,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -387,7 +387,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -409,7 +409,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -623,7 +623,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -636,7 +636,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -657,7 +657,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -732,7 +732,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -789,7 +789,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -808,7 +808,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -834,7 +834,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -856,7 +856,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/context.md b/doc_source/context.md index 1df30ae8..e0e7f706 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -4,6 +4,9 @@ Context values are key\-value pairs that can be associated with a stack or const Context keys are strings, and values may be any type supported by JSON: numbers, strings, arrays, or objects\. +**Important** +Context values are managed by the AWS CDK and its constructs, including constructs you may write\. You should not attempt to add context values manually\. It is useful to review `cdk.context.json` to see what values are being cached; by convention, the keys start with the name of the CDK package that set them\. You sholud follow this convention when setting your own values\. + ## Construct context Context values can be provided to your AWS CDK app in six different ways: @@ -43,9 +46,7 @@ Gets the existing Amazon Virtual Private Clouds in your accounts\. [LookupMachineImage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.LookupMachineImage.html) Looks up a machine image for use with a NAT instance in an Amazon Virtual Private Cloud\. -If a given context information isn't available, the AWS CDK app notifies the AWS CDK CLI that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. - -Don't forget to add the `cdk.context.json` file to your source control repository to ensure that subsequent synth commands will return the same result, and that your AWS account won't be needed when synthesizing from your build system\. +If a required context value isn't available, the AWS CDK app notifies the AWS CDK CLI that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. ## Viewing and managing context diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index b79e7d75..a881b170 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -5,12 +5,14 @@ The AWS CDK can retrieve the value of AWS Systems Manager Parameter Store attrib The AWS CDK supports retrieving both plain and secure values\. You may request a specific version of either kind of value\. For plain values only, you may omit the version from your request to receive the latest version\. You must always specify the version when requesting the value of a secure attribute\. **Note** - This topic shows how to read attributes from the AWS Systems Manager Parameter Store\. You can also read secrets from the AWS Secrets Manager \(see [Get a value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. +This topic shows how to read attributes from the AWS Systems Manager Parameter Store\. You can also read secrets from the AWS Secrets Manager \(see [Get a value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. ## Reading Systems Manager values at deployment time To read values from the Systems Manager Parameter Store, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-string-parameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-secure-string-parameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md), not the actual value\. The value is resolved by AWS CloudFormation during deployment\. +A [limited number of AWS services](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#template-parameters-dynamic-patterns-resources) currently support this feature\. + ------ #### [ TypeScript ] @@ -104,6 +106,11 @@ It is sometimes useful to "bake in" a parameter at synthesis time, so that the r To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. +Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. + +**Important** +The retrieved value will end up in your synthenized AWS CloudFormation template, which may be a security risk depending on who has access to your your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. + ------ #### [ TypeScript ] @@ -151,8 +158,6 @@ var stringValue = StringParameter.ValueFromLookup(this, "my-plain-parameter-name ------ -Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. - ## Writing values to Systems Manager You can use the AWS CLI, the AWS Management Console, or an AWS SDK to set Systems Manager parameter values\. The following examples use the [ssm put\-parameter](https://docs.aws.amazon.com/cli/latest/reference/ssm/put-parameter.html) CLI command\. diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 602cb2a0..c58ec15d 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -53,7 +53,7 @@ We have taken pains to make AWS CDK app development in each language follow that const bucket = new s3.Bucket(this, 'MyBucket', { bucketName: 'my-bucket', versioned: true, - websiteRedirect: {host: 'aws.amazon.com'}}); + websiteRedirect: {hostName: 'aws.amazon.com'}}); ``` ------ @@ -63,7 +63,7 @@ const bucket = new s3.Bucket(this, 'MyBucket', { const bucket = new s3.Bucket(this, 'MyBucket', { bucketName: 'my-bucket', versioned: true, - websiteRedirect: {host: 'aws.amazon.com'}}); + websiteRedirect: {hostName: 'aws.amazon.com'}}); ``` ------ diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index bf00a7fe..ea85aea6 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -320,14 +320,14 @@ namespace HelloCdk ------ `Bucket` is the first construct we've seen, so let's take a closer look\. Like all constructs, the `Bucket` class takes three parameters\. -+ **scope:** Tells the bucket that the stack is its parent: it is defined within the scope of the stack\. You can define constructs inside of constructs, creating a hierarchy \(tree\)\. -+ **Id:** The logical ID of the Bucket within your AWS CDK app\. This \(plus a hash based on the bucket's location within the stack\) uniquely identifies the bucket across deployments so the AWS CDK can update it if you change how it's defined in your app\. Buckets can also have a name, which is separate from this ID \(it's the `bucketName` property\)\. ++ **scope:** Tells the bucket that the stack is its parent: it is defined within the scope of the stack\. You can define constructs inside of constructs, creating a hierarchy \(tree\)\. Here, and in most cases, the scope is `this` \(`self` in Python\), meaning the construct that contains the bucket: the stack\. ++ **Id:** The logical ID of the Bucket within your AWS CDK app\. This \(plus a hash based on the bucket's location within the stack\) uniquely identifies the bucket across deployments so the AWS CDK can update it if you change how it's defined in your app\. Here it is "MyFirstBucket\." Buckets can also have a name, which is separate from this ID \(it's the `bucketName` property\)\. + **props:** A bundle of values that define properties of the bucket\. Here we've defined only one property: `versioned`, which enables versioning for the files in the bucket\. All constructs take these same three arguments, so it's easy to stay oriented as you learn about new ones\. And as you might expect, you can subclass any construct to extend it to suit your needs, or just to change its defaults\. **Tip** -If all a construct's props are optional, you can omit the third parameter entirely\. +If a construct's props are all optional, you can omit the `props` parameter entirely\. Props are represented differently in the languages supported by the AWS CDK\. + In TypeScript and JavaScript, `props` is a single argument and you pass in an object containing the desired properties\. diff --git a/doc_source/home.md b/doc_source/home.md index a6f0dfaa..de07ca13 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -247,6 +247,12 @@ In addition to this guide, the following are other resources available to AWS CD + [AWS CloudFormation Concepts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html) + [AWS Glossary](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html) +### Resources for serverless apps with CDK + +These tools can work with the AWS CDK to simplify serverless application development and deployment\. ++ [AWS Serverless Application Model](http://aws.amazon.com/serverless/sam/) ++ [AWS Chalice](https://github.com/aws/chalice), a Python serverless microframework + ## About Amazon Web Services Amazon Web Services \(AWS\) is a collection of digital infrastructure services that developers can use when developing their applications\. The services include computing, storage, database, and application synchronization \(messaging and queueing\)\. diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index 0c2659f9..48f45441 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -111,7 +111,9 @@ var metric = new Metric(this, "Metric", new MetricProps ## Creating the alarm -Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three seconds\. Assuming the metric is the **ApproximateNumberOfMessagesVisible** metric from an Amazon SQS queue, it would raise when 100 messages are visible in the queue in two of the last three seconds\. +Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three seconds\. You can use comparisons such as less\-than in your alarms via the `comparisonOperator` property; greater\-than\-or\-equal\-to is the AWS CDK default, so we don't need to psecify it\. + +Assuming the metric is the **ApproximateNumberOfMessagesVisible** metric from an Amazon SQS queue, it would raise when 100 messages are visible in the queue in two of the last three seconds\. ------ #### [ TypeScript ] diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 86902758..507970cf 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -81,6 +81,9 @@ You may now open `src/MyWidgetService.sln` in Visual Studio\. ------ +**Note** +The CDK names source files and classes based on the name of the project directory\. If you don't use the name `MyWidgetService` as shown above, you'll have trouble following the rest of the steps because some of the files the instructions tell you to modify aren't there \(they'll have different names\)\. + The important files in the blank project are as follows\. \(We will also be adding a couple of new files\.\) ------ diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 0fb295c0..164d423d 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index c7740f00..466c94b6 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -2,9 +2,61 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-readme.html](https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-readme.html) construct converts the resources in an imported AWS CloudFormation template to AWS CDK L1 constructs\. You can work with these in your app just as if they were defined in AWS CDK code, even using them within higher\-level AWS CDK constructs, letting you use \(for example\) the L2 permission grant methods with the resources they define\. -This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\.\. +This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\. -## Importing an AWS CloudFormation template +**Note** +The AWS CDK also includes [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html), which was previously used for the same general purpose\. However, `core.CfnInclude` lacks much of the functionality of `cloudformation-include.CfnInclude`\. `core.CfnInclude` has been deprecated and will not be available in CDK 2\.0\. + +## Install the `cloudformation-include` module + +Follow these instructions to install the `cloudformation-include` module\. + +------ +#### [ TypeScript ] + +``` +npm install @aws-cdk/cloudformation-include +``` + +------ +#### [ JavaScript ] + +``` +npm install @aws-cdk/cloudformation-include +``` + +------ +#### [ Python ] + +``` +python -m pip install aws-cdk.cloudformation-include +``` + +------ +#### [ Java ] + +Add the following to the `` container of `pom.xml`\. + +``` + + software.amazon.awscdk + cdk-cloudformation-include + ${cdk.version} + +``` + +------ +#### [ C\# ] + +Right\-click the project in Visual Studio's Solution Explorer and choose **Manage NuGet Packages**\. Search for and install the package `Amazon.CDK.CloudFormation.Include`\. Or change to your project's directory and issue: + +``` +dotnet add package Amazon.CDK.CloudFormation.Include +``` + +------ + +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. @@ -46,11 +98,11 @@ export class MyStack extends cdk.Stack { #### [ JavaScript ] ``` -cost cdk = require('@aws-cdk/core'); +const cdk = require('@aws-cdk/core'); const cfninc = require('@aws-cdk/cloudformation-include'); class MyStack extends cdk.Stack { - constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { + constructor(scope, id, props) { super(scope, id, props); const template = new cfninc.CfnInclude(this, 'Template', { diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index 04b52fe0..63c56bb0 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -37,7 +37,7 @@ Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest For the most part, this guide assumes you install TypeScript and the CDK Toolkit globally \(`npm install -g typescript aws-cdk`\), and the provided command examples \(such as `cdk synth`\) follow this assumption\. This approach makes it easy to keep both components up to date, and since both take a strict approach to backward compatibility, there is generally little risk in always using the latest versions\. -Some teams prefer to specify all dependencies within each project, including tools like the TypeScript compiler and the CDK Toolkit\. This practice lets you pin these components to specific versions and ensure that all developers on your team \(and your CI/CD environment\) use exactly those versions\. This eliminates a possible source of change, helping to make builds and deployments more consistent nand repeatable\. +Some teams prefer to specify all dependencies within each project, including tools like the TypeScript compiler and the CDK Toolkit\. This practice lets you pin these components to specific versions and ensure that all developers on your team \(and your CI/CD environment\) use exactly those versions\. This eliminates a possible source of change, helping to make builds and deployments more consistent and repeatable\. The CDK includes dependencies for both TypeScript and the CDK Toolkit in the TypeScript project template's `package.json`, so if you want to use this approach, you don't need to make any changes to your project\. All you need to do is use slightly different commands for building your app and for issunig `cdk` commands\. @@ -60,7 +60,7 @@ alias cdk=npx aws-cdk ``` ``` -doskey cdk=npx aws-cdk +doskey cdk=npx aws-cdk $* ``` ## Managing AWS Construct Library modules diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index e23b76f2..363f1a5f 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -29,7 +29,7 @@ Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prereq To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. -### Updating `cdk.json` +### Updating `cdk.json` Remove all feature flags from `cdk.json`\. You can add one or more of the three flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these are needed\. diff --git a/doc_source/work-with.md b/doc_source/work-with.md index c09a0abd..376d1c43 100644 --- a/doc_source/work-with.md +++ b/doc_source/work-with.md @@ -28,7 +28,9 @@ npm install -g aws-cdk **Note** If you get a permission error, and have administrator access on your system, try `sudo npm install -g aws-cdk`\. -Test the installation by issuing `cdk --version`\. +Test the installation by issuing `cdk --version`\. + +If you get an error message at this point, try uninstalling \(`npm uninstall -g aws-cdk`\) and reinstalling\. As a last resort, delete the `node-modules` folder from the current project as well as the global `node-modules` folder\. To figure out where this folder is, issue `npm config get prefix`\. The specific language you work in also has its own prerequisites, described in the corresponding topic listed here\. From f6c95f9493570abd3aa3ea1ac2db4c880de9d687 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 7 Oct 2021 04:08:50 +0000 Subject: [PATCH 455/655] add info on rollback and hot-swapping options for cdk deploy --- doc_source/cli.md | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 80e65df4..6ff69ee7 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -387,7 +387,21 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying AWS CloudFormation parameters +### Disabling rollback + +One of AWS CloudFormation's marquee features is its ability to roll back changes so that deployments are atomic—they either succeed or fail as a whole\. The AWS CDK inherits this capability because it synthesizes and deploys AWS CloudFormation templates\. + +Rollback makes sure your resources are in a consistent state at all times, which is vital for production stacks\. However, while you're still developing your infrastructure, some failures are inevitable, and rolling back failed deployments just slows you down\. + +For this reason, the CDK Toolkit; allows you to disable rollback by adding ``--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. + +### Hot swapping + +Use the `--hotswap` flag with `cdk deploy` to attempt to update your AWS resources directly instead of generating a AWS CloudFormation changeset and deploying it\. Deployment falls back to AWS CloudFormation deployment if hot swapping is not possible\. + +Hot swapping is intended primarily for updating Lambda functions to increase development velocity\. It is not recommended for production environments\. + +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -409,7 +423,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -417,7 +431,7 @@ If your stack declares AWS CloudFormation outputs, these are normally displayed cdk deploy --outputs-file outputs.json MyStack ``` -## Security\-related changes +### Security\-related changes To protect you against unintended changes that affect your security posture, the AWS CDK Toolkit prompts you to approve security\-related changes before deploying them\. You can specify the level of change that requires approval: @@ -623,7 +637,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -636,7 +650,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -657,7 +671,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -732,7 +746,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -789,7 +803,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -808,7 +822,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -834,7 +848,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -856,7 +870,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context From 81caf418799bd019db28c9873ff2d4c1ec6b464f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 7 Oct 2021 04:24:55 +0000 Subject: [PATCH 456/655] tweaks --- doc_source/cli.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 6ff69ee7..3d5da9e4 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -399,7 +399,10 @@ For this reason, the CDK Toolkit; allows you to disable rollback by adding ``--n Use the `--hotswap` flag with `cdk deploy` to attempt to update your AWS resources directly instead of generating a AWS CloudFormation changeset and deploying it\. Deployment falls back to AWS CloudFormation deployment if hot swapping is not possible\. -Hot swapping is intended primarily for updating Lambda functions to increase development velocity\. It is not recommended for production environments\. +Currently hot swapping supports only Lambda functions\. The `--hotswap` flag also disables rollback \(i\.e\., implies `--no-rollback`\)\. + +**Important** +Hot swapping is not recommended for production environments\. ### Specifying AWS CloudFormation parameters From d7045dc1c734cc5189eee5654d12d40a27566d64 Mon Sep 17 00:00:00 2001 From: Okkar Min Date: Thu, 7 Oct 2021 20:13:46 -0400 Subject: [PATCH 457/655] Fix typo (#357) Possible typo in **Managing AWS Construct Library modules** section --- doc_source/work-with-cdk-typescript.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index 63c56bb0..b3b0e030 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -67,7 +67,7 @@ doskey cdk=npx aws-cdk $* Use the Node Package Manager \(`npm`\) to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. -The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an * a* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. +The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an *aws* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. **Note** The [CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) also shows the package names\. @@ -160,4 +160,4 @@ cdk deploy "*Stack" # PipeStack, LambdaStack, etc. **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. From 862f92c835bf3bec2f093407fa3f95c80c4a864a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 8 Oct 2021 15:36:31 +0000 Subject: [PATCH 458/655] add info about API, API ref, interfaces vs. classes, --no-rollback, --hotswap --- doc_source/cli.md | 30 +++++++++---------- doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-typescript.md | 2 +- doc_source/work-with-cdk-v2.md | 2 +- doc_source/work-with.md | 40 ++++++++++++++++++++++---- 6 files changed, 53 insertions(+), 25 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 3d5da9e4..93ff8135 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -336,7 +336,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -355,7 +355,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -363,7 +363,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -387,7 +387,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Disabling rollback +### Disabling rollback One of AWS CloudFormation's marquee features is its ability to roll back changes so that deployments are atomic—they either succeed or fail as a whole\. The AWS CDK inherits this capability because it synthesizes and deploys AWS CloudFormation templates\. @@ -395,7 +395,7 @@ Rollback makes sure your resources are in a consistent state at all times, which For this reason, the CDK Toolkit; allows you to disable rollback by adding ``--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. -### Hot swapping +### Hot swapping Use the `--hotswap` flag with `cdk deploy` to attempt to update your AWS resources directly instead of generating a AWS CloudFormation changeset and deploying it\. Deployment falls back to AWS CloudFormation deployment if hot swapping is not possible\. @@ -404,7 +404,7 @@ Currently hot swapping supports only Lambda functions\. The `--hotswap` flag als **Important** Hot swapping is not recommended for production environments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -426,7 +426,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -640,7 +640,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -653,7 +653,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -674,7 +674,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -749,7 +749,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -806,7 +806,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -825,7 +825,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -851,7 +851,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -873,7 +873,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 164d423d..3ed551b1 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 466c94b6..7891087f 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index b3b0e030..14721b05 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -160,4 +160,4 @@ cdk deploy "*Stack" # PipeStack, LambdaStack, etc. **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index 363f1a5f..d4f63c94 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -29,7 +29,7 @@ Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prereq To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. -### Updating `cdk.json` +### Updating `cdk.json` Remove all feature flags from `cdk.json`\. You can add one or more of the three flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these are needed\. diff --git a/doc_source/work-with.md b/doc_source/work-with.md index 376d1c43..460171b2 100644 --- a/doc_source/work-with.md +++ b/doc_source/work-with.md @@ -3,11 +3,12 @@ The AWS Cloud Development Kit \(AWS CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and \(in developer preview\) Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. **Note** -This Guide does not include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. +This Guide does not currently include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. Go support is currently in developer preview\. -We develop the AWS CDK in TypeScript and use [JSII](https://github.com/aws/jsii) to provide a "native" experience in other supported languages\. For example, we distribute AWS Construct Library modules using your preferred language's standard repository, and you install them using the language's standard package manager\. Methods and properties are even named using your language's recommended naming patterns\. +We develop the AWS CDK in TypeScript and use [JSII](https://github.com/aws/jsii) to provide a "native" experience in other supported languages\. For example, we distribute AWS Construct Library modules using your preferred language's standard repository, and you install them using the language's standard package manager\. Methods and properties are even named using your language's recommended naming patterns\. + +## AWS CDK prerequisites -**AWS CDK prerequisites** To use the AWS CDK, you need an AWS account and a corresponding access key\. If you don't have an AWS account yet, see [Create and Activate an AWS Account](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)\. To find out how to obtain an access key ID and secret access key for your AWS account, see [Understanding and Getting Your Security Credentials](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html)\. To find out how to configure your workstation so the AWS CDK uses your credentials, see [Setting Credentials in Node\.js](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html)\. **Tip** @@ -32,12 +33,39 @@ Test the installation by issuing `cdk --version`\. If you get an error message at this point, try uninstalling \(`npm uninstall -g aws-cdk`\) and reinstalling\. As a last resort, delete the `node-modules` folder from the current project as well as the global `node-modules` folder\. To figure out where this folder is, issue `npm config get prefix`\. -The specific language you work in also has its own prerequisites, described in the corresponding topic listed here\. +### Language\-specific prerequisites -**Topics** +The specific language you work in also has its own prerequisites, described in the corresponding topic listed here\. + [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) + [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) + [Working with the AWS CDK in Python](work-with-cdk-python.md) + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) -+ [Working with the AWS CDK in Go](work-with-cdk-go.md) \ No newline at end of file ++ [Working with the AWS CDK in Go](work-with-cdk-go.md) + +## AWS Construct Library + +The AWS CDK includes the AWS Construct Library, a collection of construct modules organized by AWS service\. The [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) provides detailed documentation of the constructs \(and other components\) in the library\. A version of the API Reference is provided for each supported programming language, along with a generic version\. + +Each module's reference material is broken into the following sections\. ++ *Overview*: Introductory material you'll need to know to work with the service in the AWS CDK, including concepts and examples\. ++ *Constructs*: Library classes that represent one or more concrete AWS resources\. These are the "curated" \(L2\) resources or patterns \(L3 resources\) that provide a high\-level interface with sane defaults\. ++ *Classes*: Non\-construct library classes that provide functionality used by constructs in the module\. ++ *Structs*: Data structures \(attribute bundles\) that define the structure of composite values such as properties \(the `props` argument of constructs\) and options\. ++ *Interfaces*: Interfaces, whose names all begin with "I", define the absolute minimum functionality for the corresponding construct or other class\. The CDK uses construct interfaces to represent AWS resources that are defined outside your AWS CDK app and imported by methods such as `Bucket.fromBucketArn()`\. ++ *Enums*: Collections of named values for use in specifying \*certain construct parameters\. Using an enumerated value allows the CDK to check these values for validity during synthesis\. ++ *CloudFormation Resources*: These L1 constructs, whose names begin with "Cfn", represent exactly the resources defined in the CloudFormation specification\. They are automatically generated from that specification with each CDK release\. Each L2 or L3 construct encapsulates one or more CloudFormation resource\. ++ *CloudFormation Property Types*: The collection of named values that define the properties for each CloudFormation Resource\. + +### Interfaces vs\. construct classes + +Interfaces are used in a specific way the AWS CDK that might not be obvious even if you are familiar with interfaces as a programming concept\. + +The AWS CDK supports importing resources defined outside CDK applications using methods such as `Bucket.fromBucketArn()`\. Imported resources cannot be modified and may not have all the functionality available with resources defined in your CDK app using e\.g\. the `Bucket` class\. Interfaces, then, represent the bare minimum functionality available in the CDK for a given AWS resource type, *including imported resources\.* + +When instantiating resources in your CDK app, then, you should always use concrete classes such as `Bucket`\. When specifying the type of an argument you are accepting in one of your own constructs, use the interface type such as `IBucket` if you are prepared to deal with imported resources \(that is, you won't need to change them\)\. If you require a CDK\-defined construct, specify the most general type you can use\. + +Some interfaces are minimum versions of properties or options bundles \(shown in the AWS CDK API Reference as Structs\) that are associated with specific constructs\. For example, `IBucketProps` is the smallest set of properties required to instantiate a bucket\. Such interfaces can be useful when subclassing constructs to accept arguments that you'll pass on to your parent class\. If you require one or more additional properties, you'll want to implement or derive from this interface, or from a more specific type such as `BucketProps`\. + +**Note** +Some programming languages supported by the AWS CDK don't have an interface feature\. In these languages, interfaces are just ordinary classes\. You can identify them by their names, which follow the pattern of an initial "I" followed by the name of some other construct \(e\.g\. `IBucket`\)\. The same rules apply\. \ No newline at end of file From d99434dd4c9895717df3928476e2bdb8d6ef8990 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 25 Oct 2021 22:09:07 +0000 Subject: [PATCH 459/655] latest minor changes --- doc_source/best-practices.md | 2 +- doc_source/cdk_pipeline.md | 2 +- doc_source/context.md | 2 +- doc_source/hello_world.md | 6 +++--- doc_source/resources.md | 2 +- doc_source/work-with-cdk-javascript.md | 10 +++++----- doc_source/work-with-cdk-typescript.md | 10 +++++----- doc_source/work-with.md | 2 +- 8 files changed, 18 insertions(+), 18 deletions(-) diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md index 62dd19bd..d399be04 100644 --- a/doc_source/best-practices.md +++ b/doc_source/best-practices.md @@ -125,7 +125,7 @@ A better approach is to specify as few names as possible\. If you leave out reso If the place you need it is another AWS CDK stack, that's even easier\. Given one stack that defines the resource and another than needs to use it: + If the two stacks are in the same AWS CDK app, just pass a reference between the two stacks\. For example, save a reference to the resource's construct as an attribute of the defining stack \(`this.stack.uploadBucket = myBucket`\), then pass that attribute to the constructor of the stack that needs the resource\. -+ When the two stacks are in different AWS CDK apps, use a static `from` method to import an externally\-defined resource based on its ARN, name, or other attributes \(for example, `Table.fromarn()` for a DynamoDB table\)\. Use the `CfnOutput` consturct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS console\. Or the second app can parse the CloudFormation template generated by the first app and retrieve that value from the Outputs section\. ++ When the two stacks are in different AWS CDK apps, use a static `from` method to import an externally\-defined resource based on its ARN, name, or other attributes \(for example, `Table.fromarn()` for a DynamoDB table\)\. Use the `CfnOutput` construct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS console\. Or the second app can parse the CloudFormation template generated by the first app and retrieve that value from the Outputs section\. ### Define removal policies and log retention diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index f5a5d964..f8f19ca0 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -647,7 +647,7 @@ Create the new file `my_pipeline/my_pipeline_lambda_stack.py` to hold our applic ``` from aws_cdk import core as cdk -from aws_cdk.aws_lambda import Function, InlieCode, Runtime +from aws_cdk.aws_lambda import Function, InlineCode, Runtime class MyLambdaStack(cdk.Stack): def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: diff --git a/doc_source/context.md b/doc_source/context.md index e0e7f706..1913e445 100644 --- a/doc_source/context.md +++ b/doc_source/context.md @@ -5,7 +5,7 @@ Context values are key\-value pairs that can be associated with a stack or const Context keys are strings, and values may be any type supported by JSON: numbers, strings, arrays, or objects\. **Important** -Context values are managed by the AWS CDK and its constructs, including constructs you may write\. You should not attempt to add context values manually\. It is useful to review `cdk.context.json` to see what values are being cached; by convention, the keys start with the name of the CDK package that set them\. You sholud follow this convention when setting your own values\. +Context values are managed by the AWS CDK and its constructs, including constructs you may write\. You should not attempt to add context values manually\. It is useful to review `cdk.context.json` to see what values are being cached; by convention, the keys start with the name of the CDK package that set them\. You should follow this convention when setting your own values\. ## Construct context diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index ea85aea6..016ed6b9 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -254,7 +254,7 @@ module.exports = { HelloCdkStack } ------ #### [ Python ] -Add the following import statement in `hello_cdk_stack.py` in the `hello_cdk` directory below the existing imports\. +Add the following import statement in `hello_cdk/hello_cdk_stack.py` in the `hello_cdk` directory below the existing imports\. ``` from aws_cdk import aws_s3 as s3 @@ -296,7 +296,7 @@ public class HelloCdkStack extends Stack { ------ #### [ C\# ] -In `HelloCdkStack.cs`: +In `src/HelloCdk/HelloCdkStack.cs`: ``` using Amazon.CDK; @@ -449,7 +449,7 @@ Bucket.Builder.create(this, "MyFirstBucket") ------ #### [ C\# ] -Update `HelloCdkStack.cs`\. +Update `src/HelloCdk/HelloCdkStack.cs`\. ``` new Bucket(this, "MyFirstBucket", new BucketProps diff --git a/doc_source/resources.md b/doc_source/resources.md index 31c1053c..08830822 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -263,7 +263,7 @@ var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = p If the AWS CDK determines that the resource is in the same account and Region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. -Referencing a resource from one stack in a different stack creates a dependency between the two stacks,\. Once this dependency is established, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure if the AWS CDK Toolkit deploys the producing stack before the consuming stack\. This happens if there is another dependency between the two stacks, but it can also happen that the producing stack is chosen by the AWS CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it is no longer needed, but the exported resource is still being used in the consuming stack because its update has not yet been deployed, so deploying the producer stack fails\. +Referencing a resource from one stack in a different stack creates a dependency between the two stacks\. Once this dependency is established, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure if the AWS CDK Toolkit deploys the producing stack before the consuming stack\. This happens if there is another dependency between the two stacks, but it can also happen that the producing stack is chosen by the AWS CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it is no longer needed, but the exported resource is still being used in the consuming stack because its update has not yet been deployed, so deploying the producer stack fails\. To break this deadlock, remove the use of the shared resource from the consuming stack \(which will remove the automatic export from the producing stack\), then manually add the same export to the producing stack using exactly the same logical ID as the automatically\-generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then remove the manual export \(and the shared resource if it is no longer nededed\), and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#exportwbrvalueexportedvalue-options)` method is a convenient way to create the manual export for this purpose \(see the example in the linked method reference\)\. diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 23075407..e5703c02 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -34,22 +34,22 @@ The CDK includes a dependency for the CDK Toolkit in the JavaScript project temp | Operation | Use global CDK Toolkit | Use local CDK Toolkit | | --- |--- |--- | -| Initialize project | `cdk init --language javascript` | `npx aws-cdk init --language javascript` | +| Initialize project | `cdk init --language javascript` | `npx cdk init --language javascript` | | --- |--- |--- | -| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx aws-cdk ...` | +| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx cdk ...` | | --- |--- |--- | -`npx aws-cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@1.120 --version` prints `1.120.0`\. +`npx cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@1.120 --version` prints `1.120.0`\. **Tip** Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. ``` -alias cdk=npx aws-cdk +alias cdk=npx cdk ``` ``` -doskey cdk=npx aws-cdk +doskey cdk=npx acdk $* ``` ## Managing AWS Construct Library modules diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index 14721b05..38e8366a 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -43,24 +43,24 @@ The CDK includes dependencies for both TypeScript and the CDK Toolkit in the Typ | Operation | Use global tools | Use local tools | | --- |--- |--- | -| Initialize project | `cdk init --language typescript` | `npx aws-cdk init --language typescript` | +| Initialize project | `cdk init --language typescript` | `npx cdk init --language typescript` | | --- |--- |--- | | Build | `tsc` | `npm run build` | | --- |--- |--- | -| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx aws-cdk ...` | +| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx cdk ...` | | --- |--- |--- | -`npx aws-cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@1.120 --version` prints `1.120.0`\. +`npx cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@1.120 --version` prints `1.120.0`\. **Tip** Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. ``` -alias cdk=npx aws-cdk +alias cdk=npx cdk ``` ``` -doskey cdk=npx aws-cdk $* +doskey cdk=npx cdk $* ``` ## Managing AWS Construct Library modules diff --git a/doc_source/work-with.md b/doc_source/work-with.md index 460171b2..b4d48acc 100644 --- a/doc_source/work-with.md +++ b/doc_source/work-with.md @@ -59,7 +59,7 @@ Each module's reference material is broken into the following sections\. ### Interfaces vs\. construct classes -Interfaces are used in a specific way the AWS CDK that might not be obvious even if you are familiar with interfaces as a programming concept\. +The AWS CDK uses interfaces in a specific way that might not be obvious even if you are familiar with interfaces as a programming concept\. The AWS CDK supports importing resources defined outside CDK applications using methods such as `Bucket.fromBucketArn()`\. Imported resources cannot be modified and may not have all the functionality available with resources defined in your CDK app using e\.g\. the `Bucket` class\. Interfaces, then, represent the bare minimum functionality available in the CDK for a given AWS resource type, *including imported resources\.* From 116462184a0d41b8285ccb33327ad9b3b97b4499 Mon Sep 17 00:00:00 2001 From: Tim Condit Date: Mon, 25 Oct 2021 15:51:41 -0700 Subject: [PATCH 460/655] Update get_ssm_value.md (#361) --- doc_source/get_ssm_value.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index a881b170..b6cb967e 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -109,7 +109,7 @@ To read a value from the Systems Manager parameter store at synthesis time, use Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. **Important** -The retrieved value will end up in your synthenized AWS CloudFormation template, which may be a security risk depending on who has access to your your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. +The retrieved value will end up in your synthesized AWS CloudFormation template, which may be a security risk depending on who has access to your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. ------ #### [ TypeScript ] @@ -172,4 +172,4 @@ When updating an SSM value that already exists, also include the `--overwrite` o ``` aws ssm put-parameter --overwrite --name "parameter-name" --type "String" --value "parameter-value" aws ssm put-parameter --overwrite --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" -``` \ No newline at end of file +``` From 24403fb670db9cf6055fb4346d791f24938fd719 Mon Sep 17 00:00:00 2001 From: Geremy Cohen Date: Mon, 25 Oct 2021 15:53:37 -0700 Subject: [PATCH 461/655] Update resources.md (#360) Removed trailing comma --- doc_source/resources.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/resources.md b/doc_source/resources.md index 08830822..12baceee 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1272,4 +1272,4 @@ resource.ApplyRemovalPolicy(cdk.RemovalPolicy.DESTROY); ------ **Note** -The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. \ No newline at end of file +The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. From cba97b7e5a5a1bf6bd5a3cba37f27567ac60505a Mon Sep 17 00:00:00 2001 From: Geremy Cohen Date: Mon, 25 Oct 2021 15:56:08 -0700 Subject: [PATCH 462/655] Update assets.md (#359) corrected name for Python grant_read() method --- doc_source/assets.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/assets.md b/doc_source/assets.md index aefd9f9c..7cb82fb4 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -461,7 +461,7 @@ dirname = os.path.dirname(__file__) path=os.path.join(dirname, "my-image.png")) group = iam.Group(self, "MyUserGroup") - asset.grantRead(group) + asset.grant_read(group) ``` ------ @@ -880,4 +880,4 @@ To enable such use cases, external tools consult a set of metadata entries on AW Using these two metadata entries, tools can identify that assets are used by a certain resource, and enable advanced local experiences\. -To add these metadata entries to a resource, use the `asset.addResourceMetadata` \(Python: `add_resource_metadata`\) method\. \ No newline at end of file +To add these metadata entries to a resource, use the `asset.addResourceMetadata` \(Python: `add_resource_metadata`\) method\. From 73c43dd89691094f7922ee7b87b848b5645b9860 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 25 Oct 2021 22:59:38 +0000 Subject: [PATCH 463/655] markdown conversion churn --- doc_source/apps.md | 2 +- doc_source/assets.md | 2 +- doc_source/get_ssm_value.md | 4 ++-- doc_source/resources.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/doc_source/apps.md b/doc_source/apps.md index ca565aa4..35da5e1a 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -76,7 +76,7 @@ public class MyFirstStack : Stack ## The app construct -To define the previous stack within the scope of an application, use the [App](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/app.html) construct\. The following example app instantiates a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. +To define the previous stack within the scope of an application, use the [App](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.App.html) construct\. The following example app instantiates a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. ------ #### [ TypeScript ] diff --git a/doc_source/assets.md b/doc_source/assets.md index 7cb82fb4..3c070955 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -880,4 +880,4 @@ To enable such use cases, external tools consult a set of metadata entries on AW Using these two metadata entries, tools can identify that assets are used by a certain resource, and enable advanced local experiences\. -To add these metadata entries to a resource, use the `asset.addResourceMetadata` \(Python: `add_resource_metadata`\) method\. +To add these metadata entries to a resource, use the `asset.addResourceMetadata` \(Python: `add_resource_metadata`\) method\. \ No newline at end of file diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index b6cb967e..46a64158 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -109,7 +109,7 @@ To read a value from the Systems Manager parameter store at synthesis time, use Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. **Important** -The retrieved value will end up in your synthesized AWS CloudFormation template, which may be a security risk depending on who has access to your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. +The retrieved value will end up in your synthesized AWS CloudFormation template, which may be a security risk depending on who has access to your your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. ------ #### [ TypeScript ] @@ -172,4 +172,4 @@ When updating an SSM value that already exists, also include the `--overwrite` o ``` aws ssm put-parameter --overwrite --name "parameter-name" --type "String" --value "parameter-value" aws ssm put-parameter --overwrite --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" -``` +``` \ No newline at end of file diff --git a/doc_source/resources.md b/doc_source/resources.md index 12baceee..08830822 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1272,4 +1272,4 @@ resource.ApplyRemovalPolicy(cdk.RemovalPolicy.DESTROY); ------ **Note** -The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. +The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. \ No newline at end of file From adbec31b833e2d6c5fc931fe6c856fa6262b1b9c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 28 Oct 2021 02:39:10 +0000 Subject: [PATCH 464/655] experimental libraries in CDKv2 --- doc_source/cli.md | 30 +++++----- doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-v2.md | 106 ++++++++++++++++++++------------- 4 files changed, 82 insertions(+), 58 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 93ff8135..c19fb1cf 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -336,7 +336,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -355,7 +355,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -363,7 +363,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -387,7 +387,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Disabling rollback +### Disabling rollback One of AWS CloudFormation's marquee features is its ability to roll back changes so that deployments are atomic—they either succeed or fail as a whole\. The AWS CDK inherits this capability because it synthesizes and deploys AWS CloudFormation templates\. @@ -395,7 +395,7 @@ Rollback makes sure your resources are in a consistent state at all times, which For this reason, the CDK Toolkit; allows you to disable rollback by adding ``--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. -### Hot swapping +### Hot swapping Use the `--hotswap` flag with `cdk deploy` to attempt to update your AWS resources directly instead of generating a AWS CloudFormation changeset and deploying it\. Deployment falls back to AWS CloudFormation deployment if hot swapping is not possible\. @@ -404,7 +404,7 @@ Currently hot swapping supports only Lambda functions\. The `--hotswap` flag als **Important** Hot swapping is not recommended for production environments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -426,7 +426,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -640,7 +640,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -653,7 +653,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -674,7 +674,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -749,7 +749,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -806,7 +806,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -825,7 +825,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -851,7 +851,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -873,7 +873,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 3ed551b1..7a6da6ce 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 7891087f..2b85f14e 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index d4f63c94..412ebed2 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -6,12 +6,25 @@ As a developer preview, CDK v2 is not intended for production use and may be sub ## Changes in AWS CDK v2 -The main changes in CDK v2 are: -+ AWS CDK v2 consolidates the AWS Construct Library into a single package; developers no longer need to install one or more individual packages for each AWS service\. This change also eliminates the requirement to keep all CDK library versions in sync\. -+ Experimental L2/L3 constructs are no longer included in the AWS Construct Library; they will instead be distributed separately with an appropriate semantic version number\. Constructs will move into the main AWS Construct Library only after being designated stable, permitting the Construct Library to adhere to strict semantic versioning going forward\. We are still finalizing the details of how experimental constructs will be distributed for CDK v2, so initially, CDK v2 does not provide experimental constructs\. -+ The core `Construct` class has been extracted from the AWS CDK into a separate library, along with related types, to support efforts to apply the CDK programming model to other domains\. If you are writing your own constructs or using related APIs, you must declare the `construct` module as a dependency and make minor changes to your imports\. If you are using advanced features, such as hooking into the CDK app lifecycle, more changes are needed\. [See the RFC](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0192-remove-constructs-compat.md#release-notes) for full details\. +The main changes in CDK v2 are as follows\. ++ AWS CDK v2 consolidates the AWS Construct Library into a single package, `aws-cdk-lib`\. Developers no longer need to install one or more individual packages for each AWS service or to keep all CDK library versions in sync\. ++ Experimental modules are not included in the main AWS Construct Library; they are instead distributed as individual packages named with an `alpha` suffix and a semantic version number that matches the first version of the AWS Construct Library mith which they are compatible, also with an `alpha` suffix\. Constructs move into the main AWS Construct Library after being designated stable, permitting the main Construct Library to adhere to strict semantic versioning going forward\. + + Stability is specified at the service level\. For example, if we begin creating one or more L2 constructs for Amazon AppFlow, which at this writing has only L1 constructs, they would appear in a module named `@aws-cdk/aws-appflow-alpha` at first, then move to `aws-cdk-lib` when we feel the new constructs meet the fundamental needs of customers\. + + Once a module has been designated stable and incorporated into `aws-cdk-lib`, new APIs are added using the "BetaN" convention described next\. + + L1 \(CfnXXXX\) constructs are always considered stable and so are included in `aws-cdk-lib`\. + + A new version of each experimental module is released with every release of the AWS CDK, but for the most part, they needn't be kept in sync\. You can upgrade `aws-cdk-lib` or the experimental module whenever you want\. The exception is that when two or more related experimental modules depend on each other, they must be the same version\. ++ For stable modules to which new functionality is being added, new APIs \(whether entirely new constructs or new methods or properties on an existing construct\) receive a `Beta1` suffix \(and then `Beta2`, `Beta3`, etc\. when breaking changes are needed\) while work is in progress\. A version of the API without the suffix is added when the API is designated stable\. All methods except the latest \(whether beta or final\) are deprecated\. + + For example, if we add a new method `grantPower()` to a construct, it initially appears as `grantPowerBeta1().` If breaking changes are needed \(for example, a new required parameter or property\), the next version of the method would be named `grantPowerBeta2()`, and so on\. When work is complete and the API is finalized, the method `grantPower()` \(with no suffix\) is added\. + + All the beta APIs remain in the Construct Library until the next major version \(3\.0\) release, and their signatures are guaranteed not to change\. They'll be deprecated, so you'll see warnings, but you can continue to use them without fear that a future AWS CDK release will break your application\. ++ The core `Construct` class has been extracted from the AWS CDK into a separate library, along with related types, to support efforts to apply this programming model to other domains\. If you are writing your own constructs or using related APIs, you must declare the `construct` module as a dependency and make minor changes to your imports\. If you are using advanced features, such as hooking into the CDK app lifecycle, more changes may be needed\. [See the RFC](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0192-remove-constructs-compat.md#release-notes) for full details\. + Deprecated properties, methods, and types in AWS CDK v1\.x and its Construct Library have been removed from the CDK v2 API\. In most supported languages, these APIs produce warnings under v1\.x, so you may have already migrated to the replacement APIs\. A complete [list of deprecated APIs](https://github.com/aws/aws-cdk/blob/master/DEPRECATED_APIs.md) in CDK v1\.x is available on GitHub\. -+ Behavior that was gated by feature flags in AWS CDK v1\.x is enabled by default in CDK v2, and the old feature flags are no longer needed or, in most cases, supported\. ++ Behavior that was gated by feature flags in AWS CDK v1\.x is enabled by default in CDK v2, and the old feature flags are no longer needed or, in most cases, supported\. A handful are still supported so that you can revert to v1 behavior in very specific circumstances; see [Updating feature flags](#v2-migrating-cdk-json)\. + CDK v2 requires that the environments you deploy into be boostrapped using the modern bootstrap stack; the legacy stack is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. Simply re\-bootstrap the affected environments to upgrade them\. It is not necessary to set any feature flags or environment variables to specify the modern bootstrap stack\. **Important** @@ -29,9 +42,9 @@ Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prereq To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. -### Updating `cdk.json` +### Updating feature flags -Remove all feature flags from `cdk.json`\. You can add one or more of the three flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these are needed\. +Remove all feature flags from `cdk.json`\. You can add one or more of the flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. `@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId` If your application uses multiple Amazon API Gateway API keys and associates them to usage plans @@ -39,6 +52,9 @@ If your application uses multiple Amazon API Gateway API keys and associates the `@aws-cdk/aws-rds:lowercaseDbIdentifier` If your application uses Amazon RDS database instance or database clusters, and explicitly specifies the identifier for these +`@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021` + If your application uses the TLS\_V1\_2\_2019 security policy with Amazon CloudFront distributions\. CDK v2 uses security policy TLSv1\.2\_2021 by default\. + `@aws-cdk/core:stackRelativeExports` If your application uses multiple stacks and you refer to resources from one stack in another, this determines whether absolute or relative path is used to construct AWS CloudFormation exports @@ -47,8 +63,9 @@ The syntax for reverting these flags in `cdk.json` is shown here\. ``` { "context": { - "@aws-cdk/aws-rds:lowercaseDbIdentifier": false, "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": false, + "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": false, + "@aws-cdk/aws-rds:lowercaseDbIdentifier": false, "@aws-cdk/core:stackRelativeExports": false, } } @@ -61,19 +78,24 @@ Update your app's dependencies in the appropriate configuration file, then insta ------ #### [ TypeScript ] -For AWS CDK applications, update `package.json` as follows\. Note that `@aws-cdk/assert` must be updated to the same version as `aws-cdk-lib`\. +For AWS CDK applications, update `package.json` as follows\. Remove dependencies on v1\-style individual stable modules\. Note that `@aws-cdk/assert` must be updated to the same version as `aws-cdk-lib`\. + +Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. ``` { "dependencies": { "aws-cdk-lib": "^2.0.0-rc.1", + "@aws-cdk/aws-codestar-alpha": "2.0.0-alpha.1", "@aws-cdk/assert": "^2.0.0-rc.1", "constructs": "^10.0.0" } } ``` -For construct libraries, establish the lowest version of `aws-cdk-lib` you require for your application \(2\.0\.0\-rc\.1 here\) and update `package.json` as follows\. Note that `aws-cdk-lib` appears both as a peer dependency and a dev dependency\. +For construct libraries, establish the lowest version of `aws-cdk-lib` you require for your application \(2\.0\.0\-rc\.1 here\) and update `package.json` as follows\. + +Note that `aws-cdk-lib` appears both as a peer dependency and a dev dependency\. ``` { @@ -96,19 +118,23 @@ Change your app's imports to import `Construct` from the new `constructs` module ``` import { Construct } from 'constructs'; -import { App, Stack } from 'aws-cdk-lib'; -import { aws_s3 as s3 } from 'aws-cdk-lib'; +import { App, Stack } from 'aws-cdk-lib'; // core constructs +import { aws_s3 as s3 } from 'aws-cdk-lib'; // stable module +import * as codestar from '@aws-cdk/aws-codestar-alpha'; // experimental module ``` ------ #### [ JavaScript ] -Update `package.json` as follows\. Note that `@aws-cdk/assert` must be updated to the same version as `aws-cdk-lib`\. +Update `package.json` as follows\. Remove dependencies on v1\-style individual stable modules\. Note that `@aws-cdk/assert` must be updated to the same version as `aws-cdk-lib`\. + +Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. ``` { "dependencies": { "aws-cdk-lib": "^2.0.0-rc.1", + "@aws-cdk/aws-codestar-alpha": "2.0.0-alpha.1", "@aws-cdk/assert": "^2.0.0-rc.1", "constructs": "^10.0.0" } @@ -121,19 +147,23 @@ Change your app's imports to import `Construct` from the new `constructs` module ``` const { Construct } = require('constructs'); -const { App, Stack } = require('aws-cdk-lib'); -const s3 = require('aws-cdk-lib').aws_s3; +const { App, Stack } = require('aws-cdk-lib'); // core constructs +const s3 = require('aws-cdk-lib').aws_s3; // stable module +const codestar = require('@aws-cdk/aws-codestar-alpha'); // experimental module ``` ------ #### [ Python ] -Update the `install_requires` definition in `setup.py` to look like this\. +Update the `install_requires` definition in `setup.py` as follows\. Remove dependencies on v1\-style individual stable modules\. Note that `@aws-cdk/assert` must be updated to the same version as `aws-cdk-lib`\. + +Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0alpha1\. ``` install_requires=[ "aws-cdk-lib>=2.0.0rc1", "constructs>=10.0.0", + "aws-cdk.aws-codestar-alpha>=2.0.0alpha1", # ... ], ``` @@ -147,8 +177,9 @@ Change your app's imports to import `Construct` from the new `constructs` module ``` from constructs import Construct -from aws_cdk import App, Stack -from aws_cdk import aws_s3 as s3 +from aws_cdk import App, Stack # core constructs +from aws_cdk import aws_s3 as s3 # stable module +import aws_cdk.aws_codestar_alpha as codestar # experimental module # ... @@ -161,34 +192,22 @@ class MyStack(Stack): s3.Bucket(...) ``` -Alternatively, you can import `constructs` and `aws_cdk`, then refer to classes through their namespace\. - -``` -import constructs -import aws_cdk as cdk -from aws_cdk import aws_s3 as s3 - -# ... - -class MyConstruct(constructs.Construct): - # ... - -class MyStack(cdk.Stack): - # ... - -s3.Bucket(...) -``` - ------ #### [ Java ] -In `pom.xml`, remove all `software.amazon.awscdk` dependencies and replace them with these dependencies on `software.constructs` and `software.amazon.awscdk`\. +In `pom.xml`, remove all `software.amazon.awscdk` dependencies for stable modules and replace them with dependencies on `software.constructs` and `software.amazon.awscdk`\. + +Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. ``` software.amazon.awscdk aws-cdk-lib 2.0.0-rc.1 + + software.amazon.awscdk + code-star-alpha + 2.0.0-alpha.1 software.constructs @@ -207,15 +226,19 @@ import software.amazon.awscdk.Stack; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.App; import software.amazon.awscdk.services.s3.Bucket; +import software.amazon.awscdk.services.codestar.alpha.GitHubRepository; ``` ------ #### [ C\# ] -The most straightforward way to upgrade the dependencies of a C\# CDK application is to edit the `.csproj` file manually\. Remove all `Amazon.CDK.*` package references and replace them with references to the `Amazon.CDK.Lib` and `Constructs` packages\. +The most straightforward way to upgrade the dependencies of a C\# CDK application is to edit the `.csproj` file manually\. Remove all stable `Amazon.CDK.*` package references and replace them with references to the `Amazon.CDK.Lib` and `Constructs` packages\. + +Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. ``` + ``` @@ -225,8 +248,9 @@ Change the imports in your source files as follows\. ``` using Constructs; // for Construct class -using Amazon.CDK; // for core classes like App and Stack -using Amazon.CDK.AWS.S3; // for service constructs like Bucket +using Amazon.CDK; // for core classes like App and Stack +using Amazon.CDK.AWS.S3; // for stable constructs like Bucket +using Amazon.CDK.Codestar.Alpha; // for experimental constructs ``` ------ @@ -234,7 +258,7 @@ using Amazon.CDK.AWS.S3; // for service constructs like Bucket ## Troubleshooting **Unexpected infrastructure changes** -Before deploying your app, use `cdk diff` to check for unexpected changes to its resources\. Such changes are typically not caused by upgrading to AWS CDK v2, but are the result of deprecated behavior that was previously hidden by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd have the same problem upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, revising your code as necessary, deploying, and then upgrading to v2\. +Before deploying your app, use `cdk diff` to check for unexpected changes to its resources\. Such changes are typically not caused by upgrading to AWS CDK v2, but are the result of deprecated behavior that was previously hidden by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, revising your code as necessary, deploying, and then upgrading to v2\. If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. From 4162a980e8d5aff0a6893d50de65f5dfc1375bc6 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 1 Nov 2021 18:21:41 +0000 Subject: [PATCH 465/655] typo --- doc_source/work-with-cdk-javascript.md | 2 +- doc_source/work-with-cdk-typescript.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index e5703c02..74fd880a 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -30,7 +30,7 @@ For the most part, this guide assumes you install the CDK Toolkit globally \(`np Some teams prefer to specify all dependencies within each project, including tools like the CDK Toolkit\. This practice lets you pin such components to specific versions and ensure that all developers on your team \(and your CI/CD environment\) use exactly those versions\. This eliminates a possible source of change, helping to make builds and deployments more consistent nand repeatable\. -The CDK includes a dependency for the CDK Toolkit in the JavaScript project template's `package.json`, so if you want to use this approach, you don't need to make any changes to your project\. All you need to do is use slightly different commands for building your app and for issunig `cdk` commands\. +The CDK includes a dependency for the CDK Toolkit in the JavaScript project template's `package.json`, so if you want to use this approach, you don't need to make any changes to your project\. All you need to do is use slightly different commands for building your app and for issuing `cdk` commands\. | Operation | Use global CDK Toolkit | Use local CDK Toolkit | | --- |--- |--- | diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index 38e8366a..c115c453 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -39,7 +39,7 @@ For the most part, this guide assumes you install TypeScript and the CDK Toolkit Some teams prefer to specify all dependencies within each project, including tools like the TypeScript compiler and the CDK Toolkit\. This practice lets you pin these components to specific versions and ensure that all developers on your team \(and your CI/CD environment\) use exactly those versions\. This eliminates a possible source of change, helping to make builds and deployments more consistent and repeatable\. -The CDK includes dependencies for both TypeScript and the CDK Toolkit in the TypeScript project template's `package.json`, so if you want to use this approach, you don't need to make any changes to your project\. All you need to do is use slightly different commands for building your app and for issunig `cdk` commands\. +The CDK includes dependencies for both TypeScript and the CDK Toolkit in the TypeScript project template's `package.json`, so if you want to use this approach, you don't need to make any changes to your project\. All you need to do is use slightly different commands for building your app and for issuing `cdk` commands\. | Operation | Use global tools | Use local tools | | --- |--- |--- | From 7e73fd9ec7861931f27bce80dac230e47b80a2fe Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 1 Nov 2021 18:22:02 +0000 Subject: [PATCH 466/655] add example of multiple tags --- doc_source/cli.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index c19fb1cf..377723e4 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -58,7 +58,11 @@ Some options are flags \(Booleans\)\. You may specify `true` or `false` as their --staging false ``` -A few flags, namely `--context`, `--parameters`, `--plugin`, `--tags`, and `--trust`, may be specified more than once to specify multiple values\. These are noted as having `[array]` type in the CDK Toolkit help\. +A few flags, namely `--context`, `--parameters`, `--plugin`, `--tags`, and `--trust`, may be specified more than once to specify multiple values\. These are noted as having `[array]` type in the CDK Toolkit help\. For example: + +``` +cdk bootstrap --tags costCenter=0123 --tags responsibleParty=jdoe +``` ## Built\-in help From 2263734032464a9ff6fadee7766e7222a6dd733a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 15 Nov 2021 18:42:10 +0000 Subject: [PATCH 467/655] tweaks --- doc_source/cli.md | 2 +- doc_source/constructs.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 377723e4..59a39783 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -397,7 +397,7 @@ One of AWS CloudFormation's marquee features is its ability to roll back changes Rollback makes sure your resources are in a consistent state at all times, which is vital for production stacks\. However, while you're still developing your infrastructure, some failures are inevitable, and rolling back failed deployments just slows you down\. -For this reason, the CDK Toolkit; allows you to disable rollback by adding ``--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. +For this reason, the CDK Toolkit; allows you to disable rollback by adding `--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. ### Hot swapping diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 43abe66a..d2e039c7 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -2,7 +2,7 @@ Constructs are the basic building blocks of AWS CDK apps\. A construct represents a "cloud component" and encapsulates everything AWS CloudFormation needs to create the component\. -A construct can represent a single resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can represent a higher\-level component consisting of multiple AWS resources\. Examples of such components include a worker queue with its associated compute capacity, a cron job with monitoring resources and a dashboard, or even an entire app spanning multiple AWS accounts and regions\. +A construct can represent a single AWS resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can be a higher\-level abstraction consisting of multiple AWS related resources\. Examples of such components include a worker queue with its associated compute capacity, or a scheduled job with monitoring resources and a dashboard\. ## AWS Construct library @@ -284,7 +284,7 @@ const bucket = new s3.CfnBucket(this, "MyBucket", { corsConfiguration: { corsRules: [{ allowedOrigins: ["*"], - allowedMethods: ["*"] + allowedMethods: ["GET"] }] } }); @@ -299,7 +299,7 @@ const bucket = new s3.CfnBucket(this, "MyBucket", { corsConfiguration: { corsRules: [{ allowedOrigins: ["*"], - allowedMethods: ["*"] + allowedMethods: ["GET"] }] } }); From fe46ad7b8939411b8282ffb634f444f6d6b894c9 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 17 Nov 2021 21:46:06 +0000 Subject: [PATCH 468/655] update testing topic to use new assertions module --- doc_source/cli.md | 30 +- doc_source/tagging.md | 2 +- doc_source/testing.md | 1662 ++++++++++++++++++++++++++++---- doc_source/use_cfn_template.md | 2 +- 4 files changed, 1483 insertions(+), 213 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 59a39783..68af885b 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -340,7 +340,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -359,7 +359,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -367,7 +367,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -391,7 +391,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Disabling rollback +### Disabling rollback One of AWS CloudFormation's marquee features is its ability to roll back changes so that deployments are atomic—they either succeed or fail as a whole\. The AWS CDK inherits this capability because it synthesizes and deploys AWS CloudFormation templates\. @@ -399,7 +399,7 @@ Rollback makes sure your resources are in a consistent state at all times, which For this reason, the CDK Toolkit; allows you to disable rollback by adding `--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. -### Hot swapping +### Hot swapping Use the `--hotswap` flag with `cdk deploy` to attempt to update your AWS resources directly instead of generating a AWS CloudFormation changeset and deploying it\. Deployment falls back to AWS CloudFormation deployment if hot swapping is not possible\. @@ -408,7 +408,7 @@ Currently hot swapping supports only Lambda functions\. The `--hotswap` flag als **Important** Hot swapping is not recommended for production environments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -430,7 +430,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -644,7 +644,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -657,7 +657,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -678,7 +678,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -753,7 +753,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -810,7 +810,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -829,7 +829,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -855,7 +855,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -877,7 +877,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 7a6da6ce..dcd4f1f5 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/testing.md b/doc_source/testing.md index 5521ffd8..363a7ee1 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -1,63 +1,80 @@ # Testing constructs -With the AWS CDK, your infrastructure can be as testable as any other code you write\. This article illustrates one approach to testing AWS CDK apps written in TypeScript using the [Jest](https://jestjs.io/) test framework\. Currently, TypeScript is the only supported language for testing AWS CDK infrastructure, though we intend to eventually make this capability available in all languages supported by the AWS CDK\. +With the AWS CDK, your infrastructure can be as testable as any other code you write\. This article illustrates the standard approach to testing AWS CDK apps using the AWS CDK's [assertions](https://docs.aws.amazon.com/cdk/api/latest/docs/assertions-readme.html) module and popular test frameworks such as [Jest](https://jestjs.io/) for TypeScript and JavaScript or [Pytest](https://docs.pytest.org/en/6.2.x/) for Python\. -There are three categories of tests you can write for AWS CDK apps\. -+ **Snapshot tests** test the synthesized AWS CloudFormation template against a previously\-stored baseline template\. This way, when you're refactoring your app, you can be sure that the refactored code works exactly the same way as the original\. If the changes were intentional, you can accept a new baseline for future tests\. -+ **Fine\-grained assertions** test specific aspects of the generated AWS CloudFormation template, such as "this resource has this property with this value\." These tests help when you're developing new features, since any code you add will cause your snapshot test to fail even if existing features still work\. When this happens, your fine\-grained tests will reassure you that the existing functionality is unaffected\. -+ **Validation tests** help you "fail fast" by making sure your AWS CDK constructs raise errors when you pass them invalid data\. The ability to do this type of testing is a big advantage of developing your infrastructure in a general\-purpose programming language\. +There are two categories of tests you can write for AWS CDK apps\. ++ **Fine\-grained assertions** test specific aspects of the generated AWS CloudFormation template, such as "this resource has this property with this value\." These tests can detect regressions, and are also useful when you're developing new features using test\-driven development \(write a test first, then make it pass by writing a correct implementation\)\. Fine\-grained assertions are the tests you'll write the most of\. ++ **Snapshot tests** test the synthesized AWS CloudFormation template against a previously\-stored baseline template or "master\." Snapshot tests let you refactor freely, since you can be sure that the refactored code works exactly the same way as the original\. If the changes were intentional, you can accept a new baseline for future tests\. However, CDK upgrades can also cause synthesized templates to change, so you can't rely only on snapshots to make sure your implementation is correct\. + +**Note** +Complete versions of the TypeScript, Python, and Java apps used as examples in this topic are [available on GitHub](https://github.com/cdklabs/aws-cdk-testing-examples/)\. ## Getting started -As an example, we'll create a [dead letter queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) construct\. A dead letter queue holds messages from another queue that have failed delivery for some time\. This usually indicates failure of the message processor, which we want to know about, so our dead letter queue has an alarm that fires when a message arrives\. The user of the construct can hook up actions such as notifying an Amazon SNS topic to this alarm\. +To illustrate how to write these tests, we'll create a stack that contains an AWS Step Functions state machine and a AWS Lambda function\. The Lambda function is subscribed to an Amazon SNS topic and simply forwards the message to the state machine\. -### Creating the construct +First, create an empty CDK application project using the CDK Toolkit and installing the construct libraries we'll need\. \(We'll also use the Amazon SNS module and the core AWS CDK library; there's no need to install these separately because they're dependencies of the ones we installed explicitly\.\) Don't forget to add your testing framework and the `assertions` module\! - Start by creating an empty construct library project using the AWS CDK Toolkit and installing the construct libraries we'll need: +------ +#### [ TypeScript ] ``` -mkdir dead-letter-queue && cd dead-letter-queue -cdk init --language=typescript lib -npm install @aws-cdk/aws-sqs @aws-cdk/aws-cloudwatch +mkdir state-machine && cd state-machine +cdk init --language=typescript +npm install @aws-cdk/aws-lambda @aws-cdk/aws-sns-subscriptions @aws-cdk/aws-stepfunctions +npm install --save-dev jest @types/jest @aws-cdk/assertions ``` - Place the following code in `lib/index.ts`: +Create a directory for your tests\. ``` -import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; -import * as sqs from '@aws-cdk/aws-sqs'; -import { Construct, Duration } from '@aws-cdk/core'; +mkdir test +``` -export class DeadLetterQueue extends sqs.Queue { - public readonly messagesInQueueAlarm: cloudwatch.IAlarm; +Edit the project's `package.json` to tell NPM how to run Jest, and to tell Jest what kinds of files to collect\. The necessary changes are as follows\. ++ Add a new `test` key to the `scripts` section ++ Add Jest and its types to the `devDependencies` section ++ Add a new `jest` top\-level key with a `moduleFileExtensions` declaration - constructor(scope: Construct, id: string) { - super(scope, id); +These changes are shown in outline below\. Place the new text where indicated in `package.json`\. The "\.\.\." placeholders indicate existing parts of the file that should not be changed\. - // Add the alarm - this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { - alarmDescription: 'There are messages in the Dead Letter Queue', - evaluationPeriods: 1, - threshold: 1, - metric: this.metricApproximateNumberOfMessagesVisible(), - }); +``` +{ + ... + "scripts": { + ... + "test": "jest" + }, + "devDependencies": { + ... + "@types/jest": "^24.0.18", + "jest": "^24.9.0" + }, + "jest": { + "moduleFileExtensions": ["js"] } } ``` -### Installing the testing framework - -Since we're using the Jest framework, our next setup step is to install Jest\. We'll also need the AWS CDK assert module, which includes helpers for writing tests for CDK libraries, including `assert` and `expect`\. +------ +#### [ JavaScript ] ``` -npm install --save-dev jest @types/jest @aws-cdk/assert +mkdir state-machine && cd state-machine +cdk init --language=javascript +npm install @aws-cdk/aws-lambda @aws-cdk/aws-sns-subscriptions @aws-cdk/aws-stepfunctions +npm install --save-dev jest @aws-cdk/assertions ``` -### Updating `package.json` +Create a directory for your tests\. -Finally, edit the project's `package.json` to tell NPM how to run Jest, and to tell Jest what kinds of files to collect\. The necessary changes are as follows\. +``` +mkdir test +``` + +Edit the project's `package.json` to tell NPM how to run Jest, and to tell Jest what kinds of files to collect\. The necessary changes are as follows\. + Add a new `test` key to the `scripts` section -+ Add Jest and its types to the `devDependencies` section ++ Add Jest to the `devDependencies` section + Add a new `jest` top\-level key with a `moduleFileExtensions` declaration These changes are shown in outline below\. Place the new text where indicated in `package.json`\. The "\.\.\." placeholders indicate existing parts of the file that should not be changed\. @@ -65,14 +82,13 @@ These changes are shown in outline below\. Place the new text where indicated in ``` { ... - "scripts": { + "scripts": { ... "test": "jest" }, "devDependencies": { ... - "@types/jest": "^24.0.18", - "jest": "^24.9.0", + "jest": "^24.9.0" }, "jest": { "moduleFileExtensions": ["js"] @@ -80,273 +96,1527 @@ These changes are shown in outline below\. Place the new text where indicated in } ``` -## Snapshot tests +------ +#### [ Python ] -Add a snapshot test by placing the following code in `test/dead-letter-queue.test.ts`\. +``` +mkdir state-machine && cd state-machine +cdk init --language=python +python -m pip install aws_cdk.aws_lambda aws_cdk.aws_sns_subscriptions aws_cdk.aws_stepfunctions +python -m pip install pytest aws_cdk.assertions +``` + +------ +#### [ Java ] ``` -import { SynthUtils } from '@aws-cdk/assert'; -import { Stack } from '@aws-cdk/core'; +mkdir state-machine && cd-state-machine +cdk init --language=java +``` -import * as dlq from '../lib/index'; +Open the project in your preferred Java IDE\. \(In Eclipse, use **File** > **Import** > Existing Maven Projects\.\) -test('dlq creates an alarm', () => { - const stack = new Stack(); - new dlq.DeadLetterQueue(stack, 'DLQ'); - expect(SynthUtils.toCloudFormation(stack)).toMatchSnapshot(); -}); +Edit `pom.xml` to include the following dependencies\. + +``` + + software.amazon.awscdk + assertions + ${cdk.version} + + + software.amazon.awscdk + cloudwatch + ${cdk.version} + + + software.amazon.awscdk + lambda + ${cdk.version} + + + software.amazon.awscdk + sns + ${cdk.version} + + + software.amazon.awscdk + sns-subscriptions + ${cdk.version} + + + software.amazon.awscdk + sqs + ${cdk.version} + + + software.amazon.awscdk + stepfunctions + ${cdk.version} + ``` -To build the project and run the test, issue these commands\. +Also add the following JUnit dependencies\. ``` -npm run build && npm test +> + org.junit.jupiter + junit-jupiter-api + ${junit.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit.version} + test + + + org.assertj + assertj-core + 3.21.0 + test + ``` -The output from Jest indicates that it has run the test and recorded a snapshot\. +------ +#### [ C\# ] ``` -PASS test/dead-letter-queue.test.js - ✓ dlq creates an alarm (55ms) - › 1 snapshot written. -Snapshot Summary -› 1 snapshot written +mkdir state-machine && cd-state-machine +cdk init --language=csharp ``` -Jest stores the snapshots in a directory named `__snapshots__` inside the project\. In this directory is a copy of the AWS CloudFormation template generated by the dead letter queue construct\. The beginning looks something like this\. +Open `src\StateMachine.sln` in Visual Studio\. + +Right\-click the solution in Solution Explorer and choose **Add** > **New Project**\. Search for MSTest C\# and add an **MSTest Test Project** for C\#\. \(The default name `TestProject1`is fine\.\) + +Right\-click `TestProject1` and choose **Add** > **Project Reference**, and add the `StateMachine` project as a reference\. + +Choose **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution** and add the following packages to both projects in the solution: ++ `AWS.CDK.Assertions` ++ `AWS.CDK.AWS.Lambda` ++ `AWS.CDK.AWS.SQL` ++ `AWS.CDK.AWS.SNS` ++ `AWS.CDK.AWS.SNS.Subscriptions` ++ `AWS.CDK.AWS.StepFunctions` + +------ + +## The example stack + +Here's the stack we'll be testing in this topic\. As we've previously described, it contains a Lambda function and a Step Functions state machine, and accepts one or more Amazon SNS topics\. The Lambda function is subscribed to the Amazon SNS topics and forwards them to the state machine\. + +You don't have to do anything special to make the app testable\. In fact, this CDK stack is not different in any important way from the other example stacks in this Guide\. + +------ +#### [ TypeScript ] + +Place the following code in `lib/state-machine-stack.ts`: ``` -exports[`dlq creates an alarm 1`] = ` -Object { - "Resources": Object { - "DLQ581697C4": Object { - "Type": "AWS::SQS::Queue", - }, - "DLQAlarm008FBE3A": Object { - "Properties": Object { - "AlarmDescription": "There are messages in the Dead Letter Queue", - "ComparisonOperator": "GreaterThanOrEqualToThreshold", -... +import * as cdk from "@aws-cdk/core"; +import * as sns from "@aws-cdk/aws-sns"; +import * as sns_subscriptions from "@aws-cdk/aws-sns-subscriptions"; +import * as lambda from "@aws-cdk/aws-lambda"; +import * as sfn from "@aws-cdk/aws-stepfunctions"; + +export interface ProcessorStackProps extends cdk.StackProps { + readonly topics: sns.Topic[]; +} + +export class ProcessorStack extends cdk.Stack { + constructor(scope: cdk.Construct, id: string, props: ProcessorStackProps) { + super(scope, id, props); + + // In the future this state machine will do some work... + const stateMachine = new sfn.StateMachine(this, "StateMachine", { + definition: new sfn.Pass(this, "StartState"), + }); + + // This Lambda function starts the state machine. + const func = new lambda.Function(this, "LambdaFunction", { + runtime: lambda.Runtime.NODEJS_14_X, + handler: "handler", + code: lambda.Code.fromAsset("./start-state-machine"), + environment: { + STATE_MACHINE_ARN: stateMachine.stateMachineArn, + }, + }); + stateMachine.grantStartExecution(func); + + const subscription = new sns_subscriptions.LambdaSubscription(func); + for (const topic of props.topics) { + topic.addSubscription(subscription); + } + } +} ``` -### Testing the test +------ +#### [ JavaScript ] -To make sure the test works, change the construct so that it generates different AWS CloudFormation output, then build and test again\. For example, add a `period` property of 1 minute to override the default of 5 minutes\. +Place the following code in `lib/state-machine-stack.js`: ``` - this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { - alarmDescription: 'There are messages in the Dead Letter Queue', - evaluationPeriods: 1, - threshold: 1, - metric: this.metricApproximateNumberOfMessagesVisible(), - period: Duration.minutes(1), -}); +const cdk = require("@aws-cdk/core"); +const sns = require("@aws-cdk/aws-sns"); +const sns_subscriptions = require("@aws-cdk/aws-sns-subscriptions"); +const lambda = require("@aws-cdk/aws-lambda"); +const sfn = require("@aws-cdk/aws-stepfunctions"); + +class ProcessorStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + // In the future this state machine will do some work... + const stateMachine = new sfn.StateMachine(this, "StateMachine", { + definition: new sfn.Pass(this, "StartState"), + }); + + // This Lambda function starts the state machine. + const func = new lambda.Function(this, "LambdaFunction", { + runtime: lambda.Runtime.NODEJS_14_X, + handler: "handler", + code: lambda.Code.fromAsset("./start-state-machine"), + environment: { + STATE_MACHINE_ARN: stateMachine.stateMachineArn, + }, + }); + stateMachine.grantStartExecution(func); + + const subscription = new sns_subscriptions.LambdaSubscription(func); + for (const topic of props.topics) { + topic.addSubscription(subscription); + } + } +} + +module.exports = { ProcessorStack } ``` -Build the project and run the tests again\. +------ +#### [ Python ] + +Place the following code in `state_machine/state_machine_stack.py`: ``` -npm run build && npm test +from typing import List + +from aws_cdk import aws_lambda as lambda_ +from aws_cdk import aws_sns as sns +from aws_cdk import aws_sns_subscriptions as sns_subscriptions +from aws_cdk import aws_stepfunctions as sfn +from aws_cdk import core as cdk + +class ProcessorStack(cdk.Stack): + def __init__( + self, + scope: cdk.Construct, + construct_id: str, + *, + topics: List[sns.Topic], + **kwargs + ) -> None: + super().__init__(scope, construct_id, **kwargs) + + # In the future this state machine will do some work... + state_machine = sfn.StateMachine( + self, "StateMachine", definition=sfn.Pass(self, "StartState") + ) + + # This Lambda function starts the state machine. + func = lambda_.Function( + self, + "LambdaFunction", + runtime=lambda_.Runtime.NODEJS_14_X, + handler="handler", + code=lambda_.Code.from_asset("./start-state-machine"), + environment={ + "STATE_MACHINE_ARN": state_machine.state_machine_arn, + }, + ) + state_machine.grant_start_execution(func) + + subscription = sns_subscriptions.LambdaSubscription(func) + for topic in topics: + topic.add_subscription(subscription) ``` +------ +#### [ Java ] + ``` -FAIL test/dead-letter-queue.test.js -✕ dlq creates an alarm (58ms) +package software.amazon.samples.awscdkassertionssamples; + +import software.amazon.awscdk.core.Construct; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.core.StackProps; +import software.amazon.awscdk.services.lambda.Code; +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.lambda.Runtime; +import software.amazon.awscdk.services.sns.ITopicSubscription; +import software.amazon.awscdk.services.sns.Topic; +import software.amazon.awscdk.services.sns.subscriptions.LambdaSubscription; +import software.amazon.awscdk.services.stepfunctions.Pass; +import software.amazon.awscdk.services.stepfunctions.StateMachine; + +import java.util.Collections; +import java.util.List; + +public class ProcessorStack extends Stack { + public ProcessorStack(final Construct scope, final String id, final List topics) { + this(scope, id, null, topics); + } -● dlq creates an alarm + public ProcessorStack(final Construct scope, final String id, final StackProps props, final List topics) { + super(scope, id, props); + + // In the future this state machine will do some work... + final StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine") + .definition(new Pass(this, "StartState")) + .build(); + + // This Lambda function starts the state machine. + final Function func = Function.Builder.create(this, "LambdaFunction") + .runtime(Runtime.NODEJS_14_X) + .handler("handler") + .code(Code.fromAsset("./start-state-machine")) + .environment(Collections.singletonMap("STATE_MACHINE_ARN", stateMachine.getStateMachineArn())) + .build(); + stateMachine.grantStartExecution(func); + + final ITopicSubscription subscription = new LambdaSubscription(func); + for (final Topic topic : topics) { + topic.addSubscription(subscription); + } + } +} +``` -expect(received).toMatchSnapshot() +------ +#### [ C\# ] -Snapshot name: `dlq creates an alarm 1` +``` +using Amazon.CDK; +using Amazon.CDK.AWS.Lambda; +using Amazon.CDK.AWS.StepFunctions; +using Amazon.CDK.AWS.SNS; +using Amazon.CDK.AWS.SNS.Subscriptions; -- Snapshot -+ Received +using System.Collections.Generic; -@@ -19,11 +19,11 @@ - }, - ], - "EvaluationPeriods": 1, - "MetricName": "ApproximateNumberOfMessagesVisible", - "Namespace": "AWS/SQS", - - "Period": 300, - + "Period": 60, - "Statistic": "Maximum", - "Threshold": 1, - }, - "Type": "AWS::CloudWatch::Alarm", - }, +namespace AwsCdkAssertionSamples +{ + public class StateMachineStackProps : StackProps + { + public Topic[] Topics; + } - › 1 snapshot failed. -Snapshot Summary - › 1 snapshot failed from 1 test suite. Inspect your code changes or run `npm test -- -u` to update them. + public class StateMachineStack : Stack + { + + internal StateMachineStack(Construct scope, string id, StateMachineStackProps props = null) : base(scope, id, props) + { + // In the future this state machine will do some work... + var stateMachine = new StateMachine(this, "StateMachine", new StateMachineProps + { + Definition = new Pass(this, "StartState") + }); + + // This Lambda function starts the state machine. + var func = new Function(this, "LambdaFunction", new FunctionProps + { + Runtime = Runtime.NODEJS_14_X, + Handler = "handler", + Code = Code.FromAsset("./start-state-machine"), + Environment = new Dictionary + { + { "STATE_MACHINE_ARN", stateMachine.StateMachineArn } + } + }); + stateMachine.GrantStartExecution(func); + + foreach (Topic topic in props?.Topics ?? new Topic[0]) + { + var subscription = new LambdaSubscription(func); + } + + } + } +} ``` -### Accepting the new snapshot +------ + +We'll modify the app's main entry point to not actually instantiate our stack, since we don't want to accidentally deploy it\. Our tests will create an app and an instance of the stack for testing\. This is a useful tactic when combined with test\-driven development: make sure the stack passes all tests before you enable deployment\. -Jest has told us that the `Period` attribute of the synthesized AWS CloudFormation template has changed from 300 to 60\. To accept the new snapshot, issue: +------ +#### [ TypeScript ] + +In `bin/state-machine.ts`: ``` -npm test -- -u +#!/usr/bin/env node +import * as cdk from "@aws-cdk/core"; + +const app = new cdk.App(); + +// Stacks are intentionally not created here -- this application isn't meant to +// be deployed. ``` -Now we can run the test again and see that it passes\. +------ +#### [ JavaScript ] -### Limitations +In `bin/state-machine.js`: -Snapshot tests are easy to create and are a powerful backstop when refactoring\. They can serve as an early warning sign that more testing is needed\. Snapshot tests can even be useful for test\-driven development: modify the snapshot to reflect the result you're aiming for, and adjust the code until the test passes\. +``` +#!/usr/bin/env node +const cdk = require("@aws-cdk/core"); -The chief limitation of snapshot tests is that they test the *entire* template\. Consider that our dead letter queue uses the default retention period\. To give ourselves as much time as possible to recover the undelivered messages, for example, we might set the queue's retention time to the maximum—14 days—by changing the code as follows\. +const app = new cdk.App(); +// Stacks are intentionally not created here -- this application isn't meant to +// be deployed. ``` -export class DeadLetterQueue extends sqs.Queue { - public readonly messagesInQueueAlarm: cloudwatch.IAlarm; - constructor(scope: Construct, id: string) { - super(scope, id, { - // Maximum retention period - retentionPeriod: Duration.days(14) - }); +------ +#### [ Python ] + +In `app.py`: + ``` +#!/usr/bin/env python3 +import os -When we run the test again, it breaks\. The name we've given the test hints that we are interested mainly in testing whether the alarm is created, but the snapshot test also tests whether the queue is created with default options—along with literally everything else about the synthesized template\. This problem is magnified when a project contains many constructs, each with a snapshot test\. +from aws_cdk import core as cdk -## Fine\-grained assertions +app = cdk.App() -To avoid needing to review every snapshot whenever you make a change, use the custom assertions in the `@aws-cdk/assert/jest` module to write fine\-grained tests that verify only part of the construct's behavior\. For example, the test we called "dlq creates an alarm" in our example really should assert only that an alarm is created with the appropriate metric\. +# Stacks are intentionally not created here -- this application isn't meant to +# be deployed. -The [AWS::CloudWatch::Alarm](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html) resource specification reveals that we're interested in the properties Namespace, MetricName and Dimensions\. We'll use the `expect(stack).toHaveResource(...)` assertion, which is in the `@aws-cdk/assert/jest` module, to make sure these properties have the appropriate values\. +app.synth() +``` -Replace the code in `test/dead-letter-queue.test.ts` with the following\. +------ +#### [ Java ] ``` -import { Stack } from '@aws-cdk/core'; -import '@aws-cdk/assert/jest'; +package software.amazon.samples.awscdkassertionssamples; -import * as dlq from '../lib/index'; +import software.amazon.awscdk.core.App; -test('dlq creates an alarm', () => { - const stack = new Stack(); - new dlq.DeadLetterQueue(stack, 'DLQ'); +public class SampleApp { + public static void main(final String[] args) { + App app = new App(); - expect(stack).toHaveResource('AWS::CloudWatch::Alarm', { - MetricName: "ApproximateNumberOfMessagesVisible", - Namespace: "AWS/SQS", - Dimensions: [ - { - Name: "QueueName", - Value: { "Fn::GetAtt": [ "DLQ581697C4", "QueueName" ] } - } - ], - }); -}); + // Stacks are intentionally not created here -- this application isn't meant to be deployed. -test('dlq has maximum retention period', () => { - const stack = new Stack(); + app.synth(); + } +} +``` - new dlq.DeadLetterQueue(stack, 'DLQ'); +------ +#### [ C\# ] - expect(stack).toHaveResource('AWS::SQS::Queue', { - MessageRetentionPeriod: 1209600 - }); -}); ``` +using Amazon.CDK; -There are now two tests\. The first checks that the dead letter queue creates an alarm on its `ApproximateNumberOfMessagesVisible` metric\. The second verifies the message retention period\. +namespace AwsCdkAssertionSamples +{ + sealed class Program + { + public static void Main(string[] args) + { + var app = new App(); -Again, build the project and run the tests\. + // Stacks are intentionally not created here -- this application isn't meant to be deployed. + app.Synth(); + } + } +} ``` -npm run build && npm test + +------ + +## Running tests + +For reference, here are the commands you use to run tests in your AWS CDK app\. These are the same commands you'd use to run the tests in any project using the same testig framework\. For languages that require a build step, include that to make sure your tests have been compiled\. + +------ +#### [ TypeScript ] + +``` +tsc && npm test ``` -**Note** -Since we've replaced the snapshot test, the first time we run the new tests, Jest reminds us that we have a snapshot that is not used by any test\. Issue `npm test -- -u` to tell Jest to clean it up\. +------ +#### [ JavaScript ] + +``` +npm test +``` + +------ +#### [ Python ] + +``` +python -m pytest +``` -## Validation tests +------ +#### [ Java ] -Suppose we want to make the dead letter queue's retention period configurable\. Of course, we also want to make sure that the value provided by the user of the construct is within an allowable range\. We can write a test to make sure that the validation logic works: pass in invalid values and see what happens\. +``` +mvn compile && mvn test +``` + +------ +#### [ C\# ] -First, create a `props` interface for the construct\. +Build your solution \(F6\) to discover the tests, then run the tests \(**Test** > **Run All Tests**\)\. To choose which tests to run, open Test Explorer \(**Test** > **Test Explorer**\)\. +Or: + +``` +dotnet test src ``` -export interface DeadLetterQueueProps { - /** - * The amount of days messages will live in the dead letter queue - * - * Cannot exceed 14 days. - * - * @default 14 - */ - retentionDays?: number; + +------ + +## Fine\-grained assertions + +The first step for testing a stack with fine\-grained assertions is to synthesize the stack, because we're writing assertions against the generated AWS CloudFormation template\. + +Our `ProcessorStack` requires that we pass it the Amazon SNS topic to be forwarded to the state machine\. So in our test, we'll create a separate stack to contain the topic\. + +Ordinarily, if you were writing a CDK app, you'd subclass `Stack` and instantiate the Amazon SNS topic in the stack's constructor\. In our test, we instantiate `Stack` directly, then pass this stack as the `Topic`'s scope, attaching it to the stack\. This is functionally equivalent, less verbose, and helps make stacks used only in tests "look different" from stacks you intend to deploy\. + +------ +#### [ TypeScript ] + +``` +import { Capture, Match, Template } from "@aws-cdk/assertions"; +import * as cdk from "@aws-cdk/core"; +import * as sns from "@aws-cdk/aws-sns"; +import { ProcessorStack } from "../lib/processor-stack"; + +describe("ProcessorStack", () => { + test("synthesizes the way we expect", () => { + const app = new cdk.App(); + + // Since the ProcessorStack consumes resources from a separate stack + // (cross-stack references), we create a stack for our SNS topics to live + // in here. These topics can then be passed to the ProcessorStack later, + // creating a cross-stack reference. + const topicsStack = new cdk.Stack(app, "TopicsStack"); + + // Create the topic the stack we're testing will reference. + const topics = [new sns.Topic(topicsStack, "Topic1", {})]; + + // Create the ProcessorStack. + const processorStack = new ProcessorStack(app, "ProcessorStack", { + topics: topics, // Cross-stack reference + }); + + // Prepare the stack for assertions. + const template = Template.fromStack(processorStack); + + +} +``` + +------ +#### [ JavaScript ] + +``` +const { Capture, Match, Template } = require("@aws-cdk/assertions"); +const cdk = require("@aws-cdk/core"); +const sns = require("@aws-cdk/aws-sns"); +const { ProcessorStack } = require("../lib/processor-stack"); + +describe("ProcessorStack", () => { + test("synthesizes the way we expect", () => { + const app = new cdk.App(); + + // Since the ProcessorStack consumes resources from a separate stack + // (cross-stack references), we create a stack for our SNS topics to live + // in here. These topics can then be passed to the ProcessorStack later, + // creating a cross-stack reference. + const topicsStack = new cdk.Stack(app, "TopicsStack"); + + // Create the topic the stack we're testing will reference. + const topics = [new sns.Topic(topicsStack, "Topic1", {})]; + + // Create the ProcessorStack. + const processorStack = new ProcessorStack(app, "ProcessorStack", { + topics: topics, // Cross-stack reference + }); + + // Prepare the stack for assertions. + const template = Template.fromStack(processorStack); +``` + +------ +#### [ Python ] + +``` +from aws_cdk import aws_sns as sns +from aws_cdk import core as cdk +from aws_cdk.assertions import Template + +from app.processor_stack import ProcessorStack + +def test_synthesizes_properly(): + app = cdk.App() + + # Since the ProcessorStack consumes resources from a separate stack + # (cross-stack references), we create a stack for our SNS topics to live + # in here. These topics can then be passed to the ProcessorStack later, + # creating a cross-stack reference. + topics_stack = cdk.Stack(app, "TopicsStack") + + # Create the topic the stack we're testing will reference. + topics = [sns.Topic(topics_stack, "Topic1")] + + # Create the ProcessorStack. + processor_stack = ProcessorStack( + app, "ProcessorStack", topics=topics # Cross-stack reference + ) + + # Prepare the stack for assertions. + template = Template.from_stack(processor_stack) +``` + +------ +#### [ Java ] + +``` +package software.amazon.samples.awscdkassertionssamples; + +import org.junit.jupiter.api.Test; +import software.amazon.awscdk.assertions.Capture; +import software.amazon.awscdk.assertions.Match; +import software.amazon.awscdk.assertions.Template; +import software.amazon.awscdk.core.App; +import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.services.sns.Topic; + +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ProcessorStackTest { + @Test + public void testSynthesizesProperly() { + final App app = new App(); + + // Since the ProcessorStack consumes resources from a separate stack (cross-stack references), we create a stack + // for our SNS topics to live in here. These topics can then be passed to the ProcessorStack later, creating a + // cross-stack reference. + final Stack topicsStack = new Stack(app, "TopicsStack"); + + // Create the topic the stack we're testing will reference. + final List topics = Collections.singletonList(Topic.Builder.create(topicsStack, "Topic1").build()); + + // Create the ProcessorStack. + final ProcessorStack processorStack = new ProcessorStack( + app, + "ProcessorStack", + topics // Cross-stack reference + ); + + // Prepare the stack for assertions. + final Template template = Template.fromStack(processorStack) +``` + +------ +#### [ C\# ] + +``` +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Amazon.CDK; +using Amazon.CDK.AWS.SNS; +using Amazon.CDK.Assertions; +using AwsCdkAssertionSamples; + +using ObjectDict = System.Collections.Generic.Dictionary; +using StringDict = System.Collections.Generic.Dictionary; + +namespace TestProject1 +{ + [TestClass] + public class ProcessorStackTest + { + [TestMethod] + public void TestMethod1() + { + var app = new App(); + + // Since the ProcessorStack consumes resources from a separate stack (cross-stack references), we create a stack + // for our SNS topics to live in here. These topics can then be passed to the ProcessorStack later, creating a + // cross-stack reference. + var topicsStack = new Stack(app, "TopicsStack"); + + // Create the topic the stack we're testing will reference. + var topics = new Topic[] { new Topic(topicsStack, "Topic1") }; + + // Create the ProcessorStack. + var processorStack = new StateMachineStack(app, "ProcessorStack", new StateMachineStackProps + { + Topics = topics + }); + + // Prepare the stack for assertions. + var template = Template.FromStack(processorStack); + + // test will go here + } + } } +``` + +------ + +Now we can assert that the Lambda function and the Amazon SNS subscription were created\. + +------ +#### [ TypeScript ] + +``` + // Assert it creates the function with the correct properties... + template.hasResourceProperties("AWS::Lambda::Function", { + Handler: "handler", + Runtime: "nodejs14.x", + }); + + // Creates the subscription... + template.resourceCountIs("AWS::SNS::Subscription", 1); +``` + +------ +#### [ JavaScript ] + +``` + // Assert it creates the function with the correct properties... + template.hasResourceProperties("AWS::Lambda::Function", { + Handler: "handler", + Runtime: "nodejs14.x", + }); + + // Creates the subscription... + template.resourceCountIs("AWS::SNS::Subscription", 1); +``` + +------ +#### [ Python ] + +``` +# Assert that we have created the function with the correct properties + template.has_resource_properties( + "AWS::Lambda::Function", + { + "Handler": "handler", + "Runtime": "nodejs14.x", + }, + ) + + # Assert that we have created a subscription + template.resource_count_is("AWS::SNS::Subscription", 1) +``` + +------ +#### [ Java ] + +``` + // Assert it creates the function with the correct properties... + template.hasResourceProperties("AWS::Lambda::Function", Map.of( + "Handler", "handler", + "Runtime", "nodejs14.x" + )); + + // Creates the subscription... + template.resourceCountIs("AWS::SNS::Subscription", 1); +``` + +------ +#### [ C\# ] + +``` + // Prepare the stack for assertions. + var template = Template.FromStack(processorStack); + + // Assert it creates the function with the correct properties... + template.HasResourceProperties("AWS::Lambda::Function", new StringDict { + { "Handler", "handler"}, + { "Runtime", "nodejs14x" } + }); + + // Creates the subscription... + template.ResourceCountIs("AWS::SNS::Subscription", 1); +``` + +------ + +Our Lambda function test asserts that two particular properties of the function resource have specific values\. By default, the `hasResourceProperties` method performs a partial match on the resource's properties as given in the synthesized CloudFormation template\. This test requires that the provided properties exist and have the specified values, but the resource can also have other properties, and these are not tested\. + +Our Amazon SNS assertion asserts that the synthesized template contains a subscription, but nothing about the subscription itself\. We included this assertion mainly to illustrate how to assert on resource counts\. The `Template` class offers more specific methods to write assertions against the `Resources`, `Outputs`, and `Mapping` sections of the CloudFormation template\. + +### Matchers + +The default partial matching behavior of `hasResourceProperties` can be changed using *matchers* from the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_assertions.Match.html#methods](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_assertions.Match.html#methods) class\. + +Matchers range from the very lenient \(`Match.anyValue`\) to the quite strict \(`Match.objectEquals`\), and can be nested to apply different matching methods to different parts of the resource properties\. Using `Match.objectEquals` and `Match.anyValue` together, for example, we can test the state machine's IAM role more fully, while not requiring specific values for properties that may change\. + +------ +#### [ TypeScript ] + +``` + // Fully assert on the state machine's IAM role with matchers. + template.hasResourceProperties( + "AWS::IAM::Role", + Match.objectEquals({ + AssumeRolePolicyDocument: { + Version: "2012-10-17", + Statement: [ + { + Action: "sts:AssumeRole", + Effect: "Allow", + Principal: { + Service: { + "Fn::Join": [ + "", + ["states.", Match.anyValue(), ".amazonaws.com"], + ], + }, + }, + }, + ], + }, + }) + ); +``` + +------ +#### [ JavaScript ] + +``` + // Fully assert on the state machine's IAM role with matchers. + template.hasResourceProperties( + "AWS::IAM::Role", + Match.objectEquals({ + AssumeRolePolicyDocument: { + Version: "2012-10-17", + Statement: [ + { + Action: "sts:AssumeRole", + Effect: "Allow", + Principal: { + Service: { + "Fn::Join": [ + "", + ["states.", Match.anyValue(), ".amazonaws.com"], + ], + }, + }, + }, + ], + }, + }) + ); +``` + +------ +#### [ Python ] + +``` +from aws_cdk.assertions import Match + + # Fully assert on the state machine's IAM role with matchers. + template.has_resource_properties( + "AWS::IAM::Role", + Match.object_equals( + { + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": { + "Fn::Join": [ + "", + [ + "states.", + Match.any_value(), + ".amazonaws.com", + ], + ], + }, + }, + }, + ], + }, + } + ), + ) +``` + +------ +#### [ Java ] + +``` + // Fully assert on the state machine's IAM role with matchers. + template.hasResourceProperties("AWS::IAM::Role", Match.objectEquals( + Collections.singletonMap("AssumeRolePolicyDocument", Map.of( + "Version", "2012-10-17", + "Statement", Collections.singletonList(Map.of( + "Action", "sts:AssumeRole", + "Effect", "Allow", + "Principal", Collections.singletonMap( + "Service", Collections.singletonMap( + "Fn::Join", Arrays.asList( + "", + Arrays.asList("states.", Match.anyValue(), ".amazonaws.com") + ) + ) + ) + )) + )) + )); +``` + +------ +#### [ C\# ] + +``` + // Fully assert on the state machine's IAM role with matchers. + template.HasResource("AWS::IAM::Role", Match.ObjectEquals(new ObjectDict + { + { "AssumeRolePolicyDocument", new ObjectDict + { + { "Version", "2012-10-17" }, + { "Action", "sts:AssumeRole" }, + { "Principal", new ObjectDict + { + { "Version", "2012-10-17" }, + { "Statement", new object[] + { + new ObjectDict { + { "Action", "sts:AssumeRole" }, + { "Effect", "Allow" }, + { "Principal", new ObjectDict + { + { "Service", new ObjectDict + { + { "", new object[] + { "states", Match.AnyValue(), ".amazonaws.com" } + } + } + } + } + } + } + } + } + } + } + } + } + })); +``` + +------ + +Many CloudFormation resources include serialized JSON objects represented as strings\. The `Match.serializedJson()` matcher can be used to match properties inside this JSON\. For example, Step Functions state machines are defined using a string in the JSON\-based [Amazon States Language](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html)\. We'll use `Match.serializedJson()` to make sure our initial state is the only step, again using nested matchers to apply different kinds of matching to different parts of the object\. + +------ +#### [ TypeScript ] + +``` + // Assert on the state machine's definition with the Match.serializedJson() + // matcher. + template.hasResourceProperties("AWS::StepFunctions::StateMachine", { + DefinitionString: Match.serializedJson( + // Match.objectEquals() is used implicitly, but we use it explicitly + // here for extra clarity. + Match.objectEquals({ + StartAt: "StartState", + States: { + StartState: { + Type: "Pass", + End: true, + // Make sure this state doesn't provide a next state -- we can't + // provide both Next and set End to true. + Next: Match.absent(), + }, + }, + }) + ), + }); +``` + +------ +#### [ JavaScript ] + +``` + // Assert on the state machine's definition with the Match.serializedJson() + // matcher. + template.hasResourceProperties("AWS::StepFunctions::StateMachine", { + DefinitionString: Match.serializedJson( + // Match.objectEquals() is used implicitly, but we use it explicitly + // here for extra clarity. + Match.objectEquals({ + StartAt: "StartState", + States: { + StartState: { + Type: "Pass", + End: true, + // Make sure this state doesn't provide a next state -- we can't + // provide both Next and set End to true. + Next: Match.absent(), + }, + }, + }) + ), + }); +``` + +------ +#### [ Python ] + +``` + # Assert on the state machine's definition with the serialized_json matcher. + template.has_resource_properties( + "AWS::StepFunctions::StateMachine", + { + "DefinitionString": Match.serialized_json( + # Match.object_equals() is the default, but specify it here for clarity + Match.object_equals( + { + "StartAt": "StartState", + "States": { + "StartState": { + "Type": "Pass", + "End": True, + # Make sure this state doesn't provide a next state -- + # we can't provide both Next and set End to true. + "Next": Match.absent(), + }, + }, + } + ) + ), + }, + ) +``` + +------ +#### [ Java ] + +``` + // Assert on the state machine's definition with the Match.serializedJson() matcher. + template.hasResourceProperties("AWS::StepFunctions::StateMachine", Collections.singletonMap( + "DefinitionString", Match.serializedJson( + // Match.objectEquals() is used implicitly, but we use it explicitly here for extra clarity. + Match.objectEquals(Map.of( + "StartAt", "StartState", + "States", Collections.singletonMap( + "StartState", Map.of( + "Type", "Pass", + "End", true, + // Make sure this state doesn't provide a next state -- we can't provide + // both Next and set End to true. + "Next", Match.absent() + ) + ) + )) + ) + )); +``` + +------ +#### [ C\# ] + +``` + // Assert on the state machine's definition with the Match.serializedJson() matcher + template.HasResourceProperties("AWS::StepFunctions::StateMachine", new ObjectDict + { + { "DefinitionString", Match.SerializedJson( + // Match.objectEquals() is used implicitly, but we use it explicitly here for extra clarity. + Match.ObjectEquals(new ObjectDict { + { "StartAt", "StartState" }, + { "States", new ObjectDict + { + { "StartState", new ObjectDict { + { "Type", "Pass" }, + { "End", "True" }, + // Make sure this state doesn't provide a next state -- we can't provide + // both Next and set End to true. + { "Next", Match.Absent() } + }} + }} + }) + )}}); +``` + +------ + +### Capturing + +It's often useful to test properties to make sure they follow specific formats, or have the same value as another property, without needing to know their exact values ahead of time\. The `assertions` module provides this capability in its [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_assertions.Capture.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_assertions.Capture.html) class\. + +By specifying a `Capture` instance in place of a value in `hasResourceProperties`, that value is retained in the `Capture` object\. The actual captured value can be retrieved using the object's `as` methods, including `asNumber()`, `asString()`, and `asObject`, and subjected to test\. Use `Capture` with a matcher to specify the exact location of the value to be captured within the resource's properties, including serialized JSON properties\. + +For example, this example tests to make sure that the starting state of our state machine has a name beginning with `Start` and also that this state is actually present within the list of states in the machine\. + +------ +#### [ TypeScript ] + +``` + // Capture some data from the state machine's definition. + const startAtCapture = new Capture(); + const statesCapture = new Capture(); + template.hasResourceProperties("AWS::StepFunctions::StateMachine", { + DefinitionString: Match.serializedJson( + Match.objectLike({ + StartAt: startAtCapture, + States: statesCapture, + }) + ), + }); + + // Assert that the start state starts with "Start". + expect(startAtCapture.asString()).toEqual(expect.stringMatching(/^Start/)); + + // Assert that the start state actually exists in the states object of the + // state machine definition. + expect(statesCapture.asObject()).toHaveProperty(startAtCapture.asString()); +``` + +------ +#### [ JavaScript ] + +``` + // Capture some data from the state machine's definition. + const startAtCapture = new Capture(); + const statesCapture = new Capture(); + template.hasResourceProperties("AWS::StepFunctions::StateMachine", { + DefinitionString: Match.serializedJson( + Match.objectLike({ + StartAt: startAtCapture, + States: statesCapture, + }) + ), + }); + + // Assert that the start state starts with "Start". + expect(startAtCapture.asString()).toEqual(expect.stringMatching(/^Start/)); + + // Assert that the start state actually exists in the states object of the + // state machine definition. + expect(statesCapture.asObject()).toHaveProperty(startAtCapture.asString()); +``` + +------ +#### [ Python ] + +``` +import re + + from aws_cdk.assertions import Capture + + # ... + + # Capture some data from the state machine's definition. + start_at_capture = Capture() + states_capture = Capture() + template.has_resource_properties( + "AWS::StepFunctions::StateMachine", + { + "DefinitionString": Match.serialized_json( + Match.object_like( + { + "StartAt": start_at_capture, + "States": states_capture, + } + ) + ), + }, + ) + + # Assert that the start state starts with "Start". + assert re.match("^Start", start_at_capture.as_string()) + + # Assert that the start state actually exists in the states object of the + # state machine definition. + assert start_at_capture.as_string() in states_capture.as_object() +``` + +------ +#### [ Java ] + +``` + // Capture some data from the state machine's definition. + final Capture startAtCapture = new Capture(); + final Capture statesCapture = new Capture(); + template.hasResourceProperties("AWS::StepFunctions::StateMachine", Collections.singletonMap( + "DefinitionString", Match.serializedJson( + Match.objectLike(Map.of( + "StartAt", startAtCapture, + "States", statesCapture + )) + ) + )); + + // Assert that the start state starts with "Start". + assertThat(startAtCapture.asString()).matches("^Start.+"); + + // Assert that the start state actually exists in the states object of the state machine definition. + assertThat(statesCapture.asObject()).containsKey(startAtCapture.asString()); +``` + +------ +#### [ C\# ] + +``` + // Capture some data from the state machine's definition. + var startAtCapture = new Capture(); + var statesCapture = new Capture(); + template.HasResourceProperties("AWS::StepFunctions::StateMachine", new ObjectDict + { + { "DefinitionString", Match.SerializedJson( + new ObjectDict + { + { "StartAt", startAtCapture }, + { "States", statesCapture } + } + )} + }); + + Assert.IsTrue(startAtCapture.ToString().StartsWith("Start")); + Assert.IsTrue(statesCapture.AsObject().ContainsKey(startAtCapture.ToString())); +``` + +------ + +## Snapshot tests + +In *snapshot testing*, you compare the entire synthesized CloudFormation template against a previously\-stored master\. This isn't useful in catching regressions, as fine\-grained assertions are, because it applies to the entire template, and things besides code changes can cause small \(or not\-so\-small\) differences in synthesis results\. For example, we may update a CDK construct to incorporate a new best pracice, which can cause changes to the synthesized resources or how they're organized, or we might update the CDK Toolkit to report additional metadata\. Changes to context values can also affect the synthesized template\. + +Snapshot tests can be of great help in refactoring, though, as long as you hold constant all other factors that might affect the synthesized template\. You will know immediately if a change you made has unintentionally changed the template\. If the change is intentional, simply accept a new master and proceed\. + +For example, if we have this `DeadLetterQueue` construct: + +------ +#### [ TypeScript ] + +``` +import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; +import * as sqs from '@aws-cdk/aws-sqs'; +import { Construct, Duration } from '@aws-cdk/core'; export class DeadLetterQueue extends sqs.Queue { public readonly messagesInQueueAlarm: cloudwatch.IAlarm; - constructor(scope: Construct, id: string, props: DeadLetterQueueProps = {}) { - if (props.retentionDays !== undefined && props.retentionDays > 14) { - throw new Error('retentionDays may not exceed 14 days'); - } + constructor(scope: Construct, id: string) { + super(scope, id); - super(scope, id, { - // Given retention period or maximum - retentionPeriod: Duration.days(props.retentionDays || 14) + // Add the alarm + this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { + alarmDescription: 'There are messages in the Dead Letter Queue', + evaluationPeriods: 1, + threshold: 1, + metric: this.metricApproximateNumberOfMessagesVisible(), }); - // ... } } ``` -To test that the new feature actually does what we expect, we write two tests: -+ One that makes sure the configured value ends up in the template -+ One that supplies an incorrect value to the construct and checks it raises the expected error +------ +#### [ JavaScript ] + +``` +const cloudwatch = require('@aws-cdk/aws-cloudwatch'); +const sqs = require('@aws-cdk/aws-sqs'); +const { Construct, Duration } = require('@aws-cdk/core'); -Add the following to `test/dead-letter-queue.test.ts`\. +class DeadLetterQueue extends sqs.Queue { + + constructor(scope, id) { + super(scope, id); + // Add the alarm + this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { + alarmDescription: 'There are messages in the Dead Letter Queue', + evaluationPeriods: 1, + threshold: 1, + metric: this.metricApproximateNumberOfMessagesVisible(), + }); + } +} + +module.exports = { DeadLetterQueue } ``` -test('retention period can be configured', () => { - const stack = new Stack(); - new dlq.DeadLetterQueue(stack, 'DLQ', { - retentionDays: 7 - }); +------ +#### [ Python ] + +``` +class DeadLetterQueue(sqs.Queue): + def __init__(self, scope: cdk.Construct, id: str): + super().__init__(scope, id) + + self.messages_in_queue_alarm = cloudwatch.Alarm( + self, + "Alarm", + alarm_description="There are messages in the Dead Letter Queue.", + evaluation_periods=1, + threshold=1, + metric=self.metric_approximate_number_of_messages_visible(), + ) +``` + +------ +#### [ Java ] + +``` +package software.amazon.samples.awscdkassertionssamples; + +import org.jetbrains.annotations.NotNull; +import software.amazon.awscdk.services.cloudwatch.Alarm; +import software.amazon.awscdk.services.cloudwatch.IAlarm; +import software.amazon.awscdk.services.sqs.Queue; +import software.constructs.Construct; + +public class DeadLetterQueue extends Queue { + private final IAlarm messagesInQueueAlarm; + + public DeadLetterQueue(@NotNull Construct scope, @NotNull String id) { + super(scope, id); + + this.messagesInQueueAlarm = Alarm.Builder.create(this, "Alarm") + .alarmDescription("There are messages in the Dead Letter Queue.") + .evaluationPeriods(1) + .threshold(1) + .metric(this.metricApproximateNumberOfMessagesVisible()) + .build(); + } + + public IAlarm getMessagesInQueueAlarm() { + return messagesInQueueAlarm; + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.SQS; +using Amazon.CDK.AWS.CloudWatch; + +namespace AwsCdkAssertionSamples +{ + public class DeadLetterQueue : Queue + { + public IAlarm messagesInQueueAlarm; + + public DeadLetterQueue(Construct scope, string id) : base(scope, id) + { + messagesInQueueAlarm = new Alarm(this, "Alarm", new AlarmProps + { + AlarmDescription = "There are messages in the Dead Letter Queue.", + EvaluationPeriods = 1, + Threshold = 1, + Metric = this.MetricApproximateNumberOfMessagesVisible() + }); + } + } +} +``` + +------ + +We can test it like this: - expect(stack).toHaveResource('AWS::SQS::Queue', { - MessageRetentionPeriod: 604800 +------ +#### [ TypeScript ] + +``` +import { Match, Template } from "@aws-cdk/assertions"; +import * as cdk from "@aws-cdk/core"; +import { DeadLetterQueue } from "../lib/dead-letter-queue"; + +describe("DeadLetterQueue", () => { + test("creates an alarm", () => { + const stack = new cdk.Stack(); + new DeadLetterQueue(stack, "DeadLetterQueue"); + + const template = Template.fromStack(stack); + template.hasResourceProperties("AWS::CloudWatch::Alarm", { + Namespace: "AWS/SQS", + MetricName: "ApproximateNumberOfMessagesVisible", + Dimensions: [ + { + Name: "QueueName", + Value: Match.anyValue(), + }, + ], + }); }); }); +``` -test('configurable retention period cannot exceed 14 days', () => { - const stack = new Stack(); +------ +#### [ JavaScript ] - expect(() => { - new dlq.DeadLetterQueue(stack, 'DLQ', { - retentionDays: 15 +``` +const { Match, Template } = require("@aws-cdk/assertions"); +const cdk = require("@aws-cdk/core"); +const { DeadLetterQueue } = require("../lib/dead-letter-queue"); + +describe("DeadLetterQueue", () => { + test("creates an alarm", () => { + const stack = new cdk.Stack(); + new DeadLetterQueue(stack, "DeadLetterQueue"); + + const template = Template.fromStack(stack); + template.hasResourceProperties("AWS::CloudWatch::Alarm", { + Namespace: "AWS/SQS", + MetricName: "ApproximateNumberOfMessagesVisible", + Dimensions: [ + { + Name: "QueueName", + Value: Match.anyValue(), + }, + ], }); - }).toThrowError(/retentionDays may not exceed 14 days/); + }); }); ``` -Run the tests to confirm the construct behaves as expected\. +------ +#### [ Python ] + +``` +from aws_cdk import core as cdk +from aws_cdk.assertions import Match, Template + +from app.dead_letter_queue import DeadLetterQueue + +def test_creates_alarm(): + stack = cdk.Stack() + DeadLetterQueue(stack, "DeadLetterQueue") + + template = Template.from_stack(stack) + template.has_resource_properties( + "AWS::CloudWatch::Alarm", + { + "Namespace": "AWS/SQS", + "MetricName": "ApproximateNumberOfMessagesVisible", + "Dimensions": [ + { + "Name": "QueueName", + "Value": Match.any_value(), + }, + ], + }, + ) +``` + +------ +#### [ Java ] ``` -npm run build && npm test +package software.amazon.samples.awscdkassertionssamples; + +import org.junit.jupiter.api.Test; +import software.amazon.awscdk.assertions.Match; +import software.amazon.awscdk.assertions.Template; +import software.amazon.awscdk.core.Stack; + +import java.util.Collections; +import java.util.Map; + +public class DeadLetterQueueTest { + @Test + public void testCreatesAlarm() { + final Stack stack = new Stack(); + new DeadLetterQueue(stack, "DeadLetterQueue"); + + final Template template = Template.fromStack(stack); + template.hasResourceProperties("AWS::CloudWatch::Alarm", Map.of( + "Namespace", "AWS/SQS", + "MetricName", "ApproximateNumberOfMessagesVisible", + "Dimensions", Collections.singletonList(Map.of( + "Name", "QueueName", + "Value", Match.anyValue() + )) + )); + } +} ``` +------ +#### [ C\# ] + ``` -PASS test/dead-letter-queue.test.js - ✓ dlq creates an alarm (62ms) - ✓ dlq has maximum retention period (14ms) - ✓ retention period can be configured (18ms) - ✓ configurable retention period cannot exceed 14 days (1ms) +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Amazon.CDK; +using Amazon.CDK.Assertions; +using AwsCdkAssertionSamples; -Test Suites: 1 passed, 1 total -Tests: 4 passed, 4 total +using ObjectDict = System.Collections.Generic.Dictionary; +using StringDict = System.Collections.Generic.Dictionary; + +namespace TestProject1 +{ + [TestClass] + public class ProcessorStackTest + + [TestClass] + public class DeadLetterQueueTest + { + [TestMethod] + public void TestCreatesAlarm() + { + var stack = new Stack(); + new DeadLetterQueue(stack, "DeadLetterQueue"); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudWatch::Alarm", new ObjectDict + { + { "Namespace", "AWS/SQS" }, + { "MetricName", "ApproximateNumberOfMessagesVisible" }, + { "Dimensions", new object[] + { + new ObjectDict + { + { "Name", "QueueName" }, + { "Value", Match.AnyValue() } + } + } + } + }); + } + } +} ``` +------ + ## Tips for tests -Remember, your tests will live just as long as the code they test, and be read and modified just as often, so it pays to take a moment to consider how best to write them\. Don't copy and paste setup lines or common assertions, for example; refactor this logic into helper functions\. Use good names that reflect what each test actually tests\. +Remember, your tests will live just as long as the code they test, and be read and modified just as often, so it pays to take a moment to consider how best to write them\. Don't copy and paste setup lines or common assertions, for example; refactor this logic into fixtures or helper functions\. Use good names that reflect what each test actually tests\. -Don't assert too much in one test\. Preferably, a test should test one and only one behavior\. If you accidentally break that behavior, exactly one test should fail, and the name of the test should tell you exactly what failed\. This is more an ideal to be striven for, however; sometimes you will unavoidably \(or inadvertently\) write tests that test more than one behavior\. Snapshot tests are, for reasons we've already described, especially prone to this problem, so use them sparingly\. \ No newline at end of file +Don't try to do too much in one test\. Preferably, a test should test one and only one behavior\. If you accidentally break that behavior, exactly one test should fail, and the name of the test should tell you exactly what failed\. This is more an ideal to be striven for, however; sometimes you will unavoidably \(or inadvertently\) write tests that test more than one behavior\. Snapshot tests are, for reasons we've already described, especially prone to this problem, so use them sparingly\. \ No newline at end of file diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 2b85f14e..02820838 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 34c1358c3ac35d93f5a791d0a2cd87f078f67e4d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 19 Nov 2021 23:08:18 +0000 Subject: [PATCH 469/655] add description of cdk watch --- doc_source/cli.md | 47 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 68af885b..2ef0603a 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -391,7 +391,7 @@ The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Disabling rollback +### Disabling rollback One of AWS CloudFormation's marquee features is its ability to roll back changes so that deployments are atomic—they either succeed or fail as a whole\. The AWS CDK inherits this capability because it synthesizes and deploys AWS CloudFormation templates\. @@ -399,16 +399,33 @@ Rollback makes sure your resources are in a consistent state at all times, which For this reason, the CDK Toolkit; allows you to disable rollback by adding `--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. -### Hot swapping +### Hot swapping Use the `--hotswap` flag with `cdk deploy` to attempt to update your AWS resources directly instead of generating a AWS CloudFormation changeset and deploying it\. Deployment falls back to AWS CloudFormation deployment if hot swapping is not possible\. Currently hot swapping supports only Lambda functions\. The `--hotswap` flag also disables rollback \(i\.e\., implies `--no-rollback`\)\. **Important** -Hot swapping is not recommended for production environments\. +Hot\-swapping is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Watch mode + +The CDK Toolkit's watch mode \(`cdk watch`\) continuously monitors your CDK app's source files and assets for changes and immediately performs a deployment of the specified stacks when a change is detected\. + +By default, these deployments use the `--hotswap` flag, which fast\-tracks deployment of changes to Lambda functions, and falls back to deploying through AWS CloudFormation if you have changed infrastructure configuration\. To have `cdk watch` always perform full AWS CloudFormation deployments, add the `--no-hotswap` flag to `cdk watch`\. + +Any changes made while `cdk watch` is already performing a deployment will be combined into a single deployment, which will begin as soon as the in\-progress deployment is complete\. + +Watch mode uses the `"watch"` key in the project's `cdk.json` to determine which files to monitor\. By default, these files are your application files and assets, but this can be changed by modifying the `"include"` and `"exclude"` entries in the `"watch"` key\. + +`cdk watch` executes the `"build"` command from `cdk.json` to build your app before synthesis\. If your deployment requires any commands to build or package your Lambda code \(or anything else that's not in your CDK app proper\), add it here\. + +Wildcards, both `*` and `**`, can be used in the `"watch"` and `"build"` keys\. Each path is interpreted relative to the parent directory of `cdk.json`\. + +**Important** +Watch mode is not recommended for production deployments\. + +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -430,7 +447,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -543,6 +560,8 @@ Commands: cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your AWS account + cdk watch [STACKS..] Shortcut for 'deploy --watch' + cdk destroy [STACKS..] Destroy the stack(s) named STACKS cdk diff [STACKS..] Compares the specified stack with the deployed @@ -805,9 +824,21 @@ Options: --progress Display mode for stack activity events [string] [choices: "bar", "events"] - --rollback Rollback stack to stable state on failure (iterate - more rapidly with --no-rollback or -R) - [boolean] [default: true] + --rollback Rollback stack to stable state on failure. Defaults + to 'true', iterate more rapidly with --no-rollback + or -R. Note: do **not** disable this flag for + deployments with resource replacements, as that + will always fail [boolean] + + --hotswap Attempts to perform a 'hotswap' deployment, which + skips CloudFormation and updates the resources + directly, and falls back to a full deployment if + that is not possible. Do not use this in production + environments [boolean] + + --watch Continuously observe the project files, and deploy + the given stack(s) automatically when changes are + detected. Implies --hotswap by default [boolean] ``` ### `cdk destroy` From 546b6dc9dca2a18554c8f321a269996c701b157c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 22 Nov 2021 04:20:20 +0000 Subject: [PATCH 470/655] Node version update, tweaks, and churn --- doc_source/cli.md | 26 +++++++++++++------------- doc_source/constructs.md | 8 ++++---- doc_source/getting_started.md | 2 +- doc_source/home.md | 2 +- doc_source/serverless_example.md | 10 +++++----- doc_source/tagging.md | 2 +- doc_source/use_cfn_template.md | 2 +- 7 files changed, 26 insertions(+), 26 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 2ef0603a..8d03c222 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -340,7 +340,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -359,7 +359,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -367,7 +367,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -425,7 +425,7 @@ Wildcards, both `*` and `**`, can be used in the `"watch"` and `"build"` keys\. **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -447,7 +447,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -663,7 +663,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -676,7 +676,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -697,7 +697,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -772,7 +772,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -841,7 +841,7 @@ Options: detected. Implies --hotswap by default [boolean] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -860,7 +860,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -886,7 +886,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -908,7 +908,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/constructs.md b/doc_source/constructs.md index d2e039c7..72d34699 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -555,7 +555,7 @@ Another common pattern is for AWS constructs to set one of the resource's attrib ``` const jobsQueue = new sqs.Queue(this, 'jobs'); const createJobLambda = new lambda.Function(this, 'create-job', { - runtime: lambda.Runtime.NODEJS_10_X, + runtime: lambda.Runtime.NODEJS_14_X, handler: 'index.handler', code: lambda.Code.fromAsset('./create-job-lambda-code'), environment: { @@ -570,7 +570,7 @@ const createJobLambda = new lambda.Function(this, 'create-job', { ``` const jobsQueue = new sqs.Queue(this, 'jobs'); const createJobLambda = new lambda.Function(this, 'create-job', { - runtime: lambda.Runtime.NODEJS_10_X, + runtime: lambda.Runtime.NODEJS_14_X, handler: 'index.handler', code: lambda.Code.fromAsset('./create-job-lambda-code'), environment: { @@ -585,7 +585,7 @@ const createJobLambda = new lambda.Function(this, 'create-job', { ``` jobs_queue = sqs.Queue(self, "jobs") create_job_lambda = lambda_.Function(self, "create-job", - runtime=lambda_.Runtime.NODEJS_10_X, + runtime=lambda_.Runtime.NODEJS_14_X, handler="index.handler", code=lambda_.Code.from_asset("./create-job-lambda-code"), environment=dict( @@ -614,7 +614,7 @@ Function createJobLambda = Function.Builder.create(this, "create-job") var jobsQueue = new Queue(this, "jobs"); var createJobLambda = new Function(this, "create-job", new FunctionProps { - Runtime = Runtime.NODEJS_10_X, + Runtime = Runtime.NODEJS_14_X, Handler = "index.handler", Code = Code.FromAsset(@".\create-job-lambda-code"), Environment = new Dictionary diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index c58ec15d..c6fca102 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -118,7 +118,7 @@ TypeScript was the first language supported by the AWS CDK, and much AWS CDK exa Here's what you need to install to use the AWS CDK\. -All AWS CDK developers, even those working in Python, Java, or C\#, need [Node\.js](https://nodejs.org/en/download/) 10\.13\.0 or later\. All supported languages use the same back end, which runs on Node\.js\. We recommend a version in [active long\-term support](https://nodejs.org/en/about/releases/), which, at this writing, is the latest 14\.x release\. Your organization may have a different recommendation\. +All AWS CDK developers, even those working in Python, Java, or C\#, need [Node\.js](https://nodejs.org/en/download/) 10\.13\.0 or later\. All supported languages use the same back end, which runs on Node\.js\. We recommend a version in [active long\-term support](https://nodejs.org/en/about/releases/), which, at this writing, is the latest 16\.x release\. Your organization may have a different recommendation\. **Important** Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. diff --git a/doc_source/home.md b/doc_source/home.md index de07ca13..c3edfffb 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -181,7 +181,7 @@ This class produces an AWS CloudFormation [template of more than 500 lines](http + [AWS::EC2::InternetGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html) + [AWS::EC2::NatGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html) + [AWS::EC2::Route](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html) -+ [AWS::EC2::RouteTable](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route-table.html) ++ [AWS::EC2::RouteTable](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-routetable.html) + [AWS::EC2::SecurityGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html) + [AWS::EC2::Subnet](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html) + [AWS::EC2::SubnetRouteTableAssociation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html) diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index 507970cf..e889c753 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -285,7 +285,7 @@ export class WidgetService extends core.Construct { const bucket = new s3.Bucket(this, "WidgetStore"); const handler = new lambda.Function(this, "WidgetHandler", { - runtime: lambda.Runtime.NODEJS_10_X, // So we can use async in widget.js + runtime: lambda.Runtime.NODEJS_14_X, // So we can use async in widget.js code: lambda.Code.fromAsset("resources"), handler: "widgets.main", environment: { @@ -327,7 +327,7 @@ class WidgetService extends core.Construct { const bucket = new s3.Bucket(this, "WidgetStore"); const handler = new lambda.Function(this, "WidgetHandler", { - runtime: lambda.Runtime.NODEJS_10_X, // So we can use async in widget.js + runtime: lambda.Runtime.NODEJS_14_X, // So we can use async in widget.js code: lambda.Code.fromAsset("resources"), handler: "widgets.main", environment: { @@ -371,7 +371,7 @@ class WidgetService(core.Construct): bucket = s3.Bucket(self, "WidgetStore") handler = lambda_.Function(self, "WidgetHandler", - runtime=lambda_.Runtime.NODEJS_10_X, + runtime=lambda_.Runtime.NODEJS_14_X, code=lambda_.Code.from_asset("resources"), handler="widgets.main", environment=dict( @@ -418,7 +418,7 @@ public class WidgetService extends Construct { Bucket bucket = new Bucket(this, "WidgetStore"); Function handler = Function.Builder.create(this, "WidgetHandler") - .runtime(Runtime.NODEJS_10_X) + .runtime(Runtime.NODEJS_14_X) .code(Code.fromAsset("resources")) .handler("widgets.main") .environment(new HashMap() {{ @@ -464,7 +464,7 @@ namespace MyWidgetService var handler = new Function(this, "WidgetHandler", new FunctionProps { - Runtime = Runtime.NODEJS_10_X, + Runtime = Runtime.NODEJS_14_X, Code = Code.FromAsset("resources"), Handler = "widgets.main", Environment = new Dictionary diff --git a/doc_source/tagging.md b/doc_source/tagging.md index dcd4f1f5..80416375 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -90,7 +90,7 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 02820838..59ac4101 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From c57a4cd3668bf925da23b7219366cd5404a3e5d4 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 2 Dec 2021 04:21:04 +0000 Subject: [PATCH 471/655] CDK v2 release --- doc_source/apps.md | 4 +- doc_source/assets.md | 8 +- doc_source/best-practices.md | 12 +- doc_source/bootstrapping.md | 3 +- doc_source/cdk_pipeline.md | 6 +- doc_source/cfn_layer.md | 2 +- doc_source/cli.md | 43 +- doc_source/constructs.md | 9 +- doc_source/doc-history.md | 9 + doc_source/get_secrets_manager_value.md | 2 +- doc_source/get_ssm_value.md | 2 +- doc_source/getting_started.md | 27 +- doc_source/hello_world.md | 9 +- doc_source/home.md | 61 +- doc_source/how_to_set_cw_alarm.md | 2 +- doc_source/identifiers.md | 2 +- doc_source/index.md | 2 +- doc_source/multiple_languages.md | 10 +- doc_source/reference.md | 8 +- doc_source/resources.md | 6 +- doc_source/serverless_example.md | 4 +- doc_source/stacks.md | 2 +- doc_source/tagging.md | 4 +- doc_source/testing.md | 7 +- doc_source/tokens.md | 2 +- doc_source/troubleshooting.md | 10 +- doc_source/use_cfn_public_registry.md | 2 +- doc_source/use_cfn_template.md | 2 +- doc_source/work-with-cdk-csharp.md | 4 +- doc_source/work-with-cdk-go.md | 4 +- doc_source/work-with-cdk-java.md | 2 +- doc_source/work-with-cdk-javascript.md | 18 +- doc_source/work-with-cdk-python.md | 13 +- doc_source/work-with-cdk-typescript.md | 14 +- doc_source/work-with-cdk-v2.md | 263 +--- doc_source/work-with.md | 8 +- v2/about_examples.md | 3 + v2/apps.md | 316 +++++ v2/aspects.md | 220 +++ v2/assets.md | 885 ++++++++++++ v2/best-practices.md | 181 +++ v2/bootstrapping.md | 557 ++++++++ v2/cdk_pipeline.md | 1423 +++++++++++++++++++ v2/cfn_layer.md | 443 ++++++ v2/cli.md | 924 +++++++++++++ v2/compliance-validation.md | 16 + v2/constructs.md | 1014 ++++++++++++++ v2/context.md | 315 +++++ v2/core_concepts.md | 5 + v2/disaster-recovery-resiliency.md | 11 + v2/doc-history.md | 10 + v2/ecs_example.md | 306 ++++ v2/environments.md | 397 ++++++ v2/examples.md | 5 + v2/featureflags.md | 35 + v2/get_cfn_param.md | 5 + v2/get_context_var.md | 104 ++ v2/get_env_var.md | 68 + v2/get_secrets_manager_value.md | 112 ++ v2/get_ssm_value.md | 175 +++ v2/getting_started.md | 299 ++++ v2/hello_world.md | 536 ++++++++ v2/home.md | 264 ++++ v2/how_to_set_cw_alarm.md | 241 ++++ v2/how_tos.md | 3 + v2/identifiers.md | 283 ++++ v2/index.md | 76 + v2/infrastructure-security.md | 3 + v2/migrating-v2.md | 345 +++++ v2/multiple_languages.md | 349 +++++ v2/parameters.md | 208 +++ v2/permissions.md | 490 +++++++ v2/pgp-keys.md | 95 ++ v2/reference.md | 53 + v2/resources.md | 1281 +++++++++++++++++ v2/sam.md | 77 ++ v2/security-iam.md | 11 + v2/security.md | 15 + v2/serverless_example.md | 840 +++++++++++ v2/stack_how_to_create_multiple_stacks.md | 569 ++++++++ v2/stacks.md | 377 +++++ v2/tagging.md | 413 ++++++ v2/testing.md | 1531 +++++++++++++++++++++ v2/tokens.md | 427 ++++++ v2/tools.md | 8 + v2/troubleshooting.md | 254 ++++ v2/use_cfn_public_registry.md | 112 ++ v2/use_cfn_template.md | 666 +++++++++ v2/videos.md | 16 + v2/vscode.md | 3 + v2/work-with-cdk-csharp.md | 173 +++ v2/work-with-cdk-go.md | 123 ++ v2/work-with-cdk-java.md | 136 ++ v2/work-with-cdk-javascript.md | 288 ++++ v2/work-with-cdk-python.md | 212 +++ v2/work-with-cdk-typescript.md | 160 +++ v2/work-with.md | 118 ++ 97 files changed, 18779 insertions(+), 392 deletions(-) create mode 100644 v2/about_examples.md create mode 100644 v2/apps.md create mode 100644 v2/aspects.md create mode 100644 v2/assets.md create mode 100644 v2/best-practices.md create mode 100644 v2/bootstrapping.md create mode 100644 v2/cdk_pipeline.md create mode 100644 v2/cfn_layer.md create mode 100644 v2/cli.md create mode 100644 v2/compliance-validation.md create mode 100644 v2/constructs.md create mode 100644 v2/context.md create mode 100644 v2/core_concepts.md create mode 100644 v2/disaster-recovery-resiliency.md create mode 100644 v2/doc-history.md create mode 100644 v2/ecs_example.md create mode 100644 v2/environments.md create mode 100644 v2/examples.md create mode 100644 v2/featureflags.md create mode 100644 v2/get_cfn_param.md create mode 100644 v2/get_context_var.md create mode 100644 v2/get_env_var.md create mode 100644 v2/get_secrets_manager_value.md create mode 100644 v2/get_ssm_value.md create mode 100644 v2/getting_started.md create mode 100644 v2/hello_world.md create mode 100644 v2/home.md create mode 100644 v2/how_to_set_cw_alarm.md create mode 100644 v2/how_tos.md create mode 100644 v2/identifiers.md create mode 100644 v2/index.md create mode 100644 v2/infrastructure-security.md create mode 100644 v2/migrating-v2.md create mode 100644 v2/multiple_languages.md create mode 100644 v2/parameters.md create mode 100644 v2/permissions.md create mode 100644 v2/pgp-keys.md create mode 100644 v2/reference.md create mode 100644 v2/resources.md create mode 100644 v2/sam.md create mode 100644 v2/security-iam.md create mode 100644 v2/security.md create mode 100644 v2/serverless_example.md create mode 100644 v2/stack_how_to_create_multiple_stacks.md create mode 100644 v2/stacks.md create mode 100644 v2/tagging.md create mode 100644 v2/testing.md create mode 100644 v2/tokens.md create mode 100644 v2/tools.md create mode 100644 v2/troubleshooting.md create mode 100644 v2/use_cfn_public_registry.md create mode 100644 v2/use_cfn_template.md create mode 100644 v2/videos.md create mode 100644 v2/vscode.md create mode 100644 v2/work-with-cdk-csharp.md create mode 100644 v2/work-with-cdk-go.md create mode 100644 v2/work-with-cdk-java.md create mode 100644 v2/work-with-cdk-javascript.md create mode 100644 v2/work-with-cdk-python.md create mode 100644 v2/work-with-cdk-typescript.md create mode 100644 v2/work-with.md diff --git a/doc_source/apps.md b/doc_source/apps.md index 35da5e1a..4e7db550 100644 --- a/doc_source/apps.md +++ b/doc_source/apps.md @@ -1,6 +1,6 @@ # Apps -As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html) construct\. +As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/docs/core/stack.html) construct\. The following example declares a stack class named `MyFirstStack` that includes a single Amazon S3 bucket\. However, this only declares a stack\. You still need to define \(also known as to instantiate\) it in some scope to deploy it\. @@ -241,7 +241,7 @@ This is the final stage of the execution of your AWS CDK app\. It's triggered by In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: -+ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. ++ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1/typescript/custom-resource/) example\. + The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)` \(Python: `is_token`\)\. See [Tokens](tokens.md) for details\. ## Cloud assemblies diff --git a/doc_source/assets.md b/doc_source/assets.md index 3c070955..3bc5b04a 100644 --- a/doc_source/assets.md +++ b/doc_source/assets.md @@ -2,7 +2,7 @@ Assets are local files, directories, or Docker images that can be bundled into AWS CDK libraries and apps; for example, a directory that contains the handler code for an AWS Lambda function\. Assets can represent any artifact that the app needs to operate\. -You typically reference assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html#code) property lets you pass an [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function's code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-assetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. +You add assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html#code) property lets you pass an [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-fromassetpath) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function's code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-assetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. ## Assets in detail @@ -132,7 +132,7 @@ var fileAsset = new Asset(this, "SampleSingleFileAsset", new AssetProps ------ -In most cases, you don't need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods that enable you to use assets\. For Lambda functions, the [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) property enables you to specify a directory or a \.zip file in the local file system\. +In most cases, you don't need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods that enable you to use assets\. For Lambda functions, the [fromAsset\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) static method enables you to specify a directory or a \.zip file in the local file system\. #### Lambda function example @@ -566,7 +566,7 @@ DockerImageAsset asset = DockerImageAsset.Builder.create(this, "MyBuildImage") ``` using System.IO; -using Amazon.CDK.AWS.Ecr.Assets; +using Amazon.CDK.AWS.ECR.Assets; var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps { @@ -780,7 +780,7 @@ taskDefinition.addContainer("my-other-container", ``` using System.IO; using Amazon.CDK.AWS.ECS; -using Amazon.CDK.AWS.Ecr.Assets; +using Amazon.CDK.AWS.ECR.Assets; var asset = new DockerImageAsset(this, "my-image", new DockerImageAssetProps { Directory = Path.Combine(Directory.GetCurrentDirectory(), "demo-image") diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md index d399be04..074ecc72 100644 --- a/doc_source/best-practices.md +++ b/doc_source/best-practices.md @@ -9,14 +9,14 @@ The AWS CDK reflects careful consideration of the needs of our customers and int At deployment time, the AWS CDK synthesizes a cloud assembly that contains not only AWS CloudFormation templates describing your infrastructure in all target environments, but file assets containing your runtime code and their supporting files\. With the CDK, every commit in your application's main version control branch can represent a complete, consistent, deployable version of your application\. Your application can then be deployed automatically whenever a change is made\. The philosophy behind the AWS CDK leads to our recommended best practices, which we have divided into four broad categories\. - -**Tip** -In addition to the guidance in this document, you should also consider [best practices for AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html) as well as for the individual AWS services you use, where they are obviously applicable to CDK\-defined infrastructure\. + [Organization best practices](#best-practices-organization) + [Coding best practices](#best-practices-code) + [Construct best practices](#best-practices-constructs) + [Application best practices](#best-practices-apps) +**Tip** +In addition to the guidance in this document, you should also consider [best practices for AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html) as well as for the individual AWS services you use, where they are obviously applicable to CDK\-defined infrastructure\. + ## Organization best practices In the beginning stages of AWS CDK adoption, it's important to consider how to set up your organization for success\. It's a best practice to have a team of experts responsible for training and guiding the rest of the company as they adopt the CDK The size of this team may vary, from one or two people at a small company to a full\-fledged Cloud Center of Excellence \(CCoE\) at a larger company\. This team is responsible for setting standards and policies for how cloud infrastructure will be done at your company, as well as for training and mentoring developers\. @@ -59,7 +59,7 @@ When packages begin to be used in multiple applications, move them to their own Also move packages to their own repo when different teams are working on them, to help enforce access control\. -To consume packages across repository boundaries, you now need a private package repository—similar to NPM, PyPi, or Maven Central, but internal to your organization, and a release process that builds, tests, and publishes the package to the private package repository\. [CodeArtifact](%url-aca-user) can host packages for most popular programming languages\. +To consume packages across repository boundaries, you now need a private package repository—similar to NPM, PyPi, or Maven Central, but internal to your organization, and a release process that builds, tests, and publishes the package to the private package repository\. [CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/) can host packages for most popular programming languages\. Dependencies on packages in the package repository are managed by your language's package manager, for example NPM for TypeScript or JavaScript applications\. Your package manager helps to make sure builds are repeatable by recording the specific versions of every package your application depends on and allows you to upgrade those dependencies in a controlled manner\. @@ -125,7 +125,7 @@ A better approach is to specify as few names as possible\. If you leave out reso If the place you need it is another AWS CDK stack, that's even easier\. Given one stack that defines the resource and another than needs to use it: + If the two stacks are in the same AWS CDK app, just pass a reference between the two stacks\. For example, save a reference to the resource's construct as an attribute of the defining stack \(`this.stack.uploadBucket = myBucket`\), then pass that attribute to the constructor of the stack that needs the resource\. -+ When the two stacks are in different AWS CDK apps, use a static `from` method to import an externally\-defined resource based on its ARN, name, or other attributes \(for example, `Table.fromarn()` for a DynamoDB table\)\. Use the `CfnOutput` construct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS console\. Or the second app can parse the CloudFormation template generated by the first app and retrieve that value from the Outputs section\. ++ When the two stacks are in different AWS CDK apps, use a static `from` method to import an externally\-defined resource based on its ARN, name, or other attributes \(for example, `Table.fromArn()` for a DynamoDB table\)\. Use the `CfnOutput` construct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS console\. Or the second app can parse the CloudFormation template generated by the first app and retrieve that value from the Outputs section\. ### Define removal policies and log retention @@ -144,7 +144,7 @@ There is no hard and fast rule to how many stacks your application needs\. You'l Determinism is key to successful AWS CDK deployments\. A AWS CDK app should have essentially the same result whenever it is deployed to a given environment\. -Since your AWS CDK app is written in a a general\-purpose programming language, it can execute arbitrary code, use arbitrary libraries, and make arbitrary network calls\. For example, you could use an AWS SDK to retrieve some information from your AWS account while synthesizing your app\. Recognize that doing so will result in additional credential setup requirements, increased latency, and a chance, however small, of failure every time you run `cdk synth`\. +Since your AWS CDK app is written in a general\-purpose programming language, it can execute arbitrary code, use arbitrary libraries, and make arbitrary network calls\. For example, you could use an AWS SDK to retrieve some information from your AWS account while synthesizing your app\. Recognize that doing so will result in additional credential setup requirements, increased latency, and a chance, however small, of failure every time you run `cdk synth`\. You should never modify your AWS account or resources during synthesis; synthesizing an app should not have side effects\. Changes to your infrastructure should happen only in the deployment phase, after the AWS CloudFormation template has been generated\. This way, if there's a problem, AWS CloudFormation will automatically roll back the change\. To make changes that can't be easily made within the AWS CDK framework, use [custom resources](https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html) to execute arbitrary code at deployment time\. diff --git a/doc_source/bootstrapping.md b/doc_source/bootstrapping.md index 636d6f80..3dc69845 100644 --- a/doc_source/bootstrapping.md +++ b/doc_source/bootstrapping.md @@ -177,8 +177,7 @@ The following additional switches are available only with the modern bootstrappi The policies must be passed as a single string argument, with the policy ARNs separated by commas, like this: ``` - --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCo - deDeployFullAccess". + --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess". ``` + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. + \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. diff --git a/doc_source/cdk_pipeline.md b/doc_source/cdk_pipeline.md index f8f19ca0..214cf1df 100644 --- a/doc_source/cdk_pipeline.md +++ b/doc_source/cdk_pipeline.md @@ -39,7 +39,7 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ ``` set CDK_NEW_BOOTSTRAP=1 -npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ +cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ aws://ACCOUNT-ID/REGION ``` @@ -55,7 +55,7 @@ Again, you may omit the \-\-profile option if your default AWS profile contains ``` export CDK_NEW_BOOTSTRAP=1 -npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ +cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ --trust PIPELINE-ACCOUNT-ID \ aws://ACCOUNT-ID/REGION @@ -66,7 +66,7 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ ``` set CDK_NEW_BOOTSTRAP=1 -npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ +cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ --trust PIPELINE-ACCOUNT-ID ^ aws://ACCOUNT-ID/REGION diff --git a/doc_source/cfn_layer.md b/doc_source/cfn_layer.md index 3badc196..e6da8c9e 100644 --- a/doc_source/cfn_layer.md +++ b/doc_source/cfn_layer.md @@ -439,5 +439,5 @@ Building a custom resource involves writing a Lambda function that responds to a The subject is too broad to completely cover here, but the following links should get you started: + [Custom Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) -+ [Custom\-Resource Example](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) ++ [Custom\-Resource Example](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1/typescript/custom-resource/) + For a more fully fledged example, see the [DnsValidatedCertificate](https://github.com/awslabs/aws-cdk/blob/master/packages/@aws-cdk/aws-certificatemanager/lib/dns-validated-certificate.ts) class in the CDK standard library\. This is implemented as a custom resource\. \ No newline at end of file diff --git a/doc_source/cli.md b/doc_source/cli.md index 8d03c222..05e094e4 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -5,12 +5,18 @@ The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting The AWS CDK Toolkit is installed with the Node Package Manager\. In most cases, we recommend installing it globally\. ``` -npm install -g aws-cdk # install latest version +npm install -g aws-cdk@1.x # install latest 1.x version npm install -g aws-cdk@X.YY.Z # install specific version ``` +You may also use CDK Toolkit v2\.x with CDK v1\.x projects\. An exception is that CDK Toolkit v2 creates CDK v2 projects\. To create CDK v1 projects while CDK Toolkit v2\.x is installed globally, use npx to run the latest 1\.x release of the CDK Toolkit\. + +``` +cdk init app --language typescript +``` + **Tip** -If you regularly work with multiple versions of the AWS CDK, you may want to install a matching version of the AWS CDK Toolkit in individual CDK projects\. To do this, omit `-g` from the `npm install` command\. Then use `npx cdk` to invoke it; this will run the local version if one exists, falling back to a global version if not\. +If you regularly work with multiple versions of the AWS CDK, you may want to install a matching version of the AWS CDK Toolkit in individual CDK projects\. TypeScript and JavaScript projects have a local copy of the CDK Toolkit already\. For other languages, omit `-g` from the `npm install` command\. Then use `npx aws-cdk` to invoke cdk; this will run the local version if one exists, falling back to a global version if not\. ## Toolkit commands @@ -245,7 +251,7 @@ cdk synth 'PipelineStack/Prod/**' # All stacks in Prod stage in a CDK Pipeline ``` **Note** -The order in which you specify the stacks is not necessarily the order in which they will be processed\. The AWS CDK Toolkit takes into account dependencies between stacks when deciding the order in which to process them\. For example, if one stack uses a value produced by another \(such as the ARN of a resource defined in the second stack\), the second stack is synthesized before the first one because of this dependency\. You can add dependencies between stacks manually using the stack's [https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html#core_Stack_addDependency](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html#core_Stack_addDependency) method\. +The order in which you specify the stacks is not necessarily the order in which they will be processed\. The AWS CDK Toolkit takes into account dependencies between stacks when deciding the order in which to process them\. For example, if one stack uses a value produced by another \(such as the ARN of a resource defined in the second stack\), the second stack is synthesized before the first one because of this dependency\. You can add dependencies between stacks manually using the stack's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#addwbrdependencytarget-reason](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#addwbrdependencytarget-reason) method\. ## Bootstrapping your AWS environment @@ -288,6 +294,9 @@ cd my-cdk-app cdk init TEMPLATE --language LANGUAGE ``` +**Tip** +If you have installed CDK Toolkit v2 globally, cdk init creates CDK v2 projects\. To avoid this, see [CDK Toolkit v2 compatibility](work-with-cdk-v2.md#work-with-cdk-v2-cli)\. + The supported languages \(*LANGUAGE*\) are: @@ -340,7 +349,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -359,7 +368,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -367,7 +376,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -410,7 +419,7 @@ Hot\-swapping is not recommended for production deployments\. ### Watch mode -The CDK Toolkit's watch mode \(`cdk watch`\) continuously monitors your CDK app's source files and assets for changes and immediately performs a deployment of the specified stacks when a change is detected\. +The CDK Toolkit's watch mode \( cdk deploy \-\-watch, or cdk watch for short\) continuously monitors your CDK app's source files and assets for changes and immediately performs a deployment of the specified stacks when a change is detected\. By default, these deployments use the `--hotswap` flag, which fast\-tracks deployment of changes to Lambda functions, and falls back to deploying through AWS CloudFormation if you have changed infrastructure configuration\. To have `cdk watch` always perform full AWS CloudFormation deployments, add the `--no-hotswap` flag to `cdk watch`\. @@ -425,7 +434,7 @@ Wildcards, both `*` and `**`, can be used in the `"watch"` and `"build"` keys\. **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -447,7 +456,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -663,7 +672,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -676,7 +685,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -697,7 +706,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -772,7 +781,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -841,7 +850,7 @@ Options: detected. Implies --hotswap by default [boolean] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -860,7 +869,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -886,7 +895,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -908,7 +917,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/doc_source/constructs.md b/doc_source/constructs.md index 72d34699..a7d4e676 100644 --- a/doc_source/constructs.md +++ b/doc_source/constructs.md @@ -2,15 +2,20 @@ Constructs are the basic building blocks of AWS CDK apps\. A construct represents a "cloud component" and encapsulates everything AWS CloudFormation needs to create the component\. +**Note** +Constructs are part of the Construct Programming Model \(CPM\) and are also used by other tools such as CDK for Terraform \(CDKtf\), CDK for Kubernetes \(CDK8s\), and Projen\. + A construct can represent a single AWS resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can be a higher\-level abstraction consisting of multiple AWS related resources\. Examples of such components include a worker queue with its associated compute capacity, or a scheduled job with monitoring resources and a dashboard\. +The AWS CDK includes a collection of constructs called the AWS Construct Library, containing constructs for every AWS service\. [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=1&sort=downloadsDesc&offset=0) is a resource to help you discover additional constructs from AWS, third parties, and the open\-source CDK community\. + ## AWS Construct library The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html), which contains constructs representing AWS resources\. This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html)` class represents an Amazon DynamoDB table\. -There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "level 1"\) or Cfn \(short for CloudFormation\) resources\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. +There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "layer 1"\) or Cfn \(short for CloudFormation\) resources\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#add-wbr-lifecycle-wbr-rulerule), which adds a lifecycle rule to the bucket\. @@ -149,7 +154,7 @@ namespace HelloCdkApp ------ -As you can see, you need a scope within which to define your bucket\. Since resources eventually need to be deployed as part of a AWS CloudFormation stack into an *AWS [environment](environments.md)*, which covers a specific AWS account and AWS region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html)\. +As you can see, you need a scope within which to define your bucket\. Since resources eventually need to be deployed as part of a AWS CloudFormation stack into an *AWS [environment](environments.md)*, which covers a specific AWS account and AWS region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/docs/core/stack.html)\. Stacks in AWS CDK apps extend the **Stack** base class, as shown in the previous example\. This is a common pattern when creating a stack within your AWS CDK app: extend the **Stack** class, define a constructor that accepts **scope**, **id**, and **props**, and invoke the base class constructor via `super` with the received **scope**, **id**, and **props**, as shown in the following example\. diff --git a/doc_source/doc-history.md b/doc_source/doc-history.md index b5f0f320..de724922 100644 --- a/doc_source/doc-history.md +++ b/doc_source/doc-history.md @@ -7,6 +7,15 @@ The table below represents significant documentation milestones\. We fix errors | Change | Description | Date | | --- |--- |--- | +| [AWS CDK v2 release](#doc-history) | Improvements to CDK v1 Developer Guide to coincide with the release of CDK v2 and its documentation\. | December 4, 2021 | +| [`cdk watch`](#doc-history) | Add description of `cdk watch` command for incremental deployments\. | November 19, 2021 | +| [Testing with `assertions`](#doc-history) | Revise testing topic to use new `assertions` library\. | November 17, 2021 | +| [Experimental modules](#doc-history) | Explain how experimental modules work with CDK v2\. | October 28, 2021 | +| [Faster local development](#doc-history) | Add information on `--no-rollback` and `--hotswap` options for accelerated local development\. | October 7, 2021 | +| [Add local tooling information](#doc-history) | Update TypeScript and JavaScript topics with information on using locally\-installed tools \(`cdk`, `tsc`\)\. | September 28, 2021 | +| [Update CDK Pipelines API](#doc-history) | Update CDK Pipelines topic to use new API\. | August 24, 2021 | +| [CloudFormation Public Registry](#doc-history) | Add topic about using resource definitions from the CloudFormation Public Registry with the AWS CDK\. | June 24, 2021 | +| [Best Practices topic](#doc-history) | Add topic about best practices for developing CDK apps\. | June 10, 2021 | | [Go developer preview](#doc-history) | Add information about Go language support \(in developer preview\) including a "Working with the CDK in Go" topic\. | April 19, 2021 | | [Import or migrate AWS CloudFormation template](#doc-history) | Add description of the new `cloudformation-include.CfnInclude` class, a powerful way to import and migrate AWS CloudFormation templates, or to vend them as AWS CDK constructs\. | October 15, 2020 | | [Add construct tree section](#doc-history) | Information about the construct tree and its relation to the constructs you define in your AWS CDK app\. | October 5, 2020 | diff --git a/doc_source/get_secrets_manager_value.md b/doc_source/get_secrets_manager_value.md index 03c80a69..3b17c81d 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/doc_source/get_secrets_manager_value.md @@ -1,6 +1,6 @@ # Get a value from AWS Secrets Manager -To use values from AWS Secrets Manager in your AWS CDK app, use the [fromSecretAttributes](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/aws-secretsmanager/secret.html#aws_secretsmanager_Secret_fromSecretAttributes) method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. +To use values from AWS Secrets Manager in your AWS CDK app, use the [fromSecretAttributes](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-secretsmanager/secret.html#aws_secretsmanager_Secret_fromSecretAttributes) method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. ------ #### [ TypeScript ] diff --git a/doc_source/get_ssm_value.md b/doc_source/get_ssm_value.md index 46a64158..e8229b46 100644 --- a/doc_source/get_ssm_value.md +++ b/doc_source/get_ssm_value.md @@ -109,7 +109,7 @@ To read a value from the Systems Manager parameter store at synthesis time, use Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. **Important** -The retrieved value will end up in your synthesized AWS CloudFormation template, which may be a security risk depending on who has access to your your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. +The retrieved value will end up in your synthesized AWS CloudFormation template, which may be a security risk depending on who has access to your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. ------ #### [ TypeScript ] diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index c6fca102..5049376f 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -4,7 +4,7 @@ This topic introduces you to important AWS CDK concepts and describes how to ins ## Your background -The AWS Cloud Development Kit \(AWS CDK\) lets you define your cloud infrastructure as code in one of five supported programming languages\. It is intended for moderately to highly experienced AWS users\. +The AWS Cloud Development Kit \(AWS CDK\) lets you define your cloud infrastructure as code in one of its supported programming languages\. It is intended for moderately to highly experienced AWS users\. Ideally, you already have experience with popular AWS services, particularly [AWS Identity and Access Management](https://aws.amazon.com/iam/) \(IAM\)\. You might already have AWS credentials on your workstation for use with an AWS SDK or the AWS CLI and experience working with AWS resources programmatically\. @@ -21,26 +21,28 @@ An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, P **Note** The AWS CDK also supports Go in a developer preview\. This Guide does not include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. -Constructs \(as well as stacks and apps\) are represented as types in your programming language of choice\. You instantiate constructs within a stack to declare them to AWS, and connect them to each other using well\-defined interfaces\. +Constructs \(as well as stacks and apps\) are represented as classes \(types\) in your programming language of choice\. You instantiate constructs within a stack to declare them to AWS, and connect them to each other using well\-defined interfaces\. The AWS CDK includes the AWS CDK Toolkit \(also called the CLI\), a command\-line tool for working with your AWS CDK apps and stacks\. Among other functions, the Toolkit provides the ability to convert one or more AWS CDK stacks to AWS CloudFormation templates and related assets \(a process called *synthesis*\) and to deploy your stacks to an AWS account\. The AWS CDK includes a library of AWS constructs called the AWS Construct Library\. Each AWS service has at least one corresponding module in the library containing the constructs that represent that service's resources\. Constructs come in three fundamental flavors: -+ **AWS CloudFormation\-only** or L1 \(short for "level 1"\)\. These constructs correspond directly to resource types defined by AWS CloudFormation\. In fact, these constructs are automatically generated from the AWS CloudFormation specification, so when a new AWS service is launched, the AWS CDK supports it as soon as AWS CloudFormation does\. ++ **AWS CloudFormation\-only** or L1 \(short for "layer 1"\)\. These constructs correspond directly to resource types defined by AWS CloudFormation\. In fact, these constructs are automatically generated from the AWS CloudFormation specification, so when a new AWS service is launched, the AWS CDK supports it a short time after AWS CloudFormation does\. - AWS CloudFormation resources always have names that begin with `Cfn`\. For example, in the Amazon S3 module, `CfnBucket` is the L1 module for an Amazon S3 bucket\. -+ **Curated** or L2\. These constructs are carefully developed by the AWS CDK team to address specific use cases and simplify infrastructure development\. For the most part, they encapsulate L1 modules, providing sensible defaults and best\-practice security policies\. For example, in the Amazon S3 module, `Bucket` is the L2 module for an Amazon S3 bucket\. + AWS CloudFormation resources always have names that begin with `Cfn`\. For example, in the Amazon S3 module, `CfnBucket` is the L1 construct for an Amazon S3 bucket\. ++ **Curated** or L2\. These constructs are carefully developed by the AWS CDK team to address specific use cases and simplify infrastructure development\. For the most part, they encapsulate L1 resources, providing sensible defaults and best\-practice security policies\. For example, in the Amazon S3 module, `Bucket` is the L2 construct for an Amazon S3 bucket\. - L2 modules may also define supporting resources needed by the primary resource\. Some services have more than one L2 module in the Construct Library for organizational purposes\. + Modules may also define supporting resources needed by the primary resource\. Some services have more than one L2 module in the Construct Library for organizational purposes\. + **Patterns** or L3\. Patterns declare multiple resources to create entire AWS architectures for particular use cases\. All the plumbing is already hooked up, and configuration is boiled down to a few important parameters\. In the AWS Construct Library, patterns are in separate modules from L1 and L2 constructs\. -The AWS CDK's core module \(usually imported into code as `core` or `cdk`\) contains constructs used by the AWS CDK itself as well as base classes for constructs, apps, resources, and other AWS CDK objects\. +The AWS CDK's core module \(usually imported into code as `core` or `cdk`\) contains constructs used by the AWS CDK itself as well as base classes for apps, stacks, and other AWS CDK objects\. + +Numerous third parties have also published constructs compatible with the AWS CDK\. Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=1&offset=0) to explore the AWS CDK construct ecosystem\. ## Supported programming languages -The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) +The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) Go support is available as a Develper Preview\. To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. @@ -158,7 +160,7 @@ Other prerequisites depend on the language in which you develop AWS CDK applicat ------ #### [ TypeScript ] -+ TypeScript 2\.7 or later \(`npm -g install typescript`\) ++ TypeScript 3\.8 or later \(`npm -g install typescript`\) ------ #### [ JavaScript ] @@ -190,7 +192,7 @@ Visual Studio 2019 \(any edition\) or Visual Studio Code recommended\. Install the AWS CDK Toolkit globally using the following Node Package Manager command\. ``` -npm install -g aws-cdk +npm install -g aws-cdk@1.x ``` Run the following command to verify correct installation and print the version number of the AWS CDK\. @@ -236,8 +238,9 @@ The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode Where do you go now that you've dipped your toes in the AWS CDK? + Come on in; the water's fine\! Build [your first AWS CDK app](hello_world.md)\. + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. -+ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite AWS services\. ++ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the provided constructs available for your favorite AWS services\. ++ Visit the [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=1&sort=downloadsDesc&offset=0) to find constructs from the CDK community as well as from AWS\. + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. -+ Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. ++ Explore [Examples](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1) of using the AWS CDK\. The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/doc_source/hello_world.md b/doc_source/hello_world.md index 016ed6b9..9654ee47 100644 --- a/doc_source/hello_world.md +++ b/doc_source/hello_world.md @@ -389,7 +389,7 @@ You've deployed your first stack using the AWS CDK—congratulations\! But that' ## Modifying the app -The AWS CDK can update your deployed resources after you modify your app\. Let's change our bucket so it can be automatically deleted when we delete the stack, which involves changing its `RemovalPolicy`\. Also, because AWS CloudFormation won't delete Amazon S3 buckets that contain any objects, we'll ask the AWS CDK to delete the objects from our bucket before destroying the bucket, via the `autoDeleteObjects` property\.\. +The AWS CDK can update your deployed resources after you modify your app\. Let's change our bucket so it can be automatically deleted when we delete the stack, which involves changing its `RemovalPolicy`\. Also, because AWS CloudFormation won't delete Amazon S3 buckets that contain any objects, we'll ask the AWS CDK to delete the objects from our bucket before destroying the bucket, via the `autoDeleteObjects` property\. ------ #### [ TypeScript ] @@ -540,7 +540,7 @@ cdk deploy The AWS CDK warns you about the security policy changes we've already seen in the diff\. Enter y to approve the changes and deploy the updated stack\. The CDK Toolkit updates the bucket configuration as you requested\. ``` -HHelloCdkStack: deploying... +HelloCdkStack: deploying... [0%] start: Publishing 4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392:current [100%] success: Published 4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392:current HelloCdkStack: creating CloudFormation changeset... @@ -584,8 +584,9 @@ If we hadn't changed the bucket's `RemovalPolicy`, the stack deletion would comp Where do you go now that you've dipped your toes in the AWS CDK? + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. -+ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite AWS services\. + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. -+ Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. ++ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite AWS services\. ++ Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=1&sort=downloadsDesc&offset=0) to discover constructs created by AWS and others\. ++ Explore [Examples](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1) of using the AWS CDK\. The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/doc_source/home.md b/doc_source/home.md index c3edfffb..72784188 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -1,22 +1,28 @@ # What is the AWS CDK? -Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, which is a software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. +Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. -AWS CloudFormation enables you to: -+ Create and provision AWS infrastructure deployments predictably and repeatedly\. -+ Leverage AWS products such as Amazon EC2, Amazon Elastic Block Store, Amazon SNS, Elastic Load Balancing, and Auto Scaling\. -+ Build highly reliable, highly scalable, cost\-effective applications in the cloud without worrying about creating and configuring the underlying AWS infrastructure\. -+ Use a template file to create and delete a collection of resources together as a single unit \(a stack\)\. +**Important** +The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v1\. +CDK v1 will continue to be fully supported until June 2, 2022, at which time it will enter maintenance\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 2, 2023, support will end for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. -Use the AWS CDK to define your cloud resources in a familiar programming language\. The AWS CDK supports TypeScript, JavaScript, Python, Java, C\#/\.Net, and \(in developer preview\) Go\. +The AWS CDK lets you build reliable, scalable, cost\-effective applications in the cloud with the considerable expressive power of a programming language\. This approach yields many benefits, including: ++ Build with high\-level constructs that automatically provide sensible, secure defaults for your AWS resources, defining more infrastructure with less code\. ++ Use programming idioms like parameters, conditionals, loops, composition, and inheritance to model your system design from building blocks provided by AWS and others\. ++ Put your infrastructure, application code, and configuration all in one place, ensuring that at every milestone you have a complete, cloud\-deployable system\. ++ Employ software engineering practices such as code reviews, unit tests, and source control to make your infrastructure more robust\. ++ Connect your AWS resources together \(even across stacks\) and grant permissions using simple, intent\-oriented APIs\. ++ Import existing AWS CloudFormation templates to give your resources a CDK API\. ++ Use the power of AWS CloudFormation to perform infrastructure deployments predictably and repeatedly, with rollback on error\. ++ Easily share infrastructure design patterns among teams within your organization or even with the public\. -Developers can use one of the supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. +The AWS CDK supports TypeScript, JavaScript, Python, Java, C\#/\.Net, and \(in developer preview\) Go\. Developers can use one of these supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/AppStacks.png) ## Why use the AWS CDK? -Let's look at the power of the AWS CDK\. Here is some code in an AWS CDK project to create an Amazon ECS service with AWS Fargate launch type \(this is the code we use in the [Creating an AWS Fargate service using the AWS CDK](ecs_example.md)\)\. +It's easier to show than to explain\! Here's some CDK code that creates an Amazon ECS service with AWS Fargate launch type \(this is the code we use in the [Creating an AWS Fargate service using the AWS CDK](ecs_example.md)\)\. ------ #### [ TypeScript ] @@ -138,11 +144,6 @@ public class MyEcsConstructStack extends Stack { #### [ C\# ] ``` -using Amazon.CDK; -using Amazon.CDK.AWS.EC2; -using Amazon.CDK.AWS.ECS; -using Amazon.CDK.AWS.ECS.Patterns; - public class MyEcsConstructStack : Stack { public MyEcsConstructStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) @@ -197,39 +198,37 @@ This class produces an AWS CloudFormation [template of more than 500 lines](http + [AWS::IAM::Role](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html) + [AWS::Logs::LogGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html) -Other advantages of the AWS CDK include: -+ Use logic \(if statements, for\-loops, etc\) when defining your infrastructure -+ Use object\-oriented techniques to create a model of your system -+ Define high level abstractions, share them, and publish them to your team, company, or community -+ Organize your project into logical modules -+ Share and reuse your infrastructure as a library -+ Testing your infrastructure code using industry\-standard protocols -+ Use your existing code review workflow -+ Code completion within your IDE +And lest we forget\.\.\. code completion within your IDE or editor\! + ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/CodeCompletion.png) ## Developing with the AWS CDK -Code snippets and longer examples are available in the AWS CDK's supported programming languages: TypeScript, JavaScript, Python, Java, and C\#\. See [AWS CDK examples](about_examples.md) for a list of the examples\. +It's easy to [get set up](getting_started.md) and [write your first CDK app](hello_world.md)\. Short code examples are available throughout this Guide in the AWS CDK's supported programming languages: TypeScript, JavaScript, Python, Java, and C\#\. Longer examples are available [in our GitHub repository](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1)\. The [AWS CDK Toolkit](cli.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. -The [AWS Construct Library](constructs.md) includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to create resources for an Amazon or AWS service\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. +The [AWS Construct Library](constructs.md) offers constructs for each AWS service, many with "rich" APIs that provide high\-level abstractions\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. **Note** There is no charge for using the AWS CDK, but you might incur AWS charges for creating or using AWS [chargeable resources](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Pricing Calculator](https://calculator.aws/#/) to estimate charges for the use of various AWS resources\. -## Contributing to the AWS CDK +## The Construct Programming Model -Because the AWS CDK is open source, the team encourages you to contribute to make it an even better tool\. For details, see [Contributing](https://github.com/awslabs/aws-cdk/blob/master/CONTRIBUTING.md)\. +The Construct Programming Model \(CPM\) extends the concepts behind the AWS CDK into additional domains\. Other tools using the CPM include: ++ [CDK for Terraform](https://www.terraform.io/docs/cdktf/index.html) \(CDKtf\) ++ [CDK for Kubernetes](https://cdk8s.io/) \(CDK8s\) ++ [Projen](https://github.com/projen/projen), for building project configurations + +[Construct Hub](https://constructs.dev/) is an online registry where you can find and publish construct libraries for CDKs like the AWS CDK\. ## Additional documentation and resources -In addition to this guide, the following are other resources available to AWS CDK users: +In addition to this guide, the following other resources are available to AWS CDK users: + [API Reference](https://docs.aws.amazon.com/cdk/api/latest) + [AWS CDK Workshop](https://cdkworkshop.com/) + [cdk\.dev](https://cdk.dev/) community hub, including a Slack channel -+ [AWS CDK Examples](https://github.com/aws-samples/aws-cdk-examples) ++ [AWS CDK Examples](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1) + [CDK Patterns](https://cdkpatterns.com/) + [Awesome CDK](https://github.com/kolomied/awesome-cdk) + [AWS Solutions Constructs](http://aws.amazon.com/solutions/constructs/) @@ -253,6 +252,10 @@ These tools can work with the AWS CDK to simplify serverless application develop + [AWS Serverless Application Model](http://aws.amazon.com/serverless/sam/) + [AWS Chalice](https://github.com/aws/chalice), a Python serverless microframework +## Contributing to the AWS CDK + +Because the AWS CDK is open source, the team encourages you to contribute to make it an even better tool\. For details, see [Contributing](https://github.com/awslabs/aws-cdk/blob/master/CONTRIBUTING.md)\. + ## About Amazon Web Services Amazon Web Services \(AWS\) is a collection of digital infrastructure services that developers can use when developing their applications\. The services include computing, storage, database, and application synchronization \(messaging and queueing\)\. diff --git a/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md index 48f45441..5e6a1fb6 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/doc_source/how_to_set_cw_alarm.md @@ -111,7 +111,7 @@ var metric = new Metric(this, "Metric", new MetricProps ## Creating the alarm -Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three seconds\. You can use comparisons such as less\-than in your alarms via the `comparisonOperator` property; greater\-than\-or\-equal\-to is the AWS CDK default, so we don't need to psecify it\. +Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three seconds\. You can use comparisons such as less\-than in your alarms via the `comparisonOperator` property; greater\-than\-or\-equal\-to is the AWS CDK default, so we don't need to specify it\. Assuming the metric is the **ApproximateNumberOfMessagesVisible** metric from an Amazon SQS queue, it would raise when 100 messages are visible in the queue in two of the last three seconds\. diff --git a/doc_source/identifiers.md b/doc_source/identifiers.md index 76e1bcd2..928cca43 100644 --- a/doc_source/identifiers.md +++ b/doc_source/identifiers.md @@ -13,7 +13,7 @@ The most common identifier, `id`, is the identifier passed as the second argumen **Note** The `id` of a stack is also the identifier you use to refer to it in the [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. -Let's look at an example where we have two constructs with the identifier `MyBucket` in our app\. However, since they are defined in different scopes, the first in the scope of the stack with the identifier `Stack1`, and the second in the scope of a stack with the identifier `Stack2`, that doesn't cause any sort of conflict, and they can co\-exist in the same app without any issues\. +Let's look at an example where we have two constructs with the identifier `MyBucket` in our app\. However, since they are defined in different scopes, the first in the scope of the stack with the identifier `Stack1`, and the second in the scope of a stack with the identifier `Stack2`, that doesn't cause any sort of conflict, and they can coexist in the same app without any issues\. ------ #### [ TypeScript ] diff --git a/doc_source/index.md b/doc_source/index.md index e6e53181..2cec9a4d 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -1,4 +1,4 @@ -# AWS Cloud Development Kit (AWS CDK) Developer Guide +# AWS Cloud Development Kit (AWS CDK) v1 Developer Guide ----- *****Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** diff --git a/doc_source/multiple_languages.md b/doc_source/multiple_languages.md index 584dba1b..992520c6 100644 --- a/doc_source/multiple_languages.md +++ b/doc_source/multiple_languages.md @@ -14,14 +14,14 @@ For more details on working with the AWS CDK in its supported programming langua ------ #### [ TypeScript/JavaScript ] -TypeScript supports importing either an entire module, or individual objects from a module\. +TypeScript supports importing either an entire namespace, or individual objects from a namespace\. Each namespace includes constructs and other classes for use with a given AWS service\. ``` -// Import entire module as s3 into current namespace -import * as s3 from '@aws-cdk/aws-s3'; +// Import namespace as s3 into current namespace +import * as s3 from '@aws-cdk-lib/aws-s3'; -// Import an entire module using Node.js require() (import * as s3 generally preferred) -const s3 = require('@aws-cdk/aws-s3'); +// Import namespace using Node.js require() (import * as s3 generally preferred) +const s3 = require('@aws-cdk-lib/aws-s3'); // TypeScript version of require() (again, import * as s3 generally preferred) import s3 = require('@aws-cdk/aws-s3'); diff --git a/doc_source/reference.md b/doc_source/reference.md index 15221912..60f07191 100644 --- a/doc_source/reference.md +++ b/doc_source/reference.md @@ -1,8 +1,10 @@ # API reference -The [API Reference](https://docs.aws.amazon.com/cdk/api/latest) contains information about the AWS CDK libraries\. +The [API Reference](https://docs.aws.amazon.com/cdk/api/latest) contains information about the AWS Construct Library and other APIs provided by the AWS CDK\. It is organized by module\. -Each library contains information about how to use the library\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) library demonstrates how to set default encryption on an Amazon S3 bucket\. +Each module has an overview that includes information about how to use its APIs\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) overview demonstrates how to set default encryption on an Amazon S3 bucket\. + +Separate versions of the API Reference are provided for TypeScript/JavaScript, Python, Java, and C\#/\.NET\. ## Versioning @@ -56,7 +58,7 @@ For more information about these maturity stages, see [AWS Construct Library Mod ### Language binding stability -From time to time, we may add support to the AWS CDK for additional programming languages\. Although the API described in all the languages is the same, the way that API is expressed varies by language and may change as the language support evolves\. For this reason, language bindings are deemed experimental for a time until they are considered ready for production use\. Currently, all supported languages are considered stable\. +From time to time, we may add support to the AWS CDK for additional programming languages\. Although the API described in all the languages is the same, the way that API is expressed varies by language and may change as the language support evolves\. For this reason, language bindings are deemed experimental for a time until they are considered ready for production use\. | Language | Stability | diff --git a/doc_source/resources.md b/doc_source/resources.md index 08830822..f44e0acd 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -89,7 +89,7 @@ const url = queue.queueUrl; // => A string representing a deploy-time value #### [ Python ] ``` -from aws_cdk.aws_sqs as sqs +import aws_cdk.aws_sqs as sqs queue = sqs.Queue(self, "MyQueue") url = queue.queue_url # => A string representing a deploy-time value @@ -265,7 +265,7 @@ If the AWS CDK determines that the resource is in the same account and Region, b Referencing a resource from one stack in a different stack creates a dependency between the two stacks\. Once this dependency is established, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure if the AWS CDK Toolkit deploys the producing stack before the consuming stack\. This happens if there is another dependency between the two stacks, but it can also happen that the producing stack is chosen by the AWS CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it is no longer needed, but the exported resource is still being used in the consuming stack because its update has not yet been deployed, so deploying the producer stack fails\. -To break this deadlock, remove the use of the shared resource from the consuming stack \(which will remove the automatic export from the producing stack\), then manually add the same export to the producing stack using exactly the same logical ID as the automatically\-generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then remove the manual export \(and the shared resource if it is no longer nededed\), and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#exportwbrvalueexportedvalue-options)` method is a convenient way to create the manual export for this purpose \(see the example in the linked method reference\)\. +To break this deadlock, remove the use of the shared resource from the consuming stack \(which will remove the automatic export from the producing stack\), then manually add the same export to the producing stack using exactly the same logical ID as the automatically\-generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then remove the manual export \(and the shared resource if it is no longer needed\), and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#exportwbrvalueexportedvalue-options)` method is a convenient way to create the manual export for this purpose \(see the example in the linked method reference\)\. ## Physical names @@ -317,7 +317,7 @@ var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-buc ------ -Assigning physical names to resources has some disadvantages in AWS CloudFormation\. Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource's properties that are immutable after creation, will fail if a resource has a physical name assigned\. If you end up in a state like that, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again\. See the [AWS CloudFormation documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) for details\. +Assigning physical names to resources has some disadvantages in AWS CloudFormation\. Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource's properties that are immutable after creation, will fail if a resource has a physical name assigned\. If you end up in that state, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again\. See the [AWS CloudFormation documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) for details\. In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value `PhysicalName.GENERATE_IF_NEEDED`, as follows\. diff --git a/doc_source/serverless_example.md b/doc_source/serverless_example.md index e889c753..2720efed 100644 --- a/doc_source/serverless_example.md +++ b/doc_source/serverless_example.md @@ -7,7 +7,7 @@ This example walks you through creating the resources for a simple widget dispen This tutorial contains the following steps\. -1. Create a AWS CDK app +1. Create an AWS CDK app 1. Create a Lambda function that gets a list of widgets with HTTP GET / @@ -24,7 +24,7 @@ This tutorial contains the following steps\. 1. Tear everything down when you're finished -## Create a AWS CDK app +## Create an AWS CDK app Create the app **MyWidgetService** in the current folder\. diff --git a/doc_source/stacks.md b/doc_source/stacks.md index e3e51146..a6cf8a3b 100644 --- a/doc_source/stacks.md +++ b/doc_source/stacks.md @@ -347,7 +347,7 @@ new MyStack(this, "not:a:stack:name", new StackProps ## Stack API -The [Stack](https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/stack.html) object provides a rich API, including the following: +The [Stack](https://docs.aws.amazon.com/cdk/api/latest/docs/core/stack.html) object provides a rich API, including the following: + `Stack.of(construct)` – A static method that returns the **Stack** in which a construct is defined\. This is useful if you need to interact with a stack from within a reusable construct\. The call fails if a stack cannot be found in scope\. + `stack.stackName` \(Python: `stack_name`\) – Returns the physical name of the stack\. As mentioned previously, all AWS CDK stacks have a physical name that the AWS CDK can resolve during synthesis\. + `stack.region` and `stack.account` – Return the AWS Region and account, respectively, into which this stack will be deployed\. These properties return either the account or Region explicitly specified when the stack was defined, or a string\-encoded token that resolves to the AWS CloudFormation pseudo\-parameters for account and Region to indicate that this stack is environment agnostic\. See [Environments](environments.md) for information about how environments are determined for stacks\. diff --git a/doc_source/tagging.md b/doc_source/tagging.md index 80416375..56d25711 100644 --- a/doc_source/tagging.md +++ b/doc_source/tagging.md @@ -6,8 +6,8 @@ Tags are informational key\-value elements that you can add to constructs in you For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf)\. The [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#removekey-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#removekey-props) applies a new tag to the given construct and all of its children\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#static-removescope-key-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#static-removescope-key-props) removes a tag from the given construct and any of its children, including tags a child construct may have applied to itself\. ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#addkey-value-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#addkey-value-props) applies a new tag to the given construct and all of its children\. ++ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#removekey-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#removekey-props) removes a tag from the given construct and any of its children, including tags a child construct may have applied to itself\. **Note** Tagging is implemented using [Aspects](aspects.md)\. Aspects are a way to apply an operation \(such as tagging\) to all constructs in a given scope\. diff --git a/doc_source/testing.md b/doc_source/testing.md index 363a7ee1..f595ff6d 100644 --- a/doc_source/testing.md +++ b/doc_source/testing.md @@ -102,6 +102,9 @@ These changes are shown in outline below\. Place the new text where indicated in ``` mkdir state-machine && cd state-machine cdk init --language=python +source .venv/bin/activate +python -m pip install -r requirements.txt +python -m pip install -r requirements-dev.txt python -m pip install aws_cdk.aws_lambda aws_cdk.aws_sns_subscriptions aws_cdk.aws_stepfunctions python -m pip install pytest aws_cdk.assertions ``` @@ -546,7 +549,7 @@ namespace AwsCdkAssertionSamples ## Running tests -For reference, here are the commands you use to run tests in your AWS CDK app\. These are the same commands you'd use to run the tests in any project using the same testig framework\. For languages that require a build step, include that to make sure your tests have been compiled\. +For reference, here are the commands you use to run tests in your AWS CDK app\. These are the same commands you'd use to run the tests in any project using the same testing framework\. For languages that require a build step, include that to make sure your tests have been compiled\. ------ #### [ TypeScript ] @@ -1309,7 +1312,7 @@ import re ## Snapshot tests -In *snapshot testing*, you compare the entire synthesized CloudFormation template against a previously\-stored master\. This isn't useful in catching regressions, as fine\-grained assertions are, because it applies to the entire template, and things besides code changes can cause small \(or not\-so\-small\) differences in synthesis results\. For example, we may update a CDK construct to incorporate a new best pracice, which can cause changes to the synthesized resources or how they're organized, or we might update the CDK Toolkit to report additional metadata\. Changes to context values can also affect the synthesized template\. +In *snapshot testing*, you compare the entire synthesized CloudFormation template against a previously\-stored master\. This isn't useful in catching regressions, as fine\-grained assertions are, because it applies to the entire template, and things besides code changes can cause small \(or not\-so\-small\) differences in synthesis results\. For example, we may update a CDK construct to incorporate a new best practice, which can cause changes to the synthesized resources or how they're organized, or we might update the CDK Toolkit to report additional metadata\. Changes to context values can also affect the synthesized template\. Snapshot tests can be of great help in refactoring, though, as long as you hold constant all other factors that might affect the synthesized template\. You will know immediately if a change you made has unintentionally changed the template\. If the change is intentional, simply accept a new master and proceed\. diff --git a/doc_source/tokens.md b/doc_source/tokens.md index 61f5a70a..a6017e44 100644 --- a/doc_source/tokens.md +++ b/doc_source/tokens.md @@ -260,7 +260,7 @@ As with list tokens, you cannot modify the number value, as doing so is likely t In addition to representing deploy\-time values, such as AWS CloudFormation [parameters](parameters.md), Tokens are also commonly used to represent synthesis\-time lazy values\. These are values for which the final value will be determined before synthesis has completed, just not at the point where the value is constructed\. Use tokens to pass a literal string or number value to another construct, while the actual value at synthesis time may depend on some calculation that has yet to occur\. -You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.stringValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-string-valueproducer-options) \(Python: `Lazy.string_value`\) and [Lazy\.numberValue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-number-valueproducer) \(Python: `Lazy.number_value`\. These methods accept an object whose `produce` property is a function that accepts a context argument and returns the final value when called\. +You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.string](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-stringproducer-options) and [Lazy\.number](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-numberproducer)\. These methods accept an object whose `produce` property is a function that accepts a context argument and returns the final value when called\. The following example creates an Auto Scaling group whose capacity is determined after its creation\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index d2971700..c3856839 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -19,7 +19,7 @@ The modules that make up the AWS Construct Library are a matched set\. They are We also update the libraries that are used by the AWS Construct Library from time to time, and different versions of the library modules may have incompatible dependencies\. Synchronizing the versions of the library modules will also address this issue\. -[JSII](https://github.com/aws/jsii) is an important AWS CDK dependency, especially if you are using the AWS CDK in a language other than TypeScript or JavaScript\. You do not ordinarily have to concern yourself with the JSII versions, since it is a declared dependency of all AWS CDK modules\. If a compatible version is not installed, however, you can see unexpected type\-relatd errors, such as `'undefined' is not a valid TargetType`\. Making sure all AWS CDK modules are the same version will resolve JSII compatibility issues, since they will all depend on the same JSII version\. +[JSII](https://github.com/aws/jsii) is an important AWS CDK dependency, especially if you are using the AWS CDK in a language other than TypeScript or JavaScript\. You do not ordinarily have to concern yourself with the JSII versions, since it is a declared dependency of all AWS CDK modules\. If a compatible version is not installed, however, you can see unexpected type\-related errors, such as `'undefined' is not a valid TargetType`\. Making sure all AWS CDK modules are the same version will resolve JSII compatibility issues, since they will all depend on the same JSII version\. Below, you'll find details on managing the versions of your installed AWS Construct Library modules in TypeScript, JavaScript, Python, Java, and C\#\. @@ -140,16 +140,16 @@ If you are using a language other than TypeScript or JavaScript, first create a npm install aws-cdk@1.50.0 ``` -To run a locally\-installed AWS CDK Toolkit, use the command `npx cdk` rather than just `cdk`\. For example: +To run a locally\-installed AWS CDK Toolkit, use the command `npx aws-cdk` rather than just `cdk`\. For example: ``` -npx cdk deploy MyStack +npx aws-cdk deploy MyStack ``` -`npx cdk` runs the local version of the AWS CDK Toolkit if one exists, and falls back to the global version when a project doesn't have a local installation\. You may find it convenient to set up a shell alias or batch file to make sure `cdk` is always invoked this way\. For example, Linux users might add the following statement to their `.bash_profile` file\. +`npx aws-cdk` runs the local version of the AWS CDK Toolkit if one exists, and falls back to the global version when a project doesn't have a local installation\. You may find it convenient to set up a shell alias or batch file to make sure `cdk` is always invoked this way\. For example, Linux users might add the following statement to their `.bash_profile` file\. ``` -alias cdk=npx cdk +alias cdk=npx aws-cdk ``` \([back to list](#troubleshooting_top)\) diff --git a/doc_source/use_cfn_public_registry.md b/doc_source/use_cfn_public_registry.md index 297197d1..cc3071f5 100644 --- a/doc_source/use_cfn_public_registry.md +++ b/doc_source/use_cfn_public_registry.md @@ -42,7 +42,7 @@ To activate an extension through CloudFormation or the CDK, deploy a resource of + `ExecutionRoleArn` \- The ARN of the IAM role under which this extension will run\. + `LoggingConfig` \- The logging configuration for the extension\. -The `TypeActivation` resource can be deployed by the CDK using the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html) construct, as shown below for the actual etxensions\. +The `TypeActivation` resource can be deployed by the CDK using the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html) construct, as shown below for the actual extensions\. ## Adding a resource from the AWS CloudFormation Public Registry to your CDK app diff --git a/doc_source/use_cfn_template.md b/doc_source/use_cfn_template.md index 59ac4101..098dc2ad 100644 --- a/doc_source/use_cfn_template.md +++ b/doc_source/use_cfn_template.md @@ -5,7 +5,7 @@ The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-read This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\. **Note** -The AWS CDK also includes [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html), which was previously used for the same general purpose\. However, `core.CfnInclude` lacks much of the functionality of `cloudformation-include.CfnInclude`\. `core.CfnInclude` has been deprecated and will not be available in CDK 2\.0\. +The AWS CDK also includes [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. ## Install the `cloudformation-include` module diff --git a/doc_source/work-with-cdk-csharp.md b/doc_source/work-with-cdk-csharp.md index ebfc02a6..7eacbcd6 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/doc_source/work-with-cdk-csharp.md @@ -12,7 +12,7 @@ To work with the AWS CDK, you must have an AWS account and credentials and have C\# AWS CDK applications require \.NET Core v3\.1 or later, [available here](https://dotnet.microsoft.com/download/dotnet-core/3.1)\. -The \.NET Standard toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if you work mainly in Visual Studio, this command can be useful for batch operations and for installing AWS Construct Library packages\. +The \.NET toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if you work mainly in Visual Studio, this command can be useful for batch operations and for installing AWS Construct Library packages\. ## Creating a project @@ -156,7 +156,7 @@ string MimeType = props?.MimeType ?? "text/plain"; The AWS CDK automatically compiles your app before running it\. However, it can be useful to build your app manually to check for errors and run tests\. You can do this by pressing F6 in Visual Studio or by issuing `dotnet build src` from the command line, where `src` is the directory in your project directory that contains the Visual Studio Solution \(`.sln`\) file\. -The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. diff --git a/doc_source/work-with-cdk-go.md b/doc_source/work-with-cdk-go.md index ca5a6b11..9cbea934 100644 --- a/doc_source/work-with-cdk-go.md +++ b/doc_source/work-with-cdk-go.md @@ -2,7 +2,7 @@ The Go language binding for the AWS CDK is now available as a Developer Preview\. It is not suitable for production use and may undergo significant changes before being designated stable\. To follow development, see the [Project Board](https://github.com/aws/jsii/projects/3) on GitHub\. Please [report any issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. -Unlike the other languages the CDK supports, Go is not a traditional object\-oriented programming language\. Go uses composition where other languages often leverage inheritance\. We have tried to employ idiomatic Go approaches as much as possible, but there are places where the CDK charts its own path\. +Unlike the other languages the CDK supports, Go is not a traditional object\-oriented programming language\. Go uses composition where other languages often leverage inheritance\. We have tried to employ idiomatic Go approaches as much as possible, but there are places where the CDK charts its own course\. This topic explains the ins and outs of working with the AWS CDK in Go\. See the [announcement blog post](https://aws.amazon.com/blogs/developer/getting-started-with-the-aws-cloud-development-kit-and-go/) for a walkthrough of a simple Go project for the AWS CDK\. @@ -99,7 +99,7 @@ The AWS CDK automatically compiles your app before running it\. However, it can Run any tests you've written by running `go test` at a command prompt\. -The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. diff --git a/doc_source/work-with-cdk-java.md b/doc_source/work-with-cdk-java.md index 13f4ef9b..f993a3db 100644 --- a/doc_source/work-with-cdk-java.md +++ b/doc_source/work-with-cdk-java.md @@ -123,7 +123,7 @@ The AWS CDK automatically compiles your app before running it\. However, it can Run any tests you've written by running `mvn test` at a command prompt\. -The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 74fd880a..4868cccd 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -28,28 +28,28 @@ Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest For the most part, this guide assumes you install the CDK Toolkit globally \(`npm install -g aws-cdk`\), and the provided command examples \(such as `cdk synth`\) follow this assumption\. This approach makes it easy to keep the CDK Toolkit up to date, and since the CDK takes a strict approach to backward compatibility, there is generally little risk in always using the latest version\. -Some teams prefer to specify all dependencies within each project, including tools like the CDK Toolkit\. This practice lets you pin such components to specific versions and ensure that all developers on your team \(and your CI/CD environment\) use exactly those versions\. This eliminates a possible source of change, helping to make builds and deployments more consistent nand repeatable\. +Some teams prefer to specify all dependencies within each project, including tools like the CDK Toolkit\. This practice lets you pin such components to specific versions and ensure that all developers on your team \(and your CI/CD environment\) use exactly those versions\. This eliminates a possible source of change, helping to make builds and deployments more consistent and repeatable\. The CDK includes a dependency for the CDK Toolkit in the JavaScript project template's `package.json`, so if you want to use this approach, you don't need to make any changes to your project\. All you need to do is use slightly different commands for building your app and for issuing `cdk` commands\. | Operation | Use global CDK Toolkit | Use local CDK Toolkit | | --- |--- |--- | -| Initialize project | `cdk init --language javascript` | `npx cdk init --language javascript` | +| Initialize project | `cdk init --language javascript` | `npx aws-cdk init --language javascript` | | --- |--- |--- | -| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx cdk ...` | +| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx aws-cdk ...` | | --- |--- |--- | -`npx cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@1.120 --version` prints `1.120.0`\. +`npx aws-cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@1.120 --version` prints `1.120.0`\. **Tip** Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. ``` -alias cdk=npx cdk +alias cdk=npx aws-cdk ``` ``` -doskey cdk=npx acdk $* +doskey cdk=npx aws-cdk $* ``` ## Managing AWS Construct Library modules @@ -76,7 +76,7 @@ npm update ``` In JavaScript, you import modules into your code under the same name you use to install them using NPM\. We recommend the following practices when importing AWS CDK classes and AWS Construct Library modules in your applications\. Following these guidelines will help make your code consistent with other AWS CDK applications as well as easier to understand\. -+ Use `require()`, not ES6\-style `import` directives\. Most of the versions of Node\.js that the AWS CDK runs on do not support ES6 imports, so using the older syntax is more widely compatible\. \(If you really want to use ES6 imports, use [esm](https://www.npmjs.com/package/esm) to ensure your project is compatible with all supported versions of Node\.js\.\) ++ Use `require()`, not ES6\-style `import` directives\. Older versions of Node\.js do not support ES6 imports, so using the older syntax is more widely compatible\. \(If you really want to use ES6 imports, use [esm](https://www.npmjs.com/package/esm) to ensure your project is compatible with all supported versions of Node\.js\.\) + Generally, import individual classes from `@aws-cdk/core`\. ``` @@ -135,7 +135,7 @@ Node\.js 14\.0 and later support new operators that can simplify the handling of ## Synthesizing and deploying -The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. @@ -278,7 +278,7 @@ When a function or method returns a general\-purpose type \(such as `object`\), Finally, TypeScript supports the access modifiers `public`, `protected`, and `private` for members of classes\. All class members in JavaScript are public\. Simply remove these modifiers wherever you see them\. -Knowing how to identify and remove these TypeScript features goes a long way toward adapting short TypeScript snippets to JavaScript\. But it may be impractical to convert longer TypeScript examples in this fashion, since they are more likely to use other TypeScript features\. For these situations, we recommend [Babel](https://babeljs.io/) with the [TypeScript plug\-in](https://babeljs.io/docs/en/babel-plugin-transform-typescript)\. Babel won't complain if code uses an undefined variable, for example, as `tsc` would\. If it is syntactically valid, then with few exceptions, Babel can translate it to JavaScript\. This makes Babel particularly valuable for converting snippets that may not be runnable on their own\. +Knowing how to identify and remove these TypeScript features goes a long way toward adapting short TypeScript snippets to JavaScript\. But it may be impractical to convert longer TypeScript examples in this fashion, since they are more likely to use other TypeScript features\. For these situations, we recommend [Sucrase](https://github.com/alangpierce/sucrase)\. Sucrase won't complain if code uses an undefined variable, for example, as `tsc` would\. If it is syntactically valid, then with few exceptions, Sucrase can translate it to JavaScript\. This makes it particularly valuable for converting snippets that may not be runnable on their own\. ## Migrating to TypeScript diff --git a/doc_source/work-with-cdk-python.md b/doc_source/work-with-cdk-python.md index 941700f2..f61b0856 100644 --- a/doc_source/work-with-cdk-python.md +++ b/doc_source/work-with-cdk-python.md @@ -70,6 +70,9 @@ python -m pip install aws-cdk.aws-s3 aws-cdk.aws-lambda Some services' Construct Library support is in more than one module\. For example, besides the `aws-cdk.aws-route53` module, there are three additional Amazon Route 53 modules, named `aws-route53-targets`, `aws-route53-patterns`, and `aws-route53resolver`\. +**Note** +The [Python edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/python/index.html) also shows the package names\. + The names used for importing AWS Construct Library modules into your Python code are similar to their package names\. Simply replace the hyphens with underscores\. ``` @@ -120,7 +123,7 @@ All AWS Construct Library modules used in your project must be the same version\ In Python, `lambda` is a language keyword, so you cannot use it as a name for the AWS Lambda construct library module or Lambda functions\. The Python convention for such conflicts is to use a trailing underscore, as in `lambda_`, in the variable name\. -By convention, the second argument to AWS CDK constructs is named `id`\. When writing your own stacks and constructs, calling a parameter `id` "shadows" the Python built\-in function `id()`, which returns an object's unique identifier\. This function isn't used very often, but if you should happen to need it in your construct, rename the argument, for example `id_`, or else call the built\-in function as `__builtins__.id()`\. +By convention, the second argument to AWS CDK constructs is named `id`\. When writing your own stacks and constructs, calling a parameter `id` "shadows" the Python built\-in function `id()`, which returns an object's unique identifier\. This function isn't used very often, but if you should happen to need it in your construct, rename the argument, for example `construct_id`\. ### Arguments and properties @@ -183,17 +186,17 @@ class MyAspect(): ### Type pitfalls -Python uses dynamic typing, where variables may refer to a value of any type\. Parameters and return values may be annotated with types, but these are "hints" and are not enforced\. This means that in Python, it is easy to pass the incorrect type of value to a AWS CDK construct\. Instead of getting a type error during build, as you would from a statically\-typed language, you may instead get a runtime error when the JSII layer \(which translates between Python and the AWS CDK's TypeScript core\) is unable to deal with the unexpected type\. +Python uses dynamic typing, where all variables may refer to a value of any type\. Parameters and return values may be annotated with types, but these are "hints" and are not enforced\. This means that in Python, it is easy to pass the incorrect type of value to a AWS CDK construct\. Instead of getting a type error during build, as you would from a statically\-typed language, you may instead get a runtime error when the JSII layer \(which translates between Python and the AWS CDK's TypeScript core\) is unable to deal with the unexpected type\. In our experience, the type errors Python programmers make tend to fall into these categories\. + Passing a single value where a construct expects a container \(Python list or dictionary\) or vice versa\. -+ Passing a value of a type associated with a Level 1 \(`CfnXxxxxx`\) construct to a higher\-level construct, or vice versa\. ++ Passing a value of a type associated with a layer 1 \(`CfnXxxxxx`\) construct to an L2 or L3 construct, or vice versa\. -The AWS CDK Python modules do include type annotations, so you can use tools that support them to help with types\. If you are not using an IDE that supports these, such as [PyCharm](https://www.jetbrains.com/pycharm/), you might want to call the [MyPy](http://mypy-lang.org/) type validator as a step in your build process\. There are also runtime type checkers that can improve error messages for type\-related errors\. +The AWS CDK Python modules include type annotations, so you can use tools that support them to help with types\. If you are not using an IDE that supports these, such as [PyCharm](https://www.jetbrains.com/pycharm/), you might want to call the [MyPy](http://mypy-lang.org/) type validator as a step in your build process\. There are also runtime type checkers that can improve error messages for type\-related errors\. ## Synthesizing and deploying -The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index c115c453..54fff852 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -8,7 +8,7 @@ You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code]( To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. -You also need TypeScript itself\. If you don't already have it, you can install it using `npm`\. +You also need TypeScript itself \(version 2\.7 or later\)\. If you don't already have it, you can install it using `npm`\. ``` npm install -g typescript @@ -43,24 +43,24 @@ The CDK includes dependencies for both TypeScript and the CDK Toolkit in the Typ | Operation | Use global tools | Use local tools | | --- |--- |--- | -| Initialize project | `cdk init --language typescript` | `npx cdk init --language typescript` | +| Initialize project | `cdk init --language typescript` | `npx aws-cdk init --language typescript` | | --- |--- |--- | | Build | `tsc` | `npm run build` | | --- |--- |--- | -| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx cdk ...` | +| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx aws-cdk ...` | | --- |--- |--- | -`npx cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@1.120 --version` prints `1.120.0`\. +`npx aws-cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@1.120 --version` prints `1.120.0`\. **Tip** Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. ``` -alias cdk=npx cdk +alias cdk=npx aws-cdk ``` ``` -doskey cdk=npx cdk $* +doskey cdk=npx aws-cdk $* ``` ## Managing AWS Construct Library modules @@ -139,7 +139,7 @@ Node\.js cannot run TypeScript directly; instead, your application is converted The AWS CDK automatically does this whenever it needs to run your app\. However, it can be useful to compile manually to check for errors and to run tests\. To compile your TypeScript app manually, issue `npm run build`\. You may also issue `npm run watch` to enter watch mode, in which the TypeScript compiler automatically rebuilds your app whenever you save changes to a source file\. -The [stacks](stacks.md) defined in your AWS CDK app can be deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. + `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. + `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index 412ebed2..3cd592a8 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -1,266 +1,31 @@ # Migrating to AWS CDK v2 -Version 2 of the AWS Cloud Development Kit \(AWS CDK\) is designed to make writing infrastructure as code in your preferred programming language even easier\. +Version 2 of the AWS CDK, now Generally Available, provides an improved development experience that aims to make Infrastructure as Code \(IAC\) even simpler\. See [Migrating to AWS CDK v2](../../v2/guide/migrating-v2.html) in the CDK v1 Developer Guide to learn how to migrate to CDK v2\. -As a developer preview, CDK v2 is not intended for production use and may be subject to breaking API changes before it is finalized\. We are eager to hear your feedback on how CDK v2 works for you, and your suggestions for making it better, via [GitHub Issues](https://github.com/aws/aws-cdk/issues/new/choose)\. +CDK v1 will continue to be fully supported until June 2, 2022, at which time it will enter maintenance\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 2, 2023, support will end entirely for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. -## Changes in AWS CDK v2 +For information on migrating your apps to AWS CDK v2, see [Migrating to AWS CDK v2](../../v2/migrating_v2.html)\. -The main changes in CDK v2 are as follows\. -+ AWS CDK v2 consolidates the AWS Construct Library into a single package, `aws-cdk-lib`\. Developers no longer need to install one or more individual packages for each AWS service or to keep all CDK library versions in sync\. -+ Experimental modules are not included in the main AWS Construct Library; they are instead distributed as individual packages named with an `alpha` suffix and a semantic version number that matches the first version of the AWS Construct Library mith which they are compatible, also with an `alpha` suffix\. Constructs move into the main AWS Construct Library after being designated stable, permitting the main Construct Library to adhere to strict semantic versioning going forward\. +## CDK Toolkit v2 compatibility - Stability is specified at the service level\. For example, if we begin creating one or more L2 constructs for Amazon AppFlow, which at this writing has only L1 constructs, they would appear in a module named `@aws-cdk/aws-appflow-alpha` at first, then move to `aws-cdk-lib` when we feel the new constructs meet the fundamental needs of customers\. +CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compatible with CDK v1 apps, so you can use a single globally\-installed version of CDK Toolkit with all your AWS CDK projects, whether they use v1 or v2\. An exception is that CDK Toolkit v2 creates CDK v2 projects\. - Once a module has been designated stable and incorporated into `aws-cdk-lib`, new APIs are added using the "BetaN" convention described next\. - - L1 \(CfnXXXX\) constructs are always considered stable and so are included in `aws-cdk-lib`\. - - A new version of each experimental module is released with every release of the AWS CDK, but for the most part, they needn't be kept in sync\. You can upgrade `aws-cdk-lib` or the experimental module whenever you want\. The exception is that when two or more related experimental modules depend on each other, they must be the same version\. -+ For stable modules to which new functionality is being added, new APIs \(whether entirely new constructs or new methods or properties on an existing construct\) receive a `Beta1` suffix \(and then `Beta2`, `Beta3`, etc\. when breaking changes are needed\) while work is in progress\. A version of the API without the suffix is added when the API is designated stable\. All methods except the latest \(whether beta or final\) are deprecated\. - - For example, if we add a new method `grantPower()` to a construct, it initially appears as `grantPowerBeta1().` If breaking changes are needed \(for example, a new required parameter or property\), the next version of the method would be named `grantPowerBeta2()`, and so on\. When work is complete and the API is finalized, the method `grantPower()` \(with no suffix\) is added\. - - All the beta APIs remain in the Construct Library until the next major version \(3\.0\) release, and their signatures are guaranteed not to change\. They'll be deprecated, so you'll see warnings, but you can continue to use them without fear that a future AWS CDK release will break your application\. -+ The core `Construct` class has been extracted from the AWS CDK into a separate library, along with related types, to support efforts to apply this programming model to other domains\. If you are writing your own constructs or using related APIs, you must declare the `construct` module as a dependency and make minor changes to your imports\. If you are using advanced features, such as hooking into the CDK app lifecycle, more changes may be needed\. [See the RFC](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0192-remove-constructs-compat.md#release-notes) for full details\. -+ Deprecated properties, methods, and types in AWS CDK v1\.x and its Construct Library have been removed from the CDK v2 API\. In most supported languages, these APIs produce warnings under v1\.x, so you may have already migrated to the replacement APIs\. A complete [list of deprecated APIs](https://github.com/aws/aws-cdk/blob/master/DEPRECATED_APIs.md) in CDK v1\.x is available on GitHub\. -+ Behavior that was gated by feature flags in AWS CDK v1\.x is enabled by default in CDK v2, and the old feature flags are no longer needed or, in most cases, supported\. A handful are still supported so that you can revert to v1 behavior in very specific circumstances; see [Updating feature flags](#v2-migrating-cdk-json)\. -+ CDK v2 requires that the environments you deploy into be boostrapped using the modern bootstrap stack; the legacy stack is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. Simply re\-bootstrap the affected environments to upgrade them\. It is not necessary to set any feature flags or environment variables to specify the modern bootstrap stack\. - -**Important** -The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. - -Aside from this topic, the AWS CDK Developer Guide describes CDK v1\.x\. Most of the information in the Guide still applies in CDK v2, or can be adapted with only minor changes\. A v2 Developer Guide will be available at General Availability \(GA\) of CDK v2\. A version of the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) is available for CDK v2\. - -## Prerequisites - -Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. See [Prerequisites](getting_started.md#getting_started_prerequisites)\. Additional requirements are listed here\. -+ For TypeScript developers, TypeScript 3\.8 or later is required\. -+ A new version of the CDK Toolkit is required for use with CDK v2\. To install it, issue `npm install -g aws-cdk@next`\. - -## Migrating to AWS CDK v2 - -To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. - -### Updating feature flags - -Remove all feature flags from `cdk.json`\. You can add one or more of the flags listed below, set to `false`, if your app relies on these specific AWS CDK v1\.x behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. - -`@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId` -If your application uses multiple Amazon API Gateway API keys and associates them to usage plans - -`@aws-cdk/aws-rds:lowercaseDbIdentifier` -If your application uses Amazon RDS database instance or database clusters, and explicitly specifies the identifier for these - -`@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021` - If your application uses the TLS\_V1\_2\_2019 security policy with Amazon CloudFront distributions\. CDK v2 uses security policy TLSv1\.2\_2021 by default\. - -`@aws-cdk/core:stackRelativeExports` -If your application uses multiple stacks and you refer to resources from one stack in another, this determines whether absolute or relative path is used to construct AWS CloudFormation exports - -The syntax for reverting these flags in `cdk.json` is shown here\. - -``` -{ - "context": { - "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": false, - "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": false, - "@aws-cdk/aws-rds:lowercaseDbIdentifier": false, - "@aws-cdk/core:stackRelativeExports": false, - } -} -``` - -### Updating dependencies and imports - -Update your app's dependencies in the appropriate configuration file, then install the new dependencies\. Finally, update the imports in your code\. - ------- -#### [ TypeScript ] - -For AWS CDK applications, update `package.json` as follows\. Remove dependencies on v1\-style individual stable modules\. Note that `@aws-cdk/assert` must be updated to the same version as `aws-cdk-lib`\. - -Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. - -``` -{ - "dependencies": { - "aws-cdk-lib": "^2.0.0-rc.1", - "@aws-cdk/aws-codestar-alpha": "2.0.0-alpha.1", - "@aws-cdk/assert": "^2.0.0-rc.1", - "constructs": "^10.0.0" - } -} -``` - -For construct libraries, establish the lowest version of `aws-cdk-lib` you require for your application \(2\.0\.0\-rc\.1 here\) and update `package.json` as follows\. - -Note that `aws-cdk-lib` appears both as a peer dependency and a dev dependency\. - -``` -{ - "peerDependencies": { - "aws-cdk-lib": "^2.0.0-rc.1", - "constructs": "^10.0.0" - }, - "devDependencies": { - "aws-cdk-lib": "2.0.0-rc.1", - "@aws-cdk/assert": "^2.0.0-rc.1", - "constructs": "^10.0.0", - "typescript": "~3.9.0" - } -} -``` - -Install the new dependencies by running `npm install` or `yarn install`\. - -Change your app's imports to import `Construct` from the new `constructs` module, core types such as `App` and `Stack` from the top level of `aws-cdk-lib`, and AWS Construct Library modules from namespaces under `aws-cdk-lib`\. - -``` -import { Construct } from 'constructs'; -import { App, Stack } from 'aws-cdk-lib'; // core constructs -import { aws_s3 as s3 } from 'aws-cdk-lib'; // stable module -import * as codestar from '@aws-cdk/aws-codestar-alpha'; // experimental module -``` - ------- -#### [ JavaScript ] - -Update `package.json` as follows\. Remove dependencies on v1\-style individual stable modules\. Note that `@aws-cdk/assert` must be updated to the same version as `aws-cdk-lib`\. - -Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. +If you need to create both v1 and v2 CDK projects, **do not install CDK Toolkit v2 globally\.** \(Remove it if you already have it installed: `npm remove -g aws-cdk`\.\) To invoke the CDK Toolkit, use npx to run v1 or v2 of the CDK Toolkit as desired\. ``` -{ - "dependencies": { - "aws-cdk-lib": "^2.0.0-rc.1", - "@aws-cdk/aws-codestar-alpha": "2.0.0-alpha.1", - "@aws-cdk/assert": "^2.0.0-rc.1", - "constructs": "^10.0.0" - } -} +npx cdk init@1.x app --language typescript +npx cdk init@2.x app --language typescript ``` -Install the new dependencies by running `npm install` or `yarn install`\. - -Change your app's imports to import `Construct` from the new `constructs` module, core types such as `App` and `Stack` from the top level of `aws-cdk-lib`, and AWS Construct Library modules from namespaces under `aws-cdk-lib`\. - -``` -const { Construct } = require('constructs'); -const { App, Stack } = require('aws-cdk-lib'); // core constructs -const s3 = require('aws-cdk-lib').aws_s3; // stable module -const codestar = require('@aws-cdk/aws-codestar-alpha'); // experimental module -``` - ------- -#### [ Python ] - -Update the `install_requires` definition in `setup.py` as follows\. Remove dependencies on v1\-style individual stable modules\. Note that `@aws-cdk/assert` must be updated to the same version as `aws-cdk-lib`\. - -Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0alpha1\. - -``` -install_requires=[ - "aws-cdk-lib>=2.0.0rc1", - "constructs>=10.0.0", - "aws-cdk.aws-codestar-alpha>=2.0.0alpha1", - # ... -], -``` - -Install the new dependencies with `pip install -r requirements.txt`\. - **Tip** -Uninstall any other versions of AWS CDK modules already installed in your app's virtual environment using `pip uninstall`\. - -Change your app's imports to import `Construct` from the new `constructs` module, core types such as `App` and `Stack` from the top level of `aws_cdk`, and AWS Construct Library modules from namespaces under `aws_cdk`\. - -``` -from constructs import Construct -from aws_cdk import App, Stack # core constructs -from aws_cdk import aws_s3 as s3 # stable module -import aws_cdk.aws_codestar_alpha as codestar # experimental module - -# ... - -class MyConstruct(Construct): - # ... - -class MyStack(Stack): - # ... - -s3.Bucket(...) -``` - ------- -#### [ Java ] - -In `pom.xml`, remove all `software.amazon.awscdk` dependencies for stable modules and replace them with dependencies on `software.constructs` and `software.amazon.awscdk`\. - -Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. - -``` - - software.amazon.awscdk - aws-cdk-lib - 2.0.0-rc.1 - - software.amazon.awscdk - code-star-alpha - 2.0.0-alpha.1 - - - software.constructs - constructs - 10.0.0 - -``` - -Install the new dependencies by running `mvn package`\. - -Change your code to import `Construct` from the new `software.constructs` library, core classes like `Stack` and `App` from `software.amazon.awscdk`, and service constructs from `software.amazon.awscdk.services`\. - -``` -import software.constructs.Construct; -import software.amazon.awscdk.Stack; -import software.amazon.awscdk.StackProps; -import software.amazon.awscdk.App; -import software.amazon.awscdk.services.s3.Bucket; -import software.amazon.awscdk.services.codestar.alpha.GitHubRepository; -``` - ------- -#### [ C\# ] - -The most straightforward way to upgrade the dependencies of a C\# CDK application is to edit the `.csproj` file manually\. Remove all stable `Amazon.CDK.*` package references and replace them with references to the `Amazon.CDK.Lib` and `Constructs` packages\. - -Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. +Set up command line aliases so you can use cdk and cdk2 commands to invoke the desired version of the CDK Toolkit\. ``` - - - +alias cdk=npx aws-cdk@1.x +alias cdk2=npx aws-cdk@2.x ``` -Install the new dependencies by running `dotnet restore`\. - -Change the imports in your source files as follows\. - -``` -using Constructs; // for Construct class -using Amazon.CDK; // for core classes like App and Stack -using Amazon.CDK.AWS.S3; // for stable constructs like Bucket -using Amazon.CDK.Codestar.Alpha; // for experimental constructs ``` - ------- - -## Troubleshooting - -**Unexpected infrastructure changes** -Before deploying your app, use `cdk diff` to check for unexpected changes to its resources\. Such changes are typically not caused by upgrading to AWS CDK v2, but are the result of deprecated behavior that was previously hidden by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, revising your code as necessary, deploying, and then upgrading to v2\. - -If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. - -**Typescript `'from' expected` or `';' expected` error in imports** -Upgrade to TypeScript 3\.8 or later\. \ No newline at end of file +doskey cdk=npx aws-cdk@1.x $* +doskey cdk2=npx aws-cdk@2.x $* +``` \ No newline at end of file diff --git a/doc_source/work-with.md b/doc_source/work-with.md index b4d48acc..bbf536e2 100644 --- a/doc_source/work-with.md +++ b/doc_source/work-with.md @@ -18,7 +18,7 @@ If you have the [AWS CLI](https://aws.amazon.com/cli/) installed, the simplest w aws configure ``` -All AWS CDK applications require Node\.js 10\.13 or later, even if you work in Python, Java, or C\#\. You may download a compatible version at [nodejs\.org](https://nodejs.org/)\. We recommend the [active LTS version](https://nodejs.org/en/about/releases/) \(at this writing, the latest 14\.x release\)\. Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. +All AWS CDK applications require Node\.js 10\.13 or later, even if you work in Python, Java, or C\#\. You may download a compatible version at [nodejs\.org](https://nodejs.org/)\. We recommend the [active LTS version](https://nodejs.org/en/about/releases/) \(at this writing, the latest 16\.x release\)\. Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. After installing Node\.js, install the AWS CDK Toolkit \(the `cdk` command\): @@ -45,16 +45,16 @@ The specific language you work in also has its own prerequisites, described in t ## AWS Construct Library -The AWS CDK includes the AWS Construct Library, a collection of construct modules organized by AWS service\. The [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) provides detailed documentation of the constructs \(and other components\) in the library\. A version of the API Reference is provided for each supported programming language, along with a generic version\. +The AWS CDK includes the AWS Construct Library, a collection of construct modules organized by AWS service\. The [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) provides detailed documentation of the constructs \(and other components\) in the library\. A version of the API Reference is provided for each supported programming language\. Each module's reference material is broken into the following sections\. + *Overview*: Introductory material you'll need to know to work with the service in the AWS CDK, including concepts and examples\. + *Constructs*: Library classes that represent one or more concrete AWS resources\. These are the "curated" \(L2\) resources or patterns \(L3 resources\) that provide a high\-level interface with sane defaults\. -+ *Classes*: Non\-construct library classes that provide functionality used by constructs in the module\. ++ *Classes*: Non\-construct classes that provide functionality used by constructs in the module\. + *Structs*: Data structures \(attribute bundles\) that define the structure of composite values such as properties \(the `props` argument of constructs\) and options\. + *Interfaces*: Interfaces, whose names all begin with "I", define the absolute minimum functionality for the corresponding construct or other class\. The CDK uses construct interfaces to represent AWS resources that are defined outside your AWS CDK app and imported by methods such as `Bucket.fromBucketArn()`\. + *Enums*: Collections of named values for use in specifying \*certain construct parameters\. Using an enumerated value allows the CDK to check these values for validity during synthesis\. -+ *CloudFormation Resources*: These L1 constructs, whose names begin with "Cfn", represent exactly the resources defined in the CloudFormation specification\. They are automatically generated from that specification with each CDK release\. Each L2 or L3 construct encapsulates one or more CloudFormation resource\. ++ *CloudFormation Resources*: These L1 constructs, whose names begin with "Cfn", represent exactly the resources defined in the CloudFormation specification\. They are automatically generated from that specification with each CDK release\. Each L2 or L3 construct encapsulates one or more CloudFormation resources\. + *CloudFormation Property Types*: The collection of named values that define the properties for each CloudFormation Resource\. ### Interfaces vs\. construct classes diff --git a/v2/about_examples.md b/v2/about_examples.md new file mode 100644 index 00000000..eea1ebeb --- /dev/null +++ b/v2/about_examples.md @@ -0,0 +1,3 @@ +# AWS CDK examples + +For more examples of AWS CDK stacks and apps in your favorite supported programming language, see the [CDK Examples](https://github.com/aws-samples/aws-cdk-examples) repository on GitHub\. \ No newline at end of file diff --git a/v2/apps.md b/v2/apps.md new file mode 100644 index 00000000..baf6ca89 --- /dev/null +++ b/v2/apps.md @@ -0,0 +1,316 @@ +# Apps + +As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html) construct\. + +The following example declares a stack class named `MyFirstStack` that includes a single Amazon S3 bucket\. However, this only declares a stack\. You still need to define \(also known as to instantiate\) it in some scope to deploy it\. + +------ +#### [ TypeScript ] + +``` +class MyFirstStack extends Stack { + constructor(scope: Construct, id: string, props?: StackProps) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket'); + } +} +``` + +------ +#### [ JavaScript ] + +``` +class MyFirstStack extends Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket'); + } +} +``` + +------ +#### [ Python ] + +``` +class MyFirstStack(Stack): + + def __init__(self, scope: Construct, id: str, **kwargs): + super().__init__(scope, id, **kwargs) + + s3.Bucket(self, "MyFirstBucket") +``` + +------ +#### [ Java ] + +``` +public class MyFirstStack extends Stack { + public MyFirstStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyFirstStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + new Bucket(this, "MyFirstBucket"); + } +} +``` + +------ +#### [ C\# ] + +``` +public class MyFirstStack : Stack +{ + public MyFirstStack(Stack scope, string id, StackProps props = null) : base(scope, id, props) + { + new Bucket(this, "MyFirstBucket"); + } +} +``` + +------ + +## The app construct + +To define the previous stack within the scope of an application, use the [App](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.App.html) construct\. The following example app instantiates a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. + +------ +#### [ TypeScript ] + +``` +const app = new App(); +new MyFirstStack(app, 'hello-cdk'); +app.synth(); +``` + +------ +#### [ JavaScript ] + +``` +const app = new App(); +new MyFirstStack(app, 'hello-cdk'); +app.synth(); +``` + +------ +#### [ Python ] + +``` +app = App() +MyFirstStack(app, "hello-cdk") +app.synth() +``` + +------ +#### [ Java ] + +``` +App app = new App(); +new MyFirstStack(app, "hello-cdk"); +app.synth(); +``` + +------ +#### [ C\# ] + +``` +var app = new App(); +new MyFirstStack(app, "hello-cdk"); +app.Synth(); +``` + +------ + +The `App` construct doesn't require any initialization arguments, because it's the only construct that can be used as a root for the construct tree\. You can now use the `App` instance as a scope for defining a single instance of your stack\. + +You can also define constructs within an App\-derived class as follows\. + +------ +#### [ TypeScript ] + +``` +class MyApp extends App { + constructor() { + new MyFirstStack(this, 'hello-cdk'); + } +} + +new MyApp().synth(); +``` + +------ +#### [ JavaScript ] + +``` +class MyApp extends App { + constructor() { + new MyFirstStack(this, 'hello-cdk'); + } +} + +new MyApp().synth(); +``` + +------ +#### [ Python ] + +``` +class MyApp(App): + def __init__(self): + MyFirstStack(self, "hello-cdk") + +MyApp().synth() +``` + +------ +#### [ Java ] + +``` +// MyApp.java +package com.myorg; + +import software.amazon.awscdk.App; + +public class MyApp extends App{ + public MyApp() { + new MyFirstStack(this, "hello-cdk"); + } +} + +// Main.java +package com.myorg; + +public class Main { + public static void main(String[] args) { + new MyApp().synth(); + } +} +``` + +------ +#### [ C\# ] + +``` +public class MyApp : App +{ + public MyApp(AppProps props = null) : base(props) + { + new MyFirstStack(this, "hello-cdk"); + + } +} + +class Program +{ + static void Main(string[] args) + { + new MyApp().Synth(); + } +} +``` + +------ + +These two methods are equivalent\. + +## App lifecycle + +The following diagram shows the phases that the AWS CDK goes through when you call the cdk deploy\. This command deploys the resources that your app defines\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/Lifecycle.png) + +An AWS CDK app goes through the following phases in its lifecycle\. + +1\. Construction \(or Initialization\) + Your code instantiates all of the defined constructs and then links them together\. In this stage, all of the constructs \(app, stacks, and their child constructs\) are instantiated and the constructor chain is executed\. Most of your app code is executed in this stage\. + +2\. Preparation +All constructs that have implemented the `prepare` method participate in a final round of modifications, to set up their final state\. The preparation phase happens automatically\. As a user, you don't see any feedback from this phase\. It's rare to need to use the "prepare" hook, and generally not recommended\. You should be very careful when mutating the construct tree during this phase, because the order of operations could impact behavior\. + +3\. Validation +All constructs that have implemented the `validate` method can validate themselves to ensure that they're in a state that will correctly deploy\. You will get notified of any validation failures that happen during this phase\. Generally, we recommend that you perform validation as soon as possible \(usually as soon as you get some input\) and throw exceptions as early as possible\. Performing validation early improves diagnosability as stack traces will be more accurate, and ensures that your code can continue to execute safely\. + +4\. Synthesis +This is the final stage of the execution of your AWS CDK app\. It's triggered by a call to `app.synth()`, and it traverses the construct tree and invokes the `synthesize` method on all constructs\. Constructs that implement `synthesize` can participate in synthesis and emit deployment artifacts to the resulting cloud assembly\. These artifacts include AWS CloudFormation templates, AWS Lambda application bundles, file and Docker image assets, and other deployment artifacts\. [Cloud assemblies](#apps_cloud_assembly) describes the output of this phase\. In most cases, you won't need to implement the `synthesize` method + +5\. Deployment +In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. + +By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: ++ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. ++ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)` \(Python: `is_token`\)\. See [Tokens](tokens.md) for details\. + +## Cloud assemblies + +The call to `app.synth()` is what tells the AWS CDK to synthesize a cloud assembly from an app\. Typically you don't interact directly with cloud assemblies\. They are files that include everything needed to deploy your app to a cloud environment\. For example, it includes an AWS CloudFormation template for each stack in your app, and a copy of any file assets or Docker images that you reference in your app\. + +See the [cloud assembly specification](https://github.com/aws/aws-cdk/blob/master/design/cloud-assembly.md) for details on how cloud assemblies are formatted\. + +To interact with the cloud assembly that your AWS CDK app creates, you typically use the AWS CDK Toolkit, a command\-line tool\. But any tool that can read the cloud assembly format can be used to deploy your app\. + +The CDK Toolkit needs to know how to execute your AWS CDK app\. If you created the project from a template using the `cdk init` command, your app's `cdk.json` file includes an `app` key that specifies the necessary command for the language the app is written in\. If your language requires compilation, the command line performs this step before running the app, so you can't forget to do it\. + +------ +#### [ TypeScript ] + +``` +{ + "app": "npx ts-node --prefer-ts-exts bin/my-app.ts" +} +``` + +------ +#### [ JavaScript ] + +``` +{ + "app": "node bin/my-app.js" +} +``` + +------ +#### [ Python ] + +``` +{ + "app": "python app.py" +} +``` + +------ +#### [ Java ] + +``` +{ + "app": "mvn -e -q compile exec:java" +} +``` + +------ +#### [ C\# ] + +``` +{ + "app": "dotnet run -p src/MyApp/MyApp.csproj" +} +``` + +------ + +If you did not create your project using the CDK Toolkit, or wish to override the command line given in `cdk.json`, you can use the \-\-app option when issuing the `cdk` command\. + +``` +cdk --app 'executable' cdk-command ... +``` + +The *executable* part of the command indicates the command that should be run to execute your CDK application\. Use quotation marks as shown, since such commands contain spaces\. The *cdk\-command* is a subcommand like synth or deploy that tells the CDK Toolkit what you want to do with your app\. Follow this with any additional options needed for that subcommand\. + +The CLI can also interact directly with an already\-synthesized cloud assembly\. To do that, just pass the directory in which the cloud assembly is stored in \-\-app\. The following example lists the stacks defined in the cloud assembly stored under `./my-cloud-assembly`\. + +``` +cdk --app ./my-cloud-assembly ls +``` \ No newline at end of file diff --git a/v2/aspects.md b/v2/aspects.md new file mode 100644 index 00000000..72054db9 --- /dev/null +++ b/v2/aspects.md @@ -0,0 +1,220 @@ +# Aspects + +Aspects are a way to apply an operation to all constructs in a given scope\. The aspect could modify the constructs, such as by adding tags, or it could verify something about the state of the constructs, such as ensuring that all buckets are encrypted\. + +To apply an aspect to a construct and all constructs in the same scope, call [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Aspects.html#static-ofscope](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Aspects.html#static-ofscope)`.of(SCOPE).add()` with a new aspect, as shown in the following example\. + +------ +#### [ TypeScript ] + +``` +Aspects.of(myConstruct).add(new SomeAspect(...)); +``` + +------ +#### [ JavaScript ] + +``` +Aspects.of(myConstruct).add(new SomeAspect(...)); +``` + +------ +#### [ Python ] + +``` +Aspects.of(my_construct).add(SomeAspect(...)) +``` + +------ +#### [ Java ] + +``` +Aspects.of(myConstruct).add(new SomeAspect(...)); +``` + +------ +#### [ C\# ] + +``` +Aspects.Of(myConstruct).add(new SomeAspect(...)); +``` + +------ + +The AWS CDK currently uses aspects only to [tag resources](tagging.md), but the framework is extensible and can also be used for other purposes\. For example, you can use it to validate or change the AWS CloudFormation resources that are defined for you by higher\-level constructs\. + +## Aspects in detail + +Aspects employ the [visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern)\. An aspect is a class that implements the following interface\. + +------ +#### [ TypeScript ] + +``` +interface IAspect { + visit(node: IConstruct): void;} +``` + +------ +#### [ JavaScript ] + +JavaScript doesn't have interfaces as a language feature, so an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. + +------ +#### [ Python ] + +Python doesn't have interfaces as a language feature, so an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. + +------ +#### [ Java ] + +``` +public interface IAspect { + public void visit(Construct node); +} +``` + +------ +#### [ C\# ] + +``` +public interface IAspect +{ + void Visit(IConstruct node); +} +``` + +------ + +When you call `Aspects.of(SCOPE).add(...)`, the construct adds the aspect to an internal list of aspects\. You can obtain the list with `Aspects.of(SCOPE)`\. + +During the [prepare phase](apps.md#lifecycle), the AWS CDK calls the `visit` method of the object for the construct and each of its children in top\-down order\. + +The `visit` method is free to change anything in the construct\. In strongly\-typed languages, cast the received construct to a more specific type before accessing construct\-specific properties or methods\. + +## Example + +The following example validates that all buckets created in the stack have versioning enabled\. The aspect adds an error annotation to the constructs that fail the validation, which results in the synth operation failing and prevents deploying the resulting cloud assembly\. + +------ +#### [ TypeScript ] + +``` +class BucketVersioningChecker implements IAspect { + public visit(node: IConstruct): void { + // See that we're dealing with a CfnBucket + if (node instanceof s3.CfnBucket) { + + // Check for versioning property, exclude the case where the property + // can be a token (IResolvable). + if (!node.versioningConfiguration + || (!Tokenization.isResolvable(node.versioningConfiguration) + && node.versioningConfiguration.status !== 'Enabled')) { + Annotations.of(node).addError('Bucket versioning is not enabled'); + } + } + } +} + +// Later, apply to the stack +Aspects.of(stack).add(new BucketVersioningChecker()); +``` + +------ +#### [ JavaScript ] + +``` +class BucketVersioningChecker { + visit(node) { + // See that we're dealing with a CfnBucket + if ( node instanceof s3.CfnBucket) { + + // Check for versioning property, exclude the case where the property + // can be a token (IResolvable). + if (!node.versioningConfiguration + || !Tokenization.isResolvable(node.versioningConfiguration) + && node.versioningConfiguration.status !== 'Enabled') { + Annotations.of(node).addError('Bucket versioning is not enabled'); + } + } + } +} + +// Later, apply to the stack +Aspects.of(stack).add(new BucketVersioningChecker()); +``` + +------ +#### [ Python ] + +``` +@jsii.implements(cdk.IAspect) +class BucketVersioningChecker: + + def visit(self, node): + # See that we're dealing with a CfnBucket + if isinstance(node, s3.CfnBucket): + + # Check for versioning property, exclude the case where the property + # can be a token (IResolvable). + if (not node.versioning_configuration or + not Tokenization.is_resolvable(node.versioning_configuration) + and node.versioning_configuration.status != "Enabled"): + Annotations.of(node).add_error('Bucket versioning is not enabled') + +# Later, apply to the stack +Aspects.of(stack).add(BucketVersioningChecker()) +``` + +------ +#### [ Java ] + +``` +public class BucketVersioningChecker implements IAspect +{ + @Override + public void visit(Construct node) + { + // See that we're dealing with a CfnBucket + if (node instanceof CfnBucket) + { + CfnBucket bucket = (CfnBucket)node; + Object versioningConfiguration = bucket.getVersioningConfiguration(); + if (versioningConfiguration == null || + !Tokenization.isResolvable(versioningConfiguration.toString()) && + !versioningConfiguration.toString().contains("Enabled") + Annotations.of(bucket.getNode()).addError("Bucket versioning is not enabled"); + } + } +} + + +// Later, apply to the stack +Aspects.of(stack).add(new BucketVersioningChecker()); +``` + +------ +#### [ C\# ] + +``` +class BucketVersioningChecker : Amazon.Jsii.Runtime.DeputyBase, IAspect +{ + public void Visit(IConstruct node) + { + // See that we're dealing with a CfnBucket + if (node is CfnBucket) + { + var bucket = (CfnBucket)node; + if (bucket.VersioningConfiguration is null || + !Tokenization.IsResolvable(bucket.VersioningConfiguration) && + !bucket.VersioningConfiguration.ToString().Contains("Enabled") + Annotations.Of(bucket.Node).AddError("Bucket versioning is not enabled"); + } + } +} + +// Later, apply to the stack +Aspects.Of(stack).add(new BucketVersioningChecker()); +``` + +------ \ No newline at end of file diff --git a/v2/assets.md b/v2/assets.md new file mode 100644 index 00000000..a629a5e9 --- /dev/null +++ b/v2/assets.md @@ -0,0 +1,885 @@ +# Assets + +Assets are local files, directories, or Docker images that can be bundled into AWS CDK libraries and apps; for example, a directory that contains the handler code for an AWS Lambda function\. Assets can represent any artifact that the app needs to operate\. + +You add assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html#code) property lets you pass an [asset](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Code.html#static-fromwbrassetpath-options) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function's code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ContainerImage.html#static-fromwbrassetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. + +## Assets in detail + +When you refer to an asset in your app, the [cloud assembly](apps.md#apps_cloud_assembly) synthesized from your application includes metadata information with instructions for the AWS CDK CLI on where to find the asset on the local disk, and what type of bundling to perform based on the type of asset, such as a directory to compress \(zip\) or a Docker image to build\. + +The AWS CDK generates a source hash for assets, which can be used at construction time to determine whether the contents of an asset have changed\. + +By default, the AWS CDK creates a copy of the asset in the cloud assembly directory, which defaults to `cdk.out`, under the source hash\. This is so that the cloud assembly is self\-contained and moved over to a different host for deployment\. See [Cloud assemblies](apps.md#apps_cloud_assembly) for details\. + +The AWS CDK also synthesizes AWS CloudFormation parameters that the AWS CDK CLI specifies during deployment\. The AWS CDK uses those parameters to refer to the deploy\-time values of the asset\. + +When the AWS CDK deploys an app that references assets \(either directly by the app code or through a library\), the AWS CDK CLI first prepares and publishes them to Amazon S3 or Amazon ECR, and only then deploys the stack\. The AWS CDK specifies the locations of the published assets as AWS CloudFormation parameters to the relevant stacks, and uses that information to enable referencing these locations within an AWS CDK app\. + +This section describes the low\-level APIs available in the framework\. + +## Asset types + +The AWS CDK supports the following types of assets: + +Amazon S3 Assets +These are local files and directories that the AWS CDK uploads to Amazon S3\. + +Docker Image +These are Docker images that the AWS CDK uploads to Amazon ECR\. + +These asset types are explained in the following sections\. + +### Amazon S3 assets + +You can define local files and directories as assets, and the AWS CDK packages and uploads them to Amazon S3 through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets-readme.html) module\. + +The following example defines a local directory asset and a file asset\. + +------ +#### [ TypeScript ] + +``` +import { Asset } from 'aws-cdk-lib/aws-s3-assets'; + +// Archived and uploaded to Amazon S3 as a .zip file +const directoryAsset = new Asset(this, "SampleZippedDirAsset", { + path: path.join(__dirname, "sample-asset-directory") +}); + +// Uploaded to Amazon S3 as-is +const fileAsset = new Asset(this, 'SampleSingleFileAsset', { + path: path.join(__dirname, 'file-asset.txt') +}); +``` + +------ +#### [ JavaScript ] + +``` +const { Asset } = require('aws-cdk-lib/aws-s3-assets'); + +// Archived and uploaded to Amazon S3 as a .zip file +const directoryAsset = new Asset(this, "SampleZippedDirAsset", { + path: path.join(__dirname, "sample-asset-directory") +}); + +// Uploaded to Amazon S3 as-is +const fileAsset = new Asset(this, 'SampleSingleFileAsset', { + path: path.join(__dirname, 'file-asset.txt') +}); +``` + +------ +#### [ Python ] + +``` +import os.path +dirname = os.path.dirname(__file__) + +from aws_cdk.aws_s3_assets import Asset + +# Archived and uploaded to Amazon S3 as a .zip file +directory_asset = Asset(self, "SampleZippedDirAsset", + path=os.path.join(dirname, "sample-asset-directory") +) + +# Uploaded to Amazon S3 as-is +file_asset = Asset(self, 'SampleSingleFileAsset', + path=os.path.join(dirname, 'file-asset.txt') +) +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.services.s3.assets.Asset; + +// Directory where app was started +File startDir = new File(System.getProperty("user.dir")); + +// Archived and uploaded to Amazon S3 as a .zip file +Asset directoryAsset = Asset.Builder.create(this, "SampleZippedDirAsset") + .path(new File(startDir, "sample-asset-directory").toString()).build(); + +// Uploaded to Amazon S3 as-is +Asset fileAsset = Asset.Builder.create(this, "SampleSingleFileAsset") + .path(new File(startDir, "file-asset.txt").toString()).build(); +``` + +------ +#### [ C\# ] + +``` +using System.IO; +using Amazon.CDK.AWS.S3.Assets; + +// Archived and uploaded to Amazon S3 as a .zip file +var directoryAsset = new Asset(this, "SampleZippedDirAsset", new AssetProps +{ + Path = Path.Combine(Directory.GetCurrentDirectory(), "sample-asset-directory") +}); + +// Uploaded to Amazon S3 as-is +var fileAsset = new Asset(this, "SampleSingleFileAsset", new AssetProps +{ + Path = Path.Combine(Directory.GetCurrentDirectory(), "file-asset.txt") +}); +``` + +------ + +In most cases, you don't need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods that enable you to use assets\. For Lambda functions, the [fromAsset\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Code.html#static-fromwbrassetpath-options) static method enables you to specify a directory or a \.zip file in the local file system\. + +#### Lambda function example + +A common use case is to create AWS Lambda functions with the handler code, which is the entry point for the function, as an Amazon S3 asset\. + +The following example uses an Amazon S3 asset to define a Python handler in the local directory `handler` and creates a Lambda function with the local directory asset as the `code` property\. Below is the Python code for the handler\. + +``` +def lambda_handler(event, context): + message = 'Hello World!' + return { + 'message': message + } +``` + +The code for the main AWS CDK app should look like the following\. + +------ +#### [ TypeScript ] + +``` +import * as cdk from 'aws-cdk-lib'; +import { Constructs } from 'constructs'; +import * as lambda from 'aws-cdk-lib/aws-lambda'; +import * as path from 'path'; + +export class HelloAssetStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + new lambda.Function(this, 'myLambdaFunction', { + code: lambda.Code.fromAsset(path.join(__dirname, 'handler')), + runtime: lambda.Runtime.PYTHON_3_6, + handler: 'index.lambda_handler' + }); + } +} +``` + +------ +#### [ JavaScript ] + +``` +const cdk = require('aws-cdk-lib'); +const lambda = require('aws-cdk-lib/aws-lambda'); +const path = require('path'); + +class HelloAssetStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new lambda.Function(this, 'myLambdaFunction', { + code: lambda.Code.fromAsset(path.join(__dirname, 'handler')), + runtime: lambda.Runtime.PYTHON_3_6, + handler: 'index.lambda_handler' + }); + } +} + +module.exports = { HelloAssetStack } +``` + +------ +#### [ Python ] + +``` +from aws_cdk import Stack +from constructs import Construct +from aws_cdk import aws_lambda as lambda_ + +import os.path +dirname = os.path.dirname(__file__) + +class HelloAssetStack(Stack): + def __init__(self, scope: Construct, id: str, **kwargs): + super().__init__(scope, id, **kwargs) + + lambda_.Function(self, 'myLambdaFunction', + code=lambda_.Code.from_asset(os.path.join(dirname, 'handler')), + runtime=lambda_.Runtime.PYTHON_3_6, + handler="index.lambda_handler") +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.lambda.Runtime; + +public class HelloAssetStack extends Stack { + + public HelloAssetStack(final App scope, final String id) { + this(scope, id, null); + } + + public HelloAssetStack(final App scope, final String id, final StackProps props) { + super(scope, id, props); + + File startDir = new File(System.getProperty("user.dir")); + + Function.Builder.create(this, "myLambdaFunction") + .code(Code.fromAsset(new File(startDir, "handler").toString())) + .runtime(Runtime.PYTHON_3_6) + .handler("index.lambda_handler").build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.Lambda; +using System.IO; + +public class HelloAssetStack : Stack +{ + public HelloAssetStack(Construct scope, string id, StackProps props) : base(scope, id, props) + { + new Function(this, "myLambdaFunction", new FunctionProps + { + Code = Code.FromAsset(Path.Combine(Directory.GetCurrentDirectory(), "handler")), + Runtime = Runtime.PYTHON_3_6, + Handler = "index.lambda_handler" + }); + } +} +``` + +------ + +The `Function` method uses assets to bundle the contents of the directory and use it for the function's code\. + +#### Deploy\-time attributes example + +Amazon S3 asset types also expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. + +The following example uses deploy\-time attributes to pass the location of an image asset into a Lambda function as environment variables\. \(The kind of file doesn't matter; the PNG image used here is just an example\.\) + +------ +#### [ TypeScript ] + +``` +import { Asset } from 'aws-cdk-lib/aws-s3-assets'; +import * as path from 'path'; + +const imageAsset = new Asset(this, "SampleAsset", { + path: path.join(__dirname, "images/my-image.png") +}); + +new lambda.Function(this, "myLambdaFunction", { + code: lambda.Code.asset(path.join(__dirname, "handler")), + runtime: lambda.Runtime.PYTHON_3_6, + handler: "index.lambda_handler", + environment: { + 'S3_BUCKET_NAME': imageAsset.s3BucketName, + 'S3_OBJECT_KEY': imageAsset.s3ObjectKey, + 'S3_URL': imageAsset.s3Url + } +}); +``` + +------ +#### [ JavaScript ] + +``` +const { Asset } = require('aws-cdk-lib/aws-s3-assets'); +const path = require('path'); + +const imageAsset = new Asset(this, "SampleAsset", { + path: path.join(__dirname, "images/my-image.png") +}); + +new lambda.Function(this, "myLambdaFunction", { + code: lambda.Code.asset(path.join(__dirname, "handler")), + runtime: lambda.Runtime.PYTHON_3_6, + handler: "index.lambda_handler", + environment: { + 'S3_BUCKET_NAME': imageAsset.s3BucketName, + 'S3_OBJECT_KEY': imageAsset.s3ObjectKey, + 'S3_URL': imageAsset.s3Url + } +}); +``` + +------ +#### [ Python ] + +``` +import os.path + +import aws_cdk.aws_lambda as lambda_ +from aws_cdk.aws_s3_assets import Asset + +dirname = os.path.dirname(__file__) + +image_asset = Asset(self, "SampleAsset", + path=os.path.join(dirname, "images/my-image.png")) + +lambda_.Function(self, "myLambdaFunction", + code=lambda_.Code.asset(os.path.join(dirname, "handler")), + runtime=lambda_.Runtime.PYTHON_3_6, + handler="index.lambda_handler", + environment=dict( + S3_BUCKET_NAME=image_asset.s3_bucket_name, + S3_OBJECT_KEY=image_asset.s3_object_key, + S3_URL=image_asset.s3_url)) +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.lambda.Runtime; +import software.amazon.awscdk.services.s3.assets.Asset; + +public class FunctionStack extends Stack { + public FunctionStack(final App scope, final String id, final StackProps props) { + super(scope, id, props); + + File startDir = new File(System.getProperty("user.dir")); + + Asset imageAsset = Asset.Builder.create(this, "SampleAsset") + .path(new File(startDir, "images/my-image.png").toString()).build()) + + Function.Builder.create(this, "myLambdaFunction") + .code(Code.fromAsset(new File(startDir, "handler").toString())) + .runtime(Runtime.PYTHON_3_6) + .handler("index.lambda_handler") + .environment(new HashMap() {{ + put("S3_BUCKET_NAME", imageAsset.getS3BucketName()); + put("S3_OBJECT_KEY", imageAsset.getS3ObjectKey()); + put("S3_URL", imageAsset.getS3Url()); + }}).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.Lambda; +using Amazon.CDK.AWS.S3.Assets; +using System.IO; +using System.Collections.Generic; + +var imageAsset = new Asset(this, "SampleAsset", new AssetProps +{ + Path = Path.Combine(Directory.GetCurrentDirectory(), @"images\my-image.png") +}); + +new Function(this, "myLambdaFunction", new FunctionProps +{ + Code = Code.FromAsset(Path.Combine(Directory.GetCurrentDirectory(), "handler")), + Runtime = Runtime.PYTHON_3_6, + Handler = "index.lambda_handler", + Environment = new Dictionary + { + ["S3_BUCKET_NAME"] = imageAsset.S3BucketName, + ["S3_OBJECT_KEY"] = imageAsset.S3ObjectKey, + ["S3_URL"] = imageAsset.S3Url + } +}); +``` + +------ + +#### Permissions + +If you use Amazon S3 assets directly through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets-readme.html) module, IAM roles, users, or groups, and need to read assets in runtime, grant those assets IAM permissions through the [asset\.grantRead](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets.Asset.html#grantwbrreadgrantee) method\. + +The following example grants an IAM group read permissions on a file asset\. + +------ +#### [ TypeScript ] + +``` +import { Asset } from 'aws-cdk-lib/aws-s3-assets'; +import * as path from 'path'; + +const asset = new Asset(this, 'MyFile', { + path: path.join(__dirname, 'my-image.png') +}); + +const group = new iam.Group(this, 'MyUserGroup'); +asset.grantRead(group); +``` + +------ +#### [ JavaScript ] + +``` +const { Asset } = require('aws-cdk-lib/aws-s3-assets'); +const path = require('path'); + +const asset = new Asset(this, 'MyFile', { + path: path.join(__dirname, 'my-image.png') +}); + +const group = new iam.Group(this, 'MyUserGroup'); +asset.grantRead(group); +``` + +------ +#### [ Python ] + +``` +from aws_cdk.aws_s3_assets import Asset +import aws_cdk.aws_iam as iam + +import os.path +dirname = os.path.dirname(__file__) + + asset = Asset(self, "MyFile", + path=os.path.join(dirname, "my-image.png")) + + group = iam.Group(self, "MyUserGroup") + asset.grant_read(group) +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.services.iam.Group; +import software.amazon.awscdk.services.s3.assets.Asset; + +public class GrantStack extends Stack { + public GrantStack(final App scope, final String id, final StackProps props) { + super(scope, id, props); + + File startDir = new File(System.getProperty("user.dir")); + + Asset asset = Asset.Builder.create(this, "SampleAsset") + .path(new File(startDir, "images/my-image.png").toString()).build(); + + Group group = new Group(this, "MyUserGroup"); + asset.grantRead(group); } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.IAM; +using Amazon.CDK.AWS.S3.Assets; +using System.IO; + +var asset = new Asset(this, "MyFile", new AssetProps { + Path = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), @"images\my-image.png")) +}); + +var group = new Group(this, "MyUserGroup"); +asset.GrantRead(group); +``` + +------ + +### Docker image assets + +The AWS CDK supports bundling local Docker images as assets through the [aws\-ecr\-assets](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr_assets-readme.html) module\. + +The following example defines a docker image that is built locally and pushed to Amazon ECR\. Images are built from a local Docker context directory \(with a Dockerfile\) and uploaded to Amazon ECR by the AWS CDK CLI or your app's CI/CD pipeline, and can be naturally referenced in your AWS CDK app\. + +------ +#### [ TypeScript ] + +``` +import { DockerImageAsset } from 'aws-cdk-lib/aws-ecr-assets'; + +const asset = new DockerImageAsset(this, 'MyBuildImage', { + directory: path.join(__dirname, 'my-image') +}); +``` + +------ +#### [ JavaScript ] + +``` +const { DockerImageAsset } = require('aws-cdk-lib/aws-ecr-assets'); + +const asset = new DockerImageAsset(this, 'MyBuildImage', { + directory: path.join(__dirname, 'my-image') +}); +``` + +------ +#### [ Python ] + +``` +from aws_cdk.aws_ecr_assets import DockerImageAsset + +import os.path +dirname = os.path.dirname(__file__) + +asset = DockerImageAsset(self, 'MyBuildImage', + directory=os.path.join(dirname, 'my-image')) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.ecr.assets.DockerImageAsset; + +File startDir = new File(System.getProperty("user.dir")); + +DockerImageAsset asset = DockerImageAsset.Builder.create(this, "MyBuildImage") + .directory(new File(startDir, "my-image").toString()).build(); +``` + +------ +#### [ C\# ] + +``` +using System.IO; +using Amazon.CDK.AWS.ECR.Assets; + +var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps +{ + Directory = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "my-image")) +}); +``` + +------ + +The `my-image` directory must include a Dockerfile\. The AWS CDK CLI builds a Docker image from `my-image`, pushes it to an Amazon ECR repository, and specifies the name of the repository as an AWS CloudFormation parameter to your stack\. Docker image asset types expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. + +#### Amazon ECS task definition example + +A common use case is to create an Amazon ECS [TaskDefinition](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.TaskDefinition.html) to run docker containers\. The following example specifies the location of a Docker image asset that the AWS CDK builds locally and pushes to Amazon ECR\. + +------ +#### [ TypeScript ] + +``` +import * as ecs from 'aws-cdk-lib/aws-ecs'; +import * as path from 'path'; + +const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { + memoryLimitMiB: 1024, + cpu: 512 +}); + +taskDefinition.addContainer("my-other-container", { + image: ecs.ContainerImage.fromAsset(path.join(__dirname, "..", "demo-image")) +}); +``` + +------ +#### [ JavaScript ] + +``` +const ecs = require('aws-cdk-lib/aws-ecs'); +const path = require('path'); + +const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { + memoryLimitMiB: 1024, + cpu: 512 +}); + +taskDefinition.addContainer("my-other-container", { + image: ecs.ContainerImage.fromAsset(path.join(__dirname, "..", "demo-image")) +}); +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_ecs as ecs + +import os.path +dirname = os.path.dirname(__file__) + +task_definition = ecs.FargateTaskDefinition(self, "TaskDef", + memory_limit_mib=1024, + cpu=512) + +task_definition.add_container("my-other-container", + image=ecs.ContainerImage.from_asset( + os.path.join(dirname, "..", "demo-image"))) +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.services.ecs.FargateTaskDefinition; +import software.amazon.awscdk.services.ecs.ContainerDefinitionOptions; +import software.amazon.awscdk.services.ecs.ContainerImage; + +File startDir = new File(System.getProperty("user.dir")); + +FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create( + this, "TaskDef").memoryLimitMiB(1024).cpu(512).build(); + +taskDefinition.addContainer("my-other-container", + ContainerDefinitionOptions.builder() + .image(ContainerImage.fromAsset(new File(startDir, + "demo-image").toString())).build()); +``` + +------ +#### [ C\# ] + +``` +using System.IO; +using Amazon.CDK.AWS.ECS; + +var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps +{ + MemoryLimitMiB = 1024, + Cpu = 512 +}); + +taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions +{ + Image = ContainerImage.FromAsset(Path.Combine(Directory.GetCurrentDirectory(), "demo-image"); +}); +``` + +------ + +#### Deploy\-time attributes example + +The following example shows how to use the deploy\-time attributes `repository` and `imageUri` to create an Amazon ECS task definition with the AWS Fargate launch type\. Note that the Amazon ECR repo lookup requires the image's tag, not its URI, so we snip it from the end of the asset's URI\. + +------ +#### [ TypeScript ] + +``` +import * as ecs from 'aws-cdk-lib/aws-ecs'; +import * as path from 'path'; +import { DockerImageAsset } from 'aws-cdk-lib/aws-ecr-assets'; + +const asset = new DockerImageAsset(this, 'my-image', { + directory: path.join(__dirname, "..", "demo-image") +}); + +const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { + memoryLimitMiB: 1024, + cpu: 512 +}); + +taskDefinition.addContainer("my-other-container", { + image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri.split(":").pop()) +}); +``` + +------ +#### [ JavaScript ] + +``` +const ecs = require('aws-cdk-lib/aws-ecs'); +const path = require('path'); +const { DockerImageAsset } = require('aws-cdk-lib/aws-ecr-assets'); + +const asset = new DockerImageAsset(this, 'my-image', { + directory: path.join(__dirname, "..", "demo-image") +}); + +const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { + memoryLimitMiB: 1024, + cpu: 512 +}); + +taskDefinition.addContainer("my-other-container", { + image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri.split(":").pop()) +}); +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_ecs as ecs +from aws_cdk.aws_ecr_assets import DockerImageAsset + +import os.path +dirname = os.path.dirname(__file__) + +asset = DockerImageAsset(self, 'my-image', + directory=os.path.join(dirname, "..", "demo-image")) + +task_definition = ecs.FargateTaskDefinition(self, "TaskDef", + memory_limit_mib=1024, cpu=512) + +task_definition.add_container("my-other-container", + image=ecs.ContainerImage.from_ecr_repository( + asset.repository, asset.image_uri.rpartition(":")[-1])) +``` + +------ +#### [ Java ] + +``` +import java.io.File; + +import software.amazon.awscdk.services.ecr.assets.DockerImageAsset; + +import software.amazon.awscdk.services.ecs.FargateTaskDefinition; +import software.amazon.awscdk.services.ecs.ContainerDefinitionOptions; +import software.amazon.awscdk.services.ecs.ContainerImage; + +File startDir = new File(System.getProperty("user.dir")); + +DockerImageAsset asset = DockerImageAsset.Builder.create(this, "my-image") + .directory(new File(startDir, "demo-image").toString()).build(); + +FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create( + this, "TaskDef").memoryLimitMiB(1024).cpu(512).build(); + +// extract the tag from the asset's image URI for use in ECR repo lookup +String imageUri = asset.getImageUri(); +String imageTag = imageUri.substring(imageUri.lastIndexOf(":") + 1); + +taskDefinition.addContainer("my-other-container", + ContainerDefinitionOptions.builder().image(ContainerImage.fromEcrRepository( + asset.getRepository(), imageTag)).build()); +``` + +------ +#### [ C\# ] + +``` +using System.IO; +using Amazon.CDK.AWS.ECS; +using Amazon.CDK.AWS.ECR.Assets; + +var asset = new DockerImageAsset(this, "my-image", new DockerImageAssetProps { + Directory = Path.Combine(Directory.GetCurrentDirectory(), "demo-image") +}); + +var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps +{ + MemoryLimitMiB = 1024, + Cpu = 512 +}); + +taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions +{ + Image = ContainerImage.FromEcrRepository(asset.Repository, asset.ImageUri.Split(":").Last()) +}); +``` + +------ + +#### Build arguments example + +You can provide customized build arguments for the Docker build step through the `buildArgs` \(Python: `build_args`\) property option when the AWS CDK CLI builds the image during deployment\. + +------ +#### [ TypeScript ] + +``` +const asset = new DockerImageAsset(this, 'MyBuildImage', { + directory: path.join(__dirname, 'my-image'), + buildArgs: { + HTTP_PROXY: 'http://10.20.30.2:1234' + } +}); +``` + +------ +#### [ JavaScript ] + +``` +const asset = new DockerImageAsset(this, 'MyBuildImage', { + directory: path.join(__dirname, 'my-image'), + buildArgs: { + HTTP_PROXY: 'http://10.20.30.2:1234' + } +}); +``` + +------ +#### [ Python ] + +``` +asset = DockerImageAsset(self, "MyBulidImage", + directory=os.path.join(dirname, "my-image"), + build_args=dict(HTTP_PROXY="http://10.20.30.2:1234")) +``` + +------ +#### [ Java ] + +``` +DockerImageAsset asset = DockerImageAsset.Builder.create(this, "my-image"), + .directory(new File(startDir, "my-image").toString()) + .buildArgs(new HashMap() {{ + put("HTTP_PROXY", "http://10.20.30.2:1234"); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps { + Directory = Path.Combine(Directory.GetCurrentDirectory(), "my-image"), + BuildArgs = new Dictionary + { + ["HTTP_PROXY"] = "http://10.20.30.2:1234" + } +}); +``` + +------ + +#### Permissions + +If you use a module that supports Docker image assets, such as [aws\-ecs](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs-readme.html), the AWS CDK manages permissions for you when you use assets directly or through [ContainerImage\.fromEcrRepository](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ContainerImage.html#static-fromwbrecrwbrrepositoryrepository-tag) \(Python: `from_ecr_repository`\)\. If you use Docker image assets directly, you need to ensure that the consuming principal has permissions to pull the image\. + +In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr.Repository.html#grantwbrpullgrantee) method \(Python: `grant_pull`\. This modifies the IAM policy of the principal to enable it to pull images from this repository\. If the principal that is pulling the image is not in the same account or is an AWS service, such as AWS CodeBuild, that does not assume a role in your account, you must grant pull permissions on the resource policy and not on the principal's policy\. Use the [asset\.repository\.addToResourcePolicy](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr.Repository.html#addwbrtowbrresourcewbrpolicystatement) method \(Python: `add_to_resource_policy`\) to grant the appropriate principal permissions\. + +## AWS CloudFormation resource metadata + +**Note** +This section is relevant only for construct authors\. In certain situations, tools need to know that a certain CFN resource is using a local asset\. For example, you can use the AWS SAM CLI to invoke Lambda functions locally for debugging purposes\. See [SAM CLI](sam.md) for details\. + +To enable such use cases, external tools consult a set of metadata entries on AWS CloudFormation resources: ++ `aws:asset:path` – Points to the local path of the asset\. ++ `aws:asset:property` – The name of the resource property where the asset is used\. + +Using these two metadata entries, tools can identify that assets are used by a certain resource, and enable advanced local experiences\. + +To add these metadata entries to a resource, use the `asset.addResourceMetadata` \(Python: `add_resource_metadata`\) method\. \ No newline at end of file diff --git a/v2/best-practices.md b/v2/best-practices.md new file mode 100644 index 00000000..5a001455 --- /dev/null +++ b/v2/best-practices.md @@ -0,0 +1,181 @@ +# Best practices for developing and deploying cloud infrastructure with the AWS CDK + +The AWS CDK allows developers or administrators to define their cloud infrastructure using a supported programming language\. CDK applications should be organized into logical units, such as API, database, and monitoring resources, and optionally have a pipeline for automated deployments\. The logical units should be implemented as constructs including the infrastructure \(e\.g\. Amazon S3 buckets, Amazon RDS databases, Amazon VPC network\), runtime code \(e\.g\. AWS Lambda functions\), and configuration code\. Stacks define the deployment model of these logical units\. For a more detailed introduction to the concepts behind the CDK, see [Getting started with the AWS CDK](getting_started.md)\. + +The AWS CDK reflects careful consideration of the needs of our customers and internal teams and of the failure patterns that often arise during the deployment and ongoing maintenance of complex cloud applications\. We discovered that failures are often related to "out\-of\-band" changes to an application, such as configuration changes, that were not fully tested\. Therefore, we developed the AWS CDK around a model in which your entire application, not just business logic but also infrastructure and configuration, is defined in code\. That way, proposed changes can be carefully reviewed, comprehensively tested in environments resembling production to varying degrees, and fully rolled back if something goes wrong\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/all-in-one.jpg) + +At deployment time, the AWS CDK synthesizes a cloud assembly that contains not only AWS CloudFormation templates describing your infrastructure in all target environments, but file assets containing your runtime code and their supporting files\. With the CDK, every commit in your application's main version control branch can represent a complete, consistent, deployable version of your application\. Your application can then be deployed automatically whenever a change is made\. + +The philosophy behind the AWS CDK leads to our recommended best practices, which we have divided into four broad categories\. ++ [Organization best practices](#best-practices-organization) ++ [Coding best practices](#best-practices-code) ++ [Construct best practices](#best-practices-constructs) ++ [Application best practices](#best-practices-apps) + +**Tip** +In addition to the guidance in this document, you should also consider [best practices for AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html) as well as for the individual AWS services you use, where they are obviously applicable to CDK\-defined infrastructure\. + +## Organization best practices + +In the beginning stages of AWS CDK adoption, it's important to consider how to set up your organization for success\. It's a best practice to have a team of experts responsible for training and guiding the rest of the company as they adopt the CDK The size of this team may vary, from one or two people at a small company to a full\-fledged Cloud Center of Excellence \(CCoE\) at a larger company\. This team is responsible for setting standards and policies for how cloud infrastructure will be done at your company, as well as for training and mentoring developers\. + +The CCoE may provide guidance on what programming languages should be used for cloud infrastructure\. The details will vary from one organization to the next, but a good policy helps make sure developers can easily understand and maintain all cloud infrastructure throughout the company\. + +The CCoE also creates a "landing zone" that defines your organizational units within AWS\. A landing zone is a pre\-configured, secure, scalable, multi\-account AWS environment based on best practice blueprints\. You can tie together the services that make up your landing zone with [AWS Control Tower](https://aws.amazon.com/controltower/), a high\-level service configures and manages your entire multi\-account system from a single user interface\. + +Development teams should be able use their own accounts for testing and have the ability to deploy new resources in these accounts as needed\. Individual developers can treat these resources as extensions of their own development workstation\. Using [CDK Pipelines](cdk_pipeline.md), the AWS CDK applications can then be deployed via a CI/CD account to testing, integration, and production environments \(each isolated in its own AWS region and/or account\) by merging the developers' code into your organization's canonical repository\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/best-practice-deploy-to-multiple-accounts.png) + +## Coding best practices + + This section presents best practices for organizing your AWS CDK code\. The diagram below shows the relationship between a team and that team's code repositories, packages, applications, and construct libraries\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/code-organization.jpg) + +### Start simple and add complexity only when you need it + +The guiding principle for most of our best practices is to keep things simple as possible—but no simpler\. Add complexity only when your requirements dictate a more complicated solution\. With the AWS CDK, you can always refactor your code as necessary to support new requirements, so it doesn't make sense to architect for all possible scenarios up front\. + +### Align with the AWS Well\-Architected framework + +The [AWS Well\-Architected](http://aws.amazon.com/architecture/well-architected/) framework defines a *component* as the code, configuration, and AWS resources that together deliver against a requirement\. A component is often the unit of technical ownership, and is decoupled from other components\. The term *workload* is used to identify a set of components that together deliver business value\. A workload is usually the level of detail that business and technology leaders communicate about\. + +An AWS CDK application maps to a component as defined by the AWS Well\-Architected Framework\. AWS CDK apps are a mechanism to codify and deliver Well\-Architected cloud application best practices\. You can also create and share components as reusable code libraries through artifact repositories, such as AWS CodeArtifact\. + +### Every application starts with a single package in a single repository + +A single package is the entry point of your AWS CDK app\. This is where you define how and where the different logical units of your application are deployed, as well as the CI/CD pipeline to deploy the application\. The app's constructs define the logical units of your solution\. + +Use additional packages for constructs that you use in more than one application\. \(Shared constructs should also have their own lifecycle and testing strategy\.\) Dependencies between packages in the same repository are managed by your repo's build tooling\. + +Though it is possible, it is not recommended to put multiple applications in the same repository, especially when using automated deployment pipelines, because this increases the "blast radius" of changes during deployment\. With multiple applications in a repository, not only do changes to one application trigger deployment of the others \(even if they have not changed\), but a break in one application prevents the other applications from being deployed\. + +### Move code into repositories based on code lifecycle or team ownership + +When packages begin to be used in multiple applications, move them to their own repository, so they can be referenced by the build systems of the applications that use them, but updated on cadences independent of the lifecycles of those applications\. It may make sense to put all shared constructs in one repository at first\. + +Also move packages to their own repo when different teams are working on them, to help enforce access control\. + +To consume packages across repository boundaries, you now need a private package repository—similar to NPM, PyPi, or Maven Central, but internal to your organization, and a release process that builds, tests, and publishes the package to the private package repository\. [CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/) can host packages for most popular programming languages\. + +Dependencies on packages in the package repository are managed by your language's package manager, for example NPM for TypeScript or JavaScript applications\. Your package manager helps to make sure builds are repeatable by recording the specific versions of every package your application depends on and allows you to upgrade those dependencies in a controlled manner\. + +Shared packages need a different testing strategy: although for a single application it might be good enough to deploy the application to a testing environment and confirm that it still works, shared packages need to be tested independently of the consuming application, as if they were being released to the public\. \(Your organization might in fact choose to actually release some shared packages to the public\.\) + +Keep in mind that a construct can be arbitrarily simple or complex\. A `Bucket` is a construct, but `CameraShopWebsite` could be a construct, too\. + +### Infrastructure and runtime code live in the same package + +The AWS CDK not only generates AWS CloudFormation templates for deploying infrastructure, it also bundles runtime assets like Lambda functions and Docker images and deploys them alongside your infrastructure\. So it's not only possible to combine the code that defines your infrastructure and the code that implements your runtime logic into a single construct— it's a best practice\. These two kinds of code don't need to live in separate repositories or even in separate packages\. + +A construct that is self\-contained, in other words that completely describes a piece of functionality including its infrastructure and logic, makes it easy to evolve the two kinds of code together, test them in isolation, share and reuse the code across projects, and version all the code in sync\. + +## Construct best practices + + This section contains best practices for developing constructs\. Constructs are reusable, composable modules that encapsulate resources, and the building blocks of AWS CDK apps\. + +### Model your app through constructs, not stacks + +When breaking down your application into logical units, represent each unit as a descendant of [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) and not of [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html)\. Stacks are a unit of deployment, and so tend to be oriented to specific applications\. By using constructs instead of stacks, you give yourself and your users the flexibility to build stacks in the way that makes the most sense for each deployment scenario\. For example, you could compose multiple constructs into a `DevStack` with some configuration for development environments and then have a different composition for your `ProdStack`\. + +### Configure with properties and methods, not environment variables + +Environment variable lookups inside constructs and stacks are a common anti\-pattern\. Both constructs and stacks should accept a properties object to allow for full configurability completely in code\. To do otherwise is to introduce a dependency on the machine that the code will run on, which becomes another bit of configuration information you have to keep track of and manage\. + +In general, environment variable lookups should be limited to the top level of an AWS CDK app, and should be used to pass in information needed for running in a development environment; see [Environments](environments.md)\. + +### Unit test your infrastructure + +If you avoid network lookups during synthesis and model all your production stages in code \(best practices we cover later\), you can run a full suite of unit tests at build time, consistently, in all environments\. If any single commit always results in the same generated template, you can trust the unit tests that you write to confirm that the generated templates look how you expect them to\. See [Testing constructs](testing.md)\. + +### Don't change the logical ID of stateful resources + +Changing the logical ID of a resource results in the resource being replaced with a new one at the next deployment\. For stateful resources like databases and buckets, or persistent infrastructure like an Amazon VPC, this is almost never what you want\. Be careful about any refactor of your AWS CDK code that could cause the ID to change, and write unit tests that assert that the logical IDs of your stateful resources remain static\. The logical ID is derived from the `id` you specify when you instantiate the construct, and the construct's position in the construct tree; see [Logical IDs](identifiers.md#identifiers_logical_ids)\. + +### Constructs aren't enough for compliance + +Many enterprise customers are writing their own wrappers for L2 constructs \(the "curated" constructs that represent individual AWS resources with built\-in sane defaults and best practices\) to enforce security best practices such as static encryption and specific IAM policies\. For example, you might create a `MyCompanyBucket` that you then use in your applications in place of the usual Amazon S3 `Bucket` construct\. This pattern is useful for surfacing security guidance early in the software development lifecycle, but it cannot be relied on as the sole means of enforcement\. + +Instead, use AWS features such as [service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) and [permission boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to enforce your security guardrails at the organization level\. Use [Aspects](aspects.md) or tools like [CloudFormation Guard](https://github.com/aws-cloudformation/cloudformation-guard) to make assertions about the security properties of infrastructure elements before deployment\. Use AWS CDK for what it does best\. + +Finally, keep in mind that writing your own "L2\+" constructs like these may prevent your developers from taking advantage of the growing ecosystems of AWS CDK packages, such as [AWS Solutions Constructs](https://docs.aws.amazon.com/solutions/latest/constructs/welcome.html), as these are typically built upon standard AWS CDK constructs and won't be able to use your custom versions\. + +## Application best practices + +In this section we discuss how best to write your AWS CDK applications, combining constructs to define how your AWS resources are connected\. + +### Make decisions at synthesis time + +Although AWS CloudFormation lets you make decisions at deployment time \(using `Conditions`, `{ Fn::If }`, and `Parameters`\), and the AWS CDK gives you some access to these mechanisms, we recommend against using them\. The types of values you can use, and the types of operations you can perform on them, are quite limited compared to those available in a general\-purpose programming language\. + +Instead, try to make all decisions, such as which construct to instantiate, in your AWS CDK application, using your programming language's `if` statements and other features\. For example, a common CDK idiom, iterating over a list and instantiating a construct with values from each item in the list, simply isn't possible using AWS CloudFormation expressions\. + +Treat AWS CloudFormation as an implementation detail that the AWS CDK uses for robust cloud deployments, not as a language target\. You're not writing AWS CloudFormation templates in TypeScript or Python, you're writing CDK code that happens to use CloudFormation for deployment\. + +### Use generated resource names, not physical names + +Names are a precious resource\. Every name can only be used once, so if you hard\-code a table name or bucket name into your infrastructure and application, you can't deploy that piece of infrastructure twice in the same account\. \(The name we're talking about here is the name specified by, for example, the `bucketName` property on an Amazon S3 bucket construct\.\) + +What's worse, you can't make changes to the resource that require it to be replaced\. If a property can only be set at resource creation, for example the `KeySchema` of an Amazon DynamoDB table, that property is immutable, and changing it requires a new resource\. But the new resource must have the same name in order to be a true replacement, and it can't while the existing resource is still using that name\. + +A better approach is to specify as few names as possible\. If you leave out resource names, the AWS CDK will generate them for you, and it'll do so in a way that won't cause these problems\. You then, for example, pass the generated table name \(which you can reference as `table.tableName` in your AWS CDK application\) as an environment variable into your AWS Lambda function, or you generate a configuration file on your Amazon EC2 instance on startup, or you write the actual table name to AWS Systems Manager Parameter Store and your application reads it from there\. + +If the place you need it is another AWS CDK stack, that's even easier\. Given one stack that defines the resource and another than needs to use it: ++ If the two stacks are in the same AWS CDK app, just pass a reference between the two stacks\. For example, save a reference to the resource's construct as an attribute of the defining stack \(`this.stack.uploadBucket = myBucket`\), then pass that attribute to the constructor of the stack that needs the resource\. ++ When the two stacks are in different AWS CDK apps, use a static `from` method to import an externally\-defined resource based on its ARN, name, or other attributes \(for example, `Table.fromArn()` for a DynamoDB table\)\. Use the `CfnOutput` construct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS console\. Or the second app can parse the CloudFormation template generated by the first app and retrieve that value from the Outputs section\. + +### Define removal policies and log retention + +The AWS CDK does its best to keep you from losing data by defaulting to policies that retain everything you create\. For example, the default removal policy on resources that contain data \(such as Amazon S3 buckets and database tables\) is to never delete the resource when it is removed from the stack, but rather orphan the resource from the stack\. Similarly, the CDK's default is to retain all logs forever\. In production environments, these defaults can quickly result in the storage of large amounts of data you don't actually need, and a corresponding AWS bill\. + +Consider carefully what you want these policies to actually be for each production resource and specify them accordingly\. Use [Aspects](aspects.md) to validate the removal and logging policies in your stack\. + +### Separate your application into multiple stacks as dictated by deployment requirements + +There is no hard and fast rule to how many stacks your application needs\. You'll usually end up basing the decision on your deployment patterns\. Keep in mind the following guidelines: ++ It's typically easier to keep as many resources in the same stack as possible, so keep them together unless you know you want them separated\. ++ Consider keeping stateful resources \(like databases\) in a separate stack from stateless resources\. You can then turn on termination protection on the stateful stack, and can freely destroy or create multiple copies of the stateless stack without risk of data loss\. ++ Stateful resources are more sensitive to construct renaming—renaming leads to resource replacement—so it makes sense not to nest them inside constructs that are likely to be moved around or renamed \(unless the state can be rebuilt if lost, like a cache\)\. This is another good reason to put stateful resources in their own stack\. + +### Commit `cdk.context.json` to avoid non\-deterministic behavior + +Determinism is key to successful AWS CDK deployments\. A AWS CDK app should have essentially the same result whenever it is deployed to a given environment\. + +Since your AWS CDK app is written in a general\-purpose programming language, it can execute arbitrary code, use arbitrary libraries, and make arbitrary network calls\. For example, you could use an AWS SDK to retrieve some information from your AWS account while synthesizing your app\. Recognize that doing so will result in additional credential setup requirements, increased latency, and a chance, however small, of failure every time you run `cdk synth`\. + +You should never modify your AWS account or resources during synthesis; synthesizing an app should not have side effects\. Changes to your infrastructure should happen only in the deployment phase, after the AWS CloudFormation template has been generated\. This way, if there's a problem, AWS CloudFormation will automatically roll back the change\. To make changes that can't be easily made within the AWS CDK framework, use [custom resources](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.custom_resources-readme.html) to execute arbitrary code at deployment time\. + +Even strictly read\-only calls are not necessarily safe\. Consider what happens if the value returned by a network call changes\. What part of your infrastructure will that impact? What will happen to already\-deployed resources? Here are just two of the situations in which a sudden change in values might cause a problem\. ++ If you provision an Amazon VPC to all available Availability Zones in a specified region, and the number of AZs is two on deployment day, your IP space gets split in half\. If AWS launches a new Availability Zone the next day, the next deployment after that tries to split your IP space into thirds, requiring all subnets to be recreated\. This probably won't be possible because your Amazon EC2 instances are still running, and you'll have to clean this up manually\. ++ If you query for the latest Amazon Linux machine image and deploy an Amazon EC2 instance, and the next day a new image is released, a subsequent deployment picks up the new AMI and replaces all your instances\. This may not be what you expected to happen\. + +These situations can be particularly pernicious because the AWS\-side change may occur after months or years of successful deployments\. Suddenly your deployments are failing "for no reason" and you long ago forgot what you did and why\. + +Fortunately, the AWS CDK includes a mechanism called *context providers* to record a snapshot of non\-deterministic values, allowing future synthesis operations produce exactly the same template\. The only changes in the new template are the changes *you* made in your code\. When you use a construct's `.fromLookup()` method, the result of the call is cached in `cdk.context.json`, which you should commit to version control along with the rest of your code to ensure future executions of your CDK app use the same value\. The CDK Toolkit includes commands to manage the context cache, so you can refresh specific entries when you need to\. For more information, see [Runtime context](context.md)\. + +If you need some value \(from AWS or elsewhere\) for which there is no native CDK context provider, we recommend writing a separate script to retrieve the value and write it to a file, then read that file in your CDK app\. Run the script only when you want to refresh the stored value, not as part of your regular build process\. + +### Let the AWS CDK manage roles and security groups + +One of the great features of the AWS CDK construct library is the `grant()` convenience methods that allow quick and simple creation of AWS Identity and Access Management roles granting access to one resource by another using minimally\-scoped permissions\. For example, consider a line like the following: + +``` +myBucket.grantRead(myLambda) +``` + +This single line results in a policy being added to the Lambda function's role \(which is also created for you\)\. That role and its policies are more than a dozen lines of CloudFormation that you don't have to write, and the AWS CDK grants only the minimal permissions required for the function to read from the bucket\. + +If you require developers to always use predefined roles that were created by a security team, AWS CDK coding becomes much more complicated, and your teams lose a lot of flexibility in how they design their applications\. A better alternative is to use [service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) and [permission boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to ensure that developers stay within the guardrails\. + +### Model all production stages in code + + In traditional AWS CloudFormation scenarios, your goal is to produce a single artifact that is parameterized so that it can be deployed to various target environments after applying configuration values specific to those environments\. In the CDK, you can, and should, build that configuration right into your source code\. Create a stack for your production environment, and a separate one for each of your other stages, and put the configuration values for each right there in the code\. Use services like [Secrets Manager](https://aws.amazon.com/secrets-manager/) and [Systems Manager](https://aws.amazon.com/systems-manager/) Parameter Store for sensitive values that you don't want to check in to source control, using the names or ARNs of those resources\. + + When you synthesize your application, the cloud assembly created in the `cdk.out` folder contains a separate template for each environment\. Your entire build is deterministic: there are no out\-of\-band changes to your application, and any given commit always yields the exact same AWS CloudFormation template and accompanying assets, which makes unit testing much more reliable\. + +### Measure everything + +Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_dynamodb.Table.html) class\. \ No newline at end of file diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md new file mode 100644 index 00000000..bb6b3530 --- /dev/null +++ b/v2/bootstrapping.md @@ -0,0 +1,557 @@ +# Bootstrapping + +Deploying AWS CDK apps into an AWS [environment](environments.md) \(a combination of an AWS account and region\) may require that you provision resources the AWS CDK needs to perform the deployment\. These resources include an Amazon S3 bucket for storing files and IAM roles that grant permissions needed to perform deployments\. The process of provisioning these initial resources is called *bootstrapping*\. + +An environment needs to be bootstrapped if any of the following apply\. ++ An AWS CDK stack being deployed uses [Assets](assets.md)\. ++ An AWS CloudFormation template generated by the app exceeds 50 kilobytes\. + +The required resources are defined in a AWS CloudFormation stack, called the *bootstrap stack*, which is usually named `CDKToolkit`\. Like any AWS CloudFormation stack, it appears in the AWS CloudFormation console once it has been deployed\. + +**Note** +CDK v2 uses a bootstrap template dubbed the modern template\. The legacy template from CDK v1 is not supported in v2\. + +Environments are independent, so if you want to deploy to multiple environments \(different AWS accounts or different regions in the same account\), each environment must be bootstrapped separately\. + +**Important** +You may incur AWS charges for data stored in the bootstrapped resources\. + +**Note** +Older versions of the bootstrap template created a Customer Master Key \(CMK\) in each bootstrapped environment by default\. To avoid charges for the CMK, re\-bootstrap these environments using `--no-bootstrap-customer-key`\. The current default is to not use a CMK to avoid these charges\. + +If you attempt to deploy an AWS CDK application that requires bootstrap resources into an environment that does not have them, you receive an error message telling you that you need to bootstrap the environment\. + +If you are using CDK Pipelines to deploy into another account's environment, and you receive a message like the following: + +``` +Policy contains a statement with one or more invalid principals +``` + +This error message means that the appropriate IAM roles do not exist in the other environment, which is most likely caused by a lack of bootstrapping\. + +**Note** +Do not delete and recreate an account's bootstrap stack if you are using CDK Pipelines to deploy into that account\. The pipeline will stop working\. To update the bootstrap stack to a new version, instead re\-run `cdk bootstrap` to update the bootstrap stack in place\. + +## How to bootstrap + +Bootstrapping is the deployment of a AWS CloudFormation template to a specific AWS environment \(account and region\)\. The bootstrapping template accepts parameters that customize some aspects of the bootstrapped resources \(see [Customizing bootstrapping](#bootstrapping-customizing)\)\. Thus, you can bootstrap in one of two ways\. ++ Use the AWS CDK Toolkit's cdk bootstrap command\. This is the simplest method and works well if you have only a few environments to bootstrap\. ++ Deploy the template provided by the AWS CDK Toolkit using another AWS CloudFormation deployment tool\. This lets you use AWS CloudFormation Stack Sets or AWS Control Tower as well as the AWS CloudFormation console or the AWS CLI\. You can even make small modifications to the template before deployment\. This approach is more flexible and is suitable for large\-scale deployments\. + +It is not an error to bootstrap an environment more than once\. If an environment you bootstrap has already been bootstrapped, its bootstrap stack will be upgraded if necessary; otherwise, nothing happens\. + +### Bootstrapping with the AWS CDK Toolkit + +Use the `cdk bootstrap` command to bootstrap one or more AWS environments\. In its basic form, this command bootstraps one or more specified AWS environments \(two, in this example\)\. + +``` +cdk bootstrap aws://ACCOUNT-NUMBER-1/REGION-1 aws://ACCOUNT-NUMBER-2/REGION-2 ... +``` + +The following examples illustrate bootstrapping of one and two environments, respectively\. \(Both use the same AWS account\.\) As shown in the second example, the `aws://` prefix is optional when specifying an environment\. + +``` +cdk bootstrap aws://123456789012/us-east-1 +cdk bootstrap 123456789012/us-east-1 123456789012/us-west-1 +``` + +If you do not specify at least one environment in the `cdk bootstrap` command, the AWS CDK Toolkit synthesizes the AWS CDK app in the current directory and bootstraps all the environments referenced in the app\. If a stack is environment\-agnostic \(that is, it does not have an `env` property\), the CDK's environment \(for example, the one specified using \-\-profile, or the default AWS environment otherwise\) is applied to make the stack environment\-specific, and that environment is then bootstrapped\. + +For example, the following command synthesizes the current AWS CDK app using the `prod` AWS profile, then bootstraps its environments\. + +``` +cdk bootstrap --profile prod +``` + +### Bootstrapping from the AWS CloudFormation template + +AWS CDK bootstrapping is performed by an AWS CloudFormation template\. To get a copy of this template in the file `bootstrap-template.yaml`, run the following command\. + +------ +#### [ macOS/Linux ] + +``` +cdk bootstrap --show-template > bootstrap-template.yaml +``` + +------ +#### [ Windows ] + +On Windows, PowerShell must be used to preserve the encoding of the template\. + +``` +powershell "cdk bootstrap --show-template | Out-File -encoding utf8 bootstrap-template.yaml" +``` + +------ + +The template is also available in the [AWS CDK GitHub repository](https://github.com/aws/aws-cdk/blob/master/packages/aws-cdk/lib/api/bootstrap/bootstrap-template.yaml)\. + +Deploy this template using your preferred deployment mechanism for AWS CloudFormation templates\. For example, the following command deploys the template using the AWS CLI: + +------ +#### [ macOS/Linux ] + +``` +aws cloudformation create-stack \ + --stack-name CDKToolkit \ + --template-body file://bootstrap-template.yaml +``` + +------ +#### [ Windows ] + +``` +aws cloudformation create-stack ^ + --stack-name CDKToolkit ^ + --template-body file://bootstrap-template.yaml +``` + +------ + +## Bootstrapping template + +As previously mentioned, AWS CDK v1 supported two bootstrapping templates, legacy and modern\. CDK v2 supports only the modern template\. For reference, here are the high\-level differences between these two templates\. + +[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html) + +\* *We will add additional resources to the bootstrap template as needed\.* + +An environment that has been bootstrapped using the legacy template can \(and must\) be upgraded to use the modern template for use with CDK v2 by re\-bootstrapping\. Re\-deploy all AWS CDK applications in the environment at least once before deleting the legacy bucket\. + +## Customizing bootstrapping + +There are two ways to customize the bootstrapping resources\. ++ Use command\-line parameters with the `cdk bootstrap` command\. This lets you modify a few aspects of the template\. ++ Modify the default bootstrap template and deploy it yourself\. This gives you unlimited control over the bootstrap resources\. + +The following command\-line options, when used with CDK Toolkit's cdk bootstrap, provide commonly\-needed adjustments to the bootstrapping template\. ++ \-\-bootstrap\-bucket\-name overrides the name of the Amazon S3 bucket\. May require changes to your CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. ++ \-\-bootstrap\-kms\-key\-id overrides the AWS KMS key used to encrypt the S3 bucket\. ++ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. +**Tip** +The policies must be passed as a single string argument, with the policy ARNs separated by commas, like this: + + ``` + --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess". + ``` ++ \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. ++ \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. ++ \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. ++ \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. ++ \-\-termination\-protection prevents the bootstrap stack from being deleted \(see [Protecting a stack from being deleted](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html) in the AWS CloudFormation User Guide\) + +**Important** +The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. + +### Customizing the template + +When you need more customization than the AWS CDK Toolkit switches can provide, you can modify the bootstrap template to suit your needs\. Remember that you can obtain the template by using the \-\-show\-template flag\. + +``` +export CDK_NEW_BOOTSTRAP=1 +cdk bootstrap --show-template +``` + +Any modifications you make must adhere to the [bootstrapping template contract](#bootstrapping-contract)\. + +Deploy your modified template as described in [Bootstrapping from the AWS CloudFormation template](#bootstrapping-howto-cfn), or using cdk bootstrap \-\-template\. + +``` +cdk bootstrap --template bootstrap-template.yaml +``` + +## Stack synthesizers + +Your AWS CDK app needs to know about the bootstrapping resources available to it in order to successfully synthesize a stack that can be deployed\. The *stack synthesizer* is an AWS CDK class that controls how the stack's template is synthesized, including how it uses bootstrapping resources \(for example, how it refers to assets stored in the bootstrap bucket\)\. + +The AWS CDK's built\-in stack synthesizers is called `DefaultStackSynthesizer`\. It includes capabilities for cross\-account deployments and [CDK Pipelines](cdk_pipeline.md) deployments\. + +You can pass a stack synthesizer to a stack when you instantiate it using the `synthesizer` property\. + +------ +#### [ TypeScript ] + +``` +new MyStack(this, 'MyStack', { + // stack properties + synthesizer: new DefaultStackSynthesizer({ + // synthesizer properties + }), +}); +``` + +------ +#### [ JavaScript ] + +``` +new MyStack(this, 'MyStack', { + // stack properties + synthesizer: new DefaultStackSynthesizer({ + // synthesizer properties + }), +}); +``` + +------ +#### [ Python ] + +``` +MyStack(self, "MyStack", + # stack properties + synthesizer=DefaultStackSynthesizer( + # synthesizer properties +)) +``` + +------ +#### [ Java ] + + + +``` +new MyStack(app, "MyStack", StackProps.builder() + // stack properties + .synthesizer(DefaultStackSynthesizer.Builder.create() + // synthesizer properties + .build()) + .build(); +``` + +------ +#### [ C\# ] + +``` +new MyStack(app, "MyStack", new StackProps +// stack properties +{ + Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps + { + // synthesizer properties + }) +}); +``` + +------ + +If you don't provide the `synthesizer` property, `DefaultStackSynthesizer` is used\. + +## Customizing synthesis + +Depending on the changes you made to the bootstrap template, you may also need to customize synthesis\. The `DefaultStackSynthesizer` can be customized using the properties described below\. If none of these properties provide the customizations you require, you can write your synthesizer as a class that implements `IStackSynthesizer` \(perhaps deriving from `DefaultStackSynthesizer`\)\. + +### Changing the qualifier + +The *qualifier* is added to the name of bootstrap resources to distinguish the resources in separate bootstrap stacks\. To deploy two different versions of the bootstrap stack in the same environment \(AWS account and region\), then, the stacks must have different qualifiers\. This feature is intended for name isolation between automated tests of the CDK itself\. Unless you can very precisely scope down the IAM permissions given to the AWS CloudFormation execution role, there are no privilege isolation benefits to having two different bootstrap stacks in a single account, so there is usually no need to change this value\. + +To change the qualifier, configure the `DefaultStackSynthesizer` either by instantiating the synthesizer with the property: + +------ +#### [ TypeScript ] + +``` +new MyStack(this, 'MyStack', { + synthesizer: new DefaultStackSynthesizer({ + qualifier: 'MYQUALIFIER', + }), +}); +``` + +------ +#### [ JavaScript ] + +``` +new MyStack(this, 'MyStack', { + synthesizer: new DefaultStackSynthesizer({ + qualifier: 'MYQUALIFIER', + }), +}) +``` + +------ +#### [ Python ] + +``` +MyStack(self, "MyStack", + synthesizer=DefaultStackSynthesizer( + qualifier="MYQUALIFIER" +)) +``` + +------ +#### [ Java ] + +``` +new MyStack(app, "MyStack", StackProps.builder() + .synthesizer(DefaultStackSynthesizer.Builder.create() + .qualifier("MYQUALIFIER") + .build()) + .build(); +``` + +------ +#### [ C\# ] + +``` +new MyStack(app, "MyStack", new StackProps +{ + Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps + { + Qualifier = "MYQUALIFIER" + }) +}); +``` + +------ + +Or by configuring the qualifier as a context key in `cdk.json`\. + +``` +{ + "app": "...", + "context": { + "@aws-cdk/core:bootstrapQualifier": "MYQUALIFIER" + } +} +``` + +### Changing the resource names + +All the other `DefaultStackSynthesizer` properties relate to the names of the resources in the bootstrapping template\. You only need to provide any of these properties if you modified the bootstrap template and changed the resource names or naming scheme\. + +All properties accept the special placeholders `${Qualifier}`, `${AWS::Partition}`, `${AWS::AccountId}`, and `${AWS::Region}`\. These placeholders are replaced with the values of the `qualifier` parameter and with the values of the AWS partition, account ID, and region for the stack's environment, respectively\. + +The following example shows all the available properties for `DefaultStackSynthesizer` along with their default values, as if you were instantiating the synthesizer\. + +------ +#### [ TypeScript ] + +``` +new DefaultStackSynthesizer({ + // Name of the S3 bucket for file assets + fileAssetsBucketName: 'cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}', + bucketPrefix: '', + + // Name of the ECR repository for Docker image assets + imageAssetsRepositoryName: 'cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}', + + // ARN of the role assumed by the CLI and Pipeline to deploy here + deployRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}', + deployRoleExternalId: '', + + // ARN of the role used for file asset publishing (assumed from the deploy role) + fileAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}', + fileAssetPublishingExternalId: '', + + // ARN of the role used for Docker asset publishing (assumed from the deploy role) + imageAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}', + imageAssetPublishingExternalId: '', + + // ARN of the role passed to CloudFormation to execute the deployments + cloudFormationExecutionRole: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}', + + // Name of the SSM parameter which describes the bootstrap stack version number + bootstrapStackVersionSsmParameter: '/cdk-bootstrap/${Qualifier}/version', + + // Add a rule to every template which verifies the required bootstrap stack version + generateBootstrapVersionRule: true, +}) +``` + +------ +#### [ JavaScript ] + +``` +new DefaultStackSynthesizer({ + // Name of the S3 bucket for file assets + fileAssetsBucketName: 'cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}', + bucketPrefix: '', + + // Name of the ECR repository for Docker image assets + imageAssetsRepositoryName: 'cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}', + + // ARN of the role assumed by the CLI and Pipeline to deploy here + deployRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}', + deployRoleExternalId: '', + + // ARN of the role used for file asset publishing (assumed from the deploy role) + fileAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}', + fileAssetPublishingExternalId: '', + + // ARN of the role used for Docker asset publishing (assumed from the deploy role) + imageAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}', + imageAssetPublishingExternalId: '', + + // ARN of the role passed to CloudFormation to execute the deployments + cloudFormationExecutionRole: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}', + + // Name of the SSM parameter which describes the bootstrap stack version number + bootstrapStackVersionSsmParameter: '/cdk-bootstrap/${Qualifier}/version', + + // Add a rule to every template which verifies the required bootstrap stack version + generateBootstrapVersionRule: true, +}) +``` + +------ +#### [ Python ] + +``` +DefaultStackSynthesizer( + # Name of the S3 bucket for file assets + file_assets_bucket_name="cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}", + bucket_prefix="", + + # Name of the ECR repository for Docker image assets + image_assets_repository_name="cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}", + + # ARN of the role assumed by the CLI and Pipeline to deploy here + deploy_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}", + deploy_role_external_id="", + + # ARN of the role used for file asset publishing (assumed from the deploy role) + file_sset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", + file_asset_publishing_external_id="", + + # ARN of the role used for Docker asset publishing (assumed from the deploy role) + image_asset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}", + image_asset_publishing_external_id="", + + # ARN of the role passed to CloudFormation to execute the deployments + cloud_formation_execution_role="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" + + // Name of the SSM parameter which describes the bootstrap stack version number + bootstrap_stack_version_ssm_parameter="/cdk-bootstrap/${Qualifier}/version", + + // Add a rule to every template which verifies the required bootstrap stack version + generate_bootstrap_version_rule=True, +) +``` + +------ +#### [ Java ] + +``` +DefaultStackSynthesizer.Builder.create() + // Name of the S3 bucket for file assets + .fileAssetsBucketName("cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}") + .bucketPrefix('') + + // Name of the ECR repository for Docker image assets + .imageAssetsRepositoryName("cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}") + + // ARN of the role assumed by the CLI and Pipeline to deploy here + .deployRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}") + .deployRoleExternalId("") + + // ARN of the role used for file asset publishing (assumed from the deploy role) + .fileAssetPublishingRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}") + .fileAssetPublishingExternalId("") + + // ARN of the role used for Docker asset publishing (assumed from the deploy role) + .imageAssetPublishingRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}") + .imageAssetPublishingExternalId("") + + // ARN of the role passed to CloudFormation to execute the deployments + .cloudFormationExecutionRole("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}") + + // Name of the SSM parameter which describes the bootstrap stack version number + .bootstrapStackVersionSsmParameter("/cdk-bootstrap/${Qualifier}/version") + + // Add a rule to every template which verifies the required bootstrap stack version + .generateBootstrapVersionRule(true) +.build() +``` + +------ +#### [ C\# ] + +``` +new DefaultStackSynthesizer(new DefaultStackSynthesizerProps +{ + // Name of the S3 bucket for file assets + FileAssetsBucketName = "cdk-${Qualifier}-assets-${AWS::AccountId}-${AWS::Region}", + BucketPrefix = "", + + // Name of the ECR repository for Docker image assets + ImageAssetsRepositoryName = "cdk-${Qualifier}-container-assets-${AWS::AccountId}-${AWS::Region}", + + // ARN of the role assumed by the CLI and Pipeline to deploy here + DeployRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}", + DeployRoleExternalId = "", + + // ARN of the role used for file asset publishing (assumed from the deploy role) + FileAssetPublishingRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", + FileAssetPublishingExternalId = "", + + // ARN of the role used for Docker asset publishing (assumed from the deploy role) + ImageAssetPublishingRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}", + ImageAssetPublishingExternalId = "", + + // ARN of the role passed to CloudFormation to execute the deployments + CloudFormationExecutionRole = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" + + // Name of the SSM parameter which describes the bootstrap stack version number + BootstrapStackVersionSsmParameter = "/cdk-bootstrap/${Qualifier}/version", + + // Add a rule to every template which verifies the required bootstrap stack version + GenerateBootstrapVersionRule = true, +}) +``` + +------ + +## The bootstrapping template contract + +The requirements of the bootstrapping stack depend on the stack synthesizer in use\. If you write your own stack synthesizer, you have complete control of the bootstrap resources that your synthesizer requires and how the synthesizer finds them\. This section describes the expectations that the `DefaultStackSynthesizer` has of the bootstrapping template\. + +### Versioning + +The template should contain a resource to create an SSM parameter with a well\-known name and an output to reflect the template's version\. + +``` +Resources: + CdkBootstrapVersion: + Type: AWS::SSM::Parameter + Properties: + Type: String + Name: + Fn::Sub: '/cdk-bootstrap/${Qualifier}/version' + Value: 4 +Outputs: + BootstrapVersion: + Value: + Fn::GetAtt: [CdkBootstrapVersion, Value] +``` + +### Roles + +The `DefaultStackSynthesizer` requires five IAM roles for five different purposes\. If you are not using the default roles, the synthesizer needs to be told the ARNs for the roles you want to use\. The roles are: ++ The *deployment role* is assumed by the AWS CDK Toolkit and by AWS CodePipeline to deploy into an environment\. Its `AssumeRolePolicy` controls who can deploy into the environment\. The permissions this role needs can be seen in the template\. ++ The *lookup role* is assumed by the AWS CDK Toolkit to perform context lookups in an environment\. Its `AssumeRolePolicy` controls who can deploy into the environment\. The permissions this role needs can be seen in the template\. ++ The *file publishing role* and the *image publishing role* are assumed by the AWS CDK Toolkit and by AWS CodeBuild projects to publish assets into an environment: that is, to write to the S3 bucket and the ECR repository, respectively\. These roles require write access to these resources\. ++ *The AWS CloudFormation execution role* is passed to AWS CloudFormation to perform the actual deployment\. Its permissions are the permissions that the deployment will execute under\. The permissions are passed to the stack as a parameter that lists managed policy ARNs\. + +### Outputs + +The AWS CDK Toolkit requires that the following CloudFormation outputs exist on the bootstrap stack\. ++ `BucketName`: the name of the file asset bucket ++ `BucketDomainName`: the file asset bucket in domain name format ++ `BootstrapVersion`: the current version of the bootstrap stack + +### Template history + +The bootstrap template is versioned and evolves over time with the AWS CDK itself\. If you provide your own bootstrap template, keep it up\-to\-date with the canonical default template to ensure that yours continues to work with all CDK features\. This section contains a list of the changes made in each version\. + + +| Template version | AWS CDK version | Changes | +| --- | --- | --- | +| 1 | 1\.40\.0 | Initial version of template with Bucket, Key, Repository and Roles\. | +| 2 | 1\.45\.0 | Split asset publishing role into separate file and image publishing roles\. | +| 3 | 1\.46\.0 | Add FileAssetKeyArn export to be able to add decrypt permissions to asset consumers\. | +| 4 | 1\.61\.0 | KMS permissions are now implicit via S3 and no longer require FileAsetKeyArn, Add CdkBootstrapVersion SSM parameter so the bootstrap stack version can be verified without knowing the stack name\. | +| 5 | 1\.87\.0 | Deployment role can read SSM parameter\. | +| 6 | 1\.108\.0 | Add lookup role separate from deployment role\. | +| 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | +| 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | +| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | \ No newline at end of file diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md new file mode 100644 index 00000000..01ffab5d --- /dev/null +++ b/v2/cdk_pipeline.md @@ -0,0 +1,1423 @@ +# Continuous integration and delivery \(CI/CD\) using CDK Pipelines + +[CDK Pipelines](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines-readme.html) is a construct library module for painless continuous delivery of AWS CDK applications\. Whenever you check your AWS CDK app's source code in to AWS CodeCommit, GitHub, or CodeStar, CDK Pipelines can automatically build, test, and deploy your new version\. + +CDK Pipelines are self\-updating: if you add application stages or stacks, the pipeline automatically reconfigures itself to deploy those new stages and/or stacks\. + +**Note** +CDK Pipelines supports two APIs: the original API that was made available in the Developer Preview, and a modern one that incorporates feedback from CDK customers received during the preview phase\. The examples in this topic use the modern API\. For details on the differences between the two supported APIs, see [CDK Pipelines original API](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/pipelines/ORIGINAL_API.md)\. + +## Bootstrap your AWS environments + +Before you can use CDK Pipelines, you must bootstrap the AWS environment\(s\) to which you will deploy your stacks\. An [environment](environments.md) is an account/region pair to which you want to deploy a CDK stack\. A CDK Pipeline involves at least two environments: the environment where the pipeline is provisioned, and the environment where you want to deploy the application's stacks \(or its stages, which are groups of related stacks\)\. These environments can be the same, though best practices recommend you isolate stages from each other in different AWS accounts or regions\. + +**Note** +See [Bootstrapping](bootstrapping.md) for more information on the kinds of resources created by bootstrapping and how to customize the bootstrap stack\. + +You may have already bootstrapped one or more environments so you can deploy assets and Lambda functions using the AWS CDK\. Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include additional resources, so the bootstrap stack has been extended to include an additional Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. This new style of CDK Toolkit stack will eventually become the default, but at this writing, you must opt in\. The AWS CDK Toolkit will upgrade your existing bootstrap stack or create a new one, as necessary\. + +To bootstrap an environment that can provision an AWS CDK pipeline, set the environment variable `CDK_NEW_BOOTSTRAP` before invoking `cdk bootstrap`, as shown below\. Invoking the AWS CDK Toolkit via the `npx` command installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. + +\-\-cloudformation\-execution\-policies specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The default `AdministratorAccess` policy ensures that your pipeline can deploy every type of AWS resource\. If you use this policy, make sure you trust all the code and dependencies that make up your AWS CDK app\. + +Most organizations mandate stricter controls on what kinds of resources can be deployed by automation\. Check with the appropriate department within your organization to determine the policy your pipeline should use\. + +You may omit the \-\-profile option if your default AWS profile contains the necessary credentials or to instead use the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to provide your AWS account credentials\. + +------ +#### [ macOS/Linux ] + +``` +export CDK_NEW_BOOTSTRAP=1 +npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ + aws://ACCOUNT-ID/REGION +``` + +------ +#### [ Windows ] + +``` +set CDK_NEW_BOOTSTRAP=1 +npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ + aws://ACCOUNT-ID/REGION +``` + +------ + +To bootstrap additional environments into which AWS CDK applications will be deployed by the pipeline, use the commands below instead\. The \-\-trust option indicates which other account should have permissions to deploy AWS CDK applications into this environment; specify the pipeline's AWS account ID\. + +Again, you may omit the \-\-profile option if your default AWS profile contains the necessary credentials or if you are using the `AWS_*` environment variables to provide your AWS account credentials\. + +------ +#### [ macOS/Linux ] + +``` +export CDK_NEW_BOOTSTRAP=1 +npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ + --trust PIPELINE-ACCOUNT-ID \ + aws://ACCOUNT-ID/REGION +``` + +------ +#### [ Windows ] + +``` +set CDK_NEW_BOOTSTRAP=1 +npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ + --trust PIPELINE-ACCOUNT-ID ^ + aws://ACCOUNT-ID/REGION +``` + +------ + +**Tip** +Use administrative credentials only to bootstrap and to provision the initial pipeline\. Afterward, use the pipeline itself, not your local machine, to deploy changes\. + +If you are upgrading a legacy\-bootstrapped environment, the old Amazon S3 bucket is orphaned when the new bucket is created\. Delete it manually using the Amazon S3 console\. + +## Initialize project + +Create a new, empty GitHub project and clone it to your workstation in the `my-pipeline` directory\. \(Our code examples in this topic use GitHub; you can also use CodeStar or AWS CodeCommit\.\) + +``` +git clone GITHUB-CLONE-URL my-pipeline +cd my-pipeline +``` + +**Note** +You may use a name other than `my-pipeline` for your app's main directory, but since the AWS CDK Toolkit bases some file and class names on the name of the main directory, you'll need to tweak these later in this topic\. + +After cloning, initialize the project as usual\. + +------ +#### [ TypeScript ] + +``` +cdk init app --language typescript +``` + +------ +#### [ JavaScript ] + +``` +cdk init app --language javascript +``` + +------ +#### [ Python ] + +``` +cdk init app --language python +``` + +After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install the AWS CDK core dependencies\. + +``` +source .venv/bin/activate +python -m pip install -r requirements.txt +``` + +------ +#### [ Java ] + +``` +cdk init app --language java +``` + +If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set to use Java 8 \(1\.8\)\. + +------ +#### [ C\# ] + +``` +cdk init app --language csharp +``` + +If you are using Visual Studio, open the solution file in the `src` directory\. + +------ + +**Tip** +Be sure to commit your `cdk.json` and `cdk.context.json` files in source control\. The context information \(such as feature flags and cached values retrieved from your AWS account\) are part of your project's state\. The values may be different in another environment, which can cause instability \(unexpected changes\) in your results\. + +## Define a pipeline + +Your CDK Pipelines application will include at least two stacks: one that represents the pipeline itself, and one or more stacks that represent the application deployed through it\. Stacks can also be grouped into *stages*, which you can use to deploy copies of infrastructure stacks to different environments\. For now, we'll consider the pipeline, and later delve into the application it will deploy\. + +The construct [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.CodePipeline.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.CodePipeline.html) is the construct that represents a CDK Pipeline that uses AWS CodePipeline as its deployment engine\. When you instantiate `CodePipeline` in a stack, you define the source location for the pipeline \(e\.g\. a GitHub repository\) and the commands to build the app\. For example, the following defines a pipeline whose source is stored in a GitHub repository, and includes a build step for a TypeScript CDK application\. Fill in the information about your GitHub repo where indicated\. + +**Note** +By default, the pipeline authenticates to GitHub using a personal access token stored in Secrets Manager under the name `github-token`\. + +You'll also need to update the instantiation of the pipeline stack to specify the AWS account and region\. + +------ +#### [ TypeScript ] + +In `lib/my-pipeline-stack.ts` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +import * as cdk from 'aws-cdk-lib'; +import { Construct } from 'constructs'; +import { CodePipeline, CodePipelineSource, ShellStep } from 'aws-cdk-lib/pipelines'; + +export class MyPipelineStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'] + }) + }); + } +} +``` + +In `bin/my-pipeline.ts` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +#!/usr/bin/env node +import * as cdk from 'aws-cdk-lib'; +import { MyPipelineStack } from '../lib/my-pipeline-stack'; + +const app = new cdk.App(); +new MyPipelineStack(app, 'MyPipelineStack', { + env: { + account: '111111111111', + region: 'eu-west-1', + } +}); + +app.synth(); +``` + +------ +#### [ JavaScript ] + +In `lib/my-pipeline-stack.js` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +const cdk = require('aws-cdk-lib'); +const { CodePipeline, CodePipelineSource, ShellStep } = require('aws-cdk-lib/pipelines'); + + class MyPipelineStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'] + }) + }); + } +} + +module.exports = { MyPipelineStack } +``` + +In `bin/my-pipeline.js` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +#!/usr/bin/env node + +const cdk = require('aws-cdk-lib'); +const { MyPipelineStack } = require('../lib/my-pipeline-stack'); + +const app = new cdk.App(); +new MyPipelineStack(app, 'MyPipelineStack', { + env: { + account: '111111111111', + region: 'eu-west-1', + } +}); + +app.synth(); +``` + +------ +#### [ Python ] + +In `my-pipeline/my-pipeline-stack.py` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +import aws_cdk as cdk +from aws_cdk.pipelines import CodePipeline, CodePipelineSource, ShellStep + +class MyPipelineStack(cdk.Stack): + + def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + pipeline = CodePipeline(self, "Pipeline", + pipeline_name="MyPipeline", + synth=ShellStep("Synth", + input=CodePipelineSource.git_hub("OWNER/REPO", "main"), + commands=["npm install -g aws-cdk", + "python -m pip install -r requirements.txt", + "cdk synth"] + ) + ) +``` + +In `app.py`: + +``` +#!/usr/bin/env python3 +import aws_cdk as cdk +from my_pipeline.my_pipeline_stack import MyPipelineStack + +app = cdk.App() +MyPipelineStack(app, "MyPipelineStack", + env=cdk.Environment(account="111111111111", region="eu-west-1") +) + +app.synth() +``` + +------ +#### [ Java ] + +In `src/main/java/com/myorg/MyPipelineStack.java` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +package com.myorg; + +import java.util.Arrays; +import software.constructs.Construct; +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.pipelines.CodePipeline; +import software.amazon.awscdk.pipelines.CodePipelineSource; +import software.amazon.awscdk.pipelines.ShellStep; + +public class MyPipelineStack extends Stack { + public MyPipelineStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyPipelineStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + CodePipeline pipeline = CodePipeline.Builder.create(this, "pipeline") + .pipelineName("MyPipeline") + .synth(ShellStep.Builder.create("Synth") + .input(CodePipelineSource.gitHub("OWNER/REPO", "main")) + .commands(Arrays.asList("npm install -g aws-cdk", "cdk synth")) + .build()) + .build(); + } +} +``` + +In `src/main/java/com/myorg/MyPipelineApp.java` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +package com.myorg; + +import software.amazon.awscdk.App; +import software.amazon.awscdk.Environment; +import software.amazon.awscdk.StackProps; + +public class MyPipelineApp { + public static void main(final String[] args) { + App app = new App(); + + new MyPipelineStack(app, "PipelineStack", StackProps.builder() + .env(new Environment.builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build()); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +In `src/MyPipeline/MyPipelineStack.cs` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +using Amazon.CDK; +using Amazon.CDK.Pipelines; + +namespace MyPipeline +{ + public class MyPipelineStack : Stack + { + internal MyPipelineStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) + { + var pipeline = new CodePipeline(this, "pipeline", new CodePipelineProps + { + PipelineName = "MyPipeline", + Synth = new ShellStep("Synth", new ShellStepProps + { + Input = CodePipelineSource.GitHub("OWNER/REPO", "main"), + Commands = new string[] { "npm install -g aws-cdk", "cdk synth" } + }) + }); + } + } +} +``` + +In `src/MyPipeline/Program.cs` \(may vary if your project folder isn't named `my-pipeline`\): + +``` +using Amazon.CDK; + +namespace MyPipeline +{ + sealed class Program + { + public static void Main(string[] args) + { + var app = new App(); + new MyPipelineStack(app, "MyPipelineStack", new StackProps + { + Env = new Amazon.CDK.Environment { + Account = "111111111111", Region = "eu-west-1" } + }); + + app.Synth(); + } + } +} +``` + +------ + +You must deploy a pipeline manually once\. After that, the pipeline will keep itself up to date from the source code repository, so make sure the code in the repo is the code you want deployed\. Check in your changes and push to GitHub, then deploy: + +``` +git add --all +git commit -m "initial commit" +git push +cdk deploy +``` + +**Tip** +Now that you've done the initial deployment, your local AWS account no longer needs administrative access, because all changes to your app will be deployed via the pipeline\. All you need to be able to do is push to GitHub\. + +## Application stages + +To define a multi\-stack AWS application that can be added to the pipeline all at once, define a subclass of `[Stage](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stage.html)` \(not to be confused with `CdkStage` in the CDK Pipelines module\)\. + +The stage contains the stacks that make up your application\. If there are dependencies between the stacks, the stacks are automatically added to the pipeline in the right order\. Stacks that don't depend on each other are deployed in parallel\. You can add a dependency relationship between stacks by calling `stack1.addDependency(stack2)`\. + +Stages accept a default `env` argument, which becomes the default environment for the stacks inside it\. \(Stacks can still have their own environment specified\.\)\. + +An application is added to the pipeline by calling `[addStage](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.CodePipeline.html#addwbrstagestage-optionss)()` with instances of [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stage.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stage.html)\. A stage can be instantiated and added to the pipeline multiple times to define different stages of your DTAP or multi\-region application pipeline: + +We will create a stack containing a simple Lambda function and place that stack in a stage\. Then we will add the stage to the pipeline so it can be deployed\. + +------ +#### [ TypeScript ] + +Create the new file `lib/my-pipeline-lambda-stack.ts` to hold our application stack containing a Lambda function\. + +``` +import * as cdk from 'aws-cdk-lib'; +import { Construct } from 'constructs'; +import { Function, InlineCode, Runtime } from 'aws-cdk-lib/aws-lambda'; + +export class MyLambdaStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + new Function(this, 'LambdaFunction', { + runtime: Runtime.NODEJS_12_X, + handler: 'index.handler', + code: new InlineCode('exports.handler = _ => "Hello, CDK";') + }); + } +} +``` + +Create the new file `lib/my-pipeline-app-stage.ts` to hold our stage\. + +``` +import * as cdk from 'aws-cdk-lib'; +import Construct from constructs; +import { MyLambdaStack } from './my-pipeline-lambda-stack'; + +export class MyPipelineAppStage extends cdk.Stage { + + constructor(scope: Construct, id: string, props?: cdk.StageProps) { + super(scope, id, props); + + const lambdaStack = new MyLambdaStack(this, 'LambdaStack'); + } +} +``` + +Edit `lib/my-pipeline-stack.ts` to add the stage to our pipeline\. + +``` +import * as cdk from 'aws-cdk-lib'; +import { Construct } from 'constructs'; +import { CodePipeline, CodePipelineSource, ShellStep } from 'aws-cdk-lib/pipelines'; +import { MyPipelineAppStage } from './my-pipeline-app-stage'; + +export class MyPipelineStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'] + }) + }); + + pipeline.addStage(new MyPipelineAppStage(this, "test", { + env: { account: "111111111111", region: "eu-west-1" } + })); + } +} +``` + +------ +#### [ JavaScript ] + +Create the new file `lib/my-pipeline-lambda-stack.js` to hold our application stack containing a Lambda function\. + +``` +const cdk = require('aws-cdk-lib'); +const { Function, InlineCode, Runtime } = require('aws-cdk-lib/aws-lambda'); + +class MyLambdaStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new Function(this, 'LambdaFunction', { + runtime: Runtime.NODEJS_12_X, + handler: 'index.handler', + code: new InlineCode('exports.handler = _ => "Hello, CDK";') + }); + } +} + +module.exports = { MyLambdaStack } +``` + +Create the new file `lib/my-pipeline-app-stage.js` to hold our stage\. + +``` +const cdk = require('aws-cdk-lib'); +const { MyLambdaStack } = require('./my-pipeline-lambda-stack'); + +class MyPipelineAppStage extends cdk.Stage { + + constructor(scope, id, props) { + super(scope, id, props); + + const lambdaStack = new MyLambdaStack(this, 'LambdaStack'); + } +} + +module.exports = { MyPipelineAppStage }; +``` + +Edit `lib/my-pipeline-stack.ts` to add the stage to our pipeline\. + +``` +const cdk = require('aws-cdk-lib'); +const { CodePipeline, CodePipelineSource, ShellStep } = require('aws-cdk-lib/pipelines'); +const { MyPipelineAppStage } = require('./my-pipeline-app-stage'); + + class MyPipelineStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'] + }) + }); + + pipeline.addStage(new MyPipelineAppStage(this, "test", { + env: { account: "111111111111", region: "eu-west-1" } + })); + + } +} + +module.exports = { MyPipelineStack } +``` + +------ +#### [ Python ] + +Create the new file `my_pipeline/my_pipeline_lambda_stack.py` to hold our application stack containing a Lambda function\. + +``` +import aws_cdk as cdk +from constructs import Construct +from aws_cdk.aws_lambda import Function, InlineCode, Runtime + +class MyLambdaStack(cdk.Stack): + def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + Function(self, "LambdaFunction", + runtime=Runtime.NODEJS_12_X, + handler="index.handler", + code=InlineCode("exports.handler = _ => 'Hello, CDK';") + ) +``` + +Create the new file `my_pipeline/my_pipeline_app_stage.py` to hold our stage\. + +``` +import aws_cdk as cdk +from constructs import Construct +from my_pipeline.my_pipeline_lambda_stack import MyLambdaStack + +class MyPipelineAppStage(cdk.Stage): + def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + lambdaStack = MyLambdaStack(self, "LambdaStack") +``` + +Edit `my_pipeline/my_pipeline_stack.py` to add the stage to our pipeline\. + +``` +import aws_cdk as cdk +from constructs import Construct +from aws_cdk.pipelines import CodePipeline, CodePipelineSource, ShellStep +from my_pipeline.my_pipeline_app_stage import MyPipelineAppStage + +class MyPipelineStack(cdk.Stack): + + def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + pipeline = CodePipeline(self, "Pipeline", + pipeline_name="MyPipeline", + synth=ShellStep("Synth", + input=CodePipelineSource.git_hub("OWNER/REPO", "main"), + commands=["npm install -g aws-cdk", + "python -m pip install -r requirements.txt", + "cdk synth"])) + + pipeline.add_stage(MyPipelineAppStage(self, "test", + env=cdk.Environment(account="111111111111", region="eu-west-1"))) +``` + +------ +#### [ Java ] + +Create the new file `src/main/java/com.myorg/MyPipelineLambdaStack.java` to hold our application stack containing a Lambda function\. + +``` +package com.myorg; + +import software.constructs.Construct; +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; + +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.lambda.Runtime; +import software.amazon.awscdk.services.lambda.InlineCode; + +public class MyPipelineLambdaStack extends Stack { + public MyPipelineLambdaStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyPipelineLambdaStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + Function.Builder.create(this, "LambdaFunction") + .runtime(Runtime.NODEJS_12_X) + .handler("index.handler") + .code(new InlineCode("exports.handler = _ => 'Hello, CDK';")) + .build(); + + } + +} +``` + +Create the new file `src/main/java/com.myorg/MyPipelineAppStage.java` to hold our stage\. + +``` +package com.myorg; + +import software.constructs.Construct; +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.Stage; +import software.amazon.awscdk.StageProps; + +public class MyPipelineAppStage extends Stage { + public MyPipelineAppStage(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyPipelineAppStage(final Construct scope, final String id, final StageProps props) { + super(scope, id, props); + + Stack lambdaStack = new MyPipelineLambdaStack(this, "LambdaStack"); + } + +} +``` + +Edit `src/main/java/com.myorg/MyPipelineStack.java` to add the stage to our pipeline\. + +``` +package com.myorg; + +import java.util.Arrays; +import software.constructs.Construct; +import software.amazon.awscdk.Environment; +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.StageProps; +import software.amazon.awscdk.pipelines.CodePipeline; +import software.amazon.awscdk.pipelines.CodePipelineSource; +import software.amazon.awscdk.pipelines.ShellStep; + +public class MyPipelineStack extends Stack { + public MyPipelineStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyPipelineStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + final CodePipeline pipeline = CodePipeline.Builder.create(this, "pipeline") + .pipelineName("MyPipeline") + .synth(ShellStep.Builder.create("Synth") + .input(CodePipelineSource.gitHub("OWNER/REPO", "main")) + .commands(Arrays.asList("npm install -g aws-cdk", "cdk synth")) + .build()) + .build(); + + pipeline.addStage(new MyPipelineAppStage(this, "test", StageProps.builder() + .env(Environment.builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); + } +} +``` + +------ +#### [ C\# ] + +Create the new file `src/MyPipeline/MyPipelineLambdaStack.cs` to hold our application stack containing a Lambda function\. + +``` +using Amazon.CDK; +using Constructs; +using Amazon.CDK.AWS.Lambda; + +namespace MyPipeline +{ + class MyPipelineLambdaStack : Stack + { + public MyPipelineLambdaStack(Construct scope, string id, StackProps props=null) : base(scope, id, props) + { + new Function(this, "LambdaFunction", new FunctionProps + { + Runtime = Runtime.NODEJS_12_X, + Handler = "index.handler", + Code = new InlineCode("exports.handler = _ => 'Hello, CDK';") + }); + } + } +} +``` + +Create the new file `src/MyPipeline/MyPipelineAppStage.cs` to hold our stage\. + +``` +using Amazon.CDK; +using Constructs; + +namespace MyPipeline +{ + class MyPipelineAppStage : Stage + { + public MyPipelineAppStage(Construct scope, string id, StageProps props=null) : base(scope, id, props) + { + Stack lambdaStack = new MyPipelineLambdaStack(this, "LambdaStack"); + } + } +} +``` + +Edit `src/MyPipeline/MyPipelineStack.cs` to add the stage to our pipeline\. + +``` +using Amazon.CDK; +using Constructs; +using Amazon.CDK.Pipelines; + +namespace MyPipeline +{ + public class MyPipelineStack : Stack + { + internal MyPipelineStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) + { + var pipeline = new CodePipeline(this, "pipeline", new CodePipelineProps + { + PipelineName = "MyPipeline", + Synth = new ShellStep("Synth", new ShellStepProps + { + Input = CodePipelineSource.GitHub("OWNER/REPO", "main"), + Commands = new string[] { "npm install -g aws-cdk", "cdk synth" } + }) + }); + + pipeline.AddStage(new MyPipelineAppStage(this, "test", new StageProps + { + Env = new Environment + { + Account = "111111111111", Region = "eu-west-1" + } + })); + } + } +} +``` + +------ + +Every application stage added by `addStage()` results in the addition of a corresponding pipeline stage, represented by a [StageDeployment](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.StageDeployment.html) instance returned by the `addStage()` call\. You can add pre\-deployment or post\-deployment actions to the stage by calling its `addPre()` or `addPost()` method\. + +------ +#### [ TypeScript ] + +``` +// import { ManualApprovalStep } from 'aws-cdk-lib/pipelines'; + +const testingStage = pipeline.addStage(new MyPipelineAppStage(this, 'testing', { + env: { account: '111111111111', region: 'eu-west-1' } +})); + + testingStage.addPost(new ManualApprovalStep('approval')); +``` + +------ +#### [ JavaScript ] + +``` +// const { ManualApprovalStep } = require('aws-cdk-lib/pipelines'); + +const testingStage = pipeline.addStage(new MyPipelineAppStage(this, 'testing', { + env: { account: '111111111111', region: 'eu-west-1' } +})); + +testingStage.addPost(new ManualApprovalStep('approval')); +``` + +------ +#### [ Python ] + +``` +# from aws_cdk.pipelines import ManualApprovalStep + +testing_stage = pipeline.add_stage(MyPipelineAppStage(self, "testing", + env=cdk.Environment(account="111111111111", region="eu-west-1"))) + +testing_stage.add_post(ManualApprovalStep('approval')) +``` + +------ +#### [ Java ] + +``` +// import software.amazon.awscdk.pipelines.StageDeployment; +// import software.amazon.awscdk.pipelines.ManualApprovalStep; + +StageDeployment testingStage = + pipeline.addStage(new MyPipelineAppStage(this, "test", StageProps.builder() + .env(Environment.builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); + +testingStage.addPost(new ManualApprovalStep("approval")); +``` + +------ +#### [ C\# ] + +``` +var testingStage = pipeline.AddStage(new MyPipelineAppStage(this, "test", new StageProps +{ + Env = new Environment + { + Account = "111111111111", Region = "eu-west-1" + } +})); + +testingStage.AddPost(new ManualApprovalStep("approval")); +``` + +------ + +You can add stages to a [Wave](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.Wave.html) to deploy them in parallel, for example when deploying a stage to multiple accounts or regions\. + +------ +#### [ TypeScript ] + +``` +const wave = pipeline.addWave('wave'); +wave.addStage(new MyApplicationStage(this, 'MyAppEU', { + env: { account: '111111111111', region: 'eu-west-1' } +})); +wave.addStage(new MyApplicationStage(this, 'MyAppUS', { + env: { account: '111111111111', region: 'us-west-1' } +})); +``` + +------ +#### [ JavaScript ] + +``` +const wave = pipeline.addWave('wave'); +wave.addStage(new MyApplicationStage(this, 'MyAppEU', { + env: { account: '111111111111', region: 'eu-west-1' } +})); +wave.addStage(new MyApplicationStage(this, 'MyAppUS', { + env: { account: '111111111111', region: 'us-west-1' } +})); +``` + +------ +#### [ Python ] + +``` +wave = pipeline.add_wave("wave") +wave.add_stage(MyApplicationStage(self, "MyAppEU", + env=cdk.Environment(account="111111111111", region="eu-west-1"))) +wave.add_stage(MyApplicationStage(self, "MyAppUS", + env=cdk.Environment(account="111111111111", region="us-west-1"))) +``` + +------ +#### [ Java ] + +``` +// import software.amazon.awscdk.pipelines.Wave; +final Wave wave = pipeline.addWave("wave"); +wave.addStage(new MyPipelineAppStage(this, "MyAppEU", StageProps.builder() + .env(Environment.builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); +wave.addStage(new MyPipelineAppStage(this, "MyAppUS", StageProps.builder() + .env(Environment.builder() + .account("111111111111") + .region("us-west-1") + .build()) + .build())); +``` + +------ +#### [ C\# ] + +``` +var wave = pipeline.AddWave("wave"); +wave.AddStage(new MyPipelineAppStage(this, "MyAppEU", new StageProps +{ + Env = new Environment + { + Account = "111111111111", Region = "eu-west-1" + } +})); +wave.AddStage(new MyPipelineAppStage(this, "MyAppUS", new StageProps +{ + Env = new Environment + { + Account = "111111111111", Region = "us-west-1" + } +})); +``` + +------ + +## Testing deployments + +You can add steps to a CDK Pipeline to validate the deployments you are performing\. Using the CDK Pipeline library's `[ShellStep](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.ShellStep.html)`, you can try to access a just\-deployed Amazon API Gateway backed by a Lambda function, for example, or issue an AWS CLI command to check some setting of a deployed resource\. + +In its simplest form, adding validation actions looks like this: + +------ +#### [ TypeScript ] + +``` +// stage was returned by pipeline.addStage + +stage.addPost(new ShellStep("validate", { + commands: ['curl -Ssf https://my.webservice.com/'], +})); +``` + +------ +#### [ JavaScript ] + +``` +// stage was returned by pipeline.addStage + +stage.addPost(new ShellStep("validate", { + commands: ['curl -Ssf https://my.webservice.com/'], +})); +``` + +------ +#### [ Python ] + +``` +# stage was returned by pipeline.add_stage + +stage.add_post(ShellStep("validate", + commands=['curl -Ssf https://my.webservice.com/'] +)) +``` + +------ +#### [ Java ] + +``` +// stage was returned by pipeline.addStage + +stage.addPost(ShellStep.Builder.create("validate") + .commands(Arrays.asList("curl -Ssf https://my.webservice.com/")) + .build()); +``` + +------ +#### [ C\# ] + +``` +// stage was returned by pipeline.addStage + +stage.AddPost(new ShellStep("validate", new ShellStepProps +{ + Commands = new string[] { "curl -Ssf https://my.webservice.com/" } +})); +``` + +------ + +Because many AWS CloudFormation deployments result in the generation of resources with unpredictable names, CDK Pipelines provide a way to read AWS CloudFormation outputs after a deployment\. This makes it possible to pass \(for example\) the generated URL of a load balancer to a test action\. + +To use outputs, expose the `CfnOutput` object you're interested in and pass it in a step's `envFromCfnOutputs` property to make it available as an environment variable within that step\. + +------ +#### [ TypeScript ] + +``` +// given a stack lbStack that exposes a load balancer construct as loadBalancer +this.loadBalancerAddress = new cdk.CfnOutput(lbStack, 'LbAddress', { + value: `https://${lbStack.loadBalancer.loadBalancerDnsName}/` +}); + +// pass the load balancer address to a shell step +stage.addPost(new ShellStep("lbaddr", { + envFromCfnOutputs: {lb_addr: lbStack.loadBalancerAddress}, + commands: ['echo $lb_addr'] +})); +``` + +------ +#### [ JavaScript ] + +``` +// given a stack lbStack that exposes a load balancer construct as loadBalancer +this.loadBalancerAddress = new cdk.CfnOutput(lbStack, 'LbAddress', { + value: `https://${lbStack.loadBalancer.loadBalancerDnsName}/` +}); + +// pass the load balancer address to a shell step +stage.addPost(new ShellStep("lbaddr", { + envFromCfnOutputs: {lb_addr: lbStack.loadBalancerAddress}, + commands: ['echo $lb_addr'] +})); +``` + +------ +#### [ Python ] + +``` +# given a stack lb_stack that exposes a load balancer construct as load_balancer +self.load_balancer_address = cdk.CfnOutput(lb_stack, "LbAddress", + value=f"https://{lb_stack.load_balancer.load_balancer_dns_name}/") + +# pass the load balancer address to a shell step +stage.add_post(ShellStep("lbaddr", + env_from_cfn_outputs={"lb_addr": lb_stack.load_balancer_address} + commands=["echo $lb_addr"])) +``` + +------ +#### [ Java ] + +``` +// given a stack lbStack that exposes a load balancer construct as loadBalancer +loadBalancerAddress = CfnOutput.Builder.create(lbStack, "LbAddress") + .value(String.format("https://%s/", + lbStack.loadBalancer.loadBalancerDnsName)) + .build(); + +stage.addPost(ShellStep.Builder.create("lbaddr") + .envFromCfnOutputs(new HashMap() {{ + put("lbAddr", loadBalancerAddress); }}) + .commands(Arrays.asList("echo $lbAddr")) + .build()); +``` + +------ +#### [ C\# ] + +``` +// given a stack lbStack that exposes a load balancer construct as loadBalancer +loadBalancerAddress = new CfnOutput(lbStack, "LbAddress", new CfnOutputProps +{ + Value = string.Format("https://{0}/", lbStack.loadBalancer.LoadBalancerDnsName) +}); + +stage.AddPost(new ShellStep("lbaddr", new ShellStepProps +{ + EnvFromCfnOutputs = new Dictionary + { + { "lbAddr", loadBalancerAddress } + }, + Commands = new string[] { "echo $lbAddr" } +})); +``` + +------ + +You can write simple validation tests right in the `ShellStep`, but this approach becomes unwieldy when the test is more than a few lines\. For more complex tests, you can bring additional files \(such as complete shell scripts, or programs in other languages\) into the `ShellStep` via the `inputs` property\. The inputs can be any step that has an output, including a source \(such as a GitHub repo\) or another `ShellStep`\. + +Bringing in files from the source repository is appropriate if the files are directly usable in the test \(for example, if they are themselves executable\)\. In this example, we declare our GitHub repo as `source` \(rather than instantiating it inline as part of the `CodePipeline`\), then pass this fileset to both the pipeline and the validation test\. + +------ +#### [ TypeScript ] + +``` +const source = CodePipelineSource.gitHub('OWNER/REPO', 'main'); + +const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: source, + commands: ['npm ci', 'npm run build', 'npx cdk synth'] + }) +}); + +const stage = pipeline.addStage(new MyPipelineAppStage(this, 'test', { + env: { account: '111111111111', region: 'eu-west-1' } +})); + +stage.addPost(new ShellStep('validate', { + input: source, + commands: ['sh ./tests/validate.sh'] +})); +``` + +------ +#### [ JavaScript ] + +``` +const source = CodePipelineSource.gitHub('OWNER/REPO', 'main'); + +const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: new ShellStep('Synth', { + input: source, + commands: ['npm ci', 'npm run build', 'npx cdk synth'] + }) +}); + +const stage = pipeline.addStage(new MyPipelineAppStage(this, 'test', { + env: { account: '111111111111', region: 'eu-west-1' } +})); + +stage.addPost(new ShellStep('validate', { + input: source, + commands: ['sh ./tests/validate.sh'] +})); +``` + +------ +#### [ Python ] + +``` +source = CodePipelineSource.git_hub("OWNER/REPO", "main") + +pipeline = CodePipeline(self, "Pipeline", + pipeline_name="MyPipeline", + synth=ShellStep("Synth", + input=source, + commands=["npm install -g aws-cdk", + "python -m pip install -r requirements.txt", + "cdk synth"])) + +stage = pipeline.add_stage(MyApplicationStage(self, "test", + env=cdk.Environment(account="111111111111", region="eu-west-1"))) + +stage.add_post(ShellStep("validate", input=source, + commands=["curl -Ssf https://my.webservice.com/"], +)) +``` + +------ +#### [ Java ] + +``` +final CodePipelineSource source = CodePipelineSource.gitHub("OWNER/REPO", "main"); + +final CodePipeline pipeline = CodePipeline.Builder.create(this, "pipeline") + .pipelineName("MyPipeline") + .synth(ShellStep.Builder.create("Synth") + .input(source) + .commands(Arrays.asList("npm install -g aws-cdk", "cdk synth")) + .build()) + .build(); + +final StageDeployment stage = + pipeline.addStage(new MyPipelineAppStage(this, "test", StageProps.builder() + .env(Environment.builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); + +stage.addPost(ShellStep.Builder.create("validate") + .input(source) + .commands(Arrays.asList("sh ./tests/validate.sh")) + .build()); +``` + +------ +#### [ C\# ] + +``` +var source = CodePipelineSource.GitHub("OWNER/REPO", "main"); + +var pipeline = new CodePipeline(this, "pipeline", new CodePipelineProps +{ + PipelineName = "MyPipeline", + Synth = new ShellStep("Synth", new ShellStepProps + { + Input = source, + Commands = new string[] { "npm install -g aws-cdk", "cdk synth" } + }) +}); + +var stage = pipeline.AddStage(new MyPipelineAppStage(this, "test", new StageProps +{ + Env = new Environment + { + Account = "111111111111", Region = "eu-west-1" + } +})); + +stage.AddPost(new ShellStep("validate", new ShellStepProps +{ + Input = source, + Commands = new string[] { "sh ./tests/validate.sh" } +})); +``` + +------ + +Getting the additional files from the synth step is appropriate if your tests need to be compiled, which is done as part of synthesis\. + +------ +#### [ TypeScript ] + +``` +const synthStep = new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'], +}); + +const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: synthStep +}); + +const stage = pipeline.addStage(new MyPipelineAppStage(this, 'test', { + env: { account: '111111111111', region: 'eu-west-1' } +})); + +// run a script that was transpiled from TypeScript during synthesis +stage.addPost(new ShellStep('validate', { + input: synthStep, + commands: ['node tests/validate.js'] +})); +``` + +------ +#### [ JavaScript ] + +``` +const synthStep = new ShellStep('Synth', { + input: CodePipelineSource.gitHub('OWNER/REPO', 'main'), + commands: ['npm ci', 'npm run build', 'npx cdk synth'], +}); + +const pipeline = new CodePipeline(this, 'Pipeline', { + pipelineName: 'MyPipeline', + synth: synthStep +}); + +const stage = pipeline.addStage(new MyPipelineAppStage(this, "test", { + env: { account: "111111111111", region: "eu-west-1" } +})); + +// run a script that was transpiled from TypeScript during synthesis +stage.addPost(new ShellStep('validate', { + input: synthStep, + commands: ['node tests/validate.js'] +})); +``` + +------ +#### [ Python ] + +``` +synth_step = ShellStep("Synth", + input=CodePipelineSource.git_hub("OWNER/REPO", "main"), + commands=["npm install -g aws-cdk", + "python -m pip install -r requirements.txt", + "cdk synth"]) + +pipeline = CodePipeline(self, "Pipeline", + pipeline_name="MyPipeline", + synth=synth_step) + +stage = pipeline.add_stage(MyApplicationStage(self, "test", + env=cdk.Environment(account="111111111111", region="eu-west-1"))) + +# run a script that was compiled during synthesis +stage.add_post(ShellStep("validate", + input=synth_step, + commands=["node test/validate.js"], +)) +``` + +------ +#### [ Java ] + +``` +final ShellStep synth = ShellStep.Builder.create("Synth") + .input(CodePipelineSource.gitHub("OWNER/REPO", "main")) + .commands(Arrays.asList("npm install -g aws-cdk", "cdk synth")) + .build(); + +final CodePipeline pipeline = CodePipeline.Builder.create(this, "pipeline") + .pipelineName("MyPipeline") + .synth(synth) + .build(); + +final StageDeployment stage = + pipeline.addStage(new MyPipelineAppStage(this, "test", StageProps.builder() + .env(Environment.builder() + .account("111111111111") + .region("eu-west-1") + .build()) + .build())); + +stage.addPost(ShellStep.Builder.create("validate") + .input(synth) + .commands(Arrays.asList("node ./tests/validate.js")) + .build()); +``` + +------ +#### [ C\# ] + +``` +var synth = new ShellStep("Synth", new ShellStepProps +{ + Input = CodePipelineSource.GitHub("OWNER/REPO", "main"), + Commands = new string[] { "npm install -g aws-cdk", "cdk synth" } +}); + +var pipeline = new CodePipeline(this, "pipeline", new CodePipelineProps +{ + PipelineName = "MyPipeline", + Synth = synth +}); + +var stage = pipeline.AddStage(new MyPipelineAppStage(this, "test", new StageProps +{ + Env = new Environment + { + Account = "111111111111", Region = "eu-west-1" + } +})); + +stage.AddPost(new ShellStep("validate", new ShellStepProps +{ + Input = synth, + Commands = new string[] { "node ./tests/validate.js" } +})); +``` + +------ + +## Security notes + +Any form of continuous delivery has inherent security risks\. Under the AWS [Shared Responsibility Model](https://aws.amazon.com/compliance/shared-responsibility-model/), you are responsible for the security of your information in the AWS cloud\. The CDK Pipelines library gives you a head start by incorporating secure defaults and modeling best practices, but by its very nature a library that needs a high level of access to fulfill its intended purpose cannot assure complete security\. There are many attack vectors outside of AWS and your organization\. + +In particular, keep in mind the following\. ++ Be mindful of the software you depend on\. Vet all third\-party software you run in your pipeline, as it has the ability to change the infrastructure that gets deployed\. ++ Use dependency locking to prevent accidental upgrades\. CDK Pipelines respects `package-lock.json` and `yarn.lock` to ensure your dependencies are the ones you expect\. ++ Credentials for production environments should be short\-lived\. After bootstrapping and initial provisioning, there is no need for developers to have account credentials at all; changes can be deployed through the pipeline\. Eliminate the possibility of credentials leaking by not needing them in the first place\! + +## Troubleshooting + +The following issues are commonly encountered while getting started with CDK Pipelines\. + +**Pipeline: Internal Failure** + +``` +CREATE_FAILED | AWS::CodePipeline::Pipeline | Pipeline/Pipeline +Internal Failure +``` + Check your GitHub access token\. It might be missing, or might not have the permissions to access the repository\. + +**Key: Policy contains a statement with one or more invalid principals** + +``` +CREATE_FAILED | AWS::KMS::Key | Pipeline/Pipeline/ArtifactsBucketEncryptionKey +Policy contains a statement with one or more invalid principals. +``` + One of the target environments has not been bootstrapped with the new bootstrap stack\. Make sure all your target environments are bootstrapped\. + +**Stack is in ROLLBACK\_COMPLETE state and can not be updated\.** + +``` +Stack STACK_NAME is in ROLLBACK_COMPLETE state and can not be updated. (Service: +AmazonCloudFormation; Status Code: 400; Error Code: ValidationError; Request +ID: ...) +``` +The stack failed its previous deployment and is in a non\-retryable state\. Delete the stack from the AWS CloudFormation console and retry the deployment\. \ No newline at end of file diff --git a/v2/cfn_layer.md b/v2/cfn_layer.md new file mode 100644 index 00000000..3badc196 --- /dev/null +++ b/v2/cfn_layer.md @@ -0,0 +1,443 @@ +# Escape hatches + +It's possible that neither the high\-level constructs nor the low\-level CFN Resource constructs have a specific feature you are looking for\. There are three possible reasons for this lack of functionality: ++ The AWS service feature is available through AWS CloudFormation, but there are no Construct classes for the service\. ++ The AWS service feature is available through AWS CloudFormation, and there are Construct classes for the service, but the Construct classes don't yet expose the feature\. ++ The feature is not yet available through AWS CloudFormation\. + +To determine whether a feature is available through AWS CloudFormation, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. + +## Using AWS CloudFormation constructs directly + +If there are no Construct classes available for the service, you can fall back to the automatically generated CFN Resources, which map 1:1 onto all available AWS CloudFormation resources and properties\. These resources can be recognized by their name starting with `Cfn`, such as `CfnBucket` or `CfnRole`\. You instantiate them exactly as you would use the equivalent AWS CloudFormation resource\. For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. + +For example, to instantiate a low\-level Amazon S3 bucket CFN Resource with analytics enabled, you would write something like the following\. + +------ +#### [ TypeScript ] + +``` +new s3.CfnBucket(this, 'MyBucket', { + analyticsConfigurations: [ + { + id: 'Config', + // ... + } + ] +}); +``` + +------ +#### [ JavaScript ] + +``` +new s3.CfnBucket(this, 'MyBucket', { + analyticsConfigurations: [ + { + id: 'Config' + // ... + } + ] +}); +``` + +------ +#### [ Python ] + +``` +s3.CfnBucket(self, "MyBucket", + analytics_configurations: [ + dict(id="Config", + # ... + ) + ] +) +``` + +------ +#### [ Java ] + +``` +CfnBucket.Builder.create(this, "MyBucket") + .analyticsConfigurations(Arrays.asList(new HashMap() {{ + put("id", "Config"); + // ... + }})).build(); +``` + +------ +#### [ C\# ] + +``` +new CfnBucket(this, 'MyBucket', new CfnBucketProps { + AnalyticsConfigurations = new Dictionary + { + ["id"] = "Config", + // ... + } +}); +``` + +------ + +In the rare case where you want to define a resource that doesn't have a corresponding `CfnXxx` class, such as a new resource type that hasn't yet been published in the AWS CloudFormation resource specification, you can instantiate the `cdk.CfnResource` directly and specify the resource type and properties\. This is shown in the following example\. + +------ +#### [ TypeScript ] + +``` +new cdk.CfnResource(this, 'MyBucket', { + type: 'AWS::S3::Bucket', + properties: { + // Note the PascalCase here! These are CloudFormation identifiers. + AnalyticsConfigurations: [ + { + Id: 'Config', + // ... + } + ] + } +}); +``` + +------ +#### [ JavaScript ] + +``` +new cdk.CfnResource(this, 'MyBucket', { + type: 'AWS::S3::Bucket', + properties: { + // Note the PascalCase here! These are CloudFormation identifiers. + AnalyticsConfigurations: [ + { + Id: 'Config' + // ... + } + ] + } +}); +``` + +------ +#### [ Python ] + +``` +cdk.CfnResource(self, 'MyBucket', + type="AWS::S3::Bucket", + properties=dict( + # Note the PascalCase here! These are CloudFormation identifiers. + "AnalyticsConfigurations": [ + { + "Id": "Config", + # ... + } + ] + } +) +``` + +------ +#### [ Java ] + +``` +CfnResource.Builder.create(this, "MyBucket") + .type("AWS::S3::Bucket") + .properties(new HashMap() {{ + // Note the PascalCase here! These are CloudFormation identifiers + put("AnalyticsConfigurations", Arrays.asList( + new HashMap() {{ + put("Id", "Config"); + // ... + }})); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +new CfnResource(this, "MyBucket", new CfnResourceProps +{ + Type = "AWS::S3::Bucket", + Properties = new Dictionary + { // Note the PascalCase here! These are CloudFormation identifiers + ["AnalyticsConfigurations"] = new List> + { + new Dictionary { + ["Id"] = "Config" + } + } + } +}); +``` + +------ + +For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. + +## Modifying the AWS CloudFormation resource behind AWS constructs + +If a Construct is missing a feature or you are trying to work around an issue, you can modify the CFN Resource that is encapsulated by the Construct\. + +All Constructs contain within them the corresponding CFN Resource\. For example, the high\-level `Bucket` construct wraps the low\-level `CfnBucket` construct\. Because the `CfnBucket` corresponds directly to the AWS CloudFormation resource, it exposes all features that are available through AWS CloudFormation\. + +The basic approach to get access to the CFN Resource class is to use `construct.node.defaultChild` \(Python: `default_child`\), cast it to the right type \(if necessary\), and modify its properties\. Again, let's take the example of a `Bucket`\. + +------ +#### [ TypeScript ] + +``` +// Get the CloudFormation resource +const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; + +// Change its properties +cfnBucket.analyticsConfiguration = [ + { + id: 'Config', + // ... + } +]; +``` + +------ +#### [ JavaScript ] + +``` +// Get the CloudFormation resource +const cfnBucket = bucket.node.defaultChild; + +// Change its properties +cfnBucket.analyticsConfiguration = [ + { + id: 'Config' + // ... + } +]; +``` + +------ +#### [ Python ] + +``` +# Get the CloudFormation resource +cfn_bucket = bucket.node.default_child + +# Change its properties +cfn_bucket.analytics_configuration = [ + { + "id": "Config", + # ... + } +] +``` + +------ +#### [ Java ] + +``` +// Get the CloudFormation resource +CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); + +cfnBucket.setAnalyticsConfigurations( + Arrays.asList(new HashMap() {{ + put("Id", "Config"); + // ... + }})); +``` + +------ +#### [ C\# ] + +``` +// Get the CloudFormation resource +var cfnBucket = (CfnBucket)bucket.Node.DefaultChild; + +cfnBucket.AnalyticsConfigurations = new List { + new Dictionary + { + ["Id"] = "Config", + // ... + } +}; +``` + +------ + +You can also use this object to change AWS CloudFormation options such as `Metadata` and `UpdatePolicy`\. + +------ +#### [ TypeScript ] + +``` +cfnBucket.cfnOptions.metadata = { + MetadataKey: 'MetadataValue' +}; +``` + +------ +#### [ JavaScript ] + +``` +cfnBucket.cfnOptions.metadata = { + MetadataKey: 'MetadataValue' +}; +``` + +------ +#### [ Python ] + +``` +cfn_bucket.cfn_options.metadata = { + "MetadataKey": "MetadataValue" +} +``` + +------ +#### [ Java ] + +``` +cfnBucket.getCfnOptions().setMetadata(new HashMap() {{ + put("MetadataKey", "Metadatavalue"); +}}); +``` + +------ +#### [ C\# ] + +``` +cfnBucket.CfnOptions.Metadata = new Dictionary +{ + ["MetadataKey"] = "Metadatavalue" +}; +``` + +------ + +## Raw overrides + +If there are properties that are missing from the CFN Resource, you can bypass all typing using raw overrides\. This also makes it possible to delete synthesized properties\. + +Use one of the `addOverride` methods \(Python: `add_override`\) methods, as shown in the following example\. + +------ +#### [ TypeScript ] + +``` +// Get the CloudFormation resource +const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; + +// Use dot notation to address inside the resource template fragment +cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); +cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); + +// use index (0 here) to address an element of a list +cfnBucket.addOverride('Properties.Tags.0.Value', 'NewValue'); +cfnBucket.addDeletionOverride('Properties.Tags.0'); + +// addPropertyOverride is a convenience function for paths starting with "Properties." +cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); +cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); +cfnBucket.addPropertyOverride('Tags.0.Value', 'NewValue'); +cfnBucket.addPropertyDeletionOverride('Tags.0'); +``` + +------ +#### [ JavaScript ] + +``` +// Get the CloudFormation resource +const cfnBucket = bucket.node.defaultChild ; + +// Use dot notation to address inside the resource template fragment +cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); +cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); + +// use index (0 here) to address an element of a list +cfnBucket.addOverride('Properties.Tags.0.Value', 'NewValue'); +cfnBucket.addDeletionOverride('Properties.Tags.0'); + +// addPropertyOverride is a convenience function for paths starting with "Properties." +cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); +cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); +cfnBucket.addPropertyOverride('Tags.0.Value', 'NewValue'); +cfnBucket.addPropertyDeletionOverride('Tags.0'); +``` + +------ +#### [ Python ] + +``` +# Get the CloudFormation resource +cfn_bucket = bucket.node.default_child + +# Use dot notation to address inside the resource template fragment +cfn_bucket.add_override("Properties.VersioningConfiguration.Status", "NewStatus") +cfn_bucket.add_deletion_override("Properties.VersioningConfiguration.Status") + +# use index (0 here) to address an element of a list +cfn_bucket.add_override("Properties.Tags.0.Value", "NewValue") +cfn_bucket.add_deletion_override("Properties.Tags.0") + +# addPropertyOverride is a convenience function for paths starting with "Properties." +cfn_bucket.add_property_override("VersioningConfiguration.Status", "NewStatus") +cfn_bucket.add_property_deletion_override("VersioningConfiguration.Status") +cfn_bucket.add_property_override("Tags.0.Value", "NewValue") +cfn_bucket.add_property_deletion_override("Tags.0") +``` + +------ +#### [ Java ] + +``` +// Get the CloudFormation resource +CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); + +// Use dot notation to address inside the resource template fragment +cfnBucket.addOverride("Properties.VersioningConfiguration.Status", "NewStatus"); +cfnBucket.addDeletionOverride("Properties.VersioningConfiguration.Status"); + +// use index (0 here) to address an element of a list +cfnBucket.addOverride("Properties.Tags.0.Value", "NewValue"); +cfnBucket.addDeletionOverride("Properties.Tags.0"); + +// addPropertyOverride is a convenience function for paths starting with "Properties." +cfnBucket.addPropertyOverride("VersioningConfiguration.Status", "NewStatus"); +cfnBucket.addPropertyDeletionOverride("VersioningConfiguration.Status"); +cfnBucket.addPropertyOverride("Tags.0.Value", "NewValue"); +cfnBucket.addPropertyDeletionOverride("Tags.0"); +``` + +------ +#### [ C\# ] + +``` +// Get the CloudFormation resource +var cfnBucket = (CfnBucket)bucket.node.defaultChild; + +// Use dot notation to address inside the resource template fragment +cfnBucket.AddOverride("Properties.VersioningConfiguration.Status", "NewStatus"); +cfnBucket.AddDeletionOverride("Properties.VersioningConfiguration.Status"); + +// use index (0 here) to address an element of a list +cfnBucket.AddOverride("Properties.Tags.0.Value", "NewValue"); +cfnBucket.AddDeletionOverride("Properties.Tags.0"); + +// addPropertyOverride is a convenience function for paths starting with "Properties." +cfnBucket.AddPropertyOverride("VersioningConfiguration.Status", "NewStatus"); +cfnBucket.AddPropertyDeletionOverride("VersioningConfiguration.Status"); +cfnBucket.AddPropertyOverride("Tags.0.Value", "NewValue"); +cfnBucket.AddPropertyDeletionOverride("Tags.0"); +``` + +------ + +## Custom resources + +If the feature isn't available through AWS CloudFormation, but only through a direct API call, the only solution is to write an AWS CloudFormation Custom Resource to make the API call you need\. Don't worry, the AWS CDK makes it easier to write these, and wrap them up into a regular construct interface, so from another user's perspective the feature feels native\. + +Building a custom resource involves writing a Lambda function that responds to a resource's CREATE, UPDATE and DELETE lifecycle events\. If your custom resource needs to make only a single API call, consider using the [AwsCustomResource](https://github.com/awslabs/aws-cdk/tree/master/packages/%40aws-cdk/custom-resources)\. This makes it possible to perform arbitrary SDK calls during an AWS CloudFormation deployment\. Otherwise, you should write your own Lambda function to perform the work you need to get done\. + +The subject is too broad to completely cover here, but the following links should get you started: ++ [Custom Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) ++ [Custom\-Resource Example](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) ++ For a more fully fledged example, see the [DnsValidatedCertificate](https://github.com/awslabs/aws-cdk/blob/master/packages/@aws-cdk/aws-certificatemanager/lib/dns-validated-certificate.ts) class in the CDK standard library\. This is implemented as a custom resource\. \ No newline at end of file diff --git a/v2/cli.md b/v2/cli.md new file mode 100644 index 00000000..a030077a --- /dev/null +++ b/v2/cli.md @@ -0,0 +1,924 @@ +# AWS CDK Toolkit \(`cdk` command\) + +The AWS CDK Toolkit, the CLI command `cdk`, is the primary tool for interacting with your AWS CDK app\. It executes your app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK\. It also provides other features useful for creating and working with AWS CDK projects\. This topic contains information about common use cases of the CDK Toolkit\. + +The AWS CDK Toolkit is installed with the Node Package Manager\. In most cases, we recommend installing it globally\. + +``` +npm install -g aws-cdk # install latest version +npm install -g aws-cdk@X.YY.Z # install specific version +``` + +**Tip** +If you regularly work with multiple versions of the AWS CDK, you may want to install a matching version of the AWS CDK Toolkit in individual CDK projects\. To do this, omit `-g` from the `npm install` command\. Then use `npx aws-cdk` to invoke it; this will run the local version if one exists, falling back to a global version if not\. + +## Toolkit commands + +All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(`list`, `synthesize`, `deploy`, etc\.\)\. Some subcommands have a shorter version \(`ls`, `synth`, etc\.\) that is equivalent\. Options and arguments follow the subcommand in any order\. The available commands are summarized here\. + + +| Command | Function | +| --- | --- | +| `cdk list` \(`ls`\) | Lists the stacks in the app | +| `cdk synthesize` \(`synth`\) | Synthesizes and prints the CloudFormation template for the specified stack\(s\) | +| `cdk bootstrap` | Deploys the CDK Toolkit staging stack; see [Bootstrapping](bootstrapping.md) | +| `cdk deploy` | Deploys the specified stack\(s\) | +| `cdk destroy` | Destroys the specified stack\(s\) | +| `cdk diff` | Compares the specified stack with the deployed stack or a local CloudFormation template | +| `cdk metadata` | Displays metadata about the specified stack | +| `cdk init` | Creates a new CDK project in the current directory from a specified template | +| `cdk context` | Manages cached context values | +| `cdk docs` \(`doc`\) | Opens the CDK API reference in your browser | +| `cdk doctor` | Checks your CDK project for potential problems | + +For the options available for each command, see [Toolkit reference](#cli-ref) or [Built\-in help](#cli-help)\. + +## Specifying options and their values + +Command line options begin with two hyphens \(`--`\)\. Some frequently\-used options have single\-letter synonyms that begin with a single hyphen \(for example, `--app` has a synonym `-a`\)\. The order of options in an AWS CDK Toolkit command is not important\. + +All options accept a value, which must follow the option name\. The value may be separated from the name by whitespace or by an equals sign `=`\. The following two options are equivalent + +``` +--toolkit-stack-name MyBootstrapStack +--toolkit-stack-name=MyBootstrapStack +``` + +Some options are flags \(Booleans\)\. You may specify `true` or `false` as their value\. If you do not provide a value, the value is taken to be `true`\. You may also prefix the option name with `no-` to imply `false`\. + +``` +# sets staging flag to true +--staging +--staging=true +--staging true + +# sets staging flag to false +--no-staging +--staging=false +--staging false +``` + +A few flags, namely `--context`, `--parameters`, `--plugin`, `--tags`, and `--trust`, may be specified more than once to specify multiple values\. These are noted as having `[array]` type in the CDK Toolkit help\. For example: + +``` +cdk bootstrap --tags costCenter=0123 --tags responsibleParty=jdoe +``` + +## Built\-in help + +The AWS CDK Toolkit has integrated help\. You can see general help about the utility and a list of the provided subcommands by issuing: + +``` +cdk --help +``` + +To see help for a particular subcommand, for example `deploy`, specify it before the `--help` flag\. + +``` +cdk deploy --help +``` + +Issue `cdk version` to display the version of the AWS CDK Toolkit\. Provide this information when requesting support\. + +## Version reporting + +To gain insight into how the AWS CDK is used, the constructs used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used by AWS to identify stacks using a construct with known security or reliability issues, and to contact their users with important information\. + +**Note** +Prior to version 1\.93\.0, the AWS CDK reported the names and versions of the modules loaded during synthesis, rather than the constructs used in the stack\. + +By default, the AWS CDK reports the use of constructs in the following NPM modules that are used in the stack: ++ AWS CDK core module ++ AWS Construct Library modules ++ AWS Solutions Constructs module ++ AWS Render Farm Deployment Kit module + +The `AWS::CDK::Metadata` resource looks something like the following\. + +``` +CDKMetadata: + Type: "AWS::CDK::Metadata" + Properties: + Analytics: "v2:deflate64:H4sIAND9SGAAAzXKSw5AMBAA0L1b2PdzBYnEAdio3RglglY60zQi7u6TWL/XKmNUlxeQSOKwaPTBqrNhwEWU3hGHiCzK0dWWfAxoL/Fd8mvk+QkS/0X6BdjnCdgmOOQKWz+AqqLDt2Y3YMnLYWwAAAA=" +``` + +The `Analytics` property is a gzipped, base64\-encoded, prefix\-encoded list of the constructs present in the stack\. + +To opt out of version reporting, use one of the following methods: ++ Use the cdk command with the \-\-no\-version\-reporting argument to opt out for a single command\. + + ``` + cdk --no-version-reporting synth + ``` + + Remember, the AWS CDK Toolkit synthesizes fresh templates before deploying, so you should also add `--no-version-reporting` to `cdk deploy` commands\. ++ Set versionReporting to **false** in `./cdk.json` or `~/.cdk.json`\. This opts out unless you opt in by specifying `--version-reporting` on an individual command\. + + ``` + { + "app": "...", + "versionReporting": false + } + ``` + +## Specifying credentials and region + +The CDK Toolkit needs to know your AWS account credentials and the AWS region into which you are deploying, not only for deployment operations but also to retrieve context values during synthesis\. Together, your account and region make up the *environment*\. + +**Important** +We strongly recommend against using your main AWS account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. + +Credentials and region may be specified using environment variables or in configuration files\. These are the same variables and files used by other AWS tools such as the AWS CLI and the various AWS SDKs\. The CDK Toolkit looks for this information in the following order\. ++ The `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` environment variables\. Always specify all three variables, not just one or two\. ++ A specific profile defined in the standard AWS `config` and `credentials` files, and specified using the `--profile` option on `cdk` commands\. ++ The `[default]` section of the standard AWS `config` and `credentials` files\. + +**Note** +The standard AWS `config` and `credentials` files are located at `~/.aws/config` and `~/.aws/credentials` \(macOS/Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\)\. + +The environment specified in your AWS CDK app using the stack's `env` property is used during synthesis to generate an environment\-specific AWS CloudFormation template and during deployment to override the account or region specified by one of the above methods\. For more information, see [Environments](environments.md)\. + +If you have the AWS CLI installed, the easiest way to configure your account credentials and a default region is to issue the following command: + +``` +aws configure +``` + +Provide your AWS access key ID, secret access key, and default region when prompted\. These values are written to the `[default]` section of the `config` and `credentials` files\. + +If you don't have the AWS CLI installed, you can manually create or edit the `config` and `credentials` files to contain default credentials and a default region, in the following format\. ++ In `~/.aws/config` or `%USERPROFILE%\.aws\config` + + ``` + [default] + region=us-west-2 + ``` ++ In `~/.aws/credentials` or `%USERPROFILE%\.aws\credentials` + + ``` + [default] + aws_access_key_id=AKIAI44QH8DHBEXAMPLE + aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY + ``` + +Besides specifying AWS credentials and a region in the `[default]` section, you can also add one or more `[profile NAME]` sections, where *NAME* is the name of the profile\. ++ In `~/.aws/config` or `%USERPROFILE%\.aws\config` + + ``` + [profile test] + region=us-east-1 + + [profile prod] + region=us-west-1 + ``` ++ In `~/.aws/credentials` or `%USERPROFILE%\.aws\credentials` + + ``` + [profile test] + aws_access_key_id=AKIAI44QH8DHBEXAMPLE + aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY + + [profile test] + aws_access_key_id=AKIAI44QH8DHBEXAMPLE + aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY + ``` + +Always add named profiles to both the `config` and `credentials` files\. The AWS CDK Toolkit does not fall back to using the region in the `[default]` section when the specified named profile is not found in the `config` file, as some other AWS tools do\. + +**Important** +Do not name a profile `default`: that is, do not use a `[profile default]` section in either `config` or `credentials`\. + +**Note** +Although the AWS CDK uses credentials from the same sources files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. + +You may optionally use the `--role-arn` \(or `-r`\) option to specify the ARN of an IAM role that should be used for deployment\. This role must be assumable by the AWS account being used\. + +## Specifying the app command + +Many features of the CDK Toolkit require one or more AWS CloudFormation templates be synthesized, which in turn requires running your application\. Since the AWS CDK supports programs written in a variety of languages, it uses a configuration option to specify the exact command necessary to run your app\. This option can be specified in two ways\. + +First, and most commonly, it can be specified using the `app` key inside the file `cdk.json`, which is in the main directory of your AWS CDK project\. The CDK Toolkit provides an appropriate command when creating a new project with `cdk init`\. Here is the `cdk.json` from a fresh TypeScript project, for instance\. + +``` +{ + "app": "npx ts-node bin/hello-cdk.ts" +} +``` + +The CDK Toolkit looks for `cdk.json` in the current working directory when attempting to run your app, so you might keep a shell open in your project's main directory for issuing CDK Toolkit commands\. + +The CDK Toolkit also looks for the app key in `~/.cdk.json` \(that is, in your home directory\) if it can't find it in `./cdk.json`\. Adding the app command here can be useful if you usually work with CDK code in the same language, as it does not require you to be in the app's main directory when you run a `cdk` command\. + +If you are in some other directory, or if you want to run your app via a command other than the one in `cdk.json`, you can use the `--app` \(or `-a`\) option to specify it\. + +``` +cdk --app "npx ts-node bin/hello-cdk.ts" ls +``` + +## Specifying stacks + +Many CDK Toolkit commands \(for example, `cdk deploy`\) work on stacks defined in your app\. If your app contains only one stack, the CDK Toolkit assumes you mean that one if you don't specify a stack explicitly\. + +Otherwise, you must specify the stack or stacks you want to work with\. You can do this by specifying the desired stacks by ID individually on the command line\. Recall that the ID is the value specified by the second argument when you instantiate the stack\. + +``` +cdk synth PipelineStack LambdaStack +``` + +You may also use wildcards to specify IDs that match a pattern\. ++ `?` matches any single character ++ `*` matches any number of characters \(`*` alone matches all stacks\) ++ `**` matches everything in a hierarchy + +You may also use the \-\-all option to specify all stacks\. + +If your app uses [CDK Pipelines](cdk_pipeline.md), the CDK Toolkit understands your stacks and stages as a hierarchy, and the \-\-all option and the `*` wildcard only match top\-level stacks\. To match all the stacks, use `**`\. Also use `**` to indicate all the stacks under a particular hierarchy\. + +When using wildcards, enclose the pattern in quotes, or escape the wildcards with `\`\. If you don't, your shell may try to expand the pattern to the names of files in the current directory\. At best, this won't do what you expect; at worst, you could deploy stacks you didn't intend to\. This isn't strictly necessary on Windows because `cmd.exe` does not expand wildcards, but is good practice nonetheless\. + +``` +cdk synth "*Stack" # PipelineStack, LambdaStack, etc. +cdk synth 'Stack?' # StackA, StackB, Stack1, etc. +cdk synth \* # All stacks in the app, or all top-level stacks in a CDK Pipelines app +cdk synth '**' # All stacks in a CDK Pipelines app +cdk synth 'PipelineStack/Prod/**' # All stacks in Prod stage in a CDK Pipelines app +``` + +**Note** +The order in which you specify the stacks is not necessarily the order in which they will be processed\. The AWS CDK Toolkit takes into account dependencies between stacks when deciding the order in which to process them\. For example, if one stack uses a value produced by another \(such as the ARN of a resource defined in the second stack\), the second stack is synthesized before the first one because of this dependency\. You can add dependencies between stacks manually using the stack's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#addwbrdependencytarget-reason](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#addwbrdependencytarget-reason) method\. + +## Bootstrapping your AWS environment + +Deploying stacks that contain [assets](assets.md), synthesize to large templates, or use [CDK Pipelines](cdk_pipeline.md) require special dedicated AWS CDK resources to be provisioned\. The `cdk bootstrap` command creates the necessary resources for you\. You only need to bootstrap if you are deploying a stack that requires these dedicated resources\. See [Bootstrapping](bootstrapping.md) for details\. + +``` +cdk bootstrap +``` + +If issued with no arguments, as shown here, the `cdk bootstrap` command synthesizes the current app and bootstraps the environments its stacks will be deployed to\. If the app contains environment\-agnostic stacks, which do not explicitly specify an environment so they can be deployed anywhere, the default account and region are bootstrapped, or the environment specified using `--profile`\. + +Outside of an app, you must explicitly specify the environment to be bootstrapped\. You may also do so to bootstrap an environment that's not specified in your app or local AWS profile\. Credentials must be configured \(e\.g\. in `~/.aws/credentials`\) for the specified account and region\. You may specify a profile that contains the required credentials\. + +``` +cdk bootstrap ACCOUNT-NUMBER/REGION # e.g. +cdk bootstrap 1111111111/us-east-1 +cdk bootstrap --profile test 1111111111/us-east-1 +``` + +**Important** +Each environment \(account/region combination\) to which you deploy such a stack must be bootstrapped separately\. + +You may incur AWS charges for what the AWS CDK stores in the bootstrapped resources\. Additionally, if you use `-bootstrap-customer-key`, a Customer Master Key \(CMK\) will be created, which also incurs charges per environment\. + +**Note** +Older versions of the bootstrap template created a Customer Master Key by default\. To avoid charges, re\-bootstrap using `--no-bootstrap-customer-key`\. + +**Note** +CDK Toolkit v2 does not support the original bootstrap template, dubbed the legacy template, used with CDK v1\. + +**Important** +The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. + +## Creating a new app + +To create a new app, create a directory for it, then, inside the directory, issue `cdk init`\. + +``` +mkdir my-cdk-app +cd my-cdk-app +cdk init TEMPLATE --language LANGUAGE +``` + +The supported languages \(*LANGUAGE*\) are: + + +| Code | Language | +| --- | --- | +| `typescript` | TypeScript | +| `javascript` | JavaScript | +| `python` | Python | +| `java` | Java | +| `csharp` | C\# | + +*TEMPLATE* is an optional template\. If the desired template is *app*, the default, you may omit it\. The available templates are: + + +| Template | Description | +| --- | --- | +| `app` \(default\) | Creates an empty AWS CDK app\. | +| `sample-app` | Creates an AWS CDK app with a stack containing an Amazon SQS queue and an Amazon SNS topic\. | + +The templates use the name of the project folder to generate names for files and classes inside your new app\. + +## Listing stacks + +To see a list of the IDs of the stacks in your AWS CDK application, enter one of the following equivalent commands: + +``` +cdk list +cdk ls +``` + +If your application contains [CDK Pipelines](cdk_pipeline.md) stacks, the CDK Toolkit displays stack names as paths according to their location in the pipeline hierarchy \(e\.g\., `PipelineStack`, `PipelineStack/Prod`, `PipelineStack/Prod/MyService`, etc\)\. + +If your app contains many stacks, you can specify full or partial stack IDs of the stacks to be listed; see [Specifying stacks](#cli-stacks)\. + +Add the `--long` flag to see more information about the stacks, including the stack names and their environments \(AWS account and region\)\. + +## Synthesizing stacks + +The `cdk synthesize` command \(almost always abbreviated `synth`\) synthesizes a stack defined in your app into a CloudFormation template\. + +``` +cdk synth # if app contains only one stack +cdk synth MyStack +cdk synth Stack1 Stack2 +cdk synth "*" # all stacks in app +``` + +**Note** +The CDK Toolkit actually runs your app and synthesizes fresh templates before most operations \(e\.g\. when deploying or comparing stacks\)\. These templates are stored by default in the `cdk.out` directory\. The `cdk synth` command simply prints the generated templates for the specified stack\(s\)\. + +See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. + +### Specifying context values + +Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. + +``` +# specify a single context value +cdk synth --context key=value MyStack + +# specify multiple context values (any number) +cdk synth --context key1=value1 --context key2=value2 MyStack +``` + +When deploying multiple stacks, the specified context values are normally passed to all of them\. If you wish, you may specify different values for each stack by prefixing the stack name to the context value\. + +``` +# different context values for each stack +cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 +``` + +### Specifying display format + +By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. + +``` +cdk synth --json MyStack +``` + +### Specifying output directory + +Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. + +``` +cdk synth --output=~/templates +``` + +## Deploying stacks + +The `cdk deploy` subcommand deploys the specified stack\(s\) to your AWS account\. + +``` +cdk deploy # if app contains only one stack +cdk deploy MyStack +cdk deploy Stack1 Stack2 +cdk deploy "*" # all stacks in app +``` + +**Note** +The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates before deploying anything\. Therefore, most command line options you can use with `cdk synth` \(for example, `--context`\) can also be used with `cdk deploy`\. + +See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. + +### Disabling rollback + +One of AWS CloudFormation's marquee features is its ability to roll back changes so that deployments are atomic—they either succeed or fail as a whole\. The AWS CDK inherits this capability because it synthesizes and deploys AWS CloudFormation templates\. + +Rollback makes sure your resources are in a consistent state at all times, which is vital for production stacks\. However, while you're still developing your infrastructure, some failures are inevitable, and rolling back failed deployments just slows you down\. + +For this reason, the CDK Toolkit; allows you to disable rollback by adding `--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. + +### Hot swapping + +Use the `--hotswap` flag with `cdk deploy` to attempt to update your AWS resources directly instead of generating a AWS CloudFormation changeset and deploying it\. Deployment falls back to AWS CloudFormation deployment if hot swapping is not possible\. + +Currently hot swapping supports only Lambda functions\. The `--hotswap` flag also disables rollback \(i\.e\., implies `--no-rollback`\)\. + +**Important** +Hot\-swapping is not recommended for production deployments\. + +### Watch mode + +The CDK Toolkit's watch mode \( cdk deploy \-\-watch, or cdk watch for short\) continuously monitors your CDK app's source files and assets for changes and immediately performs a deployment of the specified stacks when a change is detected\. + +By default, these deployments use the `--hotswap` flag, which fast\-tracks deployment of changes to Lambda functions, and falls back to deploying through AWS CloudFormation if you have changed infrastructure configuration\. To have `cdk watch` always perform full AWS CloudFormation deployments, add the `--no-hotswap` flag to `cdk watch`\. + +Any changes made while `cdk watch` is already performing a deployment will be combined into a single deployment, which will begin as soon as the in\-progress deployment is complete\. + +Watch mode uses the `"watch"` key in the project's `cdk.json` to determine which files to monitor\. By default, these files are your application files and assets, but this can be changed by modifying the `"include"` and `"exclude"` entries in the `"watch"` key\. + +`cdk watch` executes the `"build"` command from `cdk.json` to build your app before synthesis\. If your deployment requires any commands to build or package your Lambda code \(or anything else that's not in your CDK app proper\), add it here\. + +Wildcards, both `*` and `**`, can be used in the `"watch"` and `"build"` keys\. Each path is interpreted relative to the parent directory of `cdk.json`\. + +**Important** +Watch mode is not recommended for production deployments\. + +### Specifying AWS CloudFormation parameters + +The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. + +``` +cdk deploy MyStack --parameters uploadBucketName=UploadBucket +``` + +To define multiple parameters, use multiple `--parameters` flags\. + +``` +cdk deploy MyStack --parameters uploadBucketName=UpBucket --parameters downloadBucketName=DownBucket +``` + +If you are deploying multiple stacks, you can specify a different value of each parameter for each stack by prefixing the name of the parameter with the stack name and a colon\. Otherwise, the same value is passed to all stacks\. + +``` +cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket --parameters YourStack:uploadBucketName=UpBucket +``` + +By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. + +### Specifying outputs file + +If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. + +``` +cdk deploy --outputs-file outputs.json MyStack +``` + +### Security\-related changes + +To protect you against unintended changes that affect your security posture, the AWS CDK Toolkit prompts you to approve security\-related changes before deploying them\. You can specify the level of change that requires approval: + +``` +cdk deploy --require-approval LEVEL +``` + +*LEVEL* can be one of the following: + + +| Term | Meaning | +| --- | --- | +| `never` | Approval is never required | +| `any-change` | Requires approval on any IAM or security\-group\-related change | +| `broadening` \(default\) | Requires approval when IAM statements or traffic rules are added; removals don't require approval | + +The setting can also be configured in the `cdk.json` file\. + +``` +{ + "app": "...", + "requireApproval": "never" +} +``` + +## Comparing stacks + +The `cdk diff` command compares the current version of a stack defined in your app with the already\-deployed version, or with a saved AWS CloudFormation template, and displays a list of changes \. + +``` +Stack HelloCdkStack +IAM Statement Changes +┌───┬──────────────────────────────┬────────┬──────────────────────────────┬──────────────────────────────┬───────────┐ +│ │ Resource │ Effect │ Action │ Principal │ Condition │ +├───┼──────────────────────────────┼────────┼──────────────────────────────┼──────────────────────────────┼───────────┤ +│ + │ ${Custom::S3AutoDeleteObject │ Allow │ sts:AssumeRole │ Service:lambda.amazonaws.com │ │ +│ │ sCustomResourceProvider/Role │ │ │ │ │ +│ │ .Arn} │ │ │ │ │ +├───┼──────────────────────────────┼────────┼──────────────────────────────┼──────────────────────────────┼───────────┤ +│ + │ ${MyFirstBucket.Arn} │ Allow │ s3:DeleteObject* │ AWS:${Custom::S3AutoDeleteOb │ │ +│ │ ${MyFirstBucket.Arn}/* │ │ s3:GetBucket* │ jectsCustomResourceProvider/ │ │ +│ │ │ │ s3:GetObject* │ Role.Arn} │ │ +│ │ │ │ s3:List* │ │ │ +└───┴──────────────────────────────┴────────┴──────────────────────────────┴──────────────────────────────┴───────────┘ +IAM Policy Changes +┌───┬────────────────────────────────────────────────────────┬────────────────────────────────────────────────────────┐ +│ │ Resource │ Managed Policy ARN │ +├───┼────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤ +│ + │ ${Custom::S3AutoDeleteObjectsCustomResourceProvider/Ro │ {"Fn::Sub":"arn:${AWS::Partition}:iam::aws:policy/serv │ +│ │ le} │ ice-role/AWSLambdaBasicExecutionRole"} │ +└───┴────────────────────────────────────────────────────────┴────────────────────────────────────────────────────────┘ +(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299) + +Parameters +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/S3Bucket AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3BucketBF7A7F3F: {"Type":"String","Description":"S3 bucket for asset \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/S3VersionKey AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3VersionKeyFAF93626: {"Type":"String","Description":"S3 key for asset version \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/ArtifactHash AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392ArtifactHashE56CD69A: {"Type":"String","Description":"Artifact hash for asset \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} + +Resources +[+] AWS::S3::BucketPolicy MyFirstBucket/Policy MyFirstBucketPolicy3243DEFD +[+] Custom::S3AutoDeleteObjects MyFirstBucket/AutoDeleteObjectsCustomResource MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E +[+] AWS::IAM::Role Custom::S3AutoDeleteObjectsCustomResourceProvider/Role CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092 +[+] AWS::Lambda::Function Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F +[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 + ├─ [~] DeletionPolicy + │ ├─ [-] Retain + │ └─ [+] Delete + └─ [~] UpdateReplacePolicy + ├─ [-] Retain + └─ [+] Delete +``` + +To compare your app's stack\(s\) with the existing deployment: + +``` +cdk diff MyStack +``` + +To compare your app's stack\(s\) with a saved CloudFormation template: + +``` +cdk diff --template ~/stacks/MyStack.old MyStack +``` + +## Toolkit reference + +This section provides a reference for the AWS CDK Toolkit derived from its help, first a general reference with the options available with all commands, then \(in collapsible sections\) specific references with options available only with specific subcommands\. + +``` +Usage: cdk -a COMMAND + +Commands: + + cdk list [STACKS..] Lists all stacks in the app [aliases: ls] + + cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation + template for this stack [aliases: synth] + + cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS + environment + + cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your + AWS account + + cdk watch [STACKS..] Shortcut for 'deploy --watch' + + cdk destroy [STACKS..] Destroy the stack(s) named STACKS + + cdk diff [STACKS..] Compares the specified stack with the deployed + stack or a local template file, and returns + with status 1 if any difference is found + + cdk metadata [STACK] Returns all metadata associated with this + stack + + cdk init [TEMPLATE] Create a new, empty CDK project from a + template. + + cdk context Manage cached context values + + cdk docs Opens the reference documentation in a browser + [aliases: doc] + + cdk doctor Check your set-up for potential problems + +Options: + + -a, --app REQUIRED: command-line for executing your app or a + cloud assembly directory (e.g. "node bin/my-app.js") + [string] + + -c, --context Add contextual string parameter (KEY=VALUE) [array] + + -p, --plugin Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] + + --trace Print trace for stack warnings [boolean] + + --strict Do not construct stacks with warnings [boolean] + + --lookups Perform context lookups (synthesis fails if this is + disabled and context lookups need to be performed) + [boolean] [default: true] + + --ignore-errors Ignores synthesis errors, which will likely produce + an invalid output [boolean] [default: false] + + -j, --json Use JSON output instead of YAML when templates are + printed to STDOUT [boolean] [default: false] + + -v, --verbose Show debug logs (specify multiple times to increase + verbosity) [count] [default: false] + + --debug Enable emission of additional debugging information, + such as creation stack traces of tokens + [boolean] [default: false] + + --profile Use the indicated AWS profile as the default + environment [string] + + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified [string] + + --ca-bundle-path Path to CA certificate to use when validating HTTPS + requests. Will read from AWS_CA_BUNDLE environment + variable if not specified [string] + + -i, --ec2creds Force trying to fetch EC2 instance credentials. + Default: guess EC2 instance status [boolean] + + --version-reporting Include the "AWS::CDK::Metadata" resource in + synthesized templates (enabled by default) [boolean] + + --path-metadata Include "aws:cdk:path" CloudFormation metadata for + each resource (enabled by default) + [boolean] [default: true] + + --asset-metadata Include "aws:asset:*" CloudFormation metadata for + resources that uses assets (enabled by default) + [boolean] [default: true] + + -r, --role-arn ARN of Role to use when invoking CloudFormation + [string] + + --toolkit-stack-name The name of the CDK toolkit stack [string] + + --staging Copy assets to the output directory (use + --no-staging to disable, needed for local debugging + the source files with SAM CLI) + [boolean] [default: true] + + -o, --output Emits the synthesized cloud assembly into a + directory (default: cdk.out) [string] + + --no-color Removes colors and other style from console output + [boolean] [default: false] + + --version Show version number [boolean] + + -h, --help Show help [boolean] + +If your app has a single stack, there is no need to specify the stack name + +If one of cdk.json or ~/.cdk.json exists, options specified there will be used +as defaults. Settings in cdk.json take precedence. +``` + +### `cdk list` \(`ls`\) + +``` +cdk list [STACKS..] + +Lists all stacks in the app + +Options: + + -l, --long Display environment information for each stack + [boolean] [default: false] +``` + +### `cdk synthesize` \(`synth`\) + +``` +cdk synthesize [STACKS..] + +Synthesizes and prints the CloudFormation template for this stack + +Options: + + -e, --exclusively Only synthesize requested stacks, don't include + dependencies [boolean] + + --validation After synthesis, validate stacks with the + "validateOnSynth" attribute set (can also be + controlled with CDK_VALIDATION) + [boolean] [default: true] + + -q, --quiet Do not output CloudFormation Template to stdout + [boolean] [default: false] +``` + +### `cdk bootstrap` + +``` +cdk bootstrap [ENVIRONMENTS..] + +Deploys the CDK toolkit stack into an AWS environment + +Options: + + -b, --bootstrap-bucket-name, The name of the CDK toolkit bucket; + --toolkit-bucket-name bucket will be created and must not + exist [string] + + --bootstrap-kms-key-id AWS KMS master key ID used for the + SSE-KMS encryption [string] + + --bootstrap-customer-key Create a Customer Master Key (CMK) + for the bootstrap bucket (you will + be charged but can customize + permissions, modern bootstrapping + only) [boolean] + + --qualifier Unique string to distinguish + multiple bootstrap stacks [string] + + --public-access-block-configuration Block public access configuration + on CDK toolkit bucket (enabled by + default) [boolean] + + -t, --tags Tags to add for the stack + (KEY=VALUE) [array] [default: []] + + --execute Whether to execute ChangeSet + (--no-execute will NOT execute the + ChangeSet) [boolean] [default: true] + + --trust The AWS account IDs that should be + trusted to perform deployments into + this environment (may be repeated, + modern bootstrapping only) + [array] [default: []] + + --trust-for-lookup The AWS account IDs that should be + trusted to look up values in this + environment (may be repeated, modern + bootstrapping only) + [array] [default: []] + + --cloudformation-execution-policies The Managed Policy ARNs that should + be attached to the role performing + deployments into this environment + (may be repeated, modern + bootstrapping only) + [array] [default: []] + + -f, --force Always bootstrap even if it would + downgrade template version + [boolean] [default: false] + + --termination-protection Toggle CloudFormation termination + protection on the bootstrap stacks + [boolean] + + --show-template Instead of actual bootstrapping, + print the current CLI's + bootstrapping template to stdout for + customization + [boolean] [default: false] + + --template Use the template from the given file + instead of the built-in one (use + --show-template to obtain an + example) [string] +``` + +### `cdk deploy` + +``` +cdk deploy [STACKS..] + +Deploys the stack(s) named STACKS into your AWS account + +Options: + + --all Deploy all available stacks + [boolean] [default: false] + + -E, --build-exclude Do not rebuild asset with the given ID. Can be + specified multiple times [array] [default: []] + + -e, --exclusively Only deploy requested stacks, don't include + dependencies [boolean] + + --require-approval What security-sensitive changes need manual + approval + [string] [choices: "never", "any-change", "broadening"] + + --ci Force CI detection [boolean] [default: false] + + --notification-arns ARNs of SNS topics that CloudFormation will notify + with stack related events [array] + + -t, --tags Tags to add to the stack (KEY=VALUE), overrides + tags from Cloud Assembly (deprecated) [array] + + --execute Whether to execute ChangeSet (--no-execute will NOT + execute the ChangeSet) [boolean] [default: true] + + --change-set-name Name of the CloudFormation change set to create + [string] + + -f, --force Always deploy stack even if templates are identical + [boolean] [default: false] + + --parameters Additional parameters passed to CloudFormation at + deploy time (STACK:KEY=VALUE) [array] [default: {}] + + -O, --outputs-file Path to file where stack outputs will be written as + JSON [string] + + --previous-parameters Use previous values for existing parameters (you + must specify all parameters on every deployment if + this is disabled) [boolean] [default: true] + + --progress Display mode for stack activity events + [string] [choices: "bar", "events"] + + --rollback Rollback stack to stable state on failure. Defaults + to 'true', iterate more rapidly with --no-rollback + or -R. Note: do **not** disable this flag for + deployments with resource replacements, as that + will always fail [boolean] + + --hotswap Attempts to perform a 'hotswap' deployment, which + skips CloudFormation and updates the resources + directly, and falls back to a full deployment if + that is not possible. Do not use this in production + environments [boolean] + + --watch Continuously observe the project files, and deploy + the given stack(s) automatically when changes are + detected. Implies --hotswap by default [boolean] +``` + +### `cdk destroy` + +``` +cdk destroy [STACKS..] + +Destroy the stack(s) named STACKS + +Options: + + --all Destroy all available stacks + [boolean] [default: false] + + -e, --exclusively Only destroy requested stacks, don't include + dependees [boolean] + + -f, --force Do not ask for confirmation before destroying the + stacks [boolean] +``` + +### `cdk diff` + +``` +cdk diff [STACKS..] + +Compares the specified stack with the deployed stack or a local template file, +and returns with status 1 if any difference is found + +Options: + + -e, --exclusively Only diff requested stacks, don't include + dependencies [boolean] + + --context-lines Number of context lines to include in arbitrary JSON + diff rendering [number] [default: 3] + + --template The path to the CloudFormation template to compare + with [string] + + --security-only Only diff for broadened security changes + [boolean] [default: false] + + --fail Fail with exit code 1 in case of diff + [boolean] [default: false] +``` + +### `cdk init` + +``` +cdk init [TEMPLATE] + +Create a new, empty CDK project from a template. + +Options: + + -l, --language The language to be used for the new project (default + can be configured in ~/.cdk.json) + [string] [choices: "csharp", "fsharp", "go", "java", "javascript", "python", + "typescript"] + + --list List the available templates [boolean] + + --generate-only If true, only generates project files, without + executing additional operations such as setting up a + git repo, installing dependencies or compiling the + project [boolean] [default: false] +``` + +### `cdk context` + +``` +cdk context + +Manage cached context values + +Options: + + -e, --reset The context key (or its index) to reset [string] + + --clear Clear all context [boolean] +``` \ No newline at end of file diff --git a/v2/compliance-validation.md b/v2/compliance-validation.md new file mode 100644 index 00000000..67d4b7a1 --- /dev/null +++ b/v2/compliance-validation.md @@ -0,0 +1,16 @@ +# Compliance validation for the AWS Cloud Development Kit \(AWS CDK\) + +The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. + +The security and compliance of AWS services is assessed by third\-party auditors as part of multiple AWS compliance programs\. These include SOC, PCI, FedRAMP, HIPAA, and others\. AWS provides a frequently updated list of AWS services in scope of specific compliance programs at [AWS Services in Scope by Compliance Program](https://aws.amazon.com/compliance/services-in-scope/)\. + +Third\-party audit reports are available for you to download using AWS Artifact\. For more information, see [Downloading Reports in AWS Artifact](https://docs.aws.amazon.com/artifact/latest/ug/downloading-documents.html)\. + +For more information about AWS compliance programs, see [AWS Compliance Programs](https://aws.amazon.com/compliance/programs/)\. + +Your compliance responsibility when using the AWS CDK to access an AWS service is determined by the sensitivity of your data, your organization's compliance objectives, and applicable laws and regulations\. If your use of an AWS service is subject to compliance with standards such as HIPAA, PCI, or FedRAMP, AWS provides resources to help: ++ [Security and Compliance Quick Start Guides](https://aws.amazon.com/quickstart/?quickstart-all.sort-by=item.additionalFields.updateDate&quickstart-all.sort-order=desc&awsf.quickstart-homepage-filter=categories%23security-identity-compliance) – Deployment guides that discuss architectural considerations and provide steps for deploying security\-focused 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) – A whitepaper that describes how companies can use AWS to create HIPAA\-compliant applications\. ++ [AWS Compliance Resources](https://aws.amazon.com/compliance/resources/) – A collection of workbooks and guides that might apply to your industry and location\. ++ [AWS Config](https://aws.amazon.com/config/) – A service that assesses how well your resource configurations comply with internal practices, industry guidelines, and regulations\. ++ [AWS Security Hub](https://aws.amazon.com/security-hub/) – 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/v2/constructs.md b/v2/constructs.md new file mode 100644 index 00000000..1d0c3f2d --- /dev/null +++ b/v2/constructs.md @@ -0,0 +1,1014 @@ +# Constructs + +Constructs are the basic building blocks of AWS CDK apps\. A construct represents a "cloud component" and encapsulates everything AWS CloudFormation needs to create the component\. + +**Note** +Constructs are part of the Construct Programming Model \(CPM\) and are also used by other tools such as CDK for Terraform \(CDKtf\), CDK for Kubernetes \(CDK8s\), and Projen\. + +A construct can represent a single AWS resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can be a higher\-level abstraction consisting of multiple AWS related resources\. Examples of such components include a worker queue with its associated compute capacity, or a scheduled job with monitoring resources and a dashboard\. + +The AWS CDK includes a collection of constructs called the AWS Construct Library, containing constructs for every AWS service\. [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) is a resource to help you discover additional constructs from AWS, third parties, and the open\-source CDK community\. + +**Important** +In AWS CDK v1, the `Construct` base class was in the CDK `core` module\. In CDK v2, there is a separate module called `constructs` that contains this class\. + +## AWS Construct library + +The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html), which contains constructs representing AWS resources\. + +This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_dynamodb.Table.html)` class represents an Amazon DynamoDB table\. + +There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "layer 1"\) or Cfn \(short for CloudFormation\) resources\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. + +The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#addwbrlifecyclewbrrulerule), which adds a lifecycle rule to the bucket\. + +Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. + +For more information about how to navigate the library and discover constructs that can help you build your apps, see the [API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html)\. + +## Composition + +*Composition* is the key pattern for defining higher\-level abstractions through constructs\. A high\-level construct can be composed from any number of lower\-level constructs, and in turn, those could be composed from even lower\-level constructs, which eventually are composed from AWS resources\. From a bottom\-up perspective, you use constructs to organize the individual AWS resources you want to deploy using whatever abstractions are convenient for your purpose, with as many layers as you need\. + +Composition lets you define reusable components and share them like any other code\. For example, a team can define a construct that implements the company's best practice for a DynamoDB table with backup, global replication, auto\-scaling, and monitoring, and share it with other teams in their organization, or publicly\. Teams can now use this construct as they would any other library package in their preferred programming language to define their tables and comply with their team's best practices\. When the library is updated, developers will get access to the new version's bug fixes and improvements through the workflows they already have for their other types of code\. + +## Initialization + +Constructs are implemented in classes that extend the [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) base class\. You define a construct by instantiating the class\. All constructs take three parameters when they are initialized: ++ **Scope** – The construct within which this construct is defined\. You should usually pass `this` for the scope, because it represents the current scope in which you are defining the construct\. ++ **id** – An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to allocate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. ++ **Props** – A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. + +Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tag.html) or for specifying where the constructs will be deployed\. + +## Apps and stacks + +We call your CDK application an *app*, which is represented by the AWS CDK class [App](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.App.html)\. The following example defines an app with a single stack that contains a single Amazon S3 bucket with versioning enabled: + +------ +#### [ TypeScript ] + +``` +import { App, Stack, StackProps } from 'aws-cdk-lib'; +import * as s3 from 'aws-cdk-lib/aws-s3'; + +class HelloCdkStack extends Stack { + constructor(scope: App, id: string, props?: StackProps) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} + +const app = new App(); +new HelloCdkStack(app, "HelloCdkStack"); +``` + +------ +#### [ JavaScript ] + +``` +const { App , Stack } = require('aws-cdk-lib'); +const s3 = require('aws-cdk-lib/aws-s3'); + +class HelloCdkStack extends Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} + +const app = new App(); +new HelloCdkStack(app, "HelloCdkStack"); +``` + +------ +#### [ Python ] + +``` +from aws_cdk import App, Stack +import aws_cdk.aws_s3 as s3 +from constructs import Construct + +class HelloCdkStack(Stack): + + def __init__(self, scope: Construct, id: str, **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + s3.Bucket(self, "MyFirstBucket", versioned=True) + +app = App() +HelloCdkStack(app, "HelloCdkStack") +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.*; +import software.amazon.awscdk.services.s3.*; + +public class HelloCdkStack extends Stack { + public HelloCdkStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public HelloCdkStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + Bucket.Builder.create(this, "MyFirstBucket") + .versioned(true).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +namespace HelloCdkApp +{ + internal static class Program + { + public static void Main(string[] args) + { + var app = new App(); + new HelloCdkStack(app, "HelloCdkStack"); + app.Synth(); + } + } + + public class HelloCdkStack : Stack + { + public HelloCdkStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) + { + new Bucket(this, "MyFirstBucket", new BucketProps { Versioned = true }); + } + } +} +``` + +------ + +As you can see, you need a scope within which to define your bucket\. Since resources eventually need to be deployed as part of a AWS CloudFormation stack into an *AWS [environment](environments.md)*, which covers a specific AWS account and AWS region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html)\. + +Stacks in AWS CDK apps extend the **Stack** base class, as shown in the previous example\. This is a common pattern when creating a stack within your AWS CDK app: extend the **Stack** class, define a constructor that accepts **scope**, **id**, and **props**, and invoke the base class constructor via `super` with the received **scope**, **id**, and **props**, as shown in the following example\. + +------ +#### [ TypeScript ] + +``` +class HelloCdkStack extends Stack { + constructor(scope: App, id: string, props?: StackProps) { + super(scope, id, props); + + //... + } +} +``` + +------ +#### [ JavaScript ] + +``` +class HelloCdkStack extends Stack { + constructor(scope, id, props) { + super(scope, id, props); + + //... + } +} +``` + +------ +#### [ Python ] + +``` +class HelloCdkStack(Stack): + + def __init__(self, scope: Construct, id: str, **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + # ... +``` + +------ +#### [ Java ] + +``` +public class HelloCdkStack extends Stack { + public HelloCdkStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public HelloCdkStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + // ... + } +} +``` + +------ +#### [ C\# ] + +``` +public class HelloCdkStack : Stack +{ + public HelloCdkStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) + { + //... + } +} +``` + +------ + +## Using L1 constructs + +Once you have defined a stack, you can populate it with resources by instantiating constructs\. First, we'll do it with an L1 construct\. + +L1 constructs are exactly the resources defined by AWS CloudFormation—no more, no less\. You must provide the resource's required configuration yourself\. Here, for example, is how to create an Amazon S3 bucket using the `CfnBucket` class\. \(You'll see a similar definition using the `Bucket` class in the next section\.\) + +------ +#### [ TypeScript ] + +``` +const bucket = new s3.CfnBucket(this, "MyBucket", { + bucketName: "MyBucket" +}); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = new s3.CfnBucket(this, "MyBucket", { + bucketName: "MyBucket" +}); +``` + +------ +#### [ Python ] + +``` +bucket = s3.CfnBucket(self, "MyBucket", bucket_name="MyBucket") +``` + +------ +#### [ Java ] + +``` +CfnBucket bucket = new CfnBucket.Builder().bucketName("MyBucket").build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps +{ + BucketName= "MyBucket" +}); +``` + +------ + +In Python, Java, and C\#, L1 construct properties that aren't simple Booleans, strings, numbers, or containers are represented by types defined as inner classes of the L1 construct\. For example, the optional property `corsConfiguration` of a `CfnBucket` requires a wrapper of type `CfnBucket.CorsConfigurationProperty`\. Here we are defining `corsConfiguration` on a `CfnBucket` instance\. + +------ +#### [ TypeScript ] + +``` +const bucket = new s3.CfnBucket(this, "MyBucket", { + bucketName: "MyBucket", + corsConfiguration: { + corsRules: [{ + allowedOrigins: ["*"], + allowedMethods: ["GET"] + }] + } +}); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = new s3.CfnBucket(this, "MyBucket", { + bucketName: "MyBucket", + corsConfiguration: { + corsRules: [{ + allowedOrigins: ["*"], + allowedMethods: ["GET"] + }] + } +}); +``` + +------ +#### [ Python ] + +``` +bucket = CfnBucket(self, "MyBucket", bucket_name="MyBucket", + cors_configuration=CfnBucket.CorsConfigurationProperty( + cors_rules=[CfnBucket.CorsRuleProperty( + allowed_origins=["*"], + allowed_methods=["GET"] + )] + ) +) +``` + +------ +#### [ Java ] + +``` +CfnBucket bucket = CfnBucket.Builder.create(this, "MyBucket") + .bucketName("MyBucket") + .corsConfiguration(new CfnBucket.CorsConfigurationProperty.Builder() + .corsRules(Arrays.asList(new CfnBucket.CorsRuleProperty.Builder() + .allowedOrigins(Arrays.asList("*")) + .allowedMethods(Arrays.asList("GET")) + .build())) + .build()) + .build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps +{ + BucketName = "MyBucket", + CorsConfiguration = new CfnBucket.CorsConfigurationProperty + { + CorsRules = new object[] { + new CfnBucket.CorsRuleProperty + { + AllowedOrigins = new string[] { "*" }, + AllowedMethods = new string[] { "GET" }, + } + } + } +}); +``` + +------ + +**Important** +You can't use L2 property types with L1 constructs, or vice versa\. When working with L1 constructs, always use the types defined inside the L1 construct you're using\. Do not use types from other L1 constructs \(some may have the same name, but they are not the same type\)\. +Some of our language\-specific API references currently have errors in the paths to L1 property types, or don't document these classes at all\. We hope to fix this soon\. In the meantime, just remember that such types are always inner classes of the L1 construct they are used with\. + +## Using L2 constructs + +The following example defines an Amazon S3 bucket by creating an instance of the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) class, an L2 construct\. + +------ +#### [ TypeScript ] + +``` +import * as s3 from 'aws-cdk-lib/aws-s3'; + +// "this" is HelloCdkStack +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true +}); +``` + +------ +#### [ JavaScript ] + +``` +const s3 = require('aws-cdk-lib/aws-s3'); + +// "this" is HelloCdkStack +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true +}); +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_s3 as s3 + +# "self" is HelloCdkStack +s3.Bucket(self, "MyFirstBucket", versioned=True) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.s3.*; + +public class HelloCdkStack extends Stack { + public HelloCdkStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public HelloCdkStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + Bucket.Builder.create(this, "MyFirstBucket") + .versioned(true).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.S3; + +// "this" is HelloCdkStack +new Bucket(this, "MyFirstBucket", new BucketProps +{ + Versioned = true +}); +``` + +------ + +The [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) includes constructs that represent many AWS resources\. + +**Note** +`MyFirstBucket` is not the name of the bucket that AWS CloudFormation creates\. It is a logical identifier given to the new construct\. See [Physical Names](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Resource.html#physicalname) for details\. + +## Configuration + +Most constructs accept `props` as their third argument \(or in Python, keyword arguments\), a name/value collection that defines the construct's configuration\. The following example defines a bucket with AWS Key Management Service \(AWS KMS\) encryption and static website hosting enabled\. Since it does not explicitly specify an encryption key, the `Bucket` construct defines a new `kms.Key` and associates it with the bucket\. + +------ +#### [ TypeScript ] + +``` +new s3.Bucket(this, 'MyEncryptedBucket', { + encryption: s3.BucketEncryption.KMS, + websiteIndexDocument: 'index.html' +}); +``` + +------ +#### [ JavaScript ] + +``` +new s3.Bucket(this, 'MyEncryptedBucket', { + encryption: s3.BucketEncryption.KMS, + websiteIndexDocument: 'index.html' +}); +``` + +------ +#### [ Python ] + +``` +s3.Bucket(self, "MyEncryptedBucket", encryption=s3.BucketEncryption.KMS, + website_index_document="index.html") +``` + +------ +#### [ Java ] + +``` +Bucket.Builder.create(this, "MyEncryptedBucket") + .encryption(BucketEncryption.KMS_MANAGED) + .websiteIndexDocument("index.html").build(); +``` + +------ +#### [ C\# ] + +``` +new Bucket(this, "MyEncryptedBucket", new BucketProps +{ + Encryption = BucketEncryption.KMS_MANAGED, + WebsiteIndexDocument = "index.html" +}); +``` + +------ + + AWS constructs are designed around the concept of "sensible defaults\." Most constructs have a minimal required configuration, enabling you to quickly get started while also providing full control over the configuration when you need it\. + +## Interacting with constructs + +Constructs are classes that extend the base [Construct](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) class\. After you instantiate a construct, the construct object exposes a set of methods and properties that enable you to interact with the construct and pass it around as a reference to other parts of the system\. The AWS CDK framework doesn't put any restrictions on the APIs of constructs; authors can define any API they wish\. However, the AWS constructs that are included with the AWS Construct Library, such as `s3.Bucket`, follow guidelines and common patterns in order to provide a consistent experience across all AWS resources\. + +For example, almost all AWS constructs have a set of [grant](permissions.md#permissions_grants) methods that you can use to grant AWS Identity and Access Management \(IAM\) permissions on that construct to a principal\. The following example grants the IAM group `data-science` permission to read from the Amazon S3 bucket `raw-data`\. + +------ +#### [ TypeScript ] + +``` +const rawData = new s3.Bucket(this, 'raw-data'); +const dataScience = new iam.Group(this, 'data-science'); +rawData.grantRead(dataScience); +``` + +------ +#### [ JavaScript ] + +``` +const rawData = new s3.Bucket(this, 'raw-data'); +const dataScience = new iam.Group(this, 'data-science'); +rawData.grantRead(dataScience); +``` + +------ +#### [ Python ] + +``` +raw_data = s3.Bucket(self, 'raw-data') +data_science = iam.Group(self, 'data-science') +raw_data.grant_read(data_science) +``` + +------ +#### [ Java ] + +``` +Bucket rawData = new Bucket(this, "raw-data"); +Group dataScience = new Group(this, "data-science"); +rawData.grantRead(dataScience); +``` + +------ +#### [ C\# ] + +``` +var rawData = new Bucket(this, "raw-data"); +var dataScience = new Group(this, "data-science"); +rawData.GrantRead(dataScience); +``` + +------ + +Another common pattern is for AWS constructs to set one of the resource's attributes, such as its Amazon Resource Name \(ARN\), name, or URL from data supplied elsewhere\. For example, the following code defines an AWS Lambda function and associates it with an Amazon Simple Queue Service \(Amazon SQS\) queue through the queue's URL in an environment variable\. + +------ +#### [ TypeScript ] + +``` +const jobsQueue = new sqs.Queue(this, 'jobs'); +const createJobLambda = new lambda.Function(this, 'create-job', { + runtime: lambda.Runtime.NODEJS_14_X, + handler: 'index.handler', + code: lambda.Code.fromAsset('./create-job-lambda-code'), + environment: { + QUEUE_URL: jobsQueue.queueUrl + } +}); +``` + +------ +#### [ JavaScript ] + +``` +const jobsQueue = new sqs.Queue(this, 'jobs'); +const createJobLambda = new lambda.Function(this, 'create-job', { + runtime: lambda.Runtime.NODEJS_14_X, + handler: 'index.handler', + code: lambda.Code.fromAsset('./create-job-lambda-code'), + environment: { + QUEUE_URL: jobsQueue.queueUrl + } +}); +``` + +------ +#### [ Python ] + +``` +jobs_queue = sqs.Queue(self, "jobs") +create_job_lambda = lambda_.Function(self, "create-job", + runtime=lambda_.Runtime.NODEJS_14_X, + handler="index.handler", + code=lambda_.Code.from_asset("./create-job-lambda-code"), + environment=dict( + QUEUE_URL=jobs_queue.queue_url + ) +) +``` + +------ +#### [ Java ] + +``` +final Queue jobsQueue = new Queue(this, "jobs"); +Function createJobLambda = Function.Builder.create(this, "create-job") + .handler("index.handler") + .code(Code.fromAsset("./create-job-lambda-code")) + .environment(new HashMap() {{ + put("QUEUE_URL", jobsQueue.getQueueUrl()); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +var jobsQueue = new Queue(this, "jobs"); +var createJobLambda = new Function(this, "create-job", new FunctionProps +{ + Runtime = Runtime.NODEJS_14_X, + Handler = "index.handler", + Code = Code.FromAsset(@".\create-job-lambda-code"), + Environment = new Dictionary + { + ["QUEUE_URL"] = jobsQueue.QueueUrl + } +}); +``` + +------ + +For information about the most common API patterns in the AWS Construct Library, see [Resources](resources.md)\. + +## Writing your own constructs + +In addition to using existing constructs like `s3.Bucket`, you can also write your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct imported from a third\-party library that someone published via NPM or Maven or PyPI—or to your company's internal package repository\. + +To declare a new construct, create a class that extends the [Construct](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) base class, in the `constructs` package, then follow the pattern for initializer arguments\. + +For example, you could declare a construct that represents an Amazon S3 bucket which sends an Amazon Simple Notification Service \(Amazon SNS\) notification every time someone uploads a file into it: + +------ +#### [ TypeScript ] + +``` +export interface NotifyingBucketProps { + prefix?: string; +} + +export class NotifyingBucket extends Construct { + constructor(scope: Construct, id: string, props: NotifyingBucketProps = {}) { + super(scope, id); + const bucket = new s3.Bucket(this, 'bucket'); + const topic = new sns.Topic(this, 'topic'); + bucket.addObjectCreatedNotification(new s3notify.SnsDestination(topic), + { prefix: props.prefix }); + } +} +``` + +------ +#### [ JavaScript ] + +``` +class NotifyingBucket extends Construct { + constructor(scope, id, props = {}) { + super(scope, id); + const bucket = new s3.Bucket(this, 'bucket'); + const topic = new sns.Topic(this, 'topic'); + bucket.addObjectCreatedNotification(new s3notify.SnsDestination(topic), + { prefix: props.prefix }); + } +} + +module.exports = { NotifyingBucket } +``` + +------ +#### [ Python ] + +``` +class NotifyingBucket(Construct): + + def __init__(self, scope: Construct, id: str, *, prefix=None): + super().__init__(scope, id) + bucket = s3.Bucket(self, "bucket") + topic = sns.Topic(self, "topic") + bucket.add_object_created_notification(s3notify.SnsDestination(topic), + s3.NotificationKeyFilter(prefix=prefix)) +``` + +------ +#### [ Java ] + +``` +public class NotifyingBucket extends Construct { + + public NotifyingBucket(final Construct scope, final String id) { + this(scope, id, null, null); + } + + public NotifyingBucket(final Construct scope, final String id, final BucketProps props) { + this(scope, id, props, null); + } + + public NotifyingBucket(final Construct scope, final String id, final String prefix) { + this(scope, id, null, prefix); + } + + public NotifyingBucket(final Construct scope, final String id, final BucketProps props, final String prefix) { + super(scope, id); + + Bucket bucket = new Bucket(this, "bucket"); + Topic topic = new Topic(this, "topic"); + if (prefix != null) + bucket.addObjectCreatedNotification(new SnsDestination(topic), + NotificationKeyFilter.builder().prefix(prefix).build()); + } +} +``` + +------ +#### [ C\# ] + +``` +public class NotifyingBucketProps : BucketProps +{ + public string Prefix { get; set; } +} + +public class NotifyingBucket : Construct +{ + public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id) + { + var bucket = new Bucket(this, "bucket"); + var topic = new Topic(this, "topic"); + bucket.AddObjectCreatedNotification(new SnsDestination(topic), new NotificationKeyFilter + { + Prefix = props?.Prefix + }); + } +} +``` + +------ + +The `NotifyingBucket` constructor has a typical construct signature: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. \(The base `Construct` class does not take a `props`argument\.\) You could define an instance of this construct in your app without `props`, for example: + +------ +#### [ TypeScript ] + +``` +new NotifyingBucket(this, 'MyNotifyingBucket'); +``` + +------ +#### [ JavaScript ] + +``` +new NotifyingBucket(this, 'MyNotifyingBucket'); +``` + +------ +#### [ Python ] + +``` +NotifyingBucket(self, "MyNotifyingBucket") +``` + +------ +#### [ Java ] + +``` +new NotifyingBucket(this, "MyNotifyingBucket"); +``` + +------ +#### [ C\# ] + +``` +new NotifyingBucket(this, "MyNotifyingBucket"); +``` + +------ + +Or you could use `props` \(in Java, an additional parameter\) to specify the path prefix to filter on, for example: + +------ +#### [ TypeScript ] + +``` +new NotifyingBucket(this, 'MyNotifyingBucket', { prefix: 'images/' }); +``` + +------ +#### [ JavaScript ] + +``` +new NotifyingBucket(this, 'MyNotifyingBucket', { prefix: 'images/' }); +``` + +------ +#### [ Python ] + +``` +NotifyingBucket(self, "MyNotifyingBucket", prefix="images/") +``` + +------ +#### [ Java ] + +``` +new NotifyingBucket(this, "MyNotifyingBucket", "/images"); +``` + +------ +#### [ C\# ] + +``` +new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketProps +{ + Prefix = "/images" +}); +``` + +------ + +Typically, you would also want to expose some properties or methods on your constructs\. For example, it's not very useful to have a topic hidden behind your construct, because it wouldn't be possible for users of your construct to subscribe to it\. Adding a `topic` property allows consumers to access the inner topic, as shown in the following example: + +------ +#### [ TypeScript ] + +``` +export class NotifyingBucket extends Construct { + public readonly topic: sns.Topic; + + constructor(scope: Construct, id: string, props: NotifyingBucketProps) { + super(scope, id); + const bucket = new s3.Bucket(this, 'bucket'); + this.topic = new sns.Topic(this, 'topic'); + bucket.addObjectCreatedNotification(new s3notify.SnsDestination(this.topic), { prefix: props.prefix }); + } +} +``` + +------ +#### [ JavaScript ] + +``` +class NotifyingBucket extends Construct { + + constructor(scope, id, props) { + super(scope, id); + const bucket = new s3.Bucket(this, 'bucket'); + this.topic = new sns.Topic(this, 'topic'); + bucket.addObjectCreatedNotification(new s3notify.SnsDestination(this.topic), { prefix: props.prefix }); + } +} + +module.exports = { NotifyingBucket }; +``` + +------ +#### [ Python ] + +``` +class NotifyingBucket(Construct): + + def __init__(self, scope: Construct, id: str, *, prefix=None, **kwargs): + super().__init__(scope, id) + bucket = s3.Bucket(self, "bucket") + self.topic = sns.Topic(self, "topic") + bucket.add_object_created_notification(s3notify.SnsDestination(self.topic), + s3.NotificationKeyFilter(prefix=prefix)) +``` + +------ +#### [ Java ] + +``` +public class NotifyingBucket extends Bucket { + + public Topic topic = null; + + public NotifyingBucket(final Construct scope, final String id) { + this(scope, id, null, null); + } + + public NotifyingBucket(final Construct scope, final String id, final BucketProps props) { + this(scope, id, props, null); + } + + public NotifyingBucket(final Construct scope, final String id, final String prefix) { + this(scope, id, null, prefix); + } + + public NotifyingBucket(final Construct scope, final String id, final BucketProps props, final String prefix) { + super(scope, id); + + Bucket bucket = new Bucket(this, "bucket"); + topic = new Topic(this, "topic"); + if (prefix != null) + bucket.addObjectCreatedNotification(new SnsDestination(topic), + NotificationKeyFilter.builder().prefix(prefix).build()); + } +} +``` + +------ +#### [ C\# ] + +``` +public class NotifyingBucket : Construct +{ + public readonly Topic topic; + + public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id) + { + var bucket = new Bucket(this, "bucket"); + topic = new Topic(this, "topic"); + bucket.AddObjectCreatedNotification(new SnsDestination(topic), new NotificationKeyFilter + { + Prefix = props?.Prefix + }); + } +} +``` + +------ + +Now, consumers can subscribe to the topic, for example: + +------ +#### [ TypeScript ] + +``` +const queue = new sqs.Queue(this, 'NewImagesQueue'); +const images = new NotifyingBucket(this, '/images'); +images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); +``` + +------ +#### [ JavaScript ] + +``` +const queue = new sqs.Queue(this, 'NewImagesQueue'); +const images = new NotifyingBucket(this, '/images'); +images.topic.addSubscription(new sns_sub.SqsSubscription(queue)); +``` + +------ +#### [ Python ] + +``` +queue = sqs.Queue(self, "NewImagesQueue") +images = NotifyingBucket(self, prefix="Images") +images.topic.add_subscription(sns_sub.SqsSubscription(queue)) +``` + +------ +#### [ Java ] + +``` +NotifyingBucket images = new NotifyingBucket(this, "MyNotifyingBucket", "/images"); +images.topic.addSubscription(new SqsSubscription(queue)); +``` + +------ +#### [ C\# ] + +``` +var queue = new Queue(this, "NewImagesQueue"); +var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketProps +{ + Prefix = "/images" +}); +images.topic.AddSubscription(new SqsSubscription(queue)); +``` + +------ + +## The construct tree + +As we've already seen, in AWS CDK apps, you define constructs "inside" other constructs using the `scope` argument passed to every construct\. In this way, an AWS CDK app defines a hierarchy of constructs known as the *construct tree*\. + +The root of this tree is your app—that is, an instance of the `App` class\. Within the app, you instantiate one or more stacks\. Within stacks, you instantiate either AWS CloudFormation resources or higher\-level constructs, which may themselves instantiate resources or other constructs, and so on down the tree\. + +Constructs are *always* explicitly defined within the scope of another construct, so there is never any doubt about the relationships between constructs\. Almost always, you should pass `this` \(in Python, `self`\) as the scope, indicating that the new construct is a child of the current construct\. The intended pattern is that you derive your construct from [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html), then instantiate the constructs it uses in its constructor\. + +Passing the scope explicitly allows each construct to add itself to the tree, with this behavior entirely contained within the [`Construct` base class](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html)\. It works the same way in every language supported by the AWS CDK and does not require introspection or other "magic\." + +**Important** +Technically, it's possible to pass some scope other than `this` when instantiating a construct, which allows you to add constructs anywhere in the tree, even in another stack entirely\. For example, you could write a mixin\-style function that adds constructs to a scope passed in as an argument\. The practical difficulty here is that you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope\. The practice also makes your code more difficult to understand, maintain, and reuse\. It is virtually always better to find a way to express your intent without resorting to abusing the `scope` argument\. + +The AWS CDK uses the IDs of all constructs in the path from the tree's root to each child construct to generate the unique IDs required by AWS CloudFormation\. This approach means that construct IDs need be unique only within their scope, rather than within the entire stack as in native AWS CloudFormation\. It does, however, mean that if you move a construct to a different scope, its generated stack\-unique ID will change, and AWS CloudFormation will no longer consider it the same resource\. + +The construct tree is separate from the constructs you define in your AWS CDK code, but it is accessible through any construct's `node` attribute, which is a reference to the node that represents that construct in the tree\. Each node is a [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Node.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Node.html) instance, the attributes of which provide access to the tree's root and to the node's parent scopes and children\. ++ `node.children` – The direct children of the construct\. ++ `node.id` – The identifier of the construct within its scope\. ++ `node.path` – The full path of the construct including the IDs of all of its parents\. ++ `node.root` – The root of the construct tree \(the app\)\. ++ `node.scope` – The scope \(parent\) of the construct, or undefined if the node is the root\. ++ `node.scopes` – All parents of the construct, up to the root\. ++ `node.uniqueId` – The unique alphanumeric identifier for this construct within the tree \(by default, generated from `node.path` and a hash\)\. + +The construct tree defines an implicit order in which constructs are synthesized to resources in the final AWS CloudFormation template\. Where one resource must be created before another, AWS CloudFormation or the AWS Construct Library will generally infer the dependency and make sure the resources are created in the right order\. You can also add an explicit dependency between two nodes using `node.addDependency()`; see [Dependencies](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html#dependencies) in the AWS CDK API Reference\. + +The AWS CDK provides a simple way to visit every node in the construct tree and perform an operation on each one\. See [Aspects](aspects.md)\. \ No newline at end of file diff --git a/v2/context.md b/v2/context.md new file mode 100644 index 00000000..acb7e2f8 --- /dev/null +++ b/v2/context.md @@ -0,0 +1,315 @@ +# Runtime context + +Context values are key\-value pairs that can be associated with a stack or construct\. The AWS CDK uses context to cache information from your AWS account, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs used to start your instances\. [Feature flags](featureflags.md) are also context values\. You can create your own context values for use by your apps or constructs\. + +Context keys are strings, and values may be any type supported by JSON: numbers, strings, arrays, or objects\. + +**Important** +Context values are managed by the AWS CDK and its constructs, including constructs you may write\. You should not attempt to add context values manually\. It is useful to review `cdk.context.json` to see what values are being cached; by convention, the keys start with the name of the CDK package that set them\. You should follow this convention when setting your own values\. + +## Construct context + +Context values can be provided to your AWS CDK app in six different ways: ++ Automatically from the current AWS account\. ++ Through the \-\-context option to the cdk command\. \(These values are always strings\.\) ++ In the project's `cdk.context.json` file\. ++ In the `context` key of the project's `cdk.json` file\. ++ In the `context` key of your `~/.cdk.json` file\. ++ In your AWS CDK app using the `construct.node.setContext()` method\. + +The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, changing your Auto Scaling group\. The AWS CDK does not write context data to any of the other files listed\. + +We recommend that your project's context files be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. It is also critical to successful automated deployment of stacks that rely on context values \(for example, using [CDK Pipelines](cdk_pipeline.md)\)\. + +Context values are scoped to the construct that created them; they are visible to child constructs, but not to siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), whether automatically, from a file, or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in the app\. + +You can get a context value using the `construct.node.tryGetContext` method\. If the requested entry is not found on the current construct or any of its parents, the result is `undefined` \(or your language's equivalent, such as `None` in Python\)\. + +## Context methods + +The AWS CDK supports several context methods that enable AWS CDK apps to get contextual information\. For example, you can get a list of Availability Zones that are available in a given AWS account and region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones) method\. + +The following are the context methods: + +[HostedZone\.fromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_route53.HostedZone.html#static-fromwbrlookupscope-id-query) +Gets the hosted zones in your account\. + +[stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones) +Gets the supported Availability Zones\. + +[StringParameter\.valueFromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrfromwbrlookupscope-parametername) +Gets a value from the current Region's Amazon EC2 Systems Manager Parameter Store\. + +[Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html#static-fromwbrlookupscope-id-options) +Gets the existing Amazon Virtual Private Clouds in your accounts\. + +[LookupMachineImage](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.LookupMachineImage.html) +Looks up a machine image for use with a NAT instance in an Amazon Virtual Private Cloud\. + +If a required context value isn't available, the AWS CDK app notifies the AWS CDK CLI that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. + +## Viewing and managing context + +Use the cdk context command to view and manage the information in your `cdk.context.json` file\. To see this information, use the cdk context command without any options\. The output should be something like the following\. + +``` +Context found in cdk.json: + +┌───┬─────────────────────────────────────────────────────────────┬─────────────────────────────────────────────────────────┐ +│ # │ Key │ Value │ +├───┼─────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤ +│ 1 │ availability-zones:account=123456789012:region=eu-central-1 │ [ "eu-central-1a", "eu-central-1b", "eu-central-1c" ] │ +├───┼─────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤ +│ 2 │ availability-zones:account=123456789012:region=eu-west-1 │ [ "eu-west-1a", "eu-west-1b", "eu-west-1c" ] │ +└───┴─────────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────────┘ + +Run cdk context --reset KEY_OR_NUMBER to remove a context key. If it is a cached value, it will be refreshed on the next cdk synth. +``` + +To remove a context value, run cdk context \-\-reset, specifying the value's corresponding key or number\. The following example removes the value that corresponds to the second key in the preceding example, which is the list of availability zones in the Ireland region\. + +``` +cdk context --reset 2 +``` + +``` +Context value +availability-zones:account=123456789012:region=eu-west-1 +reset. It will be refreshed on the next SDK synthesis run. +``` + +Therefore, if you want to update to the latest version of the Amazon Linux AMI, you can use the preceding example to do a controlled update of the context value and reset it, and then synthesize and deploy your app again\. + +``` +cdk synth +``` + +To clear all of the stored context values for your app, run cdk context \-\-clear, as follows\. + +``` +cdk context --clear +``` + +Only context values stored in `cdk.context.json` can be reset or cleared\. The AWS CDK does not touch other context values\. To protect a context value from being reset using these commands, then, you might copy the value to `cdk.json`\. + +## AWS CDK Toolkit `--context` flag + +Use the `--context` \(`-c` for short\) option to pass runtime context values to your CDK app during synthesis or deployment\. + +``` +cdk synth --context key=value MyStack +``` + +To specify multiple context values, repeat the \-\-context option any number of times, providing one key\-value pair each time\. + +``` +cdk synth --context key1=value1 --context key2=value2 MyStack +``` + +When deploying multiple stacks, the specified context values are normally passed to all of them\. If you wish, you may specify different values for each stack by prefixing the stack name to the context value\. + +``` +cdk synth --context Stack1:key=value --context Stack2:key=value Stack1 Stack2 +``` + +## Example + +Below is an example of importing an existing Amazon VPC using AWS CDK context\. + +------ +#### [ TypeScript ] + +``` +import * as cdk from 'aws-cdk-lib'; +import * as ec2 from 'aws-cdk-lib/aws-ec2'; +import { Construct } from 'constructs'; + +export class ExistsVpcStack extends cdk.Stack { + + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + + super(scope, id, props); + + const vpcid = this.node.tryGetContext('vpcid'); + const vpc = ec2.Vpc.fromLookup(this, 'VPC', { + vpcId: vpcid, + }); + + const pubsubnets = vpc.selectSubnets({subnetType: ec2.SubnetType.PUBLIC}); + + new cdk.CfnOutput(this, 'publicsubnets', { + value: pubsubnets.subnetIds.toString(), + }); + } +} +``` + +------ +#### [ JavaScript ] + +``` +const cdk = require('aws-cdk-lib'); +const ec2 = require('aws-cdk-lib/aws-ec2'); + +class ExistsVpcStack extends cdk.Stack { + + constructor(scope, id, props) { + + super(scope, id, props); + + const vpcid = this.node.tryGetContext('vpcid'); + const vpc = ec2.Vpc.fromLookup(this, 'VPC', { + vpcId: vpcid + }); + + const pubsubnets = vpc.selectSubnets({subnetType: ec2.SubnetType.PUBLIC}); + + new cdk.CfnOutput(this, 'publicsubnets', { + value: pubsubnets.subnetIds.toString() + }); + } +} + +module.exports = { ExistsVpcStack } +``` + +------ +#### [ Python ] + +``` +import aws_cdk as cdk +import aws_cdk.aws_ec2 as ec2 +from constructs import Construct + +class ExistsVpcStack(cdk.Stack): + + def __init__(scope: Construct, id: str, **kwargs): + + super().__init__(scope, id, **kwargs) + + vpcid = self.node.try_get_context("vpcid") + vpc = ec2.Vpc.from_lookup(self, "VPC", vpc_id=vpcid) + + pubsubnets = vpc.select_subnets(subnetType=ec2.SubnetType.PUBLIC) + + cdk.CfnOutput(self, "publicsubnets", + value=pubsubnets.subnet_ids.to_string()) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.CfnOutput; + +import software.amazon.awscdk.services.ec2.Vpc; +import software.amazon.awscdk.services.ec2.VpcLookupOptions; +import software.amazon.awscdk.services.ec2.SelectedSubnets; +import software.amazon.awscdk.services.ec2.SubnetSelection; +import software.amazon.awscdk.services.ec2.SubnetType; +import software.constructs.Construct; + +public class ExistsVpcStack extends Stack { + public ExistsVpcStack(Construct context, String id) { + this(context, id, null); + } + + public ExistsVpcStack(Construct context, String id, StackProps props) { + super(context, id, props); + + String vpcId = (String)this.getNode().tryGetContext("vpcid"); + Vpc vpc = (Vpc)Vpc.fromLookup(this, "VPC", VpcLookupOptions.builder() + .vpcId(vpcId).build()); + + SelectedSubnets pubSubNets = vpc.selectSubnets(SubnetSelection.builder() + .subnetType(SubnetType.PUBLIC).build()); + + CfnOutput.Builder.create(this, "publicsubnets") + .value(pubSubNets.getSubnetIds().toString()).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.EC2; +using Constructs; + +class ExistsVpcStack : Stack +{ + public ExistsVpcStack(Construct scope, string id, StackProps props) : base(scope, id, props) + { + var vpcId = (string)this.Node.TryGetContext("vpcid"); + var vpc = Vpc.FromLookup(this, "VPC", new VpcLookupOptions + { + VpcId = vpcId + }); + + SelectedSubnets pubSubNets = vpc.SelectSubnets([new SubnetSelection + { + SubnetType = SubnetType.PUBLIC + }]); + + new CfnOutput(this, "publicsubnets", new CfnOutputProps { + Value = pubSubNets.SubnetIds.ToString() + }); + } +} +``` + +------ + +You can use cdk diff to see the effects of passing in a context value on the command line: + +``` +cdk diff -c vpcid=vpc-0cb9c31031d0d3e22 +``` + +``` +Stack ExistsvpcStack +Outputs +[+] Output publicsubnets publicsubnets: {"Value":"subnet-06e0ea7dd302d3e8f,subnet-01fc0acfb58f3128f"} +``` + +The resulting context values can be viewed as shown here\. + +``` +cdk context -j +``` + +``` +{ + "vpc-provider:account=123456789012:filter.vpc-id=vpc-0cb9c31031d0d3e22:region=us-east-1": { + "vpcId": "vpc-0cb9c31031d0d3e22", + "availabilityZones": [ + "us-east-1a", + "us-east-1b" + ], + "privateSubnetIds": [ + "subnet-03ecfc033225be285", + "subnet-0cded5da53180ebfa" + ], + "privateSubnetNames": [ + "Private" + ], + "privateSubnetRouteTableIds": [ + "rtb-0e955393ced0ada04", + "rtb-05602e7b9f310e5b0" + ], + "publicSubnetIds": [ + "subnet-06e0ea7dd302d3e8f", + "subnet-01fc0acfb58f3128f" + ], + "publicSubnetNames": [ + "Public" + ], + "publicSubnetRouteTableIds": [ + "rtb-00d1fdfd823c82289", + "rtb-04bb1969b42969bcb" + ] + } +} +``` \ No newline at end of file diff --git a/v2/core_concepts.md b/v2/core_concepts.md new file mode 100644 index 00000000..f0a6eb5b --- /dev/null +++ b/v2/core_concepts.md @@ -0,0 +1,5 @@ +# Concepts + +This topic describes some of the concepts \(the why and how\) behind the AWS CDK\. It also discusses the AWS Construct Library\. + +AWS CDK apps are composed of building blocks known as [Constructs](constructs.md), which are composed together to form [stacks](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html) and [apps](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.App.html)\. \ No newline at end of file diff --git a/v2/disaster-recovery-resiliency.md b/v2/disaster-recovery-resiliency.md new file mode 100644 index 00000000..c99d21f9 --- /dev/null +++ b/v2/disaster-recovery-resiliency.md @@ -0,0 +1,11 @@ +# Resilience for the AWS Cloud Development Kit \(AWS CDK\) + +The Amazon Web Services \(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](https://aws.amazon.com/about-aws/global-infrastructure/)\. + +The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. \ No newline at end of file diff --git a/v2/doc-history.md b/v2/doc-history.md new file mode 100644 index 00000000..3e2a6708 --- /dev/null +++ b/v2/doc-history.md @@ -0,0 +1,10 @@ +# AWS CDK Developer Guide history + +See [Releases](https://github.com/awslabs/aws-cdk/releases) for information about AWS CDK releases\. The AWS CDK is updated approximately once a week\. Maintenance versions may be released between weekly releases to address critical issues\. Each release includes a matched AWS CDK Toolkit \(CDK CLI\), AWS Construct Library, and API Reference\. Updates to this Guide generally do not synchronize with AWS CDK releases\. + +**Note** +The table below represents significant documentation milestones\. We fix errors and improve content on an ongoing basis\. + +| Change | Description | Date | +| --- |--- |--- | +| [AWS CDK v2 release](#doc-history) | Version 2 of the AWS CDK Developer Guide is released\. [Document history](../../latest/guide/doc-history.html) for CDK v1\. | December 4, 2021 | \ No newline at end of file diff --git a/v2/ecs_example.md b/v2/ecs_example.md new file mode 100644 index 00000000..12a9ab33 --- /dev/null +++ b/v2/ecs_example.md @@ -0,0 +1,306 @@ +# Creating an AWS Fargate service using the AWS CDK + +This example walks you through how to create an AWS Fargate service running on an Amazon Elastic Container Service \(Amazon ECS\) cluster that's fronted by an internet\-facing Application Load Balancer from an image on Amazon ECR\. + +Amazon ECS is a highly scalable, fast, container management service that makes it easy to run, stop, and manage Docker containers on a cluster\. You can host your cluster on a serverless infrastructure that's managed by Amazon ECS by launching your services or tasks using the Fargate launch type\. For more control, you can host your tasks on a cluster of Amazon Elastic Compute Cloud \(Amazon EC2\) instances that you manage by using the Amazon EC2 launch type\. + +This tutorial shows you how to launch some services using the Fargate launch type\. If you've used the AWS Management Console to create a Fargate service, you know that there are many steps to follow to accomplish that task\. AWS has several tutorials and documentation topics that walk you through creating a Fargate service, including: ++ [How to Deploy Docker Containers \- AWS](https://aws.amazon.com/getting-started/tutorials/deploy-docker-containers) ++ [Setting Up with Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/get-set-up-for-amazon-ecs.html) ++ [Getting Started with Amazon ECS Using Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_GetStarted.html) + +This example creates a similar Fargate service in AWS CDK code\. + +The Amazon ECS construct used in this tutorial helps you use AWS services by providing the following benefits: ++ Automatically configures a load balancer\. ++ Automatically opens a security group for load balancers\. This enables load balancers to communicate with instances without you explicitly creating a security group\. ++ Automatically orders dependency between the service and the load balancer attaching to a target group, where the AWS CDK enforces the correct order of creating the listener before an instance is created\. ++ Automatically configures user data on automatically scaling groups\. This creates the correct configuration to associate a cluster to AMIs\. ++ Validates parameter combinations early\. This exposes AWS CloudFormation issues earlier, thus saving you deployment time\. For example, depending on the task, it's easy to misconfigure the memory settings\. Previously, you would not encounter an error until you deployed your app\. But now the AWS CDK can detect a misconfiguration and emit an error when you synthesize your app\. ++ Automatically adds permissions for Amazon Elastic Container Registry \(Amazon ECR\) if you use an image from Amazon ECR\. ++ Automatically scales\. The AWS CDK supplies a method so you can autoscalinginstances when you use an Amazon EC2 cluster\. This happens automatically when you use an instance in a Fargate cluster\. + + In addition, the AWS CDK prevents an instance from being deleted when automatic scaling tries to kill an instance, but either a task is running or is scheduled on that instance\. + + Previously, you had to create a Lambda function to have this functionality\. ++ Provides asset support, so that you can deploy a source from your machine to Amazon ECS in one step\. Previously, to use an application source you had to perform several manual steps, such as uploading to Amazon ECR and creating a Docker image\. + +See [ECS](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs-readme.html) for details\. + +## Creating the directory and initializing the AWS CDK + +Let's start by creating a directory to hold the AWS CDK code, and then creating a AWS CDK app in that directory\. + +------ +#### [ TypeScript ] + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language typescript +``` + +------ +#### [ JavaScript ] + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language javascript +``` + +------ +#### [ Python ] + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language python +source .venv/bin/activate +pip install -r requirements.txt +``` + +------ +#### [ Java ] + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language java +``` + +You may now import the Maven project into your IDE\. + +------ +#### [ C\# ] + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language csharp +``` + +You may now open `src/MyEcsConstruct.sln` in Visual Studio\. + +------ + +Run the app and confirm that it creates an empty stack\. + +``` +cdk synth +``` + +## Create a Fargate service + +There are two different ways to run your container tasks with Amazon ECS: ++ Use the `Fargate` launch type, where Amazon ECS manages the physical machines that your containers are running on for you\. ++ Use the `EC2` launch type, where you do the managing, such as specifying automatic scaling\. + +For this example, we'll create a Fargate service running on an ECS cluster fronted by an internet\-facing Application Load Balancer\. + +Add the following AWS Construct Library module imports to the indicated file\. + +------ +#### [ TypeScript ] + +File: `lib/my_ecs_construct-stack.ts` + +``` +import * as ec2 from "aws-cdk-lib/aws-ec2"; +import * as ecs from "aws-cdk-lib/aws-ecs"; +import * as ecs_patterns from "aws-cdk-lib/aws-ecs-patterns"; +``` + +------ +#### [ JavaScript ] + +File: `lib/my_ecs_construct-stack.js` + +``` +const ec2 = require("aws-cdk-lib/aws-ec2"); +const ecs = require("aws-cdk-lib/aws-ecs"); +const ecs_patterns = require("aws-cdk-lib/aws-ecs-patterns"); +``` + +------ +#### [ Python ] + +File: `my_ecs_construct/my_ecs_construct_stack.py` + +``` +from aws_cdk import (aws_ec2 as ec2, aws_ecs as ecs, + aws_ecs_patterns as ecs_patterns) +``` + +------ +#### [ Java ] + +File: `src/main/java/com/myorg/MyEcsConstructStack.java` + +``` +import software.amazon.awscdk.services.ec2.*; +import software.amazon.awscdk.services.ecs.*; +import software.amazon.awscdk.services.ecs.patterns.*; +``` + +------ +#### [ C\# ] + +File: `src/MyEcsConstruct/MyEcsConstructStack.cs` + +``` +using Amazon.CDK.AWS.EC2; +using Amazon.CDK.AWS.ECS; +using Amazon.CDK.AWS.ECS.Patterns; +``` + +------ + +Replace the comment at the end of the constructor with the following code\. + +------ +#### [ TypeScript ] + +``` + const vpc = new ec2.Vpc(this, "MyVpc", { + maxAzs: 3 // Default is all AZs in region + }); + + const cluster = new ecs.Cluster(this, "MyCluster", { + vpc: vpc + }); + + // Create a load-balanced Fargate service and make it public + new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { + cluster: cluster, // Required + cpu: 512, // Default is 256 + desiredCount: 6, // Default is 1 + taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, + memoryLimitMiB: 2048, // Default is 512 + publicLoadBalancer: true // Default is false + }); +``` + +------ +#### [ JavaScript ] + +``` + const vpc = new ec2.Vpc(this, "MyVpc", { + maxAzs: 3 // Default is all AZs in region + }); + + const cluster = new ecs.Cluster(this, "MyCluster", { + vpc: vpc + }); + + // Create a load-balanced Fargate service and make it public + new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { + cluster: cluster, // Required + cpu: 512, // Default is 256 + desiredCount: 6, // Default is 1 + taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, + memoryLimitMiB: 2048, // Default is 512 + publicLoadBalancer: true // Default is false + }); +``` + +------ +#### [ Python ] + +``` + vpc = ec2.Vpc(self, "MyVpc", max_azs=3) # default is all AZs in region + + cluster = ecs.Cluster(self, "MyCluster", vpc=vpc) + + ecs_patterns.ApplicationLoadBalancedFargateService(self, "MyFargateService", + cluster=cluster, # Required + cpu=512, # Default is 256 + desired_count=6, # Default is 1 + task_image_options=ecs_patterns.ApplicationLoadBalancedTaskImageOptions( + image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")), + memory_limit_mib=2048, # Default is 512 + public_load_balancer=True) # Default is False +``` + +------ +#### [ Java ] + +``` + Vpc vpc = Vpc.Builder.create(this, "MyVpc") + .maxAzs(3) // Default is all AZs in region + .build(); + + Cluster cluster = Cluster.Builder.create(this, "MyCluster") + .vpc(vpc).build(); + + // Create a load-balanced Fargate service and make it public + ApplicationLoadBalancedFargateService.Builder.create(this, "MyFargateService") + .cluster(cluster) // Required + .cpu(512) // Default is 256 + .desiredCount(6) // Default is 1 + .taskImageOptions( + ApplicationLoadBalancedTaskImageOptions.builder() + .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample")) + .build()) + .memoryLimitMiB(2048) // Default is 512 + .publicLoadBalancer(true) // Default is false + .build(); +``` + +------ +#### [ C\# ] + +``` + var vpc = new Vpc(this, "MyVpc", new VpcProps + { + MaxAzs = 3 // Default is all AZs in region + }); + + var cluster = new Cluster(this, "MyCluster", new ClusterProps + { + Vpc = vpc + }); + + // Create a load-balanced Fargate service and make it public + new ApplicationLoadBalancedFargateService(this, "MyFargateService", + new ApplicationLoadBalancedFargateServiceProps + { + Cluster = cluster, // Required + DesiredCount = 6, // Default is 1 + TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions + { + Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample") + }, + MemoryLimitMiB = 2048, // Default is 256 + PublicLoadBalancer = true // Default is false + } + ); +``` + +------ + +Save it and make sure it runs and creates a stack\. + +``` +cdk synth +``` + +The stack is hundreds of lines, so we won't show it here\. The stack should contain one default instance, a private subnet and a public subnet for the three Availability Zones, and a security group\. + +Deploy the stack\. + +``` +cdk deploy +``` + +AWS CloudFormation displays information about the dozens of steps that it takes as it deploys your app\. + +That's how easy it is to create a Fargate\-powered EC2 service to run a Docker image\. + +## Clean up + +To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done with this exercise\. + +``` +cdk destroy +``` \ No newline at end of file diff --git a/v2/environments.md b/v2/environments.md new file mode 100644 index 00000000..a33400bd --- /dev/null +++ b/v2/environments.md @@ -0,0 +1,397 @@ +# Environments + +Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and region into which the stack is intended to be deployed\. + +**Note** +For all but the simplest deployments, you will need to [bootstrap](bootstrapping.md) each environment you will deploy into\. Deployment requires certain AWS resources to be available, and these resources are provisioned by bootstrapping\. + +If you don't specify an environment when you instantiate a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availabilityZones` \(Python: `availability_zones`\)\. + +**Tip** +If you're using the standard AWS CDK development template, your stacks are instantiated in the same file where you instantiate the `App` object\. +The file named after your project \(for example, `hello-cdk.ts`\) in your project's `bin` folder\. +The file named after your project \(for example, `hello-cdk.js`\) in your project's `bin` folder\. +The file `app.py` in your project's main directory\. +The file named `ProjectNameApp.java`, for example `HelloCdkApp.java`, nested deep under the `src/main` directory\. +The file named `Program.cs` under `src\ProjectName`, for example `src\HelloCdk\Program.cs`\. + +In an environment\-agnostic stack, any constructs that use availability zones will see two of them, allowing the stack to be deployed to any region\. + +When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations in your AWS account\. See [AWS CDK Toolkit \(`cdk` command\)](cli.md) for details\. + +For production stacks, we recommend that you explicitly specify the environment for each stack in your app using the `env` property\. The following example specifies different environments for its two different stacks\. + +------ +#### [ TypeScript ] + +``` +const envEU = { account: '2383838383', region: 'eu-west-1' }; +const envUSA = { account: '8373873873', region: 'us-west-2' }; + +new MyFirstStack(app, 'first-stack-us', { env: envUSA }); +new MyFirstStack(app, 'first-stack-eu', { env: envEU }); +``` + +------ +#### [ JavaScript ] + +``` +const envEU = { account: '2383838383', region: 'eu-west-1' }; +const envUSA = { account: '8373873873', region: 'us-west-2' }; + +new MyFirstStack(app, 'first-stack-us', { env: envUSA }); +new MyFirstStack(app, 'first-stack-eu', { env: envEU }); +``` + +------ +#### [ Python ] + +``` +env_EU = cdk.Environment(account="8373873873", region="eu-west-1") +env_USA = cdk.Environment(account="2383838383", region="us-west-2") + +MyFirstStack(app, "first-stack-us", env=env_USA) +MyFirstStack(app, "first-stack-eu", env=env_EU) +``` + +------ +#### [ Java ] + +``` +public class MyApp { + + // Helper method to build an environment + static Environment makeEnv(String account, String region) { + return Environment.builder() + .account(account) + .region(region) + .build(); + } + + public static void main(final String argv[]) { + App app = new App(); + + Environment envEU = makeEnv("8373873873", "eu-west-1"); + Environment envUSA = makeEnv("2383838383", "us-west-2"); + + new MyFirstStack(app, "first-stack-us", StackProps.builder() + .env(envUSA).build()); + new MyFirstStack(app, "first-stack-eu", StackProps.builder() + .env(envEU).build()); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +``` +Amazon.CDK.Environment makeEnv(string account, string region) +{ + return new Amazon.CDK.Environment + { + Account = account, + Region = region + }; +} + +var envEU = makeEnv(account: "8373873873", region: "eu-west-1"); +var envUSA = makeEnv(account: "2383838383", region: "us-west-2"); + +new MyFirstStack(app, "first-stack-us", new StackProps { Env=envUSA }); +new MyFirstStack(app, "first-stack-eu", new StackProps { Env=envEU }); +``` + +------ + +When you hard\-code the target account and region as above, the stack will always be deployed to that specific account and region\. To make the stack deployable to a different target, but to determine the target at synthesis time, your stack can use two environment variables provided by the AWS CDK CLI: `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. These variables are set based on the AWS profile specified using the \-\-profile option, or the default AWS profile if you don't specify one\. + +The following code fragment shows how to access the account and region passed from the AWS CDK CLI in your stack\. + +------ +#### [ TypeScript ] + +Access environment variables via Node's `process` object\. + +**Note** + You need the DefinitelyTyped module to use `process` in TypeScript\. `cdk init` installs this module for you, but if you are working with a project created before it was added, or didn't set up your project using `cdk init`, install it manually\. + +``` +npm install @types/node +``` + +``` +new MyDevStack(app, 'dev', { + env: { + account: process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEFAULT_REGION +}}); +``` + +------ +#### [ JavaScript ] + +Access environment variables via Node's `process` object\. + +``` +new MyDevStack(app, 'dev', { + env: { + account: process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEFAULT_REGION +}}); +``` + +------ +#### [ Python ] + +Use the `os` module's `environ` dictionary to access environment variables\. + +``` +import os +MyDevStack(app, "dev", env=cdk.Environment( + account=os.environ["CDK_DEFAULT_ACCOUNT"], + region=os.environ["CDK_DEFAULT_REGION"])) +``` + +------ +#### [ Java ] + +Use `System.getenv()` to get the value of an environment variable\. + +``` +public class MyApp { + + // Helper method to build an environment + static Environment makeEnv(String account, String region) { + account = (account == null) ? System.getenv("CDK_DEFAULT_ACCOUNT") : account; + region = (region == null) ? System.getenv("CDK_DEFAULT_REGION") : region; + + return Environment.builder() + .account(account) + .region(region) + .build(); + } + + public static void main(final String argv[]) { + App app = new App(); + + Environment envEU = makeEnv(null, null); + Environment envUSA = makeEnv(null, null); + + new MyDevStack(app, "first-stack-us", StackProps.builder() + .env(envUSA).build()); + new MyDevStack(app, "first-stack-eu", StackProps.builder() + .env(envEU).build()); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +Use `System.Environment.GetEnvironmentVariable()` to get the value of an environment variable\. + +``` +Amazon.CDK.Environment makeEnv(string account=null, string region=null) +{ + return new Amazon.CDK.Environment + { + Account = account ?? System.Environment.GetEnvironmentVariable("CDK_DEFAULT_ACCOUNT"), + Region = region ?? System.Environment.GetEnvironmentVariable("CDK_DEFAULT_REGION") + }; +} + +new MyDevStack(app, "dev", new StackProps { Env = makeEnv() }); +``` + +------ + +The AWS CDK distinguishes between not specifying the `env` property at all and specifying it using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. Constructs that are defined in such a stack cannot use any information about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html#static-fromwbrlookupscope-id-options) \(Python: `from_lookup`\), which need to query your AWS account\. These features do not work at all without an explicit environment specified; to use them, you must specify `env`\. + +When you pass in your environment using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, the stack will be deployed in the account and Region determined by the AWS CDK CLI at the time of synthesis\. This allows environment\-dependent code to work, but it also means that the synthesized template could be different based on the machine, user, or session under which it is synthesized\. This behavior is often acceptable or even desirable during development, but it would probably be an anti\-pattern for production use\. + +You can set `env` however you like, using any valid expression\. For example, you might write your stack to support two additional environment variables to let you override the account and region at synthesis time\. We'll call these `CDK_DEPLOY_ACCOUNT` and `CDK_DEPLOY_REGION` here, but you could name them anything you like, as they are not set by the AWS CDK\. In the following stack's environment, we use our alternative environment variables if they're set, falling back to the default environment provided by the AWS CDK if they are not\. + +------ +#### [ TypeScript ] + +``` +new MyDevStack(app, 'dev', { + env: { + account: process.env.CDK_DEPLOY_ACCOUNT || process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEPLOY_REGION || process.env.CDK_DEFAULT_REGION +}}); +``` + +------ +#### [ JavaScript ] + +``` +new MyDevStack(app, 'dev', { + env: { + account: process.env.CDK_DEPLOY_ACCOUNT || process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEPLOY_REGION || process.env.CDK_DEFAULT_REGION +}}); +``` + +------ +#### [ Python ] + +``` +MyDevStack(app, "dev", env=cdk.Environment( + account=os.environ.get("CDK_DEPLOY_ACCOUNT", os.environ["CDK_DEFAULT_ACCOUNT"]), + region=os.environ.get("CDK_DEPLOY_REGION", os.environ["CDK_DEFAULT_REGION"]) +``` + +------ +#### [ Java ] + +``` +public class MyApp { + + // Helper method to build an environment + static Environment makeEnv(String account, String region) { + account = (account == null) ? System.getenv("CDK_DEPLOY_ACCOUNT") : account; + region = (region == null) ? System.getenv("CDK_DEPLOY_REGION") : region; + account = (account == null) ? System.getenv("CDK_DEFAULT_ACCOUNT") : account; + region = (region == null) ? System.getenv("CDK_DEFAULT_REGION") : region; + + return Environment.builder() + .account(account) + .region(region) + .build(); + } + + public static void main(final String argv[]) { + App app = new App(); + + Environment envEU = makeEnv(null, null); + Environment envUSA = makeEnv(null, null); + + new MyDevStack(app, "first-stack-us", StackProps.builder() + .env(envUSA).build()); + new MyDevStack(app, "first-stack-eu", StackProps.builder() + .env(envEU).build()); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +``` +Amazon.CDK.Environment makeEnv(string account=null, string region=null) +{ + return new Amazon.CDK.Environment + { + Account = account ?? + System.Environment.GetEnvironmentVariable("CDK_DEPLOY_ACCOUNT") ?? + System.Environment.GetEnvironmentVariable("CDK_DEFAULT_ACCOUNT"), + Region = region ?? + System.Environment.GetEnvironmentVariable("CDK_DEPLOY_REGION") ?? + System.Environment.GetEnvironmentVariable("CDK_DEFAULT_REGION") + }; +} + +new MyDevStack(app, "dev", new StackProps { Env = makeEnv() }); +``` + +------ + +With your stack's environment declared this way, you can now write a short script or batch file like the following to set the variables from command line arguments, then call `cdk deploy`\. Any arguments beyond the first two are passed through to `cdk deploy` and can be used to specify command\-line options or stacks\. + +------ +#### [ macOS/Linux ] + +``` +#!/usr/bin/env bash +if [[ $# -ge 2 ]]; then + export CDK_DEPLOY_ACCOUNT=$1 + export CDK_DEPLOY_REGION=$2 + shift; shift + npx cdk deploy "$@" + exit $? +else + echo 1>&2 "Provide account and region as first two args." + echo 1>&2 "Additional args are passed through to cdk deploy." + exit 1 +fi +``` + +Save the script as `cdk-deploy-to.sh`, then execute `chmod +x cdk-deploy-to.sh` to make it executable\. + +------ +#### [ Windows ] + +``` +@findstr /B /V @ %~dpnx0 > %~dpn0.ps1 && powershell -ExecutionPolicy Bypass %~dpn0.ps1 %* +@exit /B %ERRORLEVEL% +if ($args.length -ge 2) { + $env:CDK_DEPLOY_ACCOUNT, $args = $args + $env:CDK_DEPLOY_REGION, $args = $args + npx cdk deploy $args + exit $lastExitCode +} else { + [console]::error.writeline("Provide account and region as first two args.") + [console]::error.writeline("Additional args are passed through to cdk deploy.") + exit 1 +} +``` + +The Windows version of the script uses PowerShell to provide the same functionality as the macOS/Linux version\. It also contains instructions to allow it to be run as a batch file so it can be easily invoked from a command line\. It should be saved as `cdk-deploy-to.bat`\. The file `cdk-deploy-to.ps1` will be created when the batch file is invoked\. + +------ + +Then you can write additional scripts that call the "deploy\-to" script to deploy to specific environments \(even multiple environments per script\): + +------ +#### [ macOS/Linux ] + +``` +#!/usr/bin/env bash +# cdk-deploy-to-test.sh +./cdk-deploy-to.sh 123457689 us-east-1 "$@" +``` + +------ +#### [ Windows ] + +``` +@echo off +rem cdk-deploy-to-test.bat +cdk-deploy-to 135792469 us-east-1 %* +``` + +------ + +When deploying to multiple environments, consider whether you want to continue deploying to other environments after a deployment fails\. The following example avoids deploying to the second production environment if the first doesn't succeed\. + +------ +#### [ macOS/Linux ] + +``` +#!/usr/bin/env bash +# cdk-deploy-to-prod.sh +./cdk-deploy-to.sh 135792468 us-west-1 "$@" || exit +./cdk-deploy-to.sh 246813579 eu-west-1 "$@" +``` + +------ +#### [ Windows ] + +``` +@echo off +rem cdk-deploy-to-prod.bat +cdk-deploy-to 135792469 us-west-1 %* || exit /B +cdk-deploy-to 245813579 eu-west-1 %* +``` + +------ + +Developers could still use the normal `cdk deploy` command to deploy to their own AWS environments for development\. \ No newline at end of file diff --git a/v2/examples.md b/v2/examples.md new file mode 100644 index 00000000..873931c2 --- /dev/null +++ b/v2/examples.md @@ -0,0 +1,5 @@ +# Examples + +This topic contains the following examples: ++ [Creating a serverless application using the AWS CDK](serverless_example.md) Creates a serverless application using Lambda, API Gateway, and Amazon S3\. ++ [Creating an AWS Fargate service using the AWS CDK](ecs_example.md) Creates an Amazon ECS Fargate service from an image on DockerHub\. \ No newline at end of file diff --git a/v2/featureflags.md b/v2/featureflags.md new file mode 100644 index 00000000..57838038 --- /dev/null +++ b/v2/featureflags.md @@ -0,0 +1,35 @@ +# Feature flags + +The AWS CDK uses *feature flags* to enable potentially breaking behaviors in a release\. Flags are stored as [Runtime context](context.md) values in `cdk.json` \(or `~/.cdk.json`\)\. They are not removed by the cdk context \-\-reset or cdk context \-\-clear commands\. + +Feature flags are disabled by default, so existing projects that do not specify the flag will continue to work as expected with later AWS CDK releases\. New projects created using cdk init include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the old behavior, or to add flags to enable new behaviors after upgrading the AWS CDK\. + +**Note** +Currently, CDK v2 does not have any feature flags to enable new behaviors\. + +In CDK v2, feature flags are also used to revert certain behaviors to their v1 defaults\. The flags listed below, set to `false`, revert to specific v1 AWS CDK v1 behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. + +`@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId` +If your application uses multiple Amazon API Gateway API keys and associates them to usage plans + +`@aws-cdk/aws-rds:lowercaseDbIdentifier` +If your application uses Amazon RDS database instance or database clusters, and explicitly specifies the identifier for these + +`@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021` + If your application uses the TLS\_V1\_2\_2019 security policy with Amazon CloudFront distributions\. CDK v2 uses security policy TLSv1\.2\_2021 by default\. + +`@aws-cdk/core:stackRelativeExports` +If your application uses multiple stacks and you refer to resources from one stack in another, this determines whether absolute or relative path is used to construct AWS CloudFormation exports + +The syntax for reverting these flags in `cdk.json` is shown here\. + +``` +{ + "context": { + "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": false, + "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": false, + "@aws-cdk/aws-rds:lowercaseDbIdentifier": false, + "@aws-cdk/core:stackRelativeExports": false, + } +} +``` \ No newline at end of file diff --git a/v2/get_cfn_param.md b/v2/get_cfn_param.md new file mode 100644 index 00000000..9607aa96 --- /dev/null +++ b/v2/get_cfn_param.md @@ -0,0 +1,5 @@ +# Use an AWS CloudFormation parameter + +See [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for information about using the optional *Parameters* section to customize your AWS CloudFormation templates\. + +You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [Import or migrate an existing AWS CloudFormation template](use_cfn_template.md)\. \ No newline at end of file diff --git a/v2/get_context_var.md b/v2/get_context_var.md new file mode 100644 index 00000000..74cbd767 --- /dev/null +++ b/v2/get_context_var.md @@ -0,0 +1,104 @@ +# Get a value from a context variable + +You can specify a context variable either as part of an AWS CDK CLI command, or in `cdk.json`\. + +To create a command line context variable, use the **\-\-context** \(**\-c**\) option, as shown in the following example\. + +``` +cdk synth -c bucket_name=mygroovybucket +``` + +To specify the same context variable and value in the `cdk.json` file, use the following code\. + +``` +{ + "context": { + "bucket_name": "myotherbucket" + } +} +``` + +To get the value of a context variable in your app, use the `TryGetContext` method in the context of a construct \(that is, when `this`, or `self` in Python, is an instance of some construct\)\. The example gets the context value **bucket\_name**\. If the requested value is not defined, `TryGetContext` returns `undefined` \(`None` in Python; `null` in Java and C\#\) rather than raising an exception\. + +------ +#### [ TypeScript ] + +``` +const bucket_name = this.node.tryGetContext('bucket_name'); +``` + +------ +#### [ JavaScript ] + +``` +const bucket_name = this.node.tryGetContext('bucket_name'); +``` + +------ +#### [ Python ] + +``` +bucket_name = self.node.try_get_context("bucket_name") +``` + +------ +#### [ Java ] + +``` +String bucketName = (String)this.getNode().tryGetContext("bucket_name"); +``` + +------ +#### [ C\# ] + +``` +var bucketName = this.Node.TryGetContext("bucket_name"); +``` + +------ + +Outside the context of a construct, you can access the context variable from the app object, like this\. + +------ +#### [ TypeScript ] + +``` +const app = new cdk.App(); +const bucket_name = app.node.tryGetContext('bucket_name') +``` + +------ +#### [ JavaScript ] + +``` +const app = new cdk.App(); +const bucket_name = app.node.tryGetContext('bucket_name'); +``` + +------ +#### [ Python ] + +``` +app = cdk.App() +bucket_name = app.node.try_get_context("bucket_name") +``` + +------ +#### [ Java ] + +``` +App app = App(); +String bucketName = (String)app.getNode().tryGetContext("bucket_name"); +``` + +------ +#### [ C\# ] + +``` +app = App(); +var bucketName = app.Node.TryGetContext("bucket_name"); +``` + +------ + +For more details on working with context variables, see [Runtime context](context.md)\. \ No newline at end of file diff --git a/v2/get_env_var.md b/v2/get_env_var.md new file mode 100644 index 00000000..7d4439eb --- /dev/null +++ b/v2/get_env_var.md @@ -0,0 +1,68 @@ +# Get a value from an environment variable + +To get the value of an environment variable, use code like the following\. This code gets the value of the environment variable `MYBUCKET`\. + +------ +#### [ TypeScript ] + +``` +// Sets bucket_name to undefined if environment variable not set +var bucket_name = process.env.MYBUCKET; + +// Sets bucket_name to a default if env var doesn't exist +var bucket_name = process.env.MYBUCKET || "DefaultName"; +``` + +------ +#### [ JavaScript ] + +``` +// Sets bucket_name to undefined if environment variable not set +var bucket_name = process.env.MYBUCKET; + +// Sets bucket_name to a default if env var doesn't exist +var bucket_name = process.env.MYBUCKET || "DefaultName"; +``` + +------ +#### [ Python ] + +``` +import os + +# Raises KeyError if environment variable doesn't exist +bucket_name = os.environ["MYBUCKET"] + +# Sets bucket_name to None if environment variable doesn't exist +bucket_name = os.getenv("MYBUCKET") + +# Sets bucket_name to a default if env var doesn't exist +bucket_name = os.getenv("MYBUCKET", "DefaultName") +``` + +------ +#### [ Java ] + +``` +// Sets bucketName to null if environment variable doesn't exist +String bucketName = System.getenv("MYBUCKET"); + +// Sets bucketName to a default if env var doesn't exist +String bucketName = System.getenv("MYBUCKET"); +if (bucketName == null) bucketName = "DefaultName"; +``` + +------ +#### [ C\# ] + +``` +using System; + +// Sets bucket name to null if environment variable doesn't exist +string bucketName = Environment.GetEnvironmentVariable("MYBUCKET"); + +// Sets bucket_name to a default if env var doesn't exist +string bucketName = Environment.GetEnvironmentVariable("MYBUCKET") ?? "DefaultName"; +``` + +------ \ No newline at end of file diff --git a/v2/get_secrets_manager_value.md b/v2/get_secrets_manager_value.md new file mode 100644 index 00000000..b09865bc --- /dev/null +++ b/v2/get_secrets_manager_value.md @@ -0,0 +1,112 @@ +# Get a value from AWS Secrets Manager + +To use values from AWS Secrets Manager in your AWS CDK app, use the [fromSecretAttributes\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_secretsmanager.Secret.html#static-fromwbrsecretwbrattributesscope-id-attrs) method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. + +------ +#### [ TypeScript ] + +``` +import * as sm from "aws-cdk-lib/aws-secretsmanager"; + +export class SecretsManagerStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const secret = sm.Secret.fromSecretAttributes(this, "ImportedSecret", { + secretCompleteArn: + "arn:aws:secretsmanager:::secret:-" + // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: + // encryptionKey: ... + }); +``` + +------ +#### [ JavaScript ] + +``` +const sm = require("aws-cdk-lib/aws-secretsmanager"); + +class SecretsManagerStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const secret = sm.Secret.fromSecretAttributes(this, "ImportedSecret", { + secretCompleteArn: + "arn:aws:secretsmanager:::secret:-" + // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: + // encryptionKey: ... + }); + } +} + +module.exports = { SecretsManagerStack } +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_secretsmanager as sm + +class SecretsManagerStack(cdk.Stack): + def __init__(self, scope: cdk.App, id: str, **kwargs): + super().__init__(scope, name, **kwargs) + + secret = sm.Secret.from_secret_attributes(self, "ImportedSecret", + secret_complete_arn="arn:aws:secretsmanager:::secret:-", + # If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: + # encryption_key=.... + ) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.secretsmanager.Secret; +import software.amazon.awscdk.services.secretsmanager.SecretAttributes; + +public class SecretsManagerStack extends Stack { + public SecretsManagerStack(App scope, String id) { + this(scope, id, null); + } + + public SecretsManagerStack(App scope, String id, StackProps props) { + super(scope, id, props); + + Secret secret = (Secret)Secret.fromSecretAttributes(this, "ImportedSecret", SecretAttributes.builder() + .secretCompleteArn("arn:aws:secretsmanager:::secret:-") + // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: + // .encryptionKey(...) + .build()); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.SecretsManager; + +public class SecretsManagerStack : Stack +{ + public SecretsManagerStack(App scope, string id, StackProps props) : base(scope, id, props) { + + var secret = Secret.FromSecretAttributes(this, "ImportedSecret", new SecretAttributes { + SecretCompleteArn = "arn:aws:secretsmanager:::secret:-" + // If the secret is encrypted using a KMS-hosted CMK, either import or reference that key: + // encryptionKey = ..., + }); + } +``` + +------ + +Use the [create\-secret](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_secretsmanager.Secret.html) CLI command to create a secret from the command\-line, such as when testing: + +``` +aws secretsmanager create-secret --name ImportedSecret --secret-string mygroovybucket +``` + +The command returns an ARN you can use for the example\. \ No newline at end of file diff --git a/v2/get_ssm_value.md b/v2/get_ssm_value.md new file mode 100644 index 00000000..82e05cda --- /dev/null +++ b/v2/get_ssm_value.md @@ -0,0 +1,175 @@ +# Get a value from the Systems Manager Parameter Store + +The AWS CDK can retrieve the value of AWS Systems Manager Parameter Store attributes\. During synthesis, the AWS CDK produces a [token](tokens.md) that is resolved by AWS CloudFormation during deployment\. + +The AWS CDK supports retrieving both plain and secure values\. You may request a specific version of either kind of value\. For plain values only, you may omit the version from your request to receive the latest version\. You must always specify the version when requesting the value of a secure attribute\. + +**Note** +This topic shows how to read attributes from the AWS Systems Manager Parameter Store\. You can also read secrets from the AWS Secrets Manager \(see [Get a value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. + +## Reading Systems Manager values at deployment time + +To read values from the Systems Manager Parameter Store, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrforwbrstringwbrparameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrforwbrsecurewbrstringwbrparameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md), not the actual value\. The value is resolved by AWS CloudFormation during deployment\. + +A [limited number of AWS services](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#template-parameters-dynamic-patterns-resources) currently support this feature\. + +------ +#### [ TypeScript ] + +``` +import * as ssm from 'aws-cdk-lib/aws-ssm'; + +// Get latest version or specified version of plain string attribute +const latestStringToken = ssm.StringParameter.valueForStringParameter( + this, 'my-plain-parameter-name'); // latest version +const versionOfStringToken = ssm.StringParameter.valueForStringParameter( + this, 'my-plain-parameter-name', 1); // version 1 + +// Get specified version of secure string attribute +const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( + this, 'my-secure-parameter-name', 1); // must specify version +``` + +------ +#### [ JavaScript ] + +``` +const ssm = require('aws-cdk-lib/aws-ssm'); + +// Get latest version or specified version of plain string attribute +const latestStringToken = ssm.StringParameter.valueForStringParameter( + this, 'my-plain-parameter-name'); // latest version +const versionOfStringToken = ssm.StringParameter.valueForStringParameter( + this, 'my-plain-parameter-name', 1); // version 1 + +// Get specified version of secure string attribute +const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( + this, 'my-secure-parameter-name', 1); // must specify version +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_ssm as ssm + +# Get latest version or specified version of plain string attribute +latest_string_token = ssm.StringParameter.value_for_string_parameter( + self, "my-plain-parameter-name") +latest_string_token = ssm.StringParameter.value_for_string_parameter( + self, "my-plain-parameter-name", 1) + +# Get specified version of secure string attribute +secure_string_token = ssm.StringParameter.value_for_secure_string_parameter( + self, "my-secure-parameter-name", 1) # must specify version +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.ssm.StringParameter; + +//Get latest version or specified version of plain string attribute +String latestStringToken = StringParameter.valueForStringParameter( + this, "my-plain-parameter-name"); // latest version +String versionOfStringToken = StringParameter.valueForStringParameter( + this, "my-plain-parameter-name", 1); // version 1 + +//Get specified version of secure string attribute +String secureStringToken = StringParameter.valueForSecureStringParameter( + this, "my-secure-parameter-name", 1); // must specify version +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.SSM; + +// Get latest version or specified version of plain string attribute +var latestStringToken = StringParameter.ValueForStringParameter( + this, 'my-plain-parameter-name'); // latest version +var versionOfStringToken = StringParameter.ValueForStringParameter( + this, 'my-plain-parameter-name', 1); // version 1 + +// Get specified version of secure string attribute +var secureStringToken = StringParameter.ValueForSecureStringParameter( + this, 'my-secure-parameter-name', 1); // must specify version +``` + +------ + +## Reading Systems Manager values at synthesis time + +It is sometimes useful to "bake in" a parameter at synthesis time, so that the resulting AWS CloudFormation template always uses the same value, rather than resolving the value during deployment\. + +To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrfromwbrlookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. + +Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. + +**Important** +The retrieved value will end up in your synthesized AWS CloudFormation template, which may be a security risk depending on who has access to your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. + +------ +#### [ TypeScript ] + +``` +import * as ssm from 'aws-cdk-lib/aws-ssm'; + +const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); +``` + +------ +#### [ JavaScript ] + +``` +const ssm = require('aws-cdk-lib/aws-ssm'); + +const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_ssm as ssm + +string_value = ssm.StringParameter.value_from_lookup(self, "my-plain-parameter-name") +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.ssm.StringParameter; + +String stringValue = StringParameter.valueFromLookup(this, "my-plain-parameter-name"); +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.SSM; + +var stringValue = StringParameter.ValueFromLookup(this, "my-plain-parameter-name"); +``` + +------ + +## Writing values to Systems Manager + +You can use the AWS CLI, the AWS Management Console, or an AWS SDK to set Systems Manager parameter values\. The following examples use the [ssm put\-parameter](https://docs.aws.amazon.com/cli/latest/reference/ssm/put-parameter.html) CLI command\. + +``` +aws ssm put-parameter --name "parameter-name" --type "String" --value "parameter-value" +aws ssm put-parameter --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" +``` + +When updating an SSM value that already exists, also include the `--overwrite` option\. + +``` +aws ssm put-parameter --overwrite --name "parameter-name" --type "String" --value "parameter-value" +aws ssm put-parameter --overwrite --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" +``` \ No newline at end of file diff --git a/v2/getting_started.md b/v2/getting_started.md new file mode 100644 index 00000000..1d4993ad --- /dev/null +++ b/v2/getting_started.md @@ -0,0 +1,299 @@ +# Getting started with the AWS CDK + +This topic introduces you to important AWS CDK concepts and describes how to install and configure the AWS CDK\. When you're done, you'll be ready to create [your first AWS CDK app](hello_world.md)\. + +## Your background + +The AWS Cloud Development Kit \(AWS CDK\) lets you define your cloud infrastructure as code in one of its supported programming languages\. It is intended for moderately to highly experienced AWS users\. + +Ideally, you already have experience with popular AWS services, particularly [AWS Identity and Access Management](https://aws.amazon.com/iam/) \(IAM\)\. You might already have AWS credentials on your workstation for use with an AWS SDK or the AWS CLI and experience working with AWS resources programmatically\. + +Familiarity with [AWS CloudFormation](https://aws.amazon.com/cloudformation/) is also useful, as the output of an AWS CDK program is an AWS CloudFormation template\. + +Finally, you should be proficient in the programming language you intend to use with the AWS CDK\. + +## Key concepts + +The AWS CDK is designed around a handful of important concepts\. We will introduce a few of these here briefly\. Follow the links to learn more, or see the Concepts topics in this guide's Table of Contents\. + +An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, Python, Java, or C\# that uses the AWS CDK to define AWS infrastructure\. An app defines one or more [stacks](stacks.md)\. Stacks \(equivalent to AWS CloudFormation stacks\) contain [constructs](constructs.md), each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on\. + +**Note** +The AWS CDK also supports Go in a developer preview\. This Guide does not include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. + +Constructs \(as well as stacks and apps\) are represented as classes \(types\) in your programming language of choice\. You instantiate constructs within a stack to declare them to AWS, and connect them to each other using well\-defined interfaces\. + +The AWS CDK includes the CDK Toolkit \(also called the CLI\), a command\-line tool for working with your AWS CDK apps and stacks\. Among other functions, the Toolkit provides the ability to convert one or more AWS CDK stacks to AWS CloudFormation templates and related assets \(a process called *synthesis*\) and to deploy your stacks to an AWS account\. + +The AWS CDK includes a library of AWS constructs called the AWS Construct Library, organized into various modules\. The library contains constructs for each AWS service\. The main CDK package is called `aws-cdk-lib`, and it contains the majority of the AWS Construct Library, along with base classes like `Stack` and `App` used in most CDK applications\. + +The actual package name of the main CDK package varies by language\. + +------ +#### [ TypeScript ] + +| Install | `npm install aws-cdk-lib` | +| --- |--- | +| Import | `const cdk = require('aws-cdk-lib');` | +| --- |--- | + +------ +#### [ JavaScript ] + +| Install | `npm install aws-cdk-lib` | +| --- |--- | +| Import | `const cdk = require('aws-cdk-lib');` | +| --- |--- | + +------ +#### [ Python ] + +| Install | `python -m pip install aws-cdk-lib` | +| --- |--- | +| Import | `import aws_cdk as cdk` | +| --- |--- | + +------ +#### [ Java ] + +| Add to `pom.xml` | Group `software.amazon.awscdk`; artifact `aws-cdk-lib` | +| --- |--- | +| Import | `import software.amazon.awscdk.App;` \(for example\) | +| --- |--- | + +------ +#### [ C\# ] + +| Install | `dotnet add package Amazon.CDK.Lib` | +| --- |--- | +| Import | `using Amazon.CDK;` | +| --- |--- | + +------ + +Constructs come in three fundamental flavors: ++ **AWS CloudFormation\-only** or L1 \(short for "layer 1"\)\. These constructs correspond directly to resource types defined by AWS CloudFormation\. In fact, these constructs are automatically generated from the AWS CloudFormation specification, so when a new AWS service is launched, the AWS CDK supports it a short time after AWS CloudFormation does\. + + AWS CloudFormation resources always have names that begin with `Cfn`\. For example, for the Amazon S3 service, `CfnBucket` is the L1 construct for an Amazon S3 bucket\. + + All L1 resources are in `aws-cdk-lib`\. ++ **Curated** or L2\. These constructs are carefully developed by the AWS CDK team to address specific use cases and simplify infrastructure development\. For the most part, they encapsulate L1 resources, providing sensible defaults and best\-practice security policies\. For example, `Bucket` is the L2 construct for an Amazon S3 bucket\. + + Libraries may also define supporting resources needed by the primary L2 resource\. Some services have more than one L2 namespace in the Construct Library for organizational purposes\. + + `aws-cdk-lib` contains L2 constructs that are designated stable, i\.e\., ready for production use\. If a service's L2 support is still under development, its constructs are designated experimental and provided in a separate module\. ++ **Patterns** or L3\. Patterns declare multiple resources to create entire AWS architectures for particular use cases\. All the plumbing is already hooked up, and configuration is boiled down to a few important parameters\. + + As with L2 constructs, L3 constructs that are ready for production use \(stable\) are included in `aws-cdk-lib`, while those still under development are in separate modules\. + +Finally, the `constructs` package contains the `Construct` base class\. It's in its own package because it is used not only by the AWS CDK but also by other construct\-based tools, including CDK for Terraform and CDK for Kubernetes\. + +Numerous third parties have also published constructs compatible with the AWS CDK\. Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&offset=0) to explore the AWS CDK construct ecosystem\. + +## Supported programming languages + +The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) Go support is available as a Develper Preview\. + +To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. + +We have taken pains to make AWS CDK app development in each language follow that language's usual conventions, so writing AWS CDK apps feels natural, not like writing TypeScript in Python \(for example\)\. Take a look: + +------ +#### [ TypeScript ] + +``` +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket', + versioned: true, + websiteRedirect: {hostName: 'aws.amazon.com'}}); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket', + versioned: true, + websiteRedirect: {hostName: 'aws.amazon.com'}}); +``` + +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=True, + website_redirect=s3.RedirectTarget(host_name="aws.amazon.com")) +``` + +------ +#### [ Java ] + +``` +Bucket bucket = Bucket.Builder.create(self, "MyBucket") + .bucketName("my-bucket") + .versioned(true) + .websiteRedirect(new RedirectTarget.Builder() + .hostName("aws.amazon.com").build()) + .build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new Bucket(this, "MyBucket", new BucketProps { + BucketName = "my-bucket", + Versioned = true, + WebsiteRedirect = new RedirectTarget { + HostName = "aws.amazon.com" + }}); +``` + +------ + +**Note** +These code snippets are intended for illustration only\. They are incomplete and won't run as they are\. + +The AWS Construct Library is distributed using each language's standard package management tools, including NPM, PyPi, Maven, and NuGet\. There's even a version of the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) for each language\. + +To help you use the AWS CDK in your favorite language, this Guide includes topics that explain how to use the AWS CDK in all supported languages\. ++ [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) ++ [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) ++ [Working with the AWS CDK in Python](work-with-cdk-python.md) ++ [Working with the AWS CDK in Java](work-with-cdk-java.md) ++ [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) + +TypeScript was the first language supported by the AWS CDK, and much AWS CDK example code is written in TypeScript\. This Guide includes a topic specifically to show how to adapt TypeScript AWS CDK code for use with the other supported languages\. See [Translating TypeScript AWS CDK code to other languages](multiple_languages.md)\. + +## Prerequisites + +Here's what you need to install to use the AWS CDK\. + +All AWS CDK developers, even those working in Python, Java, or C\#, need [Node\.js](https://nodejs.org/en/download/) 10\.13\.0 or later\. All supported languages use the same back end, which runs on Node\.js\. We recommend a version in [active long\-term support](https://nodejs.org/en/about/releases/), which, at this writing, is the latest 16\.x release\. Your organization may have a different recommendation\. + +**Important** +Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. + +You must configure your workstation with your credentials and an AWS region, if you have not already done so\. If you have the AWS CLI installed, the easiest way to satisfy this requirement is issue the following command: + +``` +aws configure +``` + +Provide your AWS access key ID, secret access key, and default region when prompted\. + +You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(macOS/Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. ++ In `~/.aws/config` or `%USERPROFILE%\.aws\config` + + ``` + [default] + region=us-west-2 + ``` ++ In `~/.aws/credentials` or `%USERPROFILE%\.aws\credentials` + + ``` + [default] + aws_access_key_id=AKIAI44QH8DHBEXAMPLE + aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY + ``` + +**Note** +Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. + +Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. + +**Important** +We strongly recommend against using your AWS root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. Best practices are to change this account's access key regularly and to use a least\-privileges role \(specifying `--role-arn`\) when deploying\. + +Other prerequisites depend on the language in which you develop AWS CDK applications and are as follows\. + +------ +#### [ TypeScript ] ++ TypeScript 2\.7 or later \(`npm -g install typescript`\) + +------ +#### [ JavaScript ] + +No additional requirements + +------ +#### [ Python ] ++ Python 3\.6 or later including `pip` and `virtualenv` + +------ +#### [ Java ] ++ Java Development Kit \(JDK\) 8 \(a\.k\.a\. 1\.8\) or later ++ Apache Maven 3\.5 or later + +Java IDE recommended \(we use Eclipse in some examples in this Developer Guide\)\. IDE must be able to import Maven projects\. Check to make sure your project is set to use Java 1\.8\. Set the JAVA\_HOME environment variable to the path where you have installed the JDK\. + +------ +#### [ C\# ] + +\.NET Core 3\.1 or later\. + +Visual Studio 2019 \(any edition\) or Visual Studio Code recommended\. + +------ + +## Install the AWS CDK + +Install the AWS CDK Toolkit globally using the following Node Package Manager command\. + +``` +npm install -g aws-cdk +``` + +Run the following command to verify correct installation and print the version number of the AWS CDK\. + +``` +cdk --version +``` + +**Note** +CDK Toolkit; v2 works with your existing CDK v1 projects\. However, it can't initialize new CDK; v1 projects\. See [New prerequisites](migrating-v2.md#migrating-v2-prerequisites) if you need to be able to do that\. + +## Bootstrapping + +Many AWS CDK stacks that you write will include [assets](assets.md): external files that are deployed with the stack, such as AWS Lambda functions or Docker images\. The AWS CDK uploads these to an Amazon S3 bucket or other container so they are available to AWS CloudFormation during deployment\. Deployment requires that these containers already exist in the account and region you are deploying into\. Creating them is called [bootstrapping](bootstrapping.md)\. To bootstrap, issue: + +``` +cdk bootstrap aws://ACCOUNT-NUMBER/REGION +``` + +**Tip** +If you don't have your AWS account number handy, you can get it from the AWS Management Console\. Or, if you have the AWS CLI installed, the following command displays your default account information, including the account number\. + +``` +aws sts get-caller-identity +``` +If you have created named profiles in your local AWS configuration, you can use the `--profile` option to display the account information for a specific profile's account, such as the *prod* profile as shown here\. + +``` +aws sts get-caller-identity --profile prod +``` +To display the default region, use `aws configure get`\. + +``` +aws configure get region +aws configure get region --profile prod +``` + +## AWS CDK tools + +The AWS CDK Toolkit, also known as the Command Line Interface \(CLI\), is the main tool you use to interact with your AWS CDK app\. It executes your code and produces and deploys the AWS CloudFormation templates it generates\. It also has deployment, diff, deletion, and troubleshooting capabilities\. For more information, see cdk \-\-help or [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. + +The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open\-source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the plug\-in](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. + +## Next steps + +Where do you go now that you've dipped your toes in the AWS CDK? ++ Come on in; the water's fine\! Build [your first AWS CDK app](hello_world.md)\. ++ Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. ++ See the [API reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) to begin exploring the provided constructs available for your favorite AWS services\. ++ Visit the [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) to find constructs from the CDK community as well as from AWS\. ++ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. ++ Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. + +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/v2/hello_world.md b/v2/hello_world.md new file mode 100644 index 00000000..a499f711 --- /dev/null +++ b/v2/hello_world.md @@ -0,0 +1,536 @@ +# Your first AWS CDK app + +You've read [Getting started with the AWS CDK](getting_started.md) and set up your development environment for writing AWS CDK apps? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. + +**Note** +The AWS CDK supports Go in a developer preview\. This tutorial does not include instructions or code examples for Go\. + +In this tutorial, you'll learn about the structure of a AWS CDK project, how to use the AWS Construct Library to define AWS resources using code, and how to synthesize, diff, and deploy collections of resources using the AWS CDK Toolkit command\-line tool\. + +The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps\. + +1. Create the app from a template provided by the AWS CDK + +1. Add code to the app to create resources within stacks + +1. Build the app \(optional; the AWS CDK Toolkit will do it for you if you forget\) + +1. Synthesize one or more stacks in the app to create an AWS CloudFormation template + +1. Deploy one or more stacks to your AWS account + +The build step catches syntax and type errors\. The synthesis step catches logical errors in defining your AWS resources\. The deployment may find permission issues\. As always, you go back to the code, find the problem, fix it, then build, synthesize and deploy again\. + +**Tip** +Don't forget to keep your AWS CDK code under version control\! + +This tutorial walks you through creating and deploying a simple AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. The app contains one stack, which contains one resource: an Amazon S3 bucket\. + +We'll also show what happens when you make a change and re\-deploy, and how to clean up when you're done\. + +## Create the app + +Each AWS CDK app should be in its own directory, with its own local module dependencies\. Create a new directory for your app\. Starting in your home directory, or another directory if you prefer, issue the following commands\. + +**Important** +Be sure to name your project directory `hello-cdk`, *exactly as shown here\.* The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, the code in this tutorial won't work\. + +``` +mkdir hello-cdk +cd hello-cdk +``` + +Now initialize the app using the cdk init command, specifying the desired template \("app"\) and programming language\. That is: + +------ +#### [ TypeScript ] + +``` +cdk init app --language typescript +``` + +------ +#### [ JavaScript ] + +``` +cdk init app --language javascript +``` + +------ +#### [ Python ] + +``` +cdk init app --language python +``` + +After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install the AWS CDK core dependencies\. + +``` +source .venv/bin/activate +python -m pip install -r requirements.txt +``` + +------ +#### [ Java ] + +``` +cdk init app --language java +``` + +If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set to use Java 8 \(1\.8\)\. + +------ +#### [ C\# ] + +``` +cdk init app --language csharp +``` + +If you are using Visual Studio, open the solution file in the `src` directory\. + +------ + +**Tip** +If you don't specify a template, the default is "app," which is the one we wanted anyway, so technically you can leave it out and save four keystrokes\. + +The cdk init command creates a number of files and folders inside the `hello-cdk` directory to help you organize the source code for your AWS CDK app\. Take a moment to explore\. The structure of a basic app is all there; you'll fill in the details in this tutorial\. + +If you have Git installed, each project you create using cdk init is also initialized as a Git repository\. We'll ignore that for now, but it's there when you need it\. + +## Build the app + +In most programming environments, after making changes to your code, you'd build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you so you can't forget\. But you can still build manually whenever you want to catch syntax and type errors\. For reference, here's how\. + +------ +#### [ TypeScript ] + +``` +npm run build +``` + +------ +#### [ JavaScript ] + +No build step is necessary\. + +------ +#### [ Python ] + +No build step is necessary\. + +------ +#### [ Java ] + +``` +mvn compile -q +``` + +Or press Control\-B in Eclipse \(other Java IDEs may vary\) + +------ +#### [ C\# ] + +``` +dotnet build src +``` + +Or press F6 in Visual Studio + +------ + +**Note** +If your project was created with an older version of the AWS CDK Toolkit, it may not automatically build when you run it\. If changes you make in your code fail to be reflected in the synthesized template, try a manual build\. Make sure you are using the latest available version of the AWS CDK for this tutorial\. + +## List the stacks in the app + +Just to verify everything is working correctly, list the stacks in your app\. + +``` +cdk ls +``` + +If you don't see `HelloCdkStack`, make sure you named your app's directory `hello-cdk`\. If you didn't, go back to [Create the app](#hello_world_tutorial_create_app) and try again\. + +## Add an Amazon S3 bucket + +At this point, your app doesn't do anything because the stack it contains doesn't define any resources\. Let's add an Amazon S3 bucket\. + +The CDK's Amazon S3 support is part of its main library, `aws-cdk-lib`, so we don't need to install another library\. We can just define an Amazon S3 bucket in the stack using the [Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) construct\. + +------ +#### [ TypeScript ] + +In `lib/hello-cdk-stack.ts`: + +``` +import * as cdk from 'aws-cdk-lib'; +import { aws_s3 as s3 } from 'aws-cdk-lib'; + +export class HelloCdkStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} +``` + +------ +#### [ JavaScript ] + +In `lib/hello-cdk-stack.js`: + +``` +const cdk = require('aws-cdk-lib'); +const { aws_s3 as s3 } = require('aws-cdk-lib'); + +class HelloCdkStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + new s3.Bucket(this, 'MyFirstBucket', { + versioned: true + }); + } +} + +module.exports = { HelloCdkStack } +``` + +------ +#### [ Python ] + +In `hello_cdk/hello_cdk_stack.py`: + +``` +import aws_cdk as cdk +import aws_cdk.aws_s3 as s3 + +class HelloCdkStack(cdk.Stack): + + def __init__(self, scope: cdk.App, construct_id: str, **kwargs) -> None: + super().__init__(scope, construct_id, **kwargs) + + bucket = s3.Bucket(self, "MyFirstBucket", versioned=True) +``` + +------ +#### [ Java ] + +In `src/main/java/com/myorg/HelloCdkStack.java`: + +``` +package com.myorg; + +import software.amazon.awscdk.*; +import software.amazon.awscdk.services.s3.Bucket; + +public class HelloCdkStack extends Stack { + public HelloCdkStack(final App scope, final String id) { + this(scope, id, null); + } + + public HelloCdkStack(final App scope, final String id, final StackProps props) { + super(scope, id, props); + + Bucket.Builder.create(this, "MyFirstBucket") + .versioned(true).build(); + } +} +``` + +------ +#### [ C\# ] + +In `src/HelloCdk/HelloCdkStack.cs`: + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +namespace HelloCdk +{ + public class HelloCdkStack : Stack + { + public HelloCdkStack(App scope, string id, IStackProps props=null) : base(scope, id, props) + { + new Bucket(this, "MyFirstBucket", new BucketProps + { + Versioned = true + }); + } + } +} +``` + +------ + +`Bucket` is the first construct we've seen, so let's take a closer look\. Like all constructs, the `Bucket` class takes three parameters\. ++ **scope:** Tells the bucket that the stack is its parent: it is defined within the scope of the stack\. You can define constructs inside of constructs, creating a hierarchy \(tree\)\. Here, and in most cases, the scope is `this` \(`self` in Python\), meaning the construct that contains the bucket: the stack\. ++ **Id:** The logical ID of the Bucket within your AWS CDK app\. This \(plus a hash based on the bucket's location within the stack\) uniquely identifies the bucket across deployments so the AWS CDK can update it if you change how it's defined in your app\. Here it is "MyFirstBucket\." Buckets can also have a name, which is separate from this ID \(it's the `bucketName` property\)\. ++ **props:** A bundle of values that define properties of the bucket\. Here we've defined only one property: `versioned`, which enables versioning for the files in the bucket\. + +All constructs take these same three arguments, so it's easy to stay oriented as you learn about new ones\. And as you might expect, you can subclass any construct to extend it to suit your needs, or just to change its defaults\. + +**Tip** +If a construct's props are all optional, you can omit the `props` parameter entirely\. + +Props are represented differently in the languages supported by the AWS CDK\. ++ In TypeScript and JavaScript, `props` is a single argument and you pass in an object containing the desired properties\. ++ In Python, props are passed as keyword arguments\. ++ In Java, a Builder is provided to pass the props\. Two, actually; one for `BucketProps`, and a second for `Bucket` to let you build the construct and its props object in one step\. This code uses the latter\. ++ In C\#, you instantiate a `BucketProps` object using an object initializer and pass it as the third parameter\. + +## Synthesize an AWS CloudFormation template + +Synthesize an AWS CloudFormation template for the app, as follows\. + +``` +cdk synth +``` + +If your app contained more than one stack, you'd need to specify which stack\(s\) to synthesize\. But since it only contains one, the CDK Toolkit knows you must mean that one\. + +**Tip** +If you received an error like `--app is required...`, it's probably because you are running the command from a subdirectory\. Navigate to the main app directory and try again\. + +The `cdk synth` command executes your app, which causes the resources defined in it to be translated into an AWS CloudFormation template\. The displayed output of `cdk synth` is a YAML\-format template; the beginning of our app's output is shown below\. The template is also saved in the `cdk.out` directory in JSON format\. + +``` +Resources: + MyFirstBucketB8884501: + Type: AWS::S3::Bucket + Properties: + VersioningConfiguration: + Status: Enabled + UpdateReplacePolicy: Retain + DeletionPolicy: Retain + Metadata:... +``` + +Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for the bucket and see how the `versioned` property was translated\. + +**Note** +Every generated template contains a `AWS::CDK::Metadata` resource by default\. \(We haven't shown it here\.\) The AWS CDK team uses this metadata to gain insight into how the AWS CDK is used, so we can continue to improve it\. For details, including how to opt out of version reporting, see [Version reporting](cli.md#version_reporting)\. + +The `cdk synth` generates a perfectly valid AWS CloudFormation template\. You could take it and deploy it using the AWS CloudFormation console or another tool\. But the AWS CDK Toolkit can also do that\. + +## Deploying the stack + +To deploy the stack using AWS CloudFormation, issue: + +``` +cdk deploy +``` + +As with `cdk synth`, you don't need to specify the name of the stack since there's only one in the app\. + +It is optional \(though good practice\) to synthesize before deploying\. The AWS CDK synthesizes your stack before each deployment\. + +If your code has security implications, you'll see a summary of these and need to confirm them before deployment proceeds\. This isn't the case in our stack\. + +`cdk deploy` displays progress information as your stack is deployed\. When it's done, the command prompt reappears\. You can go to the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home) and see that it now lists `HelloCdkStack`\. You'll also find `MyFirstBucket` in the Amazon S3 console\. + +You've deployed your first stack using the AWS CDK—congratulations\! But that's not all there is to the AWS CDK\. + +## Modifying the app + +The AWS CDK can update your deployed resources after you modify your app\. Let's change our bucket so it can be automatically deleted when we delete the stack, which involves changing its `RemovalPolicy`\. Also, because AWS CloudFormation won't delete Amazon S3 buckets that contain any objects, we'll ask the AWS CDK to delete the objects from our bucket before destroying the bucket, via the `autoDeleteObjects` property\. + +------ +#### [ TypeScript ] + +Update `lib/hello-cdk-stack.ts`\. + +``` +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true, + removalPolicy: cdk.RemovalPolicy.DESTROY, + autoDeleteObjects: true +}); +``` + +------ +#### [ JavaScript ] + +Update `lib/hello-cdk-stack.js`\. + +``` +new s3.Bucket(this, 'MyFirstBucket', { + versioned: true, + removalPolicy: cdk.RemovalPolicy.DESTROY, + autoDeleteObjects: true +}); +``` + +------ +#### [ Python ] + +Update `hello_cdk/hello_cdk_stack.py`\. + +``` +bucket = s3.Bucket(self, "MyFirstBucket", + versioned=True, + removal_policy=cdk.RemovalPolicy.DESTROY, + auto_delete_objects=True) +``` + +------ +#### [ Java ] + +Update `src/main/java/com/myorg/HelloCdkStack.java`\. + +``` +Bucket.Builder.create(this, "MyFirstBucket") + .versioned(true) + .removalPolicy(RemovalPolicy.DESTROY) + .autoDeleteObjects(true) + .build(); +``` + +------ +#### [ C\# ] + +Update `src/HelloCdk/HelloCdkStack.cs`\. + +``` +new Bucket(this, "MyFirstBucket", new BucketProps +{ + Versioned = true, + RemovalPolicy = RemovalPolicy.DESTROY, + AutoDeleteObjects = true +}); +``` + +------ + +Here, we haven't written any code that, in itself, changes our Amazon S3 bucket\. Instead, our code defines the desired state of the bucket\. The AWS CDK synthesizes that state to a new AWS CloudFormation template and deploys a changeset that makes only the changes necessary to reach that state\. + +To see these changes, we'll use the `cdk diff` command \. + +``` +cdk diff +``` + +The AWS CDK Toolkit queries your AWS account for the last\-deployed AWS CloudFormation template for the `HelloCdkStack` and compares it with the template it just synthesized from your app\. The output should look like the following\. + +``` +Stack HelloCdkStack +IAM Statement Changes +┌───┬──────────────────────────────┬────────┬──────────────────────────────┬──────────────────────────────┬───────────┐ +│ │ Resource │ Effect │ Action │ Principal │ Condition │ +├───┼──────────────────────────────┼────────┼──────────────────────────────┼──────────────────────────────┼───────────┤ +│ + │ ${Custom::S3AutoDeleteObject │ Allow │ sts:AssumeRole │ Service:lambda.amazonaws.com │ │ +│ │ sCustomResourceProvider/Role │ │ │ │ │ +│ │ .Arn} │ │ │ │ │ +├───┼──────────────────────────────┼────────┼──────────────────────────────┼──────────────────────────────┼───────────┤ +│ + │ ${MyFirstBucket.Arn} │ Allow │ s3:DeleteObject* │ AWS:${Custom::S3AutoDeleteOb │ │ +│ │ ${MyFirstBucket.Arn}/* │ │ s3:GetBucket* │ jectsCustomResourceProvider/ │ │ +│ │ │ │ s3:GetObject* │ Role.Arn} │ │ +│ │ │ │ s3:List* │ │ │ +└───┴──────────────────────────────┴────────┴──────────────────────────────┴──────────────────────────────┴───────────┘ +IAM Policy Changes +┌───┬────────────────────────────────────────────────────────┬────────────────────────────────────────────────────────┐ +│ │ Resource │ Managed Policy ARN │ +├───┼────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤ +│ + │ ${Custom::S3AutoDeleteObjectsCustomResourceProvider/Ro │ {"Fn::Sub":"arn:${AWS::Partition}:iam::aws:policy/serv │ +│ │ le} │ ice-role/AWSLambdaBasicExecutionRole"} │ +└───┴────────────────────────────────────────────────────────┴────────────────────────────────────────────────────────┘ +(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299) + +Parameters +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/S3Bucket AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3BucketBF7A7F3F: {"Type":"String","Description":"S3 bucket for asset \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/S3VersionKey AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3VersionKeyFAF93626: {"Type":"String","Description":"S3 key for asset version \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} +[+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/ArtifactHash AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392ArtifactHashE56CD69A: {"Type":"String","Description":"Artifact hash for asset \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} + +Resources +[+] AWS::S3::BucketPolicy MyFirstBucket/Policy MyFirstBucketPolicy3243DEFD +[+] Custom::S3AutoDeleteObjects MyFirstBucket/AutoDeleteObjectsCustomResource MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E +[+] AWS::IAM::Role Custom::S3AutoDeleteObjectsCustomResourceProvider/Role CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092 +[+] AWS::Lambda::Function Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F +[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 + ├─ [~] DeletionPolicy + │ ├─ [-] Retain + │ └─ [+] Delete + └─ [~] UpdateReplacePolicy + ├─ [-] Retain + └─ [+] Delete +``` + +This diff has four sections\. ++ **IAM Statement Changes** and **IAM Policy Changes** \- These permission changes are there because we set the `AutoDeleteObjects` property on our Amazon S3 bucket\. The auto\-delete feature uses a custom resource to delete the objects in the bucket before the bucket itself is deleted\. The IAM objects grant the custom resource's code access to the bucket\. ++ **Parameters** \- The AWS CDK uses these entries to locate the Lambda function asset for the custom resource\. ++ **Resources** \- The new and changed resources in this stack\. We can see the aforementioned IAM objects, the custom resource ,and its associated Lambda function being added\. We can also see that the bucket's `DeletionPolicy` and `UpdateReplacePolicy` attributes are being updated\. These allow the bucket to be deleted along with the stack, and to be replaced with a new one\. + +You may be curious about why we specified `RemovalPolicy` in our AWS CDK app but got a `DeletionPolicy` property in the resulting AWS CloudFormation template\. The AWS CDK uses a different name for the property because the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it\. See [Removal policies](resources.md#resources_removal) for further details\. + +It's informative to compare the output of cdk synth here with the previous output and see the many additional lines of AWS CloudFormation template that the AWS CDK generated for us based on these relatively small changes\. + +**Important** +Since the `autoDeleteObjects` property is implemented using a AWS CloudFormation custom resource, which is implemented using an AWS Lambda function, our stack contains an [asset](assets.md)\. This fact requires that our AWS account and region be [bootstrapped](bootstrapping.md) so that there's an Amazon S3 bucket to hold the asset during deployment\. If you haven't already bootstrapped, issue: + +``` +cdk bootstrap aws://ACCOUNT-NUMBER/REGION +``` + +Now let's deploy\. + +``` +cdk deploy +``` + +The AWS CDK warns you about the security policy changes we've already seen in the diff\. Enter y to approve the changes and deploy the updated stack\. The CDK Toolkit updates the bucket configuration as you requested\. + +``` +HelloCdkStack: deploying... +[0%] start: Publishing 4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392:current +[100%] success: Published 4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392:current +HelloCdkStack: creating CloudFormation changeset... + 0/5 | 4:32:31 PM | UPDATE_IN_PROGRESS | AWS::CloudFormation::Stack | HelloCdkStack User Initiated + 0/5 | 4:32:36 PM | CREATE_IN_PROGRESS | AWS::IAM::Role | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092) + 1/5 | 4:32:36 PM | UPDATE_COMPLETE | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketB8884501) + 1/5 | 4:32:36 PM | CREATE_IN_PROGRESS | AWS::IAM::Role | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092) Resource creation Initiated + 3/5 | 4:32:54 PM | CREATE_COMPLETE | AWS::IAM::Role | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092) + 3/5 | 4:32:56 PM | CREATE_IN_PROGRESS | AWS::Lambda::Function | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F) + 3/5 | 4:32:56 PM | CREATE_IN_PROGRESS | AWS::S3::BucketPolicy | MyFirstBucket/Policy (MyFirstBucketPolicy3243DEFD) + 3/5 | 4:32:56 PM | CREATE_IN_PROGRESS | AWS::Lambda::Function | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F) Resource creation Initiated + 3/5 | 4:32:57 PM | CREATE_COMPLETE | AWS::Lambda::Function | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F) + 3/5 | 4:32:57 PM | CREATE_IN_PROGRESS | AWS::S3::BucketPolicy | MyFirstBucket/Policy (MyFirstBucketPolicy3243DEFD) Resource creation Initiated + 4/5 | 4:32:57 PM | CREATE_COMPLETE | AWS::S3::BucketPolicy | MyFirstBucket/Policy (MyFirstBucketPolicy3243DEFD) + 4/5 | 4:32:59 PM | CREATE_IN_PROGRESS | Custom::S3AutoDeleteObjects | MyFirstBucket/AutoDeleteObjectsCustomResource/Default (MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E) + 5/5 | 4:33:06 PM | CREATE_IN_PROGRESS | Custom::S3AutoDeleteObjects | MyFirstBucket/AutoDeleteObjectsCustomResource/Default (MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E) Resource creation Initiated + 5/5 | 4:33:06 PM | CREATE_COMPLETE | Custom::S3AutoDeleteObjects | MyFirstBucket/AutoDeleteObjectsCustomResource/Default (MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E) + 5/5 | 4:33:08 PM | UPDATE_COMPLETE_CLEA | AWS::CloudFormation::Stack | HelloCdkStack + 6/5 | 4:33:09 PM | UPDATE_COMPLETE | AWS::CloudFormation::Stack | HelloCdkStack + + ✅ HelloCdkStack + +Stack ARN: +arn:aws:cloudformation:REGION:ACCOUNT:stack/HelloCdkStack/UNIQUE-ID +``` + +## Destroying the app's resources + +Now that you're done with the quick tour, destroy your app's resources to avoid incurring any costs from the bucket you created, as follows\. + +``` +cdk destroy +``` + +Enter y to approve the changes and delete any stack resources\. + +**Note** +If we hadn't changed the bucket's `RemovalPolicy`, the stack deletion would complete successfully, but the bucket would become orphaned \(no longer associated with the stack\)\. + +## Next steps + +Where do you go now that you've dipped your toes in the AWS CDK? ++ Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. ++ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. ++ See the [API reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite AWS services\. ++ Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) to discover constructs created by AWS and others\. ++ Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. + +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/v2/home.md b/v2/home.md new file mode 100644 index 00000000..a2bf6154 --- /dev/null +++ b/v2/home.md @@ -0,0 +1,264 @@ +# What is the AWS CDK? + +Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. + +**Note** +The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v2\. + +The AWS CDK lets you build reliable, scalable, cost\-effective applications in the cloud with the considerable expressive power of a programming language\. This approach yields many benefits, including: ++ Build with high\-level constructs that automatically provide sensible, secure defaults for your AWS resources, defining more infrastructure with less code\. ++ Use programming idioms like parameters, conditionals, loops, composition, and inheritance to model your system design from building blocks provided by AWS and others\. ++ Put your infrastructure, application code, and configuration all in one place, ensuring that at every milestone you have a complete, cloud\-deployable system\. ++ Employ software engineering practices such as code reviews, unit tests, and source control to make your infrastructure more robust\. ++ Connect your AWS resources together \(even across stacks\) and grant permissions using simple, intent\-oriented APIs\. ++ Import existing AWS CloudFormation templates to give your resources a CDK API\. ++ Use the power of AWS CloudFormation to perform infrastructure deployments predictably and repeatedly, with rollback on error\. ++ Easily share infrastructure design patterns among teams within your organization or even with the public\. + +The AWS CDK supports TypeScript, JavaScript, Python, Java, C\#/\.Net, and \(in developer preview\) Go\. Developers can use one of these supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/AppStacks.png) + +## Why use the AWS CDK? + +It's easier to show than to explain\! Here's some CDK code that creates an Amazon ECS service with AWS Fargate launch type \(this is the code we use in the [Creating an AWS Fargate service using the AWS CDK](ecs_example.md)\)\. + +------ +#### [ TypeScript ] + +``` +export class MyEcsConstructStack extends Stack { + constructor(scope: App, id: string, props?: StackProps) { + super(scope, id, props); + + const vpc = new ec2.Vpc(this, "MyVpc", { + maxAzs: 3 // Default is all AZs in region + }); + + const cluster = new ecs.Cluster(this, "MyCluster", { + vpc: vpc + }); + + // Create a load-balanced Fargate service and make it public + new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { + cluster: cluster, // Required + cpu: 512, // Default is 256 + desiredCount: 6, // Default is 1 + taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, + memoryLimitMiB: 2048, // Default is 512 + publicLoadBalancer: true // Default is false + }); + } +} +``` + +------ +#### [ JavaScript ] + +``` +class MyEcsConstructStack extends Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const vpc = new ec2.Vpc(this, "MyVpc", { + maxAzs: 3 // Default is all AZs in region + }); + + const cluster = new ecs.Cluster(this, "MyCluster", { + vpc: vpc + }); + + // Create a load-balanced Fargate service and make it public + new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { + cluster: cluster, // Required + cpu: 512, // Default is 256 + desiredCount: 6, // Default is 1 + taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, + memoryLimitMiB: 2048, // Default is 512 + publicLoadBalancer: true // Default is false + }); + } +} + +module.exports = { MyEcsConstructStack } +``` + +------ +#### [ Python ] + +``` +class MyEcsConstructStack(Stack): + + def __init__(self, scope: Construct, id: str, **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + vpc = ec2.Vpc(self, "MyVpc", max_azs=3) # default is all AZs in region + + cluster = ecs.Cluster(self, "MyCluster", vpc=vpc) + + ecs_patterns.ApplicationLoadBalancedFargateService(self, "MyFargateService", + cluster=cluster, # Required + cpu=512, # Default is 256 + desired_count=6, # Default is 1 + task_image_options=ecs_patterns.ApplicationLoadBalancedTaskImageOptions( + image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")), + memory_limit_mib=2048, # Default is 512 + public_load_balancer=True) # Default is False +``` + +------ +#### [ Java ] + +``` +public class MyEcsConstructStack extends Stack { + + public MyEcsConstructStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyEcsConstructStack(final Construct scope, final String id, + StackProps props) { + super(scope, id, props); + + Vpc vpc = Vpc.Builder.create(this, "MyVpc").maxAzs(3).build(); + + Cluster cluster = Cluster.Builder.create(this, "MyCluster") + .vpc(vpc).build(); + + ApplicationLoadBalancedFargateService.Builder.create(this, "MyFargateService") + .cluster(cluster) + .cpu(512) + .desiredCount(6) + .taskImageOptions( + ApplicationLoadBalancedTaskImageOptions.builder() + .image(ContainerImage + .fromRegistry("amazon/amazon-ecs-sample")) + .build()).memoryLimitMiB(2048) + .publicLoadBalancer(true).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +public class MyEcsConstructStack : Stack +{ + public MyEcsConstructStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) + { + var vpc = new Vpc(this, "MyVpc", new VpcProps + { + MaxAzs = 3 + }); + + var cluster = new Cluster(this, "MyCluster", new ClusterProps + { + Vpc = vpc + }); + + new ApplicationLoadBalancedFargateService(this, "MyFargateService", + new ApplicationLoadBalancedFargateServiceProps + { + Cluster = cluster, + Cpu = 512, + DesiredCount = 6, + TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions + { + Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample") + }, + MemoryLimitMiB = 2048, + PublicLoadBalancer = true, + }); + } +} +``` + +------ + +This class produces an AWS CloudFormation [template of more than 500 lines](https://github.com/awsdocs/aws-cdk-guide/blob/main/doc_source/my_ecs_construct-stack.yaml); deploying the AWS CDK app produces more than 50 resources of the following types\. ++ [AWS::EC2::EIP](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html) ++ [AWS::EC2::InternetGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html) ++ [AWS::EC2::NatGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html) ++ [AWS::EC2::Route](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html) ++ [AWS::EC2::RouteTable](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-routetable.html) ++ [AWS::EC2::SecurityGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html) ++ [AWS::EC2::Subnet](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html) ++ [AWS::EC2::SubnetRouteTableAssociation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html) ++ [AWS::EC2::VPCGatewayAttachment](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html) ++ [AWS::EC2::VPC](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html) ++ [AWS::ECS::Cluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-cluster.html) ++ [AWS::ECS::Service](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html) ++ [AWS::ECS::TaskDefinition](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-taskdefinition.html) ++ [AWS::ElasticLoadBalancingV2::Listener](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html) ++ [AWS::ElasticLoadBalancingV2::LoadBalancer](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html) ++ [AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html) ++ [AWS::IAM::Policy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html) ++ [AWS::IAM::Role](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html) ++ [AWS::Logs::LogGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html) + +And lest we forget\.\.\. code completion within your IDE or editor\! + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/CodeCompletion.png) + +## Developing with the AWS CDK + +It's easy to [get set up](getting_started.md) and [write your first CDK app](hello_world.md)\. Short code examples are available throughout this Guide in the AWS CDK's supported programming languages: TypeScript, JavaScript, Python, Java, and C\#\. Longer examples are available [in our GitHub repository](https://github.com/aws-samples/aws-cdk-examples)\. + +The [AWS CDK Toolkit](cli.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. + +The [AWS Construct Library](constructs.md) offers constructs for each AWS service, many with "rich" APIs that provide high\-level abstractions\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. + +**Note** +There is no charge for using the AWS CDK, but you might incur AWS charges for creating or using AWS [chargeable resources](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Pricing Calculator](https://calculator.aws/#/) to estimate charges for the use of various AWS resources\. + +## The Construct Programming Model + +The Construct Programming Model \(CPM\) extends the concepts behind the AWS CDK into additional domains\. Other tools using the CPM include: ++ [CDK for Terraform](https://www.terraform.io/docs/cdktf/index.html) \(CDKtf\) ++ [CDK for Kubernetes](https://cdk8s.io/) \(CDK8s\) ++ [Projen](https://github.com/projen/projen), for building project configurations + +[Construct Hub](https://constructs.dev/) is an online registry where you can find and publish construct libraries for CDKs like the AWS CDK\. + +## Additional documentation and resources + +In addition to this guide, the following other resources are available to AWS CDK users: ++ [API Reference](https://docs.aws.amazon.com/cdk/api/v2) ++ [AWS CDK Workshop](https://cdkworkshop.com/) ++ [cdk\.dev](https://cdk.dev/) community hub, including a Slack channel ++ [AWS CDK Examples](https://github.com/aws-samples/aws-cdk-examples) ++ [CDK Patterns](https://cdkpatterns.com/) ++ [Awesome CDK](https://github.com/kolomied/awesome-cdk) ++ [AWS Solutions Constructs](http://aws.amazon.com/solutions/constructs/) ++ [AWS Developer Blog](https://aws.amazon.com/blogs/developer/category/developer-tools/aws-cloud-development-kit) CDK category ++ [Stack Overflow](https://stackoverflow.com/questions/tagged/aws-cdk) ++ [GitHub Repository](https://github.com/awslabs/aws-cdk) + + [Issues](https://github.com/awslabs/aws-cdk/issues) + + [Examples](https://github.com/aws-samples/aws-cdk-examples) + + [Documentation Source](https://github.com/awsdocs/aws-cdk-guide) + + [License](https://github.com/awslabs/aws-cdk/blob/master/LICENSE) + + [Releases](https://github.com/awslabs/aws-cdk/releases) + + [AWS CDK OpenPGP key](pgp-keys.md#cdk_pgp_key) + + [JSII OpenPGP key](pgp-keys.md#jsii_pgp_key) ++ [AWS CDK Sample for Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/sample-cdk.html) ++ [AWS CloudFormation Concepts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html) ++ [AWS Glossary](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html) + +### Resources for serverless apps with CDK + +These tools can work with the AWS CDK to simplify serverless application development and deployment\. ++ [AWS Serverless Application Model](http://aws.amazon.com/serverless/sam/) ++ [AWS Chalice](https://github.com/aws/chalice), a Python serverless microframework + +## Contributing to the AWS CDK + +Because the AWS CDK is open source, the team encourages you to contribute to make it an even better tool\. For details, see [Contributing](https://github.com/awslabs/aws-cdk/blob/master/CONTRIBUTING.md)\. + +## About Amazon Web Services + +Amazon Web Services \(AWS\) is a collection of digital infrastructure services that developers can use when developing their applications\. The services include computing, storage, database, and application synchronization \(messaging and queueing\)\. + +AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. + +To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file diff --git a/v2/how_to_set_cw_alarm.md b/v2/how_to_set_cw_alarm.md new file mode 100644 index 00000000..42fb63d3 --- /dev/null +++ b/v2/how_to_set_cw_alarm.md @@ -0,0 +1,241 @@ +# Set a CloudWatch alarm + +The [aws\-cloudwatch](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch-readme.html) package supports setting CloudWatch alarms on CloudWatch metrics\. So the first thing you need is a metric\. You can use a predefined metric or you can create your own\. + +## Using an existing metric + +Many AWS Construct Library modules let you set an alarm on an existing metric by passing the metric's name to a convenience method on an instance of an object that has metrics\. For example, given an Amazon SQS queue, you can get the metric **ApproximateNumberOfMessagesVisible** from the queue's [metric\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sqs.Queue.html#metricmetricname-props) method\. + +------ +#### [ TypeScript ] + +``` +const metric = queue.metric("ApproximateNumberOfMessagesVisible"); +``` + +------ +#### [ JavaScript ] + +``` +const metric = queue.metric("ApproximateNumberOfMessagesVisible"); +``` + +------ +#### [ Python ] + +``` +metric = queue.metric("ApproximateNumberOfMessagesVisible") +``` + +------ +#### [ Java ] + +``` +Metric metric = queue.metric("ApproximateNumberOfMessagesVisible"); +``` + +------ +#### [ C\# ] + +``` +var metric = queue.Metric("ApproximateNumberOfMessagesVisible"); +``` + +------ + +## Creating your own metric + +Create your own [metric](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html) as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. You also need to specify your metric's name and dimension\. + +------ +#### [ TypeScript ] + +``` +const metric = new cloudwatch.Metric({ + namespace: 'MyNamespace', + metricName: 'MyMetric', + dimensions: { MyDimension: 'MyDimensionValue' } +}); +``` + +------ +#### [ JavaScript ] + +``` +const metric = new cloudwatch.Metric({ + namespace: 'MyNamespace', + metricName: 'MyMetric', + dimensions: { MyDimension: 'MyDimensionValue' } +}); +``` + +------ +#### [ Python ] + +``` +metric = cloudwatch.Metric( + namespace="MyNamespace", + metric_name="MyMetric", + dimensions=dict(MyDimension="MyDimensionValue") +) +``` + +------ +#### [ Java ] + +``` +Metric metric = Metric.Builder.create() + .namespace("MyNamespace") + .metricName("MyMetric") + .dimensions(new HashMap() {{ + put("MyDimension", "MyDimensionValue"); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +var metric = new Metric(this, "Metric", new MetricProps +{ + Namespace = "MyNamespace", + MetricName = "MyMetric", + Dimensions = new Dictionary + { + { "MyDimension", "MyDimensionValue" } + } +}); +``` + +------ + +## Creating the alarm + +Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three seconds\. You can use comparisons such as less\-than in your alarms via the `comparisonOperator` property; greater\-than\-or\-equal\-to is the AWS CDK default, so we don't need to specify it\. + +Assuming the metric is the **ApproximateNumberOfMessagesVisible** metric from an Amazon SQS queue, it would raise when 100 messages are visible in the queue in two of the last three seconds\. + +------ +#### [ TypeScript ] + +``` +const alarm = new cloudwatch.Alarm(this, 'Alarm', { + metric: metric, + threshold: 100, + evaluationPeriods: 3, + datapointsToAlarm: 2, +}); +``` + +------ +#### [ JavaScript ] + +``` +const alarm = new cloudwatch.Alarm(this, 'Alarm', { + metric: metric, + threshold: 100, + evaluationPeriods: 3, + datapointsToAlarm: 2 +}); +``` + +------ +#### [ Python ] + +``` +alarm = cloudwatch.Alarm(self, "Alarm", + metric=metric, + threshold=100, + evaluation_periods=3, + datapoints_to_alarm=2 +) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.cloudwatch.Alarm; +import software.amazon.awscdk.services.cloudwatch.Metric; + +Alarm alarm = Alarm.Builder.create(this, "Alarm") + .metric(metric) + .threshold(100) + .evaluationPeriods(3) + .datapointsToAlarm(2).build(); +``` + +------ +#### [ C\# ] + +``` +var alarm = new Alarm(this, "Alarm", new AlarmProps +{ + Metric = metric, + Threshold = 100, + EvaluationPeriods = 3, + DatapointsToAlarm = 2 +}); +``` + +------ + +An alternative way to create an alarm is using the metric's [createAlarm\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html#createwbralarmscope-id-props) method, which takes essentially the same properties as the `Alarm` constructor; you just don't need to pass in the metric, since it's already known\. + +------ +#### [ TypeScript ] + +``` +metric.createAlarm(this, 'Alarm', { + threshold: 100, + evaluationPeriods: 3, + datapointsToAlarm: 2, +}); +``` + +------ +#### [ JavaScript ] + +``` +metric.createAlarm(this, 'Alarm', { + threshold: 100, + evaluationPeriods: 3, + datapointsToAlarm: 2, +}); +``` + +------ +#### [ Python ] + +``` +metric.create_alarm(self, "Alarm", + threshold=100, + evaluation_periods=3, + datapoints_to_alarm=2 +) +``` + +------ +#### [ Java ] + +``` +metric.createAlarm(this, "Alarm", new CreateAlarmOptions.Builder() + .threshold(100) + .evaluationPeriods(3) + .datapointsToAlarm(2) + .build()); +``` + +------ +#### [ C\# ] + +``` +metric.CreateAlarm(this, "Alarm", new CreateAlarmOptions +{ + Threshold = 100, + EvaluationPeriods = 3, + DatapointsToAlarm = 2 +}); +``` + +------ \ No newline at end of file diff --git a/v2/how_tos.md b/v2/how_tos.md new file mode 100644 index 00000000..229bd4c7 --- /dev/null +++ b/v2/how_tos.md @@ -0,0 +1,3 @@ +# AWS CDK how\-tos + +This section contains short code examples that show you how to accomplish a task using the AWS CDK\. \ No newline at end of file diff --git a/v2/identifiers.md b/v2/identifiers.md new file mode 100644 index 00000000..be2ac4e6 --- /dev/null +++ b/v2/identifiers.md @@ -0,0 +1,283 @@ +# Identifiers + +The AWS CDK deals with many types of identifiers and names\. To use the AWS CDK effectively and avoid errors, you need to understand the types of identifiers\. + +Identifiers must be unique within the scope in which they are created; they do not need to be globally unique in your AWS CDK application\. + +If you attempt to create an identifier with the same value within the same scope, the AWS CDK throws an exception\. + +## Construct IDs + +The most common identifier, `id`, is the identifier passed as the second argument when instantiating a construct object\. This identifier, like all identifiers, need only be unique within the scope in which it is created, which is the first argument when instantiating a construct object\. + +**Note** +The `id` of a stack is also the identifier you use to refer to it in the [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. + +Let's look at an example where we have two constructs with the identifier `MyBucket` in our app\. However, since they are defined in different scopes, the first in the scope of the stack with the identifier `Stack1`, and the second in the scope of a stack with the identifier `Stack2`, that doesn't cause any sort of conflict, and they can coexist in the same app without any issues\. + +------ +#### [ TypeScript ] + +``` +import { App, Stack, StackProps } from 'aws-cdk-lib'; +import { Construct } from 'constructs'; +import * as s3 from 'aws-cdk-lib/aws-s3'; + +class MyStack extends Stack { + constructor(scope: Construct, id: string, props: StackProps = {}) { + super(scope, id, props); + + new s3.Bucket(this, 'MyBucket'); + } +} + +const app = new App(); +new MyStack(app, 'Stack1'); +new MyStack(app, 'Stack2'); +``` + +------ +#### [ JavaScript ] + +``` +const { App , Stack } = require('aws-cdk-lib'); +const s3 = require('aws-cdk-lib/aws-s3'); + +class MyStack extends Stack { + constructor(scope, id, props = {}) { + super(scope, id, props); + + new s3.Bucket(this, 'MyBucket'); + } +} + +const app = new App(); +new MyStack(app, 'Stack1'); +new MyStack(app, 'Stack2'); +``` + +------ +#### [ Python ] + +``` +from aws_cdk import App, Construct, Stack, StackProps +from constructs import Construct +from aws_cdk import aws_s3 as s3 + +class MyStack(Stack): + + def __init__(self, scope: Construct, id: str, **kwargs): + + super().__init__(scope, id, **kwargs) + s3.Bucket(self, "MyBucket") + +app = App() +MyStack(app, 'Stack1') +MyStack(app, 'Stack2') +``` + +------ +#### [ Java ] + +``` +// MyStack.java +package com.myorg; + +import software.amazon.awscdk.App; +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.constructs.Construct; +import software.amazon.awscdk.services.s3.Bucket; + +public class MyStack extends Stack { + public MyStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + new Bucket(this, "MyBucket"); + } +} + +// Main.java +package com.myorg; + +import software.amazon.awscdk.App; + +public class Main { + public static void main(String[] args) { + App app = new App(); + new MyStack(app, "Stack1"); + new MyStack(app, "Stack2"); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using constructs; +using Amazon.CDK.AWS.S3; + +public class MyStack : Stack +{ + public MyStack(Construct scope, string id, IStackProps props) : base(scope, id, props) + { + new Bucket(this, "MyBucket"); + } +} + +class Program +{ + static void Main(string[] args) + { + var app = new App(); + new MyStack(app, "Stack1"); + new MyStack(app, "Stack2"); + } +} +``` + +------ + +## Paths + +The constructs in an AWS CDK application form a hierarchy rooted in the `App` class\. We refer to the collection of IDs from a given construct, its parent construct, its grandparent, and so on to the root of the construct tree, as a *path*\. + +The AWS CDK typically displays paths in your templates as a string, with the IDs from the levels separated by slashes, starting at the node just below the root `App` instance, which is usually a stack\. For example, the paths of the two Amazon S3 bucket resources in the previous code example are `Stack1/MyBucket` and `Stack2/MyBucket`\. + +You can access the path of any construct programmatically, as shown in the following example, which gets the path of `myConstruct` \(or `my_construct`, as Python developers would write it\)\. Since IDs must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. + +------ +#### [ TypeScript ] + +``` +const path: string = myConstruct.node.path; +``` + +------ +#### [ JavaScript ] + +``` +const path = myConstruct.node.path; +``` + +------ +#### [ Python ] + +``` +path = my_construct.node.path +``` + +------ +#### [ Java ] + +``` +String path = myConstruct.getNode().getPath(); +``` + +------ +#### [ C\# ] + +``` +string path = myConstruct.Node.Path; +``` + +------ + +## Unique IDs + +Since AWS CloudFormation requires that all logical IDs in a template are unique, the AWS CDK must be able to generate a unique identifier for each construct in an application\. Resources have paths that are globally unique \(the names of all scopes from the stack to a specific resource\) so the AWS CDK generates the necessary unique identifiers by concatenating the elements of the path and adding an 8\-digit hash\. \(The hash is necessary to distinguish distinct paths, such as `A/B/C` and `A/BC`, that would result in the same AWS CloudFormation identifier, since AWS CloudFormation identifiers are alphanumeric and cannot contain slashes or other separator characters\.\) The AWS CDK calls this string the *unique ID* of the construct\. + +In general, your AWS CDK app should not need to know about unique IDs\. You can, however, access the unique ID of any construct programmatically, as shown in the following example\. + +------ +#### [ TypeScript ] + +``` +const uid: string = Names.uniqueId(myConstruct); +``` + +------ +#### [ JavaScript ] + +``` +const uid = Names.uniqueId(myConstruct); +``` + +------ +#### [ Python ] + +``` +uid = Names.unique_id(my_construct) +``` + +------ +#### [ Java ] + +``` +String uid = Names.uniqueId(myConstruct); +``` + +------ +#### [ C\# ] + +``` +string uid = Names.Uniqueid(myConstruct); +``` + +------ + +The *address* is another kind of unique identifier that uniquely distinguishes CDK resources\. Derived from the SHA\-1 hash of the path, it is not human\-readable, but its constant, relatively short length \(always 42 hexadecimal characters\) makes it useful in situations where the "traditional" unique ID might be too long\. Some constructs may use the address in the synthesized AWS CloudFormation template instead of the unique ID\. Again, your app generally should not need to know about its constructs' addresses, but you can retrieve a construct's address as follows\. + +------ +#### [ TypeScript ] + +``` +const addr: string = myConstruct.node.addr; +``` + +------ +#### [ JavaScript ] + +``` +const addr = myConstruct.node.addr; +``` + +------ +#### [ Python ] + +``` +addr = my_construct.node.addr +``` + +------ +#### [ Java ] + +``` +String addr = myConstruct.getNode().getAddr(); +``` + +------ +#### [ C\# ] + +``` +string addr = myConstruct.Node.Addr; +``` + +------ + +## Logical IDs + +Unique IDs serve as the *logical identifiers*, which are sometimes called *logical names*, of resources in the generated AWS CloudFormation templates for those constructs that represent AWS resources\. + +For example, the Amazon S3 bucket in the previous example that is created within `Stack2` results in an `AWS::S3::Bucket` resource with the logical ID `Stack2MyBucket4DD88B4F` in the resulting AWS CloudFormation template\. + +Think of construct IDs as part of your construct's public contract\. If you change the ID of a construct in your construct tree, AWS CloudFormation will replace the deployed resource instances of that construct, potentially causing service interruption or data loss\. + +### Logical ID stability + +Avoid changing the logical ID of a resource between deployments\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID\. \ No newline at end of file diff --git a/v2/index.md b/v2/index.md new file mode 100644 index 00000000..b8cc898d --- /dev/null +++ b/v2/index.md @@ -0,0 +1,76 @@ +# AWS Cloud Development Kit (AWS CDK) v2 Developer Guide + +----- +*****Copyright © 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 the AWS CDK?](home.md) ++ [Getting started with the AWS CDK](getting_started.md) + + [Your first AWS CDK app](hello_world.md) ++ [Working with the AWS CDK](work-with.md) + + [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) + + [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) + + [Working with the AWS CDK in Python](work-with-cdk-python.md) + + [Working with the AWS CDK in Java](work-with-cdk-java.md) + + [Working with the AWS CDK in C#](work-with-cdk-csharp.md) + + [Working with the AWS CDK in Go](work-with-cdk-go.md) ++ [Migrating to AWS CDK v2](migrating-v2.md) ++ [Translating TypeScript AWS CDK code to other languages](multiple_languages.md) ++ [Concepts](core_concepts.md) + + [Constructs](constructs.md) + + [Apps](apps.md) + + [Stacks](stacks.md) + + [Environments](environments.md) + + [Resources](resources.md) + + [Identifiers](identifiers.md) + + [Tokens](tokens.md) + + [Parameters](parameters.md) + + [Tagging](tagging.md) + + [Assets](assets.md) + + [Permissions](permissions.md) + + [Runtime context](context.md) + + [Feature flags](featureflags.md) + + [Aspects](aspects.md) + + [Escape hatches](cfn_layer.md) + + [Bootstrapping](bootstrapping.md) ++ [Best practices for developing and deploying cloud infrastructure with the AWS CDK](best-practices.md) ++ [API reference](reference.md) ++ [Examples](examples.md) + + [Creating a serverless application using the AWS CDK](serverless_example.md) + + [Creating an AWS Fargate service using the AWS CDK](ecs_example.md) + + [AWS CDK examples](about_examples.md) ++ [AWS CDK how-tos](how_tos.md) + + [Get a value from an environment variable](get_env_var.md) + + [Use an AWS CloudFormation parameter](get_cfn_param.md) + + [Import or migrate an existing AWS CloudFormation template](use_cfn_template.md) + + [Using resources from the AWS CloudFormation Public Registry](use_cfn_public_registry.md) + + [Get a value from the Systems Manager Parameter Store](get_ssm_value.md) + + [Get a value from AWS Secrets Manager](get_secrets_manager_value.md) + + [Create an app with multiple stacks](stack_how_to_create_multiple_stacks.md) + + [Set a CloudWatch alarm](how_to_set_cw_alarm.md) + + [Get a value from a context variable](get_context_var.md) + + [Continuous integration and delivery (CI/CD) using CDK Pipelines](cdk_pipeline.md) ++ [AWS CDK tools](tools.md) + + [AWS CDK Toolkit (cdk command)](cli.md) + + [AWS Toolkit for Visual Studio Code](vscode.md) + + [SAM CLI](sam.md) ++ [Testing constructs](testing.md) ++ [Security for the AWS Cloud Development Kit (AWS CDK)](security.md) + + [Identity and access management for the AWS Cloud Development Kit (AWS CDK)](security-iam.md) + + [Compliance validation for the AWS Cloud Development Kit (AWS CDK)](compliance-validation.md) + + [Resilience for the AWS Cloud Development Kit (AWS CDK)](disaster-recovery-resiliency.md) + + [Infrastructure security for the AWS Cloud Development Kit (AWS CDK)](infrastructure-security.md) ++ [Troubleshooting common AWS CDK issues](troubleshooting.md) ++ [Videos](videos.md) ++ [OpenPGP keys for the AWS CDK and JSII](pgp-keys.md) ++ [AWS CDK Developer Guide history](doc-history.md) \ No newline at end of file diff --git a/v2/infrastructure-security.md b/v2/infrastructure-security.md new file mode 100644 index 00000000..e2052b67 --- /dev/null +++ b/v2/infrastructure-security.md @@ -0,0 +1,3 @@ +# Infrastructure security for the AWS Cloud Development Kit \(AWS CDK\) + +The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. \ No newline at end of file diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md new file mode 100644 index 00000000..9f67b745 --- /dev/null +++ b/v2/migrating-v2.md @@ -0,0 +1,345 @@ +# Migrating to AWS CDK v2 + +Version 2 of the AWS Cloud Development Kit \(AWS CDK\) is designed to make writing infrastructure as code in your preferred programming language even easier\. + +The main changes from AWS CDK v1 to CDK v2 are as follows\. ++ AWS CDK v2 consolidates the stable parts of the AWS Construct Library, including the core library, into a single package, `aws-cdk-lib`\. Developers no longer need to install additional packages for the individual AWS services they use\. This single\-package approach also eliminates the need to synchronize the versions of the various CDK library packages\. + + L1 \(CfnXXXX\) constructs, which represent the exact resources available in AWS CloudFormation, are always considered stable and so are included in `aws-cdk-lib`\. ++ Experimental modules, where we're still working with the community to develop new L2 or L3 constructs, are not included in `aws-cdk-lib`; they are instead distributed as individual packages\. Experimental packages are named with an `alpha` suffix and a semantic version number that matches the first version of the AWS Construct Library with which they are compatible, also with an `alpha` suffix\. Constructs move into `aws-cdk-lib` after being designated stable, permitting the main Construct Library to adhere to strict semantic versioning\. + + Stability is specified at the service level\. For example, if we begin creating one or more L2 constructs for Amazon AppFlow, which at this writing has only L1 constructs, they would first appear in a module named `@aws-cdk/aws-appflow-alpha`, then move to `aws-cdk-lib` when we feel the new constructs meet the fundamental needs of customers\. + + Once a module has been designated stable and incorporated into `aws-cdk-lib`, new APIs are added using the "BetaN" convention described in the next bullet\. + + A new version of each experimental module is released with every release of the AWS CDK, but for the most part, they needn't be kept in sync\. You can upgrade `aws-cdk-lib` or the experimental module whenever you want\. The exception is that when two or more related experimental modules depend on each other, they must be the same version\. ++ For stable modules to which new functionality is being added, new APIs \(whether entirely new constructs or new methods or properties on an existing construct\) receive a `Beta1` suffix \(and then `Beta2`, `Beta3`, etc\. when breaking changes are needed\) while work is in progress\. A version of the API without the suffix is added when the API is designated stable\. All methods except the latest \(whether beta or final\) are then deprecated\. + + For example, if we add a new method `grantPower()` to a construct, it initially appears as `grantPowerBeta1().` If breaking changes are needed \(for example, a new required parameter or property\), the next version of the method would be named `grantPowerBeta2()`, and so on\. When work is complete and the API is finalized, the method `grantPower()` \(with no suffix\) is added, and the BetaN methods are deprecated\. + + All the beta APIs remain in the Construct Library until the next major version \(3\.0\) release, and their signatures will not change\. You'll see deprecation warnings if you use them, so you should move to the final version of the API at your earliest convenience, but a future AWS CDK 2\.x release will not break your application\. ++ The `Construct` class has been extracted from the AWS CDK into a separate library, along with related types, to support efforts to apply the Construct Programming Model to other domains\. If you are writing your own constructs or using related APIs, you must declare the `construct` module as a dependency and make minor changes to your imports\. If you are using advanced features, such as hooking into the CDK app lifecycle, more changes may be needed\. [See the RFC](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0192-remove-constructs-compat.md#release-notes) for full details\. ++ Deprecated properties, methods, and types in AWS CDK v1\.x and its Construct Library have been removed completely from the CDK v2 API\. In most supported languages, these APIs produce warnings under v1\.x, so you may have already migrated to the replacement APIs\. A complete [list of deprecated APIs](https://github.com/aws/aws-cdk/blob/master/DEPRECATED_APIs.md) in CDK v1\.x is available on GitHub\. ++ Behavior that was gated by feature flags in AWS CDK v1\.x is enabled by default in CDK v2, and the old feature flags are no longer needed or, in most cases, supported\. A handful are still available to let you to revert to CDK v1 behavior in very specific circumstances; see [Updating feature flags](#migrating-v2-v1-upgrade-cdk-json)\. ++ CDK v2 requires that the environments you deploy into be boostrapped using the modern bootstrap stack; the legacy bootstrap stack \(the default under v1\) is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. Simply re\-bootstrap your existing environments to upgrade them\. It is no longer necessary to set any feature flags or environment variables to specify the modern bootstrap stack\. + +**Important** +The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. + +## New prerequisites + +Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. Additional requirements are listed here\. ++ For TypeScript developers, TypeScript 3\.8 or later is required\. ++ A new version of the CDK Toolkit is required for use with CDK v2\. Now that CDK is Generally Available, it is the default version when installing\. It is backward\-compatible with CDK v1 projects, so you do not need to keep the old version installed unless you want to create CDK v1 projects\. To upgrade, issue `npm install -g aws-cdk`\. + +## Upgrading from AWS CDK v2 Developer Preview + +If you have been using the CDK v2 Developer Preview, you have dependencies in your project on a Release Candidate version of the AWS CDK, such as `2.0.0-rc1`\. Update these to `2.0.0`, then update the modules installed in your project\. + +------ +#### [ TypeScript ] + +`npm install` or `yarn install` + +------ +#### [ JavaScript ] + +`npm install` or `yarn install` + +------ +#### [ Python ] + +``` +python -m pip install -r requirements.txt +``` + +------ +#### [ Java ] + +``` +mvn package +``` + +------ +#### [ C\# ] + +``` +dotnet restore +``` + +------ + +After updating your dependencies, issue `npm update -g aws-cdk` to update the CDK Toolkit to the release version\. + +## Migrating from AWS CDK v1 to CDK v2 + +To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. + +### Updating feature flags + +Remove all feature flags from `cdk.json`\. You can add one or more of the flags listed below, set to `false`, if your app relies on these specific AWS CDK v1 behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. + +`@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId` +If your application uses multiple Amazon API Gateway API keys and associates them to usage plans + +`@aws-cdk/aws-rds:lowercaseDbIdentifier` +If your application uses Amazon RDS database instance or database clusters, and explicitly specifies the identifier for these + +`@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021` + If your application uses the TLS\_V1\_2\_2019 security policy with Amazon CloudFront distributions\. CDK v2 uses security policy TLSv1\.2\_2021 by default\. + +`@aws-cdk/core:stackRelativeExports` +If your application uses multiple stacks and you refer to resources from one stack in another, this determines whether absolute or relative path is used to construct AWS CloudFormation exports + +The syntax for reverting these flags in `cdk.json` is shown here\. + +``` +{ + "context": { + "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": false, + "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": false, + "@aws-cdk/aws-rds:lowercaseDbIdentifier": false, + "@aws-cdk/core:stackRelativeExports": false, + } +} +``` + +### CDK Toolkit compatibility + +CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compatible with CDK v1 apps, so you can use a single globally\-installed version of CDK Toolkit with all your AWS CDK projects, whether they use v1 or v2\. An exception is that CDK Toolkit v2 creates CDK v2 projects\. + +If you need to create both v1 and v2 CDK projects, **do not install CDK Toolkit v2 globally\.** \(Remove it if you already have it installed: `npm remove -g aws-cdk`\.\) To invoke the CDK Toolkit, use npx to run v1 or v2 of the CDK Toolkit as desired\. + +``` +npx aws-cdk init@1.x app --language typescript +npx aws-cdk init@2.x app --language typescript +``` + +**Tip** +Set up command line aliases so you can use the cdk and cdk1 commands to invoke the desired version of the CDK Toolkit\. + +``` +alias cdk1=npx aws-cdk@1.x +alias cdk=npx aws-cdk@2.x +``` + +``` +doskey cdk=npx1 aws-cdk@1.x $* +doskey cdk=npx aws-cdk@2.x $* +``` + +### Updating dependencies and imports + +Update your app's dependencies, then install the new packages\. Finally, update the imports in your code\. + +------ +#### [ TypeScript ] + +**Applications** +For CDK apps, `package.json` as follows\. Remove dependencies on v1\-style individual stable modules and establish the lowest version of `aws-cdk-lib` you require for your application \(2\.0\.0 here\)\. + +Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` with which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. + +``` +{ + "dependencies": { + "aws-cdk-lib": "^2.0.0", + "@aws-cdk/aws-codestar-alpha": "2.0.0-alpha.1", + "constructs": "^10.0.0" + } +} +``` + +**Construct libraries** +For construct libraries, establish the lowest version of `aws-cdk-lib` you require for your application \(2\.0\.0 here\) and update `package.json` as follows\. + +Note that `aws-cdk-lib` appears both as a peer dependency and a dev dependency\. + +``` +{ + "peerDependencies": { + "aws-cdk-lib": "^2.0.0", + "constructs": "^10.0.0" + }, + "devDependencies": { + "aws-cdk-lib": "^2.0.0", + "constructs": "^10.0.0", + "typescript": "~3.9.0" + } +} +``` + +**Note** +You should perform a major version bump on your library's version number when releasing a v2\-compatible library, as this will be a breaking change for consumers of the library\. It is not possible to support both CDK v1 and v2 with a single library\. To continue to support customers who are still using v1, you could maintain the older release in parallel, or create a new package for v2\. +It's up to you how long you want to continue supporting AWS CDK v1 customers, but you could take your cue from the lifecycle of CDK v1 itself, and continue supporting v1 until AWS CDK v1 enters maintenance \(June 2, 2022\) or end\-of\-life \(June 2, 2023\)\. For full details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy) + +**Both libraries and apps** +Install the new dependencies by running `npm install` or `yarn install`\. + +Change your imports to import `Construct` from the new `constructs` module, core types such as `App` and `Stack` from the top level of `aws-cdk-lib`, and stable Construct Library modules for the services you use from namespaces under `aws-cdk-lib`\. + +``` +import { Construct } from 'constructs'; +import { App, Stack } from 'aws-cdk-lib'; // core constructs +import { aws_s3 as s3 } from 'aws-cdk-lib'; // stable module +import * as codestar from '@aws-cdk/aws-codestar-alpha'; // experimental module +``` + +------ +#### [ JavaScript ] + +Update `package.json` as follows\. Remove dependencies on v1\-style individual stable modules and establish the lowest version of `aws-cdk-lib` you require for your application \(2\.0\.0 here\)\. + +Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` with which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. + +``` +{ + "dependencies": { + "aws-cdk-lib": "^2.0.0-rc.1", + "@aws-cdk/aws-codestar-alpha": "2.0.0-alpha.1", + "constructs": "^10.0.0" + } +} +``` + +Install the new dependencies by running `npm install` or `yarn install`\. + +Change your app's imports to import `Construct` from the new `constructs` module, core types such as `App` and `Stack` from the top level of `aws-cdk-lib`, and AWS Construct Library modules from namespaces under `aws-cdk-lib`\. + +``` +const { Construct } = require('constructs'); +const { App, Stack } = require('aws-cdk-lib'); // core constructs +const s3 = require('aws-cdk-lib').aws_s3; // stable module +const codestar = require('@aws-cdk/aws-codestar-alpha'); // experimental module +``` + +------ +#### [ Python ] + +Update `requirements.txt` or the `install_requires` definition in `setup.py` as follows\. Remove dependencies on v1\-style individual stable modules\. + +Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0alpha1\. + +``` +install_requires=[ + "aws-cdk-lib>=2.0.0rc1", + "constructs>=10.0.0", + "aws-cdk.aws-codestar-alpha>=2.0.0alpha1", + # ... +], +``` + +**Tip** +Uninstall any other versions of AWS CDK modules already installed in your app's virtual environment using `pip uninstall`\. Then Install the new dependencies with `python -m pip install -r requirements.txt`\. + +Change your app's imports to import `Construct` from the new `constructs` module, core types such as `App` and `Stack` from the top level of `aws_cdk`, and AWS Construct Library modules from namespaces under `aws_cdk`\. + +``` +from constructs import Construct +from aws_cdk import App, Stack # core constructs +from aws_cdk import aws_s3 as s3 # stable module +import aws_cdk.aws_codestar_alpha as codestar # experimental module + +# ... + +class MyConstruct(Construct): + # ... + +class MyStack(Stack): + # ... + +s3.Bucket(...) +``` + +------ +#### [ Java ] + +In `pom.xml`, remove all `software.amazon.awscdk` dependencies for stable modules and replace them with dependencies on `software.constructs` \(for `Construct`\) and `software.amazon.awscdk`\. + +Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. + +``` + + software.amazon.awscdk + aws-cdk-lib + 2.0.0 + + software.amazon.awscdk + code-star-alpha + 2.0.0-alpha.1 + + + software.constructs + constructs + 10.0.0 + +``` + +Install the new dependencies by running `mvn package`\. + +Change your code to import `Construct` from the new `software.constructs` library, core classes like `Stack` and `App` from `software.amazon.awscdk`, and service constructs from `software.amazon.awscdk.services`\. + +``` +import software.constructs.Construct; +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.App; +import software.amazon.awscdk.services.s3.Bucket; +import software.amazon.awscdk.services.codestar.alpha.GitHubRepository; +``` + +------ +#### [ C\# ] + +The most straightforward way to upgrade the dependencies of a C\# CDK application is to edit the `.csproj` file manually\. Remove all stable `Amazon.CDK.*` package references and replace them with references to the `Amazon.CDK.Lib` and `Constructs` packages\. + +Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. + +``` + + + +``` + +Install the new dependencies by running `dotnet restore`\. + +Change the imports in your source files as follows\. + +``` +using Constructs; // for Construct class +using Amazon.CDK; // for core classes like App and Stack +using Amazon.CDK.AWS.S3; // for stable constructs like Bucket +using Amazon.CDK.Codestar.Alpha; // for experimental constructs +``` + +------ + +## Troubleshooting + +**Typescript `'from' expected` or `';' expected` error in imports** +Upgrade to TypeScript 3\.8 or later\. + +**Please run 'cdk bootstrap'** +If you see an error like this one: + +``` +❌ MyStack failed: Error: MyStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) + at CloudFormationDeployments.validateBootstrapStackVersion (.../aws-cdk/lib/api/cloudformation-deployments.ts:323:13) + at processTicksAndRejections (internal/process/task_queues.js:97:5) +MyStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) +``` + +AWS CDK v2 requires a new bootstrap stack, so you must re\-bootstrap your deployment environment\(s\)\. See [Bootstrapping](bootstrapping.md) for complete details\. + +**Unexpected infrastructure changes** +Before deploying your app, use `cdk diff` to check for unexpected changes to its resources\. Changes to logical IDs \(causing replacement of resources\) are **not** expected\. + +Expected changes include but are not limited to: ++ Changes to the `CDKMetadata` resource ++ Updated asset hashes ++ Changes related to the new\-style stack synthesis, if your app used the legacy stack synthesizer in v1 \(CDK v2 does not support the legacy stack synthesizer\) ++ The addition of a `CheckBootstrapVersion` rule + +Unexpected changes are typically not caused by upgrading to AWS CDK v2 in itself, but are usually the result of deprecated behavior that was previously changed by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, removing feature flags, revising your code as necessary, deploying, and then upgrading to v2\. + +If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. \ No newline at end of file diff --git a/v2/multiple_languages.md b/v2/multiple_languages.md new file mode 100644 index 00000000..df1e2f49 --- /dev/null +++ b/v2/multiple_languages.md @@ -0,0 +1,349 @@ +# Translating TypeScript AWS CDK code to other languages + +TypeScript was the first language supported for developing AWS CDK applications, and for that reason, there is a substantial amount of example CDK code written in TypeScript\. If you are developing in another language, it may be useful to compare how AWS CDK code is implemented in TypeScript and your language of choice, so you can, with a little effort, make use of these examples\. + +For more details on working with the AWS CDK in its supported programming languages, see: ++ [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) ++ [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) ++ [Working with the AWS CDK in Python](work-with-cdk-python.md) ++ [Working with the AWS CDK in Java](work-with-cdk-java.md) ++ [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) + +## Importing a module + +------ +#### [ TypeScript/JavaScript ] + +TypeScript supports importing either an entire namespace, or individual objects from a namespace\. Each namespace includes constructs and other classes for use with a given AWS service\. + +``` +// Import main CDK library as cdk +import * as cdk from 'aws-cdk-lib'; // ES6 import preferred in TS +const cdk = require('aws-cdk-lib'); // Node.js require() preferred in JS + +// Import specific core CDK classes +import { Stack, App } from 'aws-cdk-lib'; +const { Stack, App } = require('aws-cdk-lib'); + +// Import AWS S3 namespace as s3 into current namespace +import { aws_s3 as s3 } from 'aws-cdk-lib'; // TypeScript +const s3 = require('aws-cdk-lib/aws-s3'); // JavaScript + +// Having imported cdk already as above, this is also valid +const s3 = cdk.aws_s3; + +// Now use s3 to access the S3 types +const bucket = s3.Bucket(...); + +// Selective import of s3.Bucket +import { Bucket } from 'aws-cdk-lib/aws-s3'; // TypeScript +const { Bucket } = require('aws-cdk-lib/aws-s3'); // JavaScript + +// Now use Bucket to instantiate an S3 bucket +const bucket = Bucket(...); +``` + +------ + +------ +#### [ Python ] + +Like TypeScript, Python supports namespaced module imports and selective imports\. Namespaces in Python look like **aws\_cdk\.***xxx*, where *xxx* represents an AWS service name, such as **s3** for Amazon S3 \(we'll use Amazon S3 for our examples\)\. + +``` +# Import main CDK library as cdk +import aws_cdk as cdk + +# Selective import of specific core classes +from aws_cdk import Stack, App + +# Import entire module as s3 into current namespace +import aws_cdk.aws_s3 as s3 + +# s3 can now be used to access classes it contains +bucket = s3.Bucket(...) + +# Selective import of s3.Bucket into current namespace +from aws_cdk.s3 import Bucket + +# Bucket can now be used to instantiate a bucket +bucket = Bucket(...) +``` + +------ +#### [ Java ] + +Java's imports work differently from TypeScript's\. Each import statement imports either a single class name from a given package, or all classes defined in that package \(using `*`\)\. Classes may be accessed using either the class name by itself if it has been imported, or the *qualified* class name including its package\. + +Libraries are named like `software.amazon.awscdk.services.xxx` for the AWS Construct Library \(the main library is `software.amazon.awscdk`\)\. The Maven group ID for AWS CDK packages is `software.amazon.awscdk`\. + +``` +// Make certain core classes available +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.App; + +// Make all Amazon S3 construct library classes available +import software.amazon.awscdk.services.s3.*; + +// Make only Bucket and EventType classes available +import software.amazon.awscdk.services.s3.Bucket; +import software.amazon.awscdk.services.s3.EventType; + +// An imported class may now be accessed using the simple class name (assuming that name +// does not conflict with another class) +Bucket bucket = new Bucket(...); + +// We can always use the qualified name of a class (including its package) even without an +// import directive +software.amazon.awscdk.services.s3.Bucket bucket = + new software.amazon.awscdk.services.s3.Bucket(...); +``` + +------ +#### [ C\# ] + +In C\#, you import types with the `using` directive\. There are two styles, which give you access either all the types in the specified namespace using their plain names, or let you refer to the namespace itself using an alias\. + +Packages are named like `Amazon.CDK.AWS.xxx` for AWS Construct Library packages \(the core module is `Amazon.CDK`\)\. + +``` +// Make CDK base classes available under cdk +using cdk = Amazon.CDK; + +// Make all Amazon S3 construct library classes available +using Amazon.CDK.AWS.S3; + +// Now we can access any S3 type using its name +var bucket = new Bucket(...); + +// Import the S3 namespace under an alias +using s3 = Amazon.CDK.AWS.S3; + +// Now we can access an S3 type through the namespace alias +var bucket = new s3.Bucket(...); + +// We can always use the qualified name of a type (including its namespace) even without a +// using directive +var bucket = new Amazon.CDK.AWS.S3.Bucket(...) +``` + +------ + +## Instantiating a construct + +AWS CDK construct classes have the same name in all supported languages\. Most languages use the `new` keyword to instantiate a class \(Python is the only one that doesn't\)\. Also, in most languages, the keyword `this` refers to the current instance\. Python, again, is the exception \(it uses `self` by convention\)\. You should pass a reference to the current instance as the `scope` parameter to every construct you create\. + + The third argument to a AWS CDK construct is `props`, an object containing attributes needed to build the construct\. This argument may be optional, but when it is required, the supported languages handle it in idiomatic ways\. The names of the attributes are also adapted to the language's standard naming patterns\. + +------ +#### [ TypeScript/JavaScript ] + +``` +// Instantiate default Bucket +const bucket = new s3.Bucket(this, 'MyBucket'); + +// Instantiate Bucket with bucketName and versioned properties +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket', + versioned: true, +}); + +// Instantiate Bucket with websiteRedirect, which has its own sub-properties +const bucket = new s3.Bucket(this, 'MyBucket', { + websiteRedirect: {host: 'aws.amazon.com'}}); +``` + +------ + +------ +#### [ Python ] + +Python doesn't use a `new` keyword when instantiating a class\. The properties argument is represented using keyword arguments, and the arguments are named using `snake_case`\. + +If a props value is itself a bundle of attributes, it is represented by a class named after the property, which accepts keyword arguments for the sub\-properties\. + +In Python, the current instance is passed to methods as the first argument, which is named `self` by convention\. + +``` +# Instantiate default Bucket +bucket = s3.Bucket(self, "MyBucket") + +# Instantiate Bucket with bucket_name and versioned properties +bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=true) + +# Instantiate Bucket with website_redirect, which has its own sub-properties +bucket = s3.Bucket(self, "MyBucket", website_redirect=s3.WebsiteRedirect( + host_name="aws.amazon.com")) +``` + +------ +#### [ Java ] + +In Java, the props argument is represented by a class named `XxxxProps` \(for example, `BucketProps` for the `Bucket` construct's props\)\. You build the props argument using a builder pattern\. + +Each `XxxxProps` class has a builder, and there is also a convenient builder for each construct that builds the props and the construct in one step, as shown here\. + +Props are named the same as in TypeScript, using `camelCase`\. + +``` +// Instantiate default Bucket +Bucket bucket = Bucket(self, "MyBucket"); + +// Instantiate Bucket with bucketName and versioned properties +Bucket bucket = Bucket.Builder.create(self, "MyBucket") + .bucketName("my-bucket").versioned(true) + .build(); + +# Instantiate Bucket with websiteRedirect, which has its own sub-properties +Bucket bucket = Bucket.Builder.create(self, "MyBucket") + .websiteRedirect(new websiteRedirect.Builder() + .hostName("aws.amazon.com").build()) + .build(); +``` + +------ +#### [ C\# ] + +In C\#, props are specified using an object initializer to a class named `XxxxProps` \(for example, `BucketProps` for the `Bucket` construct's props\)\. + +Props are named similarly to TypeScript, except using `PascalCase`\. + +It is convenient to use the `var` keyword when instantiating a construct, so you don't need to type the class name twice\. However, your local code style guide may vary\. + +``` +// Instantiate default Bucket +var bucket = Bucket(self, "MyBucket"); + +// Instantiate Bucket with BucketName and versioned properties +var bucket = Bucket(self, "MyBucket", new BucketProps { + BucketName = "my-bucket", + Versioned = true}); + +// Instantiate Bucket with WebsiteRedirect, which has its own sub-properties +var bucket = Bucket(self, "MyBucket", new BucketProps { + WebsiteRedirect = new WebsiteRedirect { + HostName = "aws.amazon.com" + }}); +``` + +------ + +## Accessing members + +It is common to refer to attributes or properties of constructs and other AWS CDK classes and use these values as, for examples, inputs to build other constructs\. The naming differences described above for methods apply\. Furthermore, in Java, it is not possible to access members directly; instead, a getter method is provided\. + +------ +#### [ TypeScript/JavaScript ] + +Names are `camelCase`\. + +``` +bucket.bucketArn +``` + +------ + +------ +#### [ Python ] + +Names are `snake_case`\. + +``` +bucket.bucket_arn +``` + +------ +#### [ Java ] + +A getter method is provided for each property; these names are `camelCase`\. + +``` +bucket.getBucketArn() +``` + +------ +#### [ C\# ] + +Names are `PascalCase`\. + +``` +bucket.BucketArn +``` + +------ + +## Enum constants + +Enum constants are scoped to a class, and have uppercase names with underscores in all languages \(sometimes referred to as `SCREAMING_SNAKE_CASE`\)\. Since class names also use the same casing in all supported languages, qualified enum names are also the same\. + +``` +s3.BucketEncryption.KMS_MANAGED +``` + +## Object interfaces + +The AWS CDK uses TypeScript object interfaces to indicate that a class implements an expected set of methods and properties\. You can recognize an object interface because its name starts with `I`\. A concrete class indicates the interface\(s\) it implements using the `implements` keyword\. + +------ +#### [ TypeScript/JavaScript ] + +**Note** +JavaScript doesn't have an interface feature\. You can ignore the `implements` keyword and the class names following it\. + +``` +import { IAspect, IConstruct } from 'aws-cdk-lib'; + +class MyAspect implements IAspect { + public visit(node: IConstruct) { + console.log('Visited', node.node.path); + } +} +``` + +------ + +------ +#### [ Python ] + +Python doesn't have an interface feature\. However, for the AWS CDK you can indicate interface implementation by decorating your class with `@jsii.implements(interface)`\. + +``` +from aws_cdk import IAspect, IConstruct +import jsii + +@jsii.implements(IAspect) +class MyAspect(): + def visit(self, node: IConstruct) -> None: + print("Visited", node.node.path) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.IAspect; +import software.amazon.awscdk.IConstruct; + +public class MyAspect implements IAspect { + public void visit(IConstruct node) { + System.out.format("Visited %s", node.getNode().getPath()); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; + +public class MyAspect : IAspect +{ + public void Visit(IConstruct node) + { + System.Console.WriteLine($"Visited ${node.Node.Path}"); + } +} +``` + +------ \ No newline at end of file diff --git a/v2/parameters.md b/v2/parameters.md new file mode 100644 index 00000000..f4aae69c --- /dev/null +++ b/v2/parameters.md @@ -0,0 +1,208 @@ +# Parameters + +AWS CloudFormation templates can contain [parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html)—custom values that are supplied at deployment time and incorporated into the template\. Since the AWS CDK synthesizes AWS CloudFormation templates, it too offers support for deployment\-time parameters\. + +Using the AWS CDK, you can both define parameters, which can then be used in the properties of constructs you create, and you can also deploy stacks containing parameters\. + +When deploying the AWS CloudFormation template using the AWS CDK Toolkit, you provide the parameter values on the command line\. If you deploy the template through the AWS CloudFormation console, you are prompted for the parameter values\. + +In general, we recommend against using AWS CloudFormation parameters with the AWS CDK\. Unlike [context values](context.md) or environment variables, the usual way to pass values into your AWS CDK apps without hard\-coding them, parameter values are not available at synthesis time, and thus cannot be easily used in other parts of your AWS CDK app, particularly for control flow\. + +**Note** +To do control flow with parameters, you can use [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnCondition.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnCondition.html) constructs, although this is awkward compared to native `if` statements\. + +Using parameters requires you to be mindful of how the code you're writing behaves at deployment time, as well as at synthesis time\. This makes it harder to understand and reason about your AWS CDK application, in many cases for little benefit\. + +It is better, again in general, to have your CDK app accept any necessary information from the user and use it directly to declare constructs in your CDK app\. An ideal AWS CDK\-generated AWS CloudFormation template is concrete, with no values remaining to be specified at deployment time\. + +There are, however, use cases to which AWS CloudFormation parameters are uniquely suited\. If you have separate teams defining and deploying infrastructure, for example, you can use parameters to make the generated templates more widely useful\. Additionally, the AWS CDK's support for AWS CloudFormation parameters lets you use the AWS CDK with AWS services that use AWS CloudFormation templates \(such as AWS Service Catalog\), which use parameters to configure the template being deployed\. + +## Defining parameters + +Use the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnParameter.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnParameter.html) class to define a parameter\. You'll want to specify at least a type and a description for most parameters, though both are technically optional\. The description appears when the user is prompted to enter the parameter's value in the AWS CloudFormation console\. For more information on the available types, see [Types](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#parameters-section-structure-properties-type)\. + +**Note** +You can define parameters in any scope, but we recommend defining parameters at the stack level so that their logical ID does not change when you refactor your code\. + +------ +#### [ TypeScript ] + +``` +const uploadBucketName = new CfnParameter(this, "uploadBucketName", { + type: "String", + description: "The name of the Amazon S3 bucket where uploaded files will be stored."}); +``` + +------ +#### [ JavaScript ] + +``` +const uploadBucketName = new CfnParameter(this, "uploadBucketName", { + type: "String", + description: "The name of the Amazon S3 bucket where uploaded files will be stored."}); +``` + +------ +#### [ Python ] + +``` +upload_bucket_name = CfnParameter(self, "uploadBucketName", type="String", + description="The name of the Amazon S3 bucket where uploaded files will be stored.") +``` + +------ +#### [ Java ] + +``` +CfnParameter uploadBucketName = CfnParameter.Builder.create(this, "uploadBucketName") + .type("String") + .description("The name of the Amazon S3 bucket where uploaded files will be stored") + .build(); +``` + +------ +#### [ C\# ] + +``` +var uploadBucketName = new CfnParameter(this, "uploadBucketName", new CfnParameterProps +{ + Type = "String", + Description = "The name of the Amazon S3 bucket where uploaded files will be stored" +}); +``` + +------ + +## Using parameters + +A `CfnParameter` instance exposes its value to your AWS CDK app via a [token](tokens.md)\. Like all tokens, the parameter's token is resolved at synthesis time, but it resolves to a reference to the parameter defined in the AWS CloudFormation template, which will be resolved at deploy time, rather than to a concrete value\. + +You can retrieve the token as an instance of the `Token` class, or in string, string list, or numeric encoding, depending on the type of value required by the class or method you want to use the parameter with\. + +------ +#### [ TypeScript ] + + +| Property | kind of value | +| --- |--- | +| value | Token class instance | +| valueAsList | The token represented as a string list | +| valueAsNumber | The token represented as a number | +| valueAsString | The token represented as a string | + +------ +#### [ JavaScript ] + + +| Property | kind of value | +| --- |--- | +| value | Token class instance | +| valueAsList | The token represented as a string list | +| valueAsNumber | The token represented as a number | +| valueAsString | The token represented as a string | + +------ +#### [ Python ] + + +| Property | kind of value | +| --- |--- | +| value | Token class instance | +| value\_as\_list | The token represented as a string list | +| value\_as\_number | The token represented as a number | +| value\_as\_string | The token represented as a string | + +------ +#### [ Java ] + + +| Property | kind of value | +| --- |--- | +| getValue\(\) | Token class instance | +| getValueAsList\(\) | The token represented as a string list | +| getValueAsNumber\(\) | The token represented as a number | +| getValueAsString\(\) | The token represented as a string | + +------ +#### [ C\# ] + + +| Property | kind of value | +| --- |--- | +| Value | Token class instance | +| ValueAsList | The token represented as a string list | +| ValueAsNumber | The token represented as a number | +| ValueAsString | The token represented as a string | + +------ + +For example, to use a parameter in a Bucket definition: + +------ +#### [ TypeScript ] + +``` +const bucket = new Bucket(this, "myBucket", + { bucketName: uploadBucketName.valueAsString}); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = new Bucket(this, "myBucket", + { bucketName: uploadBucketName.valueAsString}); +``` + +------ +#### [ Python ] + +``` +bucket = Bucket(self, "myBucket", + bucket_name=upload_bucket_name.value_as_string) +``` + +------ +#### [ Java ] + +``` +Bucket bucket = Bucket.Builder.create(this, "myBucket") + .bucketName(uploadBucketName.getValueAsString()) + .build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new Bucket(this, "myBucket") +{ + BucketName = uploadBucketName.ValueAsString +}; +``` + +------ + +## Deploying with parameters + +A generated template containing parameters can be deployed in the usual way through the AWS CloudFormation console; you are prompted for the values of each parameter\. + +The AWS CDK Toolkit \(`cdk` command\-line tool\) also supports specifying parameters at deployment\. You may provide these on the command line following the `--parameters` flag\. You might deploy a stack that uses the `uploadBucketName` parameter like this\. + +``` +cdk deploy MyStack --parameters uploadBucketName=UploadBucket +``` + +To define multiple parameters, use multiple `--parameters` flags\. + +``` +cdk deploy MyStack --parameters uploadBucketName=UpBucket --parameters downloadBucketName=DownBucket +``` + +If you are deploying multiple stacks, you can specify a different value of each parameter for each stack by prefixing the name of the parameter with the stack name and a colon\. + +``` +cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket --parameters YourStack:uploadBucketName=UpBucket +``` + +By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the `--no-previous-parameters flag` to require all parameters to be specified\. \ No newline at end of file diff --git a/v2/permissions.md b/v2/permissions.md new file mode 100644 index 00000000..e51ec1bf --- /dev/null +++ b/v2/permissions.md @@ -0,0 +1,490 @@ +# Permissions + +The AWS Construct Library uses a few common, widely\-implemented idioms to manage access and permissions\. The IAM module provides you with the tools you need to use these idioms\. + +## Principals + +An IAM principal is an entity that can be authenticated in order to access AWS resources, such as a user, a service, or an application\. The AWS Construct Library supports many types of principals, including: + +1. IAM resources such as `[Role](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Group.html)` + +1. Service principals \(`new iam.[ServicePrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ServicePrincipal.html)('service.amazonaws.com')`\) + +1. Federated principals \(`new iam.[FederatedPrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.FederatedPrincipal.html)('cognito-identity.amazonaws.com')`\) + +1. Account principals \(`new iam.[AccountPrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.AccountPrincipal.html)('0123456789012'))` + +1. Canonical user principals \(`new iam.[CanonicalUserPrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.CanonicalUserPrincipal.html)('79a59d[...]7ef2be')`\) + +1. AWS organizations principals \(`new iam.[OrganizationPrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.OrganizationPrincipal.html)('org-id')`\) + +1. Arbitrary ARN principals \(`new iam.[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ArnPrincipal.html)(res.arn)`\) + +1. An `iam.[CompositePrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.CompositePrincipal.html)(principal1, principal2, ...)` to trust multiple principals + +## Grants + +Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrreadidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrreadwbrwriteidentity-objectskeypattern)` \(Python: `grant_read`, `grant_read_write`\) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. + +The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html)`\. + +Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other entities that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. + +Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly instead of granting access to their role\. For example, if `bucket` is an Amazon S3 bucket, and `function` is a Lambda function, the code below grants the function read access to the bucket\. + +------ +#### [ TypeScript ] + +``` +bucket.grantRead(function); +``` + +------ +#### [ JavaScript ] + +``` +bucket.grantRead(function); +``` + +------ +#### [ Python ] + +``` +bucket.grant_read(function) +``` + +------ +#### [ Java ] + +``` +bucket.grantRead(function); +``` + +------ +#### [ C\# ] + +``` +bucket.GrantRead(function); +``` + +------ + + Sometimes permissions must be applied while your stack is being deployed\. One such case is when you grant a AWS CloudFormation custom resource access to some other resource\. The custom resource will be invoked during deployment, so it must have the specified permissions at deployment time\. Another case is when a service verifies that the role you pass to it has the right policies applied \(a number of AWS services do this to make sure you didn't forget to set the policies\)\. In those cases, the deployment may fail if the permissions are applied too late\. + + To force the grant's permissions to be applied before another resource is created, you can add a dependency on the grant itself, as shown here\. Though the return value of grant methods is commonly discarded, every grant method in fact returns an `iam.Grant` object\. + +------ +#### [ TypeScript ] + +``` +const grant = bucket.grantRead(lambda); +const custom = new CustomResource(...); +custom.node.addDependency(grant); +``` + +------ +#### [ JavaScript ] + +``` +const grant = bucket.grantRead(lambda); +const custom = new CustomResource(...); +custom.node.addDependency(grant); +``` + +------ +#### [ Python ] + +``` +grant = bucket.grant_read(function) +custom = CustomResource(...) +custom.node.add_dependency(grant) +``` + +------ +#### [ Java ] + +``` +Grant grant = bucket.grantRead(function); +CustomResource custom = new CustomResource(...); +custom.node.addDependency(grant); +``` + +------ +#### [ C\# ] + +``` +var grant = bucket.GrantRead(function); +var custom = new CustomResource(...); +custom.node.AddDependency(grant); +``` + +------ + +## Roles + +The IAM package contains a `[Role](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html)` construct that represents IAM roles\. The following code creates a new role, trusting the Amazon EC2 service\. + +------ +#### [ TypeScript ] + +``` +import * as iam from 'aws-cdk-lib/aws-iam'; + +const role = new iam.Role(this, 'Role', { + assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'), // required +}); +``` + +------ +#### [ JavaScript ] + +``` +const iam = require('aws-cdk-lib/aws-iam'); + +const role = new iam.Role(this, 'Role', { + assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com') // required +}); +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_iam as iam + +role = iam.Role(self, "Role", + assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")) # required +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.iam.Role; +import software.amazon.awscdk.services.iam.ServicePrincipal; + +Role role = Role.Builder.create(this, "Role") + .assumedBy(new ServicePrincipal("ec2.amazonaws.com")).build(); +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.IAM; + +var role = new Role(this, "Role", new RoleProps +{ + AssumedBy = new ServicePrincipal("ec2.amazonaws.com"), // required +}); +``` + +------ + +You can add permissions to a role by calling the role's `[addToPolicy](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html#addwbrtowbrpolicystatement)` method \(Python: `add_to_policy`\), passing in a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyStatement.html)` that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. + + The following example adds a `Deny` policy statement to the role for the actions `ec2:SomeAction` and `s3:AnotherAction` on the resources `bucket` and `otherRole` \(Python: `other_role`\), under the condition that the authorized service is AWS CodeBuild\. + +------ +#### [ TypeScript ] + +``` +role.addToPolicy(new iam.PolicyStatement({ + effect: iam.Effect.DENY, + resources: [bucket.bucketArn, otherRole.roleArn], + actions: ['ec2:SomeAction', 's3:AnotherAction'], + conditions: {StringEquals: { + 'ec2:AuthorizedService': 'codebuild.amazonaws.com', +}}})); +``` + +------ +#### [ JavaScript ] + +``` +role.addToPolicy(new iam.PolicyStatement({ + effect: iam.Effect.DENY, + resources: [bucket.bucketArn, otherRole.roleArn], + actions: ['ec2:SomeAction', 's3:AnotherAction'], + conditions: {StringEquals: { + 'ec2:AuthorizedService': 'codebuild.amazonaws.com' +}}})); +``` + +------ +#### [ Python ] + +``` +role.add_to_policy(iam.PolicyStatement( + effect=iam.Effect.DENY, + resources=[bucket.bucket_arn, other_role.role_arn], + actions=["ec2:SomeAction", "s3:AnotherAction"], + conditions={"StringEquals": { + "ec2:AuthorizedService": "codebuild.amazonaws.com"}} +)) +``` + +------ +#### [ Java ] + +``` +role.addToPolicy(PolicyStatement.Builder.create() + .effect(Effect.DENY) + .resources(Arrays.asList(bucket.getBucketArn(), otherRole.getRoleArn())) + .actions(Arrays.asList("ec2:SomeAction", "s3:AnotherAction")) + .conditions(new HashMap() {{ + put("StringEquals", new HashMap() {{ + put("ec2:AuthorizedService", "codebuild.amazonaws.com"); + }}); + }}).build()); +``` + +------ +#### [ C\# ] + +``` +role.AddToPolicy(new PolicyStatement(new PolicyStatementProps +{ + Effect = Effect.DENY, + Resources = new string[] { bucket.BucketArn, otherRole.RoleArn }, + Actions = new string[] { "ec2:SomeAction", "s3:AnotherAction" }, + Conditions = new Dictionary + { + ["StringEquals"] = new Dictionary + { + ["ec2:AuthorizedService"] = "codebuild.amazonaws.com" + } + } +})); +``` + +------ + + In our example above, we've created a new `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyStatement.html)` inline with the `[addToPolicy](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html#addwbrtowbrpolicystatement)` \(Python: `add_to_policy`\) call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. + +If you're using a construct that requires a role to function correctly, you can either pass in an existing role when instantiating the construct object, or let the construct create a new role for you, trusting the appropriate service principal\. The following example uses such a construct: a CodeBuild project\. + +------ +#### [ TypeScript ] + +``` +import * as codebuild from 'aws-cdk-lib/aws-codebuild'; + +// imagine roleOrUndefined is a function that might return a Role object +// under some conditions, and undefined under other conditions +const someRole: iam.IRole | undefined = roleOrUndefined(); + +const project = new codebuild.Project(this, 'Project', { + // if someRole is undefined, the Project creates a new default role, + // trusting the codebuild.amazonaws.com service principal + role: someRole, +}); +``` + +------ +#### [ JavaScript ] + +``` +const codebuild = require('aws-cdk-lib/aws-codebuild'); + +// imagine roleOrUndefined is a function that might return a Role object +// under some conditions, and undefined under other conditions +const someRole = roleOrUndefined(); + +const project = new codebuild.Project(this, 'Project', { + // if someRole is undefined, the Project creates a new default role, + // trusting the codebuild.amazonaws.com service principal + role: someRole +}); +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_codebuild as codebuild + +# imagine role_or_none is a function that might return a Role object +# under some conditions, and None under other conditions +some_role = role_or_none(); + +project = codebuild.Project(self, "Project", +# if role is None, the Project creates a new default role, +# trusting the codebuild.amazonaws.com service principal +role=some_role) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.iam.Role; +import software.amazon.awscdk.services.codebuild.Project; + +// imagine roleOrNull is a function that might return a Role object +// under some conditions, and null under other conditions +Role someRole = roleOrNull(); + +// if someRole is null, the Project creates a new default role, +// trusting the codebuild.amazonaws.com service principal +Project project = Project.Builder.create(this, "Project") + .role(someRole).build(); +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.CodeBuild; + +// imagine roleOrNull is a function that might return a Role object +// under some conditions, and null under other conditions +var someRole = roleOrNull(); + +// if someRole is null, the Project creates a new default role, +// trusting the codebuild.amazonaws.com service principal +var project = new Project(this, "Project", new ProjectProps +{ + Role = someRole +}); +``` + +------ + +Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. This property is not available on imported resources, however, so such constructs have an `addToRolePolicy` \(Python: `add_to_role_policy`\) method that does nothing if the construct is an imported resource, and calls the `addToPolicy` \(Python: `add_to_policy`\) method of the `role` property otherwise, saving you the trouble of handling the undefined case explicitly\. The following example demonstrates: + +------ +#### [ TypeScript ] + +``` +// project is imported into the CDK application +const project = codebuild.Project.fromProjectName(this, 'Project', 'ProjectName'); + +// project is imported, so project.role is undefined, and this call has no effect +project.addToRolePolicy(new iam.PolicyStatement({ + effect: iam.Effect.ALLOW, // ... and so on defining the policy +})); +``` + +------ +#### [ JavaScript ] + +``` +// project is imported into the CDK application +const project = codebuild.Project.fromProjectName(this, 'Project', 'ProjectName'); + +// project is imported, so project.role is undefined, and this call has no effect +project.addToRolePolicy(new iam.PolicyStatement({ + effect: iam.Effect.ALLOW // ... and so on defining the policy +})); +``` + +------ +#### [ Python ] + +``` +# project is imported into the CDK application +project = codebuild.Project.from_project_name(self, 'Project', 'ProjectName') + +# project is imported, so project.role is undefined, and this call has no effect +project.add_to_role_policy(iam.PolicyStatement( + effect=iam.Effect.ALLOW, # ... and so on defining the policy +) +``` + +------ +#### [ Java ] + +``` +// project is imported into the CDK application +Project project = Project.fromProjectName(this, "Project", "ProjectName"); + +// project is imported, so project.getRole() is null, and this call has no effect +project.addToRolePolicy(PolicyStatement.Builder.create() + .effect(Effect.ALLOW) // .. and so on defining the policy + .build(); +``` + +------ +#### [ C\# ] + +``` +// project is imported into the CDK application +var project = Project.FromProjectName(this, "Project", "ProjectName"); + +// project is imported, so project.role is null, and this call has no effect +project.AddToRolePolicy(new PolicyStatement(new PolicyStatementProps +{ + Effect = Effect.ALLOW, // ... and so on defining the policy +})); +``` + +------ + +## Resource policies + +A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. These constructs have an `addToResourcePolicy` method \(Python: `add_to_resource_policy`\), which takes a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyStatement.html)` as its argument\. Every policy statement added to a resource policy must specify at least one principal\. + +In the following example, the [Amazon S3 bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) `bucket` grants a role with the `s3:SomeAction` permission to itself\. + +------ +#### [ TypeScript ] + +``` +bucket.addToResourcePolicy(new iam.PolicyStatement({ + effect: iam.Effect.ALLOW, + actions: ['s3:SomeAction'], + resources: [bucket.bucketArn], + principals: [role] +})); +``` + +------ +#### [ JavaScript ] + +``` +bucket.addToResourcePolicy(new iam.PolicyStatement({ + effect: iam.Effect.ALLOW, + actions: ['s3:SomeAction'], + resources: [bucket.bucketArn], + principals: [role] +})); +``` + +------ +#### [ Python ] + +``` +bucket.add_to_resource_policy(iam.PolicyStatement( + effect=iam.Effect.ALLOW, + actions=["s3:SomeAction"], + resources=[bucket.bucket_arn], + principals=role)) +``` + +------ +#### [ Java ] + +``` +bucket.addToResourcePolicy(PolicyStatement.Builder.create() + .effect(Effect.ALLOW) + .actions(Arrays.asList("s3:SomeAction")) + .resources(Arrays.asList(bucket.getBucketArn())) + .principals(Arrays.asList(role)) + .build()); +``` + +------ +#### [ C\# ] + +``` +bucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps +{ + Effect = Effect.ALLOW, + Actions = new string[] { "s3:SomeAction" }, + Resources = new string[] { bucket.BucketArn }, + Principals = new IPrincipal[] { role } +})); +``` + +------ \ No newline at end of file diff --git a/v2/pgp-keys.md b/v2/pgp-keys.md new file mode 100644 index 00000000..333f8d9d --- /dev/null +++ b/v2/pgp-keys.md @@ -0,0 +1,95 @@ +# OpenPGP keys for the AWS CDK and JSII + +This topic contains the OpenPGP keys for the AWS CDK and JSII\. + +## AWS CDK OpenPGP key + + +| | | +| --- |--- | +| Key ID: | 0x0566A784E17F3870 | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2018\-06\-19 | +| Expires: | 2022\-06\-18 | +| User ID: | AWS CDK Team | +| Key fingerprint: | E88B E3B6 F0B1 E350 9E36 4F96 0566 A784 E17F 3870 | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBFsovE8BEADEFVCHeAVPvoQgsjVu9FPUczxy9P+2zGIT/MLI3/vPLiULQwRy +IN2oxyBNDtcDToNa/fTkW3Ev0NTP4V1h+uBoKDZD/p+dTmSDRfByECMI0sGZ3UsG +Ohhyl2Of44s0sL8gdLtDnqSRLf+ZrfT3gpgUnplW7VitkwLxr78jDpW4QD8p8dZ9 +WNm3JgB55jyPgaJKqA1Ln4Vduni/1XkrG42nxrrU71uUdZPvPZ2ELLJa6n0/raG8 +jq3le+xQh45gAIs6PGaAgy7jAsfbwkGTBHjjujITAY1DwvQH5iS31OaCM9n4JNpc +xGZeJAVYTLilznf2QtS/a50t+ZOmpq67Ssp2j6qYpiumm0Lo9q3K/R4/yF0FZ8SL +1TuNX0ecXEptiMVUfTiqrLsANg18EPtLZZOYW+ZkbcVytkDpiqj7bMwA7mI7zGCJ +1gjaTbcEmOmVdQYS1G6ZptwbTtvrgA6AfnZxX1HUxLRQ7tT/wvRtABfbQKAh85Ff +a3U9W4oC3c1MP5IyhNV1Wo8Zm0flZiZc0iZnojTtSG6UbcxNNL4Q8e08FWjhungj +yxSsIBnQO1Aeo1N4BbzlI+n9iaXVDUN7Kz1QEyS4PNpjvUyrUiQ+a9C5sRA7WP+x +IEOaBBGpoAXB3oLsdTNO6AcwcDd9+r2NlXlhWC4/uH2YHQUIegPqHmPWxwARAQAB +tCFBV1MgQ0RLIFRlYW0gPGF3cy1jZGtAYW1hem9uLmNvbT6JAj8EEwEIACkFAlso +vE8CGy8FCQeEzgAHCwkIBwMCAQYVCAIJCgsEFgIDAQIeAQIXgAAKCRAFZqeE4X84 +cLGxD/0XHnhoR2xvz38GM8HQlwlZy9W1wVhQKmNDQUavw8Zx7+iRR3m7nq3xM7Qq +BDbcbKSg1lVLSBQ6H2V6vRpysOhkPSH1nN2dO8DtvSKIPcxK48+1x7lmO+ksSs/+ +oo1UvOmTDaRzOitYh3kOGXHHXk/l11GtF2FGQzYssX5iM4PHcjBsK1unThs56IMh +OJeZezEYzBaskTu/ytRJ236bPP2kZIEXfzAvhmTytuXWUXEftxOxc6fIAcYiKTha +aofG7WyR+Fvb1j5gNLcbY552QMxa23NZd5cSZH7468WEW1SGJ3AdLA7k5xvsPPOC +2YvQFD+vUOZ1JJuu6B5rHkiEMhRTLklkvqXEShTxuXiCp7iTOo6TBCmrWAT4eQr7 +htLmqlXrgKi8qPkWmRdXXG+MQBzI/UyZq2q8KC6cx2md1PhANmeefhiM7FZZfeNM +WLonWfh8gVCsNH5h8WJ9fxsQCADd3Xxx3NelS2zDYBPRoaqZEEBbgUP6LnWFprA2 +EkSlc/RoDqZCpBGgcoy1FFWvV/ZLgNU6OTQlYH6oYOWiylSJnaTDyurrktsxJI6d +4gdsFb6tqwTGecuUPvvZaEuvhWExLxAebhu780FdAPXgVTX+YCLI2zf+dWQvkFQf +80RE7ayn7BsiaLzFBVux/zz/WgvudsZX18r8tDiVQBL51ORmqw== +=0wuQ +-----END PGP PUBLIC KEY BLOCK----- +``` + +## JSII OpenPGP key + + +| | | +| --- |--- | +| Key ID: | 0x1C7ACE4CB2A1B93A | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2018\-08\-06 | +| Expires: | 2022\-08\-05 | +| User ID: | AWS JSII Team | +| Key fingerprint: | 85EF 6522 4CE2 1E8C 72DB 28EC 1C7A CE4C B2A1 B93A | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBFtoSs0BEAD6WweLD0B26h0F7Jo9iR6tVQ4PgQBK1Va5H/eP+A2Iqw79UyxZ +WNzHYhzQ5MjYYI1SgcPavXy5/LV1N8HJ7QzyKszybnLYpNTLPYArWE8ZM9ZmjvIR +p1GzwnVBGQfoOlxyeutE9T5ZkAn45dTS5jlno4unji4gHjnwXKf2nP1APU2CZfdK +8vDpLOgj9LeeGlerYNbx+7xtY/I+csFIQvK09FPLSNMJQLlkBhY0r6Rt9ZQG+653 +tJn+AUjyM237w0UIX1IqyYc5IONXu8HklPGu0NYuX9AY/63Ak2Cyfj0w/PZlvueQ +noQNM3j0nkOEsTOEXCyaLQw9iBKpxvLnm5RjMSODDCkj8c9uu0LHr7J4EOtgt2S1 +pem7Y/c/N+/Z+Ksg9fP8fVTfYwRPvdI1x2sCiRDfLoQSG9tdrN5VwPFi4sGV04sI +x7Al8Vf/OBjAGZrDaJgM/gVvb9SKAQUA6t3ofeP14gDrS0eYodEXZ+lamnxFglxF +Sn8NRC4JFNmkXSUaTNGUdFf//F0D69PRNT8CnFfmniGj0CphN5037PCA2LC/Buq2 +3+K6mTPkCcCHYPC/SwItp/xIDAQsGuDc1i1SfDYXrjsK7uOuwC5jLA9X6wZ/jgXQ +4umRRJBAV1aW8b1+yfaYYCO2AfXXO6caObv8IvH7Pc4leC2DoqylD3KklQARAQAB +tCNBV1MgSlNJSSBUZWFtIDxhd3MtanNpaUBhbWF6b24uY29tPokCPwQTAQgAKQUC +W2hKzQIbLwUJB4TOAAcLCQgHAwIBBhUIAgkKCwQWAgMBAh4BAheAAAoJEBx6zkyy +obk6B34P/iNb5QjKyhT0glZiq1wK7tuDDRpR6fC/sp6Jd/GhaNjO4BzlDbUPSjW5 +950VT+qwaHXbIma/QVP7EIRztfwWy7m8eOodjpiu7JyJprhwG9nocXiNsLADcMoH +BvabkDRWXWIWSurq2wbcFMlTVwxjHPIQs6kt2oojpzP985CDS/KTzyjow6/gfMim +DLdhSSbDUM34STEgew79L2sQzL7cvM/N59k+AGyEMHZDXHkEw/Bge5Ovz50YOnsp +lisH4BzPRIw7uWqPlkVPzJKwMuo2WvMjDfgbYLbyjfvs5mqDxT2GTwAx/rd2taU6 +iSqP0QmLM54BtTVVdoVXZSmJyTmXAAGlITq8ECZ/coUW9K2pUSgVuWyu63lktFP6 +MyCQYRmXPh9aSd4+ielteXM9Y39snlyLgEJBhMxioZXVO2oszwluPuhPoAp4ekwj +/umVsBf6As6PoAchg7Qzr+lRZGmV9YTJOgDn2Z7jf/7tOes0g/mdiXTQMSGtp/Fp +ggnifTBx3iXkrQhqHlwtam8XTHGHy3MvX17ZslNuB8Pjh+07hhCxv0VUVZPUHJqJ +ZsLa398LMteQ8UMxwJ3t06jwDWAd7mbr2tatIilLHtWWBFoCwBh1XLe/03ENCpDp +njZ7OsBsBK2nVVcN0H2v5ey0T1yE93o6r7xOwCwBiVp5skTCRUob +=2Tag +-----END PGP PUBLIC KEY BLOCK----- +``` \ No newline at end of file diff --git a/v2/reference.md b/v2/reference.md new file mode 100644 index 00000000..258ffce6 --- /dev/null +++ b/v2/reference.md @@ -0,0 +1,53 @@ +# API reference + +The [API Reference](https://docs.aws.amazon.com/cdk/api/v2) contains information about the AWS Construct Library and other APIs provided by the AWS CDK\. Most of the AWS Construct Library is actually contained in a single package called `aws-cdk-lib` in NPM \(it has other names for other ecosystems\)\. The CDK API Reference is organized into submodules, one or more for each AWS service\. + +Each submodule has an overview that includes information about how to use its APIs\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3-readme.html) overview demonstrates how to set default encryption on an Amazon S3 bucket\. + +Separate versions of the API Reference are provided for TypeScript/JavaScript, Python, Java, and C\#/\.NET\. + +## Versioning + +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and strictly adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version within the same major version, and will continue to build and run, producing the same output\. + +### AWS CDK Toolkit \(CLI\) compatibility + +The AWS CDK Toolkit \(that is, the `cdk` command line command\) is *always* compatible with construct libraries of a semantically *lower* or *equal* version number\. It is, therefore, always safe to upgrade the AWS CDK Toolkit within the same major version\. + +The AWS CDK Toolkit may be, but is *not always*, compatible with construct libraries of a semantically *higher* version, depending on whether the same cloud assembly schema version is employed by the two components\. The AWS CDK framework generates a cloud assembly during synthesis; the AWS CDK Toolkit consumes it for deployment\. The schema that defines the format of the cloud assembly is strictly specified and versioned\. AWS construct libraries using a given cloud assembly schema version are compatible with AWS CDK toolkit versions using that schema version or later, which may include releases of the AWS CDK Toolkit *older than* a given construct library release\. + +When the cloud assembly version required by the construct library is not compatible with the version supported by the AWS CDK Toolkit, you receive an error message like this one\. + +``` +Cloud assembly schema version mismatch: Maximum schema version supported is 3.0.0, but found 4.0.0. + Please upgrade your CLI in order to interact with this app. +``` + +To resolve this error, update the AWS CDK Toolkit to a version compatible with the required cloud assembly version, or simply to the latest available version\. The alternative \(downgrading the construct library modules your app uses\) is generally not desirable\. + +**Note** +For more details on the cloud assembly schema, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/cloud-assembly-schema#versioning)\. + +### AWS Construct Library versioning + +The modules in the AWS Construct Library move through various stages as they are developed from concept to mature API\. Different stages imply different promises for API stability in subsequent versions of the AWS CDK\. + +APIs in the main AWS CDK library, `aws-cdk-lib`, are stable, and the library is fully semantically\-versioned\. This package includes AWS CloudFormation \(L1\) constructs for all AWS services as well as all stable higher\-level \(L2/3\) modules\. \(It also includes the core CDK classes like `App` and `Construct`\.\) No APIs will be removed from this package \(though they may be deprecated\) until the next major release of the CDK\. No individual API will ever have breaking changes; if a breaking change is required, an entirely new API will be added\. + +New APIs under development for a service already incorporated in `aws-cdk-lib` are identified using a `BetaN` suffix, where `N` starts at 1 and is incremented with each breaking change to the new API\. `BetaN` APIs are never removed, only deprecated, so your existing app continues to work with newer versions of `aws-cdk-lib`\. When the API is deemed stable, a new API without the `BetaN` suffix is added\. + +When higher\-level \(L2 or L3\) APIs begin to be developed for an AWS service which previously had only L1 APIs, those APIs are initially distributed in a separate package\. The name of such a package has an "Alpha" suffix, and its version matches the first version of `aws-cdk-lib` it is compatible with, with an `alpha` sub\-version\. When the module supports the intended use cases, its APIs are added to `aws-cdk-lib`\. + +### Language binding stability + +From time to time, we may add support to the AWS CDK for additional programming languages\. Although the API described in all the languages is the same, the way that API is expressed varies by language and may change as the language support evolves\. For this reason, language bindings are deemed experimental for a time until they are considered ready for production use\. + + +| Language | Stability | +| --- |--- | +| TypeScript | Stable | +| JavaScript | Stable | +| Python | Stable | +| Java | Stable | +| C\#/\.NET | Stable | +| Go | Experimental | \ No newline at end of file diff --git a/v2/resources.md b/v2/resources.md new file mode 100644 index 00000000..ecb5e207 --- /dev/null +++ b/v2/resources.md @@ -0,0 +1,1281 @@ +# Resources + +As described in [Constructs](constructs.md), the AWS CDK provides a rich class library of constructs, called *AWS constructs*, that represent all AWS resources\. This section describes some common patterns and best practices for how to use these constructs\. + +Defining AWS resources in your CDK app is exactly like defining any other construct\. You create an instance of the construct class, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here's how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sqs.Queue.html) construct from the AWS Construct Library\. + +------ +#### [ TypeScript ] + +``` +import * as sqs from 'aws-cdk-lib/aws-sqs'; + +new sqs.Queue(this, 'MyQueue', { + encryption: sqs.QueueEncryption.KMS_MANAGED +}); +``` + +------ +#### [ JavaScript ] + +``` +const sqs = require('aws-cdk-lib/aws-sqs'); + +new sqs.Queue(this, 'MyQueue', { + encryption: sqs.QueueEncryption.KMS_MANAGED +}); +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_sqs as sqs + +sqs.Queue(self, "MyQueue", encryption=sqs.QueueEncryption.KMS_MANAGED) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.sqs.*; + +Queue.Builder.create(this, "MyQueue").encryption( + QueueEncryption.KMS_MANAGED).build(); +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.SQS; + +new Queue(this, "MyQueue", new QueueProps +{ + Encryption = QueueEncryption.KMS_MANAGED +}); +``` + +------ + +Some configuration props are optional, and in many cases have default values\. In some cases, all props are optional, and the last argument can be omitted entirely\. + +## Resource attributes + +Most resources in the AWS Construct Library expose attributes, which are resolved at deployment time by AWS CloudFormation\. Attributes are exposed in the form of properties on the resource classes with the type name as a prefix\. The following example shows how to get the URL of an Amazon SQS queue using the `queueUrl` \(Python: `queue_url`\) property\. + +------ +#### [ TypeScript ] + +``` +import * as sqs from 'aws-cdk-lib/aws-sqs'; + +const queue = new sqs.Queue(this, 'MyQueue'); +const url = queue.queueUrl; // => A string representing a deploy-time value +``` + +------ +#### [ JavaScript ] + +``` +const sqs = require('aws-cdk-lib/aws-sqs'); + +const queue = new sqs.Queue(this, 'MyQueue'); +const url = queue.queueUrl; // => A string representing a deploy-time value +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_sqs as sqs + +queue = sqs.Queue(self, "MyQueue") +url = queue.queue_url # => A string representing a deploy-time value +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.sqs.*; + +Queue queue = new Queue(this, "MyQueue"); +String url = queue.getQueueUrl(); // => A string representing a deploy-time value +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK.AWS.SQS; + +var queue = new Queue(this, "MyQueue"); +var url = queue.QueueUrl; // => A string representing a deploy-time value +``` + +------ + +See [Tokens](tokens.md) for information about how the AWS CDK encodes deploy\-time attributes as strings\. + +## Referencing resources + +Many AWS CDK classes require properties that are AWS CDK resource objects \(resources\)\. To satisfy these requirements, you can refer to a resource in one of two ways: ++ By passing the resource directly ++ By passing the resource's unique identifier, which is typically an ARN, but it could also be an ID or a name + +For example, an Amazon ECS service requires a reference to the cluster on which it runs; an Amazon CloudFront distribution requires a reference to the bucket containing source code\. + +If a construct property represents another AWS construct, its type is that of the interface type of that construct\. For example, the Amazon ECS service takes a property `cluster` of type `ecs.ICluster`; the CloudFront distribution takes a property `sourceBucket` \(Python: `source_bucket`\) of type `s3.IBucket`\. + +Because every resource implements its corresponding interface, you can directly pass any resource object you're defining in the same AWS CDK app\. The following example defines an Amazon ECS cluster and then uses it to define an Amazon ECS service\. + +------ +#### [ TypeScript ] + +``` +const cluster = new ecs.Cluster(this, 'Cluster', { /*...*/ }); + +const service = new ecs.Ec2Service(this, 'Service', { cluster: cluster }); +``` + +------ +#### [ JavaScript ] + +``` +const cluster = new ecs.Cluster(this, 'Cluster', { /*...*/ }); + +const service = new ecs.Ec2Service(this, 'Service', { cluster: cluster }); +``` + +------ +#### [ Python ] + +``` +cluster = ecs.Cluster(self, "Cluster") + +service = ecs.Ec2Service(self, "Service", cluster=cluster) +``` + +------ +#### [ Java ] + +``` +Cluster cluster = new Cluster(this, "Cluster"); +Ec2Service service = new Ec2Service(this, "Service", + new Ec2ServiceProps.Builder().cluster(cluster).build()); +``` + +------ +#### [ C\# ] + +``` +var cluster = new Cluster(this, "Cluster"); +var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cluster }); +``` + +------ + +## Accessing resources in a different stack + +You can access resources in a different stack, as long as they are in the same account and AWS Region\. The following example defines the stack `stack1`, which defines an Amazon S3 bucket\. Then it defines a second stack, `stack2`, which takes the bucket from `stack1` as a constructor property\. + +------ +#### [ TypeScript ] + +``` +const prod = { account: '123456789012', region: 'us-east-1' }; + +const stack1 = new StackThatProvidesABucket(app, 'Stack1' , { env: prod }); + +// stack2 will take a property { bucket: IBucket } +const stack2 = new StackThatExpectsABucket(app, 'Stack2', { + bucket: stack1.bucket, + env: prod +}); +``` + +------ +#### [ JavaScript ] + +``` +const prod = { account: '123456789012', region: 'us-east-1' }; + +const stack1 = new StackThatProvidesABucket(app, 'Stack1' , { env: prod }); + +// stack2 will take a property { bucket: IBucket } +const stack2 = new StackThatExpectsABucket(app, 'Stack2', { + bucket: stack1.bucket, + env: prod +}); +``` + +------ +#### [ Python ] + +``` +prod = cdk.Environment(account="123456789012", region="us-east-1") + +stack1 = StackThatProvidesABucket(app, "Stack1", env=prod) + +# stack2 will take a property "bucket" +stack2 = StackThatExpectsABucket(app, "Stack2", bucket=stack1.bucket, env=prod) +``` + +------ +#### [ Java ] + +``` +// Helper method to build an environment +static Environment makeEnv(String account, String region) { + return Environment.builder().account(account).region(region) + .build(); +} + +App app = new App(); + +Environment prod = makeEnv("123456789012", "us-east-1"); + +StackThatProvidesABucket stack1 = new StackThatProvidesABucket(app, "Stack1", + StackProps.builder().env(prod).build()); + +// stack2 will take an argument "bucket" +StackThatExpectsABucket stack2 = new StackThatExpectsABucket(app, "Stack,", + StackProps.builder().env(prod).build(), stack1.getBucket()); +``` + +------ +#### [ C\# ] + +``` +Amazon.CDK.Environment makeEnv(string account, string region) +{ + return new Amazon.CDK.Environment { Account = account, Region = region }; +} + +var prod = makeEnv(account: "123456789012", region: "us-east-1"); + +var stack1 = new StackThatProvidesABucket(app, "Stack1", new StackProps { Env = prod }); + +// stack2 will take an argument "bucket" +var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = prod, + bucket = stack1.Bucket}); +``` + +------ + +If the AWS CDK determines that the resource is in the same account and Region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. + +Referencing a resource from one stack in a different stack creates a dependency between the two stacks\. Once this dependency is established, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure if the AWS CDK Toolkit deploys the producing stack before the consuming stack\. This happens if there is another dependency between the two stacks, but it can also happen that the producing stack is chosen by the AWS CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it is no longer needed, but the exported resource is still being used in the consuming stack because its update has not yet been deployed, so deploying the producer stack fails\. + +To break this deadlock, remove the use of the shared resource from the consuming stack \(which will remove the automatic export from the producing stack\), then manually add the same export to the producing stack using exactly the same logical ID as the automatically\-generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then remove the manual export \(and the shared resource if it is no longer nededed\), and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#exportwbrvalueexportedvalue-options)` method is a convenient way to create the manual export for this purpose \(see the example in the linked method reference\)\. + +## Physical names + +The logical names of resources in AWS CloudFormation are different from the names of resources that are shown in the AWS Management Console after AWS CloudFormation has deployed the resources\. The AWS CDK calls these final names *physical names*\. + +For example, AWS CloudFormation might create the Amazon S3 bucket with the logical ID **Stack2MyBucket4DD88B4F** from the previous example with the physical name **stack2mybucket4dd88b4f\-iuv1rbv9z3to**\. + +You can specify a physical name when creating constructs that represent resources by using the property Name\. The following example creates an Amazon S3 bucket with the physical name **my\-bucket\-name**\. + +------ +#### [ TypeScript ] + +``` +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket-name', +}); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket-name' +}); +``` + +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket-name") +``` + +------ +#### [ Java ] + +``` +Bucket bucket = Bucket.Builder.create(this, "MyBucket") + .bucketName("my-bucket-name").build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-bucket-name" }); +``` + +------ + +Assigning physical names to resources has some disadvantages in AWS CloudFormation\. Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource's properties that are immutable after creation, will fail if a resource has a physical name assigned\. If you end up in that state, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again\. See the [AWS CloudFormation documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) for details\. + +In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value `PhysicalName.GENERATE_IF_NEEDED`, as follows\. + +------ +#### [ TypeScript ] + +``` +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: cdk.PhysicalName.GENERATE_IF_NEEDED, +}); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: cdk.PhysicalName.GENERATE_IF_NEEDED +}); +``` + +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, "MyBucket", + bucket_name=cdk.PhysicalName.GENERATE_IF_NEEDED) +``` + +------ +#### [ Java ] + +``` +Bucket bucket = Bucket.Builder.create(this, "MyBucket") + .bucketName(PhysicalName.GENERATE_IF_NEEDED).build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new Bucket(this, "MyBucket", new BucketProps + { BucketName = PhysicalName.GENERATE_IF_NEEDED }); +``` + +------ + +## Passing unique identifiers + +Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. For example, when you are using the low\-level AWS CloudFormation resources, or need to expose resources to the runtime components of an AWS CDK application, such as when referring to Lambda functions through environment variables\. + +These identifiers are available as attributes on the resources, such as the following\. + +------ +#### [ TypeScript ] + +``` +bucket.bucketName +lambdaFunc.functionArn +securityGroup.groupArn +``` + +------ +#### [ JavaScript ] + +``` +bucket.bucketName +lambdaFunc.functionArn +securityGroup.groupArn +``` + +------ +#### [ Python ] + +``` +bucket.bucket_name +lambda_func.function_arn +security_group_arn +``` + +------ +#### [ Java ] + +The Java AWS CDK binding uses getter methods for attributes\. + +``` +bucket.getBucketName() +lambdaFunc.getFunctionArn() +securityGroup.getGroupArn() +``` + +------ +#### [ C\# ] + +``` +bucket.BucketName +lambdaFunc.FunctionArn +securityGroup.GroupArn +``` + +------ + +The following example shows how to pass a generated bucket name to an AWS Lambda function\. + +------ +#### [ TypeScript ] + +``` +const bucket = new s3.Bucket(this, 'Bucket'); + +new lambda.Function(this, 'MyLambda', { + // ... + environment: { + BUCKET_NAME: bucket.bucketName, + }, +}); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = new s3.Bucket(this, 'Bucket'); + +new lambda.Function(this, 'MyLambda', { + // ... + environment: { + BUCKET_NAME: bucket.bucketName + } +}); +``` + +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, "Bucket") + +lambda.Function(self, "MyLambda", environment=dict(BUCKET_NAME=bucket.bucket_name)) +``` + +------ +#### [ Java ] + +``` +final Bucket bucket = new Bucket(this, "Bucket"); + +Function.Builder.create(this, "MyLambda") + .environment(new HashMap() {{ + put("BUCKET_NAME", bucket.getBucketName()); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new Bucket(this, "Bucket"); + +new Function(this, "MyLambda", new FunctionProps +{ + Environment = new Dictionary + { + ["BUCKET_NAME"] = bucket.BucketName + } +}); +``` + +------ + +## Importing existing external resources + +Sometimes you already have a resource in your AWS account and want to use it in your AWS CDK app, for example, a resource that was defined through the console, an AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into an AWS CDK object in the current stack by calling a static factory method on the resource's class\. + +The following example shows how to define a bucket based on an existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a Amazon Virtual Private Cloud based on an existing VPC having a specific ID\. + +------ +#### [ TypeScript ] + +``` +// Construct a resource (bucket) just by its name (must be same account) +s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); + +// Construct a resource (bucket) by its full ARN (can be cross account) +s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); + +// Construct a resource by giving attribute(s) (complex resources) +ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { + vpcId: 'vpc-1234567890abcde', +}); +``` + +------ +#### [ JavaScript ] + +``` +// Construct a resource (bucket) just by its name (must be same account) +s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); + +// Construct a resource (bucket) by its full ARN (can be cross account) +s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); + +// Construct a resource by giving attribute(s) (complex resources) +ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { + vpcId: 'vpc-1234567890abcde' +}); +``` + +------ +#### [ Python ] + +``` +# Construct a resource (bucket) just by its name (must be same account) +s3.Bucket.from_bucket_name(self, "MyBucket", "my-bucket-name") + +# Construct a resource (bucket) by its full ARN (can be cross account) +s3.Bucket.from_bucket_arn(self, "MyBucket", "arn:aws:s3:::my-bucket-name") + +# Construct a resource by giving attribute(s) (complex resources) +ec2.Vpc.from_vpc_attributes(self, "MyVpc", vpc_id="vpc-1234567890abcdef") +``` + +------ +#### [ Java ] + +``` +// Construct a resource (bucket) just by its name (must be same account) +Bucket.fromBucketName(this, "MyBucket", "my-bucket-name"); + +// Construct a resource (bucket) by its full ARN (can be cross account) +Bucket.fromBucketArn(this, "MyBucket", + "arn:aws:s3:::my-bucket-name"); + +// Construct a resource by giving attribute(s) (complex resources) +Vpc.fromVpcAttributes(this, "MyVpc", VpcAttributes.builder() + .vpcId("vpc-1234567890abcdef").build()); +``` + +------ +#### [ C\# ] + +``` +// Construct a resource (bucket) just by its name (must be same account) +Bucket.FromBucketName(this, "MyBucket", "my-bucket-name"); + +// Construct a resource (bucket) by its full ARN (can be cross account) +Bucket.FromBucketArn(this, "MyBucket", "arn:aws:s3:::my-bucket-name"); + +// Construct a resource by giving attribute(s) (complex resources) +Vpc.FromVpcAttributes(this, "MyVpc", new VpcAttributes +{ + VpcId = "vpc-1234567890abcdef" +}); +``` + +------ + +Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables\), it can be difficult to import those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. + +You must provide attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want to import the VPC marked as the default is sufficient\. + +------ +#### [ TypeScript ] + +``` +ec2.Vpc.fromLookup(this, 'DefaultVpc', { + isDefault: true +}); +``` + +------ +#### [ JavaScript ] + +``` +ec2.Vpc.fromLookup(this, 'DefaultVpc', { + isDefault: true +}); +``` + +------ +#### [ Python ] + +``` +ec2.Vpc.from_lookup(self, "DefaultVpc", is_default=True) +``` + +------ +#### [ Java ] + +``` +Vpc.fromLookup(this, "DefaultVpc", VpcLookupOptions.builder() + .isDefault(true).build()); +``` + +------ +#### [ C\# ] + +``` +Vpc.FromLookup(this, id = "DefaultVpc", new VpcLookupOptions { IsDefault = true }); +``` + +------ + +You can use the `tags` property to query by tag\. Tags may be added to the VPC at the time of its creation using AWS CloudFormation or the AWS CDK, and they may be edited at any time after creation using the AWS Management Console, the AWS CLI, or an AWS SDK\. In addition to any tags you have added yourself, the AWS CDK automatically adds the following tags to all VPCs it creates\. ++ *Name* – The name of the VPC\. ++ *aws\-cdk:subnet\-name* – The name of the subnet\. ++ *aws\-cdk:subnet\-type* – The type of the subnet: Public, Private, or Isolated\. + +------ +#### [ TypeScript ] + +``` +ec2.Vpc.fromLookup(this, 'PublicVpc', + {tags: {'aws-cdk:subnet-type': "Public"}}); +``` + +------ +#### [ JavaScript ] + +``` +ec2.Vpc.fromLookup(this, 'PublicVpc', + {tags: {'aws-cdk:subnet-type': "Public"}}); +``` + +------ +#### [ Python ] + +``` +ec2.Vpc.from_lookup(self, "PublicVpc", + tags={"aws-cdk:subnet-type": "Public"}) +``` + +------ +#### [ Java ] + +``` +Vpc.fromLookup(this, "PublicVpc", VpcLookupOptions.builder() + .tags(new HashMap {{ put("aws-cdk:subnet-type", "Public"); }}) + .build()); +``` + +------ +#### [ C\# ] + +``` +Vpc.FromLookup(this, id = "PublicVpc", new VpcLookupOptions + { Tags = new Dictionary { ["aws-cdk:subnet-type"] = "Public" }); +``` + +------ + +`Vpc.fromLookup()` works only in stacks that are defined with an explicit **account** and **region** in their `env` property\. If the AWS CDK attempts to look up an Amazon VPC from an [environment\-agnostic stack](stacks.md#stack_api), the CLI does not know which environment to query to find the VPC\. + +Results of `Vpc.fromLookup()` are cached in the project's `cdk.context.json` file\. Commit this file to version control if you will be deploying the stack in an environment that does not have access to the AWS account that defines the VPC, such as [CDK Pipelines](cdk_pipeline.md)\. + +Although you can use an imported resource anywhere, you cannot modify the imported resource\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an imported `s3.Bucket` does nothing\. + +## Permission grants + +AWS constructs make least\-privilege permissions easy to achieve by offering simple, intent\-based APIs to express permission requirements\. Many AWS constructs offer grant methods that enable you to easily grant an entity, such as an IAM role or a user, permission to work with the resource without having to manually craft one or more IAM permission statements\. + +The following example creates the permissions to allow a Lambda function's execution role to read and write objects to a particular Amazon S3 bucket\. If the Amazon S3 bucket is encrypted using an AWS KMS key, this method also grants the Lambda function's execution role permissions to decrypt using this key\. + +------ +#### [ TypeScript ] + +``` +if (bucket.grantReadWrite(func).success) { + // ... +} +``` + +------ +#### [ JavaScript ] + +``` +if ( bucket.grantReadWrite(func).success) { + // ... +} +``` + +------ +#### [ Python ] + +``` +if bucket.grant_read_write(func).success: + # ... +``` + +------ +#### [ Java ] + +``` +if (bucket.grantReadWrite(func).getSuccess()) { + // ... +} +``` + +------ +#### [ C\# ] + +``` +if (bucket.GrantReadWrite(func).Success) +{ + // ... +} +``` + +------ + +The grant methods return an `iam.Grant` object\. Use the `success` attribute of the `Grant` object to determine whether the grant was effectively applied \(for example, it may not have been applied on [imported resources](#resources_referencing)\)\. You can also use the `assertSuccess` \(Python: `assert_success`\) method of the `Grant` object to enforce that the grant was successfully applied\. + +If a specific grant method isn't available for the particular use case, you can use a generic grant method to define a new grant with a specified list of actions\. + +The following example shows how to grant a Lambda function access to the Amazon DynamoDB `CreateBackup` action\. + +------ +#### [ TypeScript ] + +``` +table.grant(func, 'dynamodb:CreateBackup'); +``` + +------ +#### [ JavaScript ] + +``` +table.grant(func, 'dynamodb:CreateBackup'); +``` + +------ +#### [ Python ] + +``` +table.grant(func, "dynamodb:CreateBackup") +``` + +------ +#### [ Java ] + +``` +table.grant(func, "dynamodb:CreateBackup"); +``` + +------ +#### [ C\# ] + +``` +table.Grant(func, "dynamodb:CreateBackup"); +``` + +------ + +Many resources, such as Lambda functions, require a role to be assumed when executing code\. A configuration property enables you to specify an `iam.IRole`\. If no role is specified, the function automatically creates a role specifically for this use\. You can then use grant methods on the resources to add statements to the role\. + +The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyDocument.html) objects\. Add statements directly to roles \(or a construct's attached role\) using the `addToRolePolicy` method \(Python: `add_to_role_policy`\), or to a resource's policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` \(Python: `add_to_resource_policy`\) method\. + +## Metrics and alarms + +Many resources emit CloudWatch metrics that can be used to set up monitoring dashboards and alarms\. AWS constructs have metric methods that allow easy access to the metrics without having to look up the correct name to use\. + +The following example shows how to define an alarm when the `ApproximateNumberOfMessagesNotVisible` of an Amazon SQS queue exceeds 100\. + +------ +#### [ TypeScript ] + +``` +import * as cw from 'aws-cdk-lib/aws-cloudwatch'; +import * as sqs from 'aws-cdk-lib/aws-sqs'; +import { Duration } from 'aws-cdk-lib'; + +const queue = new sqs.Queue(this, 'MyQueue'); + +const metric = queue.metricApproximateNumberOfMessagesNotVisible({ + label: 'Messages Visible (Approx)', + period: Duration.minutes(5), + // ... +}); +metric.createAlarm(this, 'TooManyMessagesAlarm', { + comparisonOperator: cw.ComparisonOperator.GREATER_THAN_THRESHOLD, + threshold: 100, + // ... +}); +``` + +------ +#### [ JavaScript ] + +``` +const cw = require('aws-cdk-lib/aws-cloudwatch'); +const sqs = require('aws-cdk-lib/aws-sqs'); +const { Duration } = require('aws-cdk-lib'); + +const queue = new sqs.Queue(this, 'MyQueue'); + +const metric = queue.metricApproximateNumberOfMessagesNotVisible({ + label: 'Messages Visible (Approx)', + period: Duration.minutes(5) + // ... +}); +metric.createAlarm(this, 'TooManyMessagesAlarm', { + comparisonOperator: cw.ComparisonOperator.GREATER_THAN_THRESHOLD, + threshold: 100 + // ... +}); +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_cloudwatch as cw +import aws_cdk.aws_sqs as sqs +from aws_cdk import Duration + +queue = sqs.Queue(self, "MyQueue") +metric = queue.metric_approximate_number_of_messages_not_visible( + label="Messages Visible (Approx)", + period=Duration.minutes(5), + # ... +) +metric.create_alarm(self, "TooManyMessagesAlarm", + comparison_operator=cw.ComparisonOperator.GREATER_THAN_THRESHOLD, + threshold=100, + # ... +) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.Duration; +import software.amazon.awscdk.services.sqs.Queue; +import software.amazon.awscdk.services.cloudwatch.Metric; +import software.amazon.awscdk.services.cloudwatch.MetricOptions; +import software.amazon.awscdk.services.cloudwatch.CreateAlarmOptions; +import software.amazon.awscdk.services.cloudwatch.ComparisonOperator; + +Queue queue = new Queue(this, "MyQueue"); + +Metric metric = queue + .metricApproximateNumberOfMessagesNotVisible(MetricOptions.builder() + .label("Messages Visible (Approx)") + .period(Duration.minutes(5)).build()); + +metric.createAlarm(this, "TooManyMessagesAlarm", CreateAlarmOptions.builder() + .comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD) + .threshold(100) + // ... + .build()); +``` + +------ +#### [ C\# ] + +``` +using cdk = Amazon.CDK; +using cw = Amazon.CDK.AWS.CloudWatch; +using sqs = Amazon.CDK.AWS.SQS; + +var queue = new sqs.Queue(this, "MyQueue"); +var metric = queue.MetricApproximateNumberOfMessagesNotVisible(new cw.MetricOptions +{ + Label = "Messages Visible (Approx)", + Period = cdk.Duration.Minutes(5), + // ... +}); +metric.CreateAlarm(this, "TooManyMessagesAlarm", new cw.CreateAlarmOptions +{ + ComparisonOperator = cw.ComparisonOperator.GREATER_THAN_THRESHOLD, + Threshold = 100, + // .. +}); +``` + +------ + +If there is no method for a particular metric, you can use the general metric method to specify the metric name manually\. + +Metrics can also be added to CloudWatch dashboards\. See [CloudWatch](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch-readme.html)\. + +## Network traffic + +In many cases, you must enable permissions on a network for an application to work, such as when the compute infrastructure needs to access the persistence layer\. Resources that establish or listen for connections expose methods that enable traffic flows, including setting security group rules or network ACLs\. + +[IConnectable](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IConnectable.html) resources have a `connections` property that is the gateway to network traffic rules configuration\. + +You enable data to flow on a given network path by using `allow` methods\. The following example enables HTTPS connections to the web and incoming connections from the Amazon EC2 Auto Scaling group `fleet2`\. + +------ +#### [ TypeScript ] + +``` +import * as asg from 'aws-cdk-lib/aws-autoscaling'; +import * as ec2 from 'aws-cdk-lib/aws-ec2'; + +const fleet1: asg.AutoScalingGroup = asg.AutoScalingGroup(/*...*/); + +// Allow surfing the (secure) web +fleet1.connections.allowTo(new ec2.Peer.anyIpv4(), new ec2.Port({ fromPort: 443, toPort: 443 })); + +const fleet2: asg.AutoScalingGroup = asg.AutoScalingGroup(/*...*/); +fleet1.connections.allowFrom(fleet2, ec2.Port.AllTraffic()); +``` + +------ +#### [ JavaScript ] + +``` +const asg = require('aws-cdk-lib/aws-autoscaling'); +const ec2 = require('aws-cdk-lib/aws-ec2'); + +const fleet1 = asg.AutoScalingGroup(); + +// Allow surfing the (secure) web +fleet1.connections.allowTo(new ec2.Peer.anyIpv4(), new ec2.Port({ fromPort: 443, toPort: 443 })); + +const fleet2 = asg.AutoScalingGroup(); +fleet1.connections.allowFrom(fleet2, ec2.Port.AllTraffic()); +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_autoscaling as asg +import aws_cdk.aws_ec2 as ec2 + +fleet1 = asg.AutoScalingGroup( ... ) + +# Allow surfing the (secure) web +fleet1.connections.allow_to(ec2.Peer.any_ipv4(), + ec2.Port(PortProps(from_port=443, to_port=443))) + +fleet2 = asg.AutoScalingGroup( ... ) +fleet1.connections.allow_from(fleet2, ec2.Port.all_traffic()) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.autoscaling.AutoScalingGroup; +import software.amazon.awscdk.services.ec2.Peer; +import software.amazon.awscdk.services.ec2.Port; + +AutoScalingGroup fleet1 = AutoScalingGroup.Builder.create(this, "MyFleet") + /* ... */.build(); + +// Allow surfing the (secure) Web +fleet1.getConnections().allowTo(Peer.anyIpv4(), + Port.Builder.create().fromPort(443).toPort(443).build()); + +AutoScalingGroup fleet2 = AutoScalingGroup.Builder.create(this, "MyFleet2") + /* ... */.build(); +fleet1.getConnections().allowFrom(fleet2, Port.allTraffic()); +``` + +------ +#### [ C\# ] + +``` +using cdk = Amazon.CDK; +using asg = Amazon.CDK.AWS.AutoScaling; +using ec2 = Amazon.CDK.AWS.EC2; + +// Allow surfing the (secure) Web +var fleet1 = new asg.AutoScalingGroup(this, "MyFleet", new asg.AutoScalingGroupProps { /* ... */ }); +fleet1.Connections.AllowTo(ec2.Peer.AnyIpv4(), new ec2.Port(new ec2.PortProps + { FromPort = 443, ToPort = 443 }); + +var fleet2 = new asg.AutoScalingGroup(this, "MyFleet2", new asg.AutoScalingGroupProps { /* ... */ }); +fleet1.Connections.AllowFrom(fleet2, ec2.Port.AllTraffic()); +``` + +------ + +Certain resources have default ports associated with them, for example, the listener of a load balancer on the public port, and the ports on which the database engine accepts connections for instances of an Amazon RDS database\. In such cases, you can enforce tight network control without having to manually specify the port by using the `allowDefaultPortFrom` and `allowToDefaultPort` methods \(Python: `allow_default_port_from`, `allow_to_default_port`\)\. + +The following example shows how to enable connections from any IPV4 address, and a connection from an Auto Scaling group to access a database\. + +------ +#### [ TypeScript ] + +``` +listener.connections.allowDefaultPortFromAnyIpv4('Allow public access'); + +fleet.connections.allowToDefaultPort(rdsDatabase, 'Fleet can access database'); +``` + +------ +#### [ JavaScript ] + +``` +listener.connections.allowDefaultPortFromAnyIpv4('Allow public access'); + +fleet.connections.allowToDefaultPort(rdsDatabase, 'Fleet can access database'); +``` + +------ +#### [ Python ] + +``` +listener.connections.allow_default_port_from_any_ipv4("Allow public access") + +fleet.connections.allow_to_default_port(rds_database, "Fleet can access database") +``` + +------ +#### [ Java ] + +``` +listener.getConnections().allowDefaultPortFromAnyIpv4("Allow public access"); + +fleet.getConnections().AllowToDefaultPort(rdsDatabase, "Fleet can access database"); +``` + +------ +#### [ C\# ] + +``` +listener.Connections.AllowDefaultPortFromAnyIpv4("Allow public access"); + +fleet.Connections.AllowToDefaultPort(rdsDatabase, "Fleet can access database"); +``` + +------ + +## Event handling + +Some resources can act as event sources\. Use the `addEventNotification` method \(Python: `add_event_notification`\) to register an event target to a particular event type emitted by the resource\. In addition to this, `addXxxNotification` methods offer a simple way to register a handler for common event types\. + +The following example shows how to trigger a Lambda function when an object is added to an Amazon S3 bucket\. + +------ +#### [ TypeScript ] + +``` +import * as s3nots from 'aws-cdk-lib/aws-s3-notifications'; + +const handler = new lambda.Function(this, 'Handler', { /*…*/ }); +const bucket = new s3.Bucket(this, 'Bucket'); +bucket.addObjectCreatedNotification(new s3nots.LambdaDestination(handler)); +``` + +------ +#### [ JavaScript ] + +``` +const s3nots = require('aws-cdk-lib/aws-s3-notifications'); + +const handler = new lambda.Function(this, 'Handler', { /*…*/ }); +const bucket = new s3.Bucket(this, 'Bucket'); +bucket.addObjectCreatedNotification(new s3nots.LambdaDestination(handler)); +``` + +------ +#### [ Python ] + +``` +import aws_cdk.aws_s3_notifications as s3_nots + +handler = lambda_.Function(self, "Handler", ...) +bucket = s3.Bucket(self, "Bucket") +bucket.add_object_created_notification(s3_nots.LambdaDestination(handler)) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.services.s3.Bucket; +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.s3.notifications.LambdaDestination; + +Function handler = Function.Builder.create(this, "Handler")/* ... */.build(); +Bucket bucket = new Bucket(this, "Bucket"); +bucket.addObjectCreatedNotification(new LambdaDestination(handler)); +``` + +------ +#### [ C\# ] + +``` +using lambda = Amazon.CDK.AWS.Lambda; +using s3 = Amazon.CDK.AWS.S3; +using s3Nots = Amazon.CDK.AWS.S3.Notifications; + +var handler = new lambda.Function(this, "Handler", new lambda.FunctionProps { .. }); +var bucket = new s3.Bucket(this, "Bucket"); +bucket.AddObjectCreatedNotification(new s3Nots.LambdaDestination(handler)); +``` + +------ + +## Removal policies + +Resources that maintain persistent data, such as databases and Amazon S3 buckets and even Amazon ECR registries, have a *removal policy* that indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the `aws-cdk-lib` module\. + +**Note** +Resources besides those that store data persistently may also have a `removalPolicy` that is used for a different purpose\. For example, a Lambda function version uses a `removalPolicy` attribute to determine whether a given version is retained when a new version is deployed\. These have different meanings and defaults compared to the removal policy on an Amazon S3 bucket or DynamoDB table\. + + +| Value | meaning | +| --- |--- | +| RemovalPolicy\.RETAIN | Keep the contents of the resource when destroying the stack \(default\)\. The resource is orphaned from the stack and must be deleted manually\. If you attempt to re\-deploy the stack while the resource still exists, you will receive an error message due to a name conflict\. | +| RemovalPolicy\.DESTROY | The resource will be destroyed along with the stack\. | + +AWS CloudFormation does not remove Amazon S3 buckets that contain files even if their removal policy is set to `DESTROY`\. Attempting to do so is a AWS CloudFormation error\. To have the AWS CDK delete all files from the bucket before destroying it, set the bucket's `autoDeleteObjects` property to `true`\. + +Following is an example of creating an Amazon S3 bucket with `RemovalPolicy` of `DESTROY` and `autoDeleteOjbects` set to `true`\. \. + +------ +#### [ TypeScript ] + +``` +import * as cdk from 'aws-cdk-lib'; +import { Construct } from 'constructs'; +import * as s3 from 'aws-cdk-lib/aws-s3'; + +export class CdkTestStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const bucket = new s3.Bucket(this, 'Bucket', { + removalPolicy: cdk.RemovalPolicy.DESTROY, + autoDeleteObjects: true + }); + } +} +``` + +------ +#### [ JavaScript ] + +``` +const cdk = require('aws-cdk-lib'); +const s3 = require('aws-cdk-lib/aws-s3'); + +class CdkTestStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const bucket = new s3.Bucket(this, 'Bucket', { + removalPolicy: cdk.RemovalPolicy.DESTROY, + autoDeleteObjects: true + }); + } +} + +module.exports = { CdkTestStack } +``` + +------ +#### [ Python ] + +``` +import aws_cdk as cdk +from constructs import Construct +import aws_cdk.aws_s3 as s3 + +class CdkTestStack(cdk.stack): + def __init__(self, scope: Construct, id: str, **kwargs): + super().__init__(scope, id, **kwargs) + + bucket = s3.Bucket(self, "Bucket", + removal_policy=cdk.RemovalPolicy.DESTROY, + auto_delete_objects=True) +``` + +------ +#### [ Java ] + +``` +software.amazon.awscdk.*; +import software.amazon.awscdk.services.s3.*; + +public class CdkTestStack extends Stack { + public CdkTestStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public CdkTestStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + Bucket.Builder.create(this, "Bucket") + .removalPolicy(RemovalPolicy.DESTROY) + .autoDeleteObjects(true).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +public CdkTestStack(Construct scope, string id, IStackProps props) : base(scope, id, props) +{ + new Bucket(this, "Bucket", new BucketProps { + RemovalPolicy = RemovalPolicy.DESTROY, + AutoDeleteObjects = true + }); +} +``` + +------ + +You can also apply a removal policy directly to the underlying AWS CloudFormation resource via the `applyRemovalPolicy()` method\. This method is available on some stateful resources that do not have a `removalPolicy` property in their L2 resource's props, including AWS CloudFormation stacks, Amazon Cognito user pools, Amazon DocumentDB database instances, Amazon EC2 volumes, Amazon Elasticsearch Service domains, Amazon FSx file systems, and Amazon SQS queues\. + +------ +#### [ TypeScript ] + +``` +const resource = bucket.node.findChild('Resource') as cdk.CfnResource; +resource.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY); +``` + +------ +#### [ JavaScript ] + +``` +const resource = bucket.node.findChild('Resource'); +resource.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY); +``` + +------ +#### [ Python ] + +``` +resource = bucket.node.find_child('Resource') +resource.apply_removal_policy(cdk.RemovalPolicy.DESTROY); +``` + +------ +#### [ Java ] + +``` +CfnResource resource = (CfnResource)bucket.node.findChild("Resource"); +resource.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY); +``` + +------ +#### [ C\# ] + +``` +var resource = (CfnResource)bucket.node.findChild('Resource'); +resource.ApplyRemovalPolicy(cdk.RemovalPolicy.DESTROY); +``` + +------ + +**Note** +The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. \ No newline at end of file diff --git a/v2/sam.md b/v2/sam.md new file mode 100644 index 00000000..67eb635c --- /dev/null +++ b/v2/sam.md @@ -0,0 +1,77 @@ +# SAM CLI + +This topic describes how to use the AWS SAM CLI with the AWS CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. + +**Note** +Full AWS CDK integration with the AWS SAM CLI is currently in public preview\. This integration allows you to locally test and build serverless application defined using the CDK\. For more information, see [AWS Cloud Development Kit \(AWS CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. +The instructions here apply to the current \(non\-preview\) version of the AWS SAM CLI\. + +1. The first step is to create a AWS CDK application and add the Lambda package\. + + ``` + mkdir cdk-sam-example + cd cdk-sam-example + cdk init app --language typescript + ``` + +1. Add a Lambda reference to `lib/cdk-sam-example-stack.ts`: + + ``` + import * as lambda from 'aws-cdk-lib/aws-lambda'; + ``` + +1. Replace the comment in `lib/cdk-sam-example-stack.ts` with the following Lambda function: + + ``` + new lambda.Function(this, 'MyFunction', { + runtime: lambda.Runtime.PYTHON_3_7, + handler: 'app.lambda_handler', + code: lambda.Code.asset('./my_function'), + }); + ``` + +1. Create the directory `my_function` + + ``` + mkdir my_function + ``` + +1. Create the file `app.py` in `my_function` with the following content: + + ``` + def lambda_handler(event, context): + return "This is a Lambda Function defined through CDK" + ``` + +1. Run your AWS CDK app and create a AWS CloudFormation template + + ``` + cdk synth --no-staging > template.yaml + ``` + +1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: + + ``` + Type: AWS::Lambda::Function + ``` + +1. Run the function by executing: + + ``` + sam local invoke MyFunction12345678 --no-event + ``` + + The output should look something like the following\. + + ``` + 2019-04-01 12:22:41 Found credentials in shared credentials file: ~/.aws/credentials + 2019-04-01 12:22:41 Invoking app.lambda_handler (python3.7) + + Fetching lambci/lambda:python3.7 Docker container image...... + 2019-04-01 12:22:43 Mounting D:\cdk-sam-example\.cdk.staging\a57f59883918e662ab3c46b964d2faa5 as /var/task:ro,delegated inside runtime container + START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST + END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 + REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB + + "This is a Lambda Function defined through CDK" + ``` \ No newline at end of file diff --git a/v2/security-iam.md b/v2/security-iam.md new file mode 100644 index 00000000..55f220ba --- /dev/null +++ b/v2/security-iam.md @@ -0,0 +1,11 @@ +# Identity and access management for the AWS Cloud Development Kit \(AWS CDK\) + +AWS Identity and Access Management \(IAM\) is an Amazon Web Services \(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 resources in AWS services\. IAM is an AWS service that you can use with no additional charge\. + +To use the AWS CDK to access AWS, you need an AWS account and AWS credentials\. To increase the security of your AWS account, we recommend that you use an *IAM user* to provide access credentials instead of using your AWS account credentials\. + +For details about working with IAM, see [AWS Identity and Access Management](https://aws.amazon.com/iam/)\. + +For an overview of IAM users and why they are important for the security of your account, see [AWS Security Credentials](https://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html) in the [Amazon Web Services General Reference](https://docs.aws.amazon.com/general/latest/gr/)\. + +The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. \ No newline at end of file diff --git a/v2/security.md b/v2/security.md new file mode 100644 index 00000000..bf319928 --- /dev/null +++ b/v2/security.md @@ -0,0 +1,15 @@ +# Security for the AWS Cloud Development Kit \(AWS CDK\) + +Cloud security at Amazon Web Services \(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](https://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 all of the services offered in the AWS Cloud and providing you with services that you can use securely\. Our security responsibility is the highest priority at AWS, and the effectiveness of our security is regularly tested and verified by third\-party auditors as part of the [AWS Compliance Programs](https://aws.amazon.com/compliance/programs/)\. + +**Security in the Cloud** – Your responsibility is determined by the AWS service you are using, and other factors including the sensitivity of your data, your organization's requirements, and applicable laws and regulations\. + +The AWS CDK follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services \(AWS\) services it supports\. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/)\. + +**Topics** ++ [Identity and access management](security-iam.md) ++ [Compliance validation](compliance-validation.md) ++ [Resilience](disaster-recovery-resiliency.md) ++ [Infrastructure security](infrastructure-security.md) \ No newline at end of file diff --git a/v2/serverless_example.md b/v2/serverless_example.md new file mode 100644 index 00000000..4bff3769 --- /dev/null +++ b/v2/serverless_example.md @@ -0,0 +1,840 @@ +# Creating a serverless application using the AWS CDK + +This example walks you through creating the resources for a simple widget dispensing service\. \(For the purpose of this example, a widget is just a name or identifier that can be added to, retrieved from, and deleted from a collection\.\) The example includes: ++ An AWS Lambda function\. ++ An Amazon API Gateway API to call the Lambda function\. ++ An Amazon S3 bucket that holds the widgets\. + +This tutorial contains the following steps\. + +1. Create an AWS CDK app + +1. Create a Lambda function that gets a list of widgets with HTTP GET / + +1. Create the service that calls the Lambda function + +1. Add the service to the AWS CDK app + +1. Test the app + +1. Add Lambda functions to do the following: + + Create a widget with POST /\{name\} + + Get a widget by name with GET /\{name\} + + Delete a widget by name with DELETE /\{name\} + +1. Tear everything down when you're finished + +## Create an AWS CDK app + +Create the app **MyWidgetService** in the current folder\. + +------ +#### [ TypeScript ] + +``` +mkdir MyWidgetService +cd MyWidgetService +cdk init --language typescript +``` + +------ +#### [ JavaScript ] + +``` +mkdir MyWidgetService +cd MyWidgetService +cdk init --language javascript +``` + +------ +#### [ Python ] + +``` +mkdir MyWidgetService +cd MyWidgetService +cdk init --language python +source .venv/bin/activate +pip install -r requirements.txt +``` + +------ +#### [ Java ] + +``` +mkdir MyWidgetService +cd MyWidgetService +cdk init --language java +``` + +You may now import the Maven project into your IDE\. + +------ +#### [ C\# ] + +``` +mkdir MyWidgetService +cd MyWidgetService +cdk init --language csharp +``` + +You may now open `src/MyWidgetService.sln` in Visual Studio\. + +------ + +**Note** +The CDK names source files and classes based on the name of the project directory\. If you don't use the name `MyWidgetService` as shown above, you'll have trouble following the rest of the steps because some of the files the instructions tell you to modify aren't there \(they'll have different names\)\. + +The important files in the blank project are as follows\. \(We will also be adding a couple of new files\.\) + +------ +#### [ TypeScript ] ++ `bin/my_widget_service.ts` – Main entry point for the application ++ `lib/my_widget_service-stack.ts` – Defines the widget service stack + +------ +#### [ JavaScript ] ++ `bin/my_widget_service.js` – Main entry point for the application ++ `lib/my_widget_service-stack.js` – Defines the widget service stack + +------ +#### [ Python ] ++ `app.py` – Main entry point for the application ++ `my_widget_service/my_widget_service_stack.py` – Defines the widget service stack + +------ +#### [ Java ] ++ `src/main/java/com/myorg/MyWidgetServiceApp.java` – Main entry point for the application ++ `src/main/java/com/myorg/MyWidgetServiceStack.java` – Defines the widget service stack + +------ +#### [ C\# ] ++ `src/MyWidgetService/Program.cs` – Main entry point for the application ++ `src/MyWidgetService/MyWidgetServiceStack.cs` – Defines the widget service stack + +------ + +Run the app and note that it synthesizes an empty stack\. + +``` +cdk synth +``` + +You should see output beginning with YAML code like the following\. + +``` +Resources: + CDKMetadata: + Type: AWS::CDK::Metadata + Properties: + Modules: "..." +``` + +## Create a Lambda function to list all widgets + +The next step is to create a Lambda function to list all of the widgets in our Amazon S3 bucket\. We will provide the Lambda function's code in JavaScript\. + +Create the `resources` directory in the project's main directory\. + +``` +mkdir resources +``` + +Create the following JavaScript file, `widgets.js`, in the `resources` directory\. + +``` +/* +This code uses callbacks to handle asynchronous function responses. +It currently demonstrates using an async-await pattern. +AWS supports both the async-await and promises patterns. +For more information, see the following: +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises +https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html +https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html +*/ +const AWS = require('aws-sdk'); +const S3 = new AWS.S3(); + +const bucketName = process.env.BUCKET; + +exports.main = async function(event, context) { + try { + var method = event.httpMethod; + + if (method === "GET") { + if (event.path === "/") { + const data = await S3.listObjectsV2({ Bucket: bucketName }).promise(); + var body = { + widgets: data.Contents.map(function(e) { return e.Key }) + }; + return { + statusCode: 200, + headers: {}, + body: JSON.stringify(body) + }; + } + } + + // We only accept GET for now + return { + statusCode: 400, + headers: {}, + body: "We only accept GET /" + }; + } catch(error) { + var body = error.stack || JSON.stringify(error, null, 2); + return { + statusCode: 400, + headers: {}, + body: JSON.stringify(body) + } + } +} +``` + +Save it and be sure the project still results in an empty stack\. We haven't yet wired the Lambda function to the AWS CDK app, so the Lambda asset doesn't appear in the output\. + +``` +cdk synth +``` + +## Creating a widget service + +Create a new source file to define the widget service with the source code shown below\. + +------ +#### [ TypeScript ] + +File: `lib/widget_service.ts` + +``` +import * as cdk from "aws-cdk-lib"; +import { Construct ) from "constructs"; +import * as apigateway from "aws-cdk-lib/aws-apigateway"; +import * as lambda from "aws-cdk-lib/aws-lambda"; +import * as s3 from "aws-cdk-lib/aws-s3"; + +export class WidgetService extends Construct { + constructor(scope: Construct, id: string) { + super(scope, id); + + const bucket = new s3.Bucket(this, "WidgetStore"); + + const handler = new lambda.Function(this, "WidgetHandler", { + runtime: lambda.Runtime.NODEJS_14_X, // So we can use async in widget.js + code: lambda.Code.fromAsset("resources"), + handler: "widgets.main", + environment: { + BUCKET: bucket.bucketName + } + }); + + bucket.grantReadWrite(handler); // was: handler.role); + + const api = new apigateway.RestApi(this, "widgets-api", { + restApiName: "Widget Service", + description: "This service serves widgets." + }); + + const getWidgetsIntegration = new apigateway.LambdaIntegration(handler, { + requestTemplates: { "application/json": '{ "statusCode": "200" }' } + }); + + api.root.addMethod("GET", getWidgetsIntegration); // GET / + } +} +``` + +------ +#### [ JavaScript ] + +File: `lib/widget_service.js` + +``` +const cdk = require("aws-cdk-lib"); +const { Construct } = require("constructs"); +const apigateway = require("aws-cdk-lib/aws-apigateway"); +const lambda = require("aws-cdk-lib/aws-lambda"); +const s3 = require("aws-cdk-lib/aws-s3"); + +class WidgetService extends Construct { + constructor(scope, id) { + super(scope, id); + + const bucket = new s3.Bucket(this, "WidgetStore"); + + const handler = new lambda.Function(this, "WidgetHandler", { + runtime: lambda.Runtime.NODEJS_14_X, // So we can use async in widget.js + code: lambda.Code.fromAsset("resources"), + handler: "widgets.main", + environment: { + BUCKET: bucket.bucketName + } + }); + + bucket.grantReadWrite(handler); // was: handler.role); + + const api = new apigateway.RestApi(this, "widgets-api", { + restApiName: "Widget Service", + description: "This service serves widgets." + }); + + const getWidgetsIntegration = new apigateway.LambdaIntegration(handler, { + requestTemplates: { "application/json": '{ "statusCode": "200" }' } + }); + + api.root.addMethod("GET", getWidgetsIntegration); // GET / + } +} + +module.exports = { WidgetService } +``` + +------ +#### [ Python ] + +File: `my_widget_service/widget_service.py` + +``` +import aws_cdk as cdk +from constructs import Construct +from aws_cdk import (aws_apigateway as apigateway, + aws_s3 as s3, + aws_lambda as lambda_) + +class WidgetService(Construct): + def __init__(self, scope: Construct, id: str): + super().__init__(scope, id) + + bucket = s3.Bucket(self, "WidgetStore") + + handler = lambda_.Function(self, "WidgetHandler", + runtime=lambda_.Runtime.NODEJS_14_X, + code=lambda_.Code.from_asset("resources"), + handler="widgets.main", + environment=dict( + BUCKET=bucket.bucket_name) + ) + + bucket.grant_read_write(handler) + + api = apigateway.RestApi(self, "widgets-api", + rest_api_name="Widget Service", + description="This service serves widgets.") + + get_widgets_integration = apigateway.LambdaIntegration(handler, + request_templates={"application/json": '{ "statusCode": "200" }'}) + + api.root.add_method("GET", get_widgets_integration) # GET / +``` + +------ +#### [ Java ] + +File: `src/src/main/java/com/myorg/WidgetService.java` + +``` +package com.myorg; + +import java.util.HashMap; + +import software.constructs.Construct; +import software.amazon.awscdk.services.apigateway.LambdaIntegration; +import software.amazon.awscdk.services.apigateway.Resource; +import software.amazon.awscdk.services.apigateway.RestApi; +import software.amazon.awscdk.services.lambda.Code; +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.lambda.Runtime; +import software.amazon.awscdk.services.s3.Bucket; + +public class WidgetService extends Construct { + + @SuppressWarnings("serial") + public WidgetService(Construct scope, String id) { + super(scope, id); + + Bucket bucket = new Bucket(this, "WidgetStore"); + + Function handler = Function.Builder.create(this, "WidgetHandler") + .runtime(Runtime.NODEJS_14_X) + .code(Code.fromAsset("resources")) + .handler("widgets.main") + .environment(new HashMap() {{ + put("BUCKET", bucket.getBucketName()); + }}).build(); + + bucket.grantReadWrite(handler); + + RestApi api = RestApi.Builder.create(this, "Widgets-API") + .restApiName("Widget Service").description("This service services widgets.") + .build(); + + LambdaIntegration getWidgetsIntegration = LambdaIntegration.Builder.create(handler) + .requestTemplates(new HashMap() {{ + put("application/json", "{ \"statusCode\": \"200\" }"); + }}).build(); + + api.getRoot().addMethod("GET", getWidgetsIntegration); + } +} +``` + +------ +#### [ C\# ] + +File: `src/MyWidgetService/WidgetService.cs` + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.APIGateway; +using Amazon.CDK.AWS.Lambda; +using Amazon.CDK.AWS.S3; +using System.Collections.Generic; +using constructs; + +namespace MyWidgetService +{ + + public class WidgetService : Construct + { + public WidgetService(Construct scope, string id) : base(scope, id) + { + var bucket = new Bucket(this, "WidgetStore"); + + var handler = new Function(this, "WidgetHandler", new FunctionProps + { + Runtime = Runtime.NODEJS_14_X, + Code = Code.FromAsset("resources"), + Handler = "widgets.main", + Environment = new Dictionary + { + ["BUCKET"] = bucket.BucketName + } + }); + + bucket.GrantReadWrite(handler); + + var api = new RestApi(this, "Widgets-API", new RestApiProps + { + RestApiName = "Widget Service", + Description = "This service services widgets." + }); + + var getWidgetsIntegration = new LambdaIntegration(handler, new LambdaIntegrationOptions + { + RequestTemplates = new Dictionary + { + ["application/json"] = "{ \"statusCode\": \"200\" }" + } + }); + + api.Root.AddMethod("GET", getWidgetsIntegration); + + } + } +} +``` + +------ + +**Tip** +We're using a `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html)` in to deploy this function because it supports a wide variety of programming languages\. For JavaScript and TypeScript specifically, you might consider a `[lambda\-nodejs\.NodejsFunction](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.NodejsFunction.html)`\. The latter uses esbuild to bundle up the script and converts code written in TypeScript automatically\. + +Save the app and make sure it still synthesizes an empty stack\. + +``` +cdk synth +``` + +## Add the service to the app + +To add the widget service to our AWS CDK app, we'll need to modify the source file that defines the stack to instantiate the service construct\. + +------ +#### [ TypeScript ] + +File: `lib/my_widget_service-stack.ts` + +Add the following line of code after the existing `import` statement\. + +``` +import * as widget_service from '../lib/widget_service'; +``` + +Replace the comment in the constructor with the following line of code\. + +``` + new widget_service.WidgetService(this, 'Widgets'); +``` + +------ +#### [ JavaScript ] + +File: `lib/my_widget_service-stack.js` + +Add the following line of code after the existing `require()` line\. + +``` +const widget_service = require('../lib/widget_service'); +``` + +Replace the comment in the constructor with the following line of code\. + +``` + new widget_service.WidgetService(this, 'Widgets'); +``` + +------ +#### [ Python ] + +File: `my_widget_service/my_widget_service_stack.py` + +Add the following line of code after the existing `import` statement\. + +``` +from . import widget_service +``` + +Replace the comment in the constructor with the following line of code\. + +``` + widget_service.WidgetService(self, "Widgets") +``` + +------ +#### [ Java ] + +File: `src/src/main/java/com/myorg/MyWidgetServiceStack.java` + +Replace the comment in the constructor with the following line of code\. + +``` +new WidgetService(this, "Widgets"); +``` + +------ +#### [ C\# ] + +File: `src/MyWidgetService/MyWidgetServiceStack.cs` + +Replace the comment in the constructor with the following line of code\. + +``` +new WidgetService(this, "Widgets"); +``` + +------ + +Be sure the app runs and synthesizes a stack \(we won't show the stack here: it's over 250 lines\)\. + +``` +cdk synth +``` + +## Deploy and test the app + +Before you can deploy your first AWS CDK app containing a lambda function, you must bootstrap your AWS environment\. This creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see [Bootstrapping your AWS environment](cli.md#cli-bootstrap)\. If you've already bootstrapped, you'll get a warning and nothing will change\. + +``` +cdk bootstrap aws://ACCOUNT-NUMBER/REGION +``` + +Now we're ready to deploy the app as follows\. + +``` +cdk deploy +``` + +If the deployment succeeds, save the URL for your server\. This URL appears in one of the last lines in the window, where *GUID* is an alphanumeric GUID and *REGION* is your AWS Region\. + +``` +https://GUID.execute-api-REGION.amazonaws.com/prod/ +``` + +Test your app by getting the list of widgets \(currently empty\) by navigating to this URL in a browser, or use the following command\. + +``` +curl -X GET 'https://GUID.execute-api.REGION.amazonaws.com/prod' +``` + +You can also test the app by: + +1. Opening the AWS Management Console\. + +1. Navigating to the API Gateway service\. + +1. Finding **Widget Service** in the list\. + +1. Selecting **GET** and **Test** to test the function\. + +Because we haven't stored any widgets yet, the output should be similar to the following\. + +``` +{ "widgets": [] } +``` + +## Add the individual widget functions + +The next step is to create Lambda functions to create, show, and delete individual widgets\. + +Replace the code in `widgets.js` \(in `resources`\) with the following\. + +``` +const AWS = require('aws-sdk'); +const S3 = new AWS.S3(); + +const bucketName = process.env.BUCKET; + +/* +This code uses callbacks to handle asynchronous function responses. +It currently demonstrates using an async-await pattern. +AWS supports both the async-await and promises patterns. +For more information, see the following: +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises +https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html +https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html +*/ +exports.main = async function(event, context) { + try { + var method = event.httpMethod; + // Get name, if present + var widgetName = event.path.startsWith('/') ? event.path.substring(1) : event.path; + + if (method === "GET") { + // GET / to get the names of all widgets + if (event.path === "/") { + const data = await S3.listObjectsV2({ Bucket: bucketName }).promise(); + var body = { + widgets: data.Contents.map(function(e) { return e.Key }) + }; + return { + statusCode: 200, + headers: {}, + body: JSON.stringify(body) + }; + } + + if (widgetName) { + // GET /name to get info on widget name + const data = await S3.getObject({ Bucket: bucketName, Key: widgetName}).promise(); + var body = data.Body.toString('utf-8'); + + return { + statusCode: 200, + headers: {}, + body: JSON.stringify(body) + }; + } + } + + if (method === "POST") { + // POST /name + // Return error if we do not have a name + if (!widgetName) { + return { + statusCode: 400, + headers: {}, + body: "Widget name missing" + }; + } + + // Create some dummy data to populate object + const now = new Date(); + var data = widgetName + " created: " + now; + + var base64data = new Buffer(data, 'binary'); + + await S3.putObject({ + Bucket: bucketName, + Key: widgetName, + Body: base64data, + ContentType: 'application/json' + }).promise(); + + return { + statusCode: 200, + headers: {}, + body: JSON.stringify(event.widgets) + }; + } + + if (method === "DELETE") { + // DELETE /name + // Return an error if we do not have a name + if (!widgetName) { + return { + statusCode: 400, + headers: {}, + body: "Widget name missing" + }; + } + + await S3.deleteObject({ + Bucket: bucketName, Key: widgetName + }).promise(); + + return { + statusCode: 200, + headers: {}, + body: "Successfully deleted widget " + widgetName + }; + } + + // We got something besides a GET, POST, or DELETE + return { + statusCode: 400, + headers: {}, + body: "We only accept GET, POST, and DELETE, not " + method + }; + } catch(error) { + var body = error.stack || JSON.stringify(error, null, 2); + return { + statusCode: 400, + headers: {}, + body: body + } + } +} +``` + +Wire up these functions to your API Gateway code at the end of the `WidgetService` constructor\. + +------ +#### [ TypeScript ] + +File: `lib/widget_service.ts` + +``` + const widget = api.root.addResource("{id}"); + + // Add new widget to bucket with: POST /{id} + const postWidgetIntegration = new apigateway.LambdaIntegration(handler); + + // Get a specific widget from bucket with: GET /{id} + const getWidgetIntegration = new apigateway.LambdaIntegration(handler); + + // Remove a specific widget from the bucket with: DELETE /{id} + const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); + + widget.addMethod("POST", postWidgetIntegration); // POST /{id} + widget.addMethod("GET", getWidgetIntegration); // GET /{id} + widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} +``` + +------ +#### [ JavaScript ] + +File: `lib/widget_service.js` + +``` + const widget = api.root.addResource("{id}"); + + // Add new widget to bucket with: POST /{id} + const postWidgetIntegration = new apigateway.LambdaIntegration(handler); + + // Get a specific widget from bucket with: GET /{id} + const getWidgetIntegration = new apigateway.LambdaIntegration(handler); + + // Remove a specific widget from the bucket with: DELETE /{id} + const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); + + widget.addMethod("POST", postWidgetIntegration); // POST /{id} + widget.addMethod("GET", getWidgetIntegration); // GET /{id} + widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} +``` + +------ +#### [ Python ] + +File: `my_widget_service/widget_service.py` + +``` + widget = api.root.add_resource("{id}") + + # Add new widget to bucket with: POST /{id} + post_widget_integration = apigateway.LambdaIntegration(handler) + + # Get a specific widget from bucket with: GET /{id} + get_widget_integration = apigateway.LambdaIntegration(handler) + + # Remove a specific widget from the bucket with: DELETE /{id} + delete_widget_integration = apigateway.LambdaIntegration(handler) + + widget.add_method("POST", post_widget_integration); # POST /{id} + widget.add_method("GET", get_widget_integration); # GET /{id} + widget.add_method("DELETE", delete_widget_integration); # DELETE /{id} +``` + +------ +#### [ Java ] + +File: `src/src/main/java/com/myorg/WidgetService.java` + +``` + Resource widget = api.getRoot().addResource("{id}"); + + // Add new widget to bucket with: POST /{id} + LambdaIntegration postWidgetIntegration = new LambdaIntegration(handler); + + // Get a specific widget from bucket with: GET /{id} + LambdaIntegration getWidgetIntegration = new LambdaIntegration(handler); + + // Remove a specific widget from the bucket with: DELETE /{id} + LambdaIntegration deleteWidgetIntegration = new LambdaIntegration(handler); + + widget.addMethod("POST", postWidgetIntegration); // POST /{id} + widget.addMethod("GET", getWidgetIntegration); // GET /{id} + widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} +``` + +------ +#### [ C\# ] + +File: `src/MyWidgetService/WidgetService.cs` + +``` + var widget = api.Root.AddResource("{id}"); + + // Add new widget to bucket with: POST /{id} + var postWidgetIntegration = new LambdaIntegration(handler); + + // Get a specific widget from bucket with: GET /{id} + var getWidgetIntegration = new LambdaIntegration(handler); + + // Remove a specific widget from the bucket with: DELETE /{id} + var deleteWidgetIntegration = new LambdaIntegration(handler); + + widget.AddMethod("POST", postWidgetIntegration); // POST /{id} + widget.AddMethod("GET", getWidgetIntegration); // GET /{id} + widget.AdMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} +``` + +------ + +Save and deploy the app\. + +``` +cdk deploy +``` + +We can now store, show, or delete an individual widget\. Use the following commands to list the widgets, create the widget **example**, list all of the widgets, show the contents of **example** \(it should show today's date\), delete **example**, and then show the list of widgets again\. + +``` +curl -X GET 'https://GUID.execute-api.REGION.amazonaws.com/prod' +curl -X POST 'https://GUID.execute-api.REGION.amazonaws.com/prod/example' +curl -X GET 'https://GUID.execute-api.REGION.amazonaws.com/prod' +curl -X GET 'https://GUID.execute-api.REGION.amazonaws.com/prod/example' +curl -X DELETE 'https://GUID.execute-api.REGION.amazonaws.com/prod/example' +curl -X GET 'https://GUID.execute-api.REGION.amazonaws.com/prod' +``` + +You can also use the API Gateway console to test these functions\. Set the **name** value to the name of a widget, such as **example**\. + +## Clean up + +To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done with this exercise\. + +``` +cdk destroy +``` \ No newline at end of file diff --git a/v2/stack_how_to_create_multiple_stacks.md b/v2/stack_how_to_create_multiple_stacks.md new file mode 100644 index 00000000..46346220 --- /dev/null +++ b/v2/stack_how_to_create_multiple_stacks.md @@ -0,0 +1,569 @@ +# Create an app with multiple stacks + +Most of the other code examples in the *AWS CDK Developer Guide* involve only a single stack\. However, you can create apps containing any number of stacks\. Each stack results in its own AWS CloudFormation template\. Stacks are the *unit of deployment:* each stack in an app can be synthesized and deployed individually using the `cdk deploy` command\. + +This topic illustrates how to extend the `Stack` class to accept new properties or arguments, how to use these properties to affect what resources the stack contains and their configuration, and how to instantiate multiple stacks from this class\. The example uses a Boolean property, named `encryptBucket` \(Python: `encrypt_bucket`\), to indicate whether an Amazon S3 bucket should be encrypted\. If so, the stack enables encryption using a key managed by AWS Key Management Service \(AWS KMS\)\. The app creates two instances of this stack, one with encryption and one without\. + +## Before you begin + +First, install Node\.js and the AWS CDK command line tools, if you haven't already\. See [Getting started with the AWS CDK](getting_started.md) for details\. + +Next, create an AWS CDK project by entering the following commands at the command line\. + +------ +#### [ TypeScript ] + +``` +mkdir multistack +cd multistack +cdk init --language=typescript +``` + +------ +#### [ JavaScript ] + +``` +mkdir multistack +cd multistack +cdk init --language=javascript +``` + +------ +#### [ Python ] + +``` +mkdir multistack +cd multistack +cdk init --language=python +source .venv/bin/activate +pip install -r requirements.txt +``` + +------ +#### [ Java ] + +``` +mkdir multistack +cd multistack +cdk init --language=java +``` + +You can import the resulting Maven project into your Java IDE\. + +------ +#### [ C\# ] + +``` +mkdir multistack +cd multistack +cdk init --language=csharp +``` + +You can open the file `src/Pipeline.sln` in Visual Studio\. + +------ + +## Add optional parameter + +The `props` argument of the `Stack` constructor fulfills the interface `StackProps`\. Because we want our stack to accept an additional property to tell us whether to encrypt the Amazon S3 bucket, we should create an interface or class that includes that property\. This allows the compiler to make sure the property has a Boolean value and enables autocompletion for it in your IDE\. + +So open the indicated source file in your IDE or editor and add the new interface, class, or argument\. The code should look like this after the changes\. The lines we added are shown in boldface\. + +------ +#### [ TypeScript ] + +File: `lib/multistack-stack.ts` + +``` +import * as cdk from 'aws-cdk-lib'; +import { Construct } from 'constructs'; + +interface MultiStackProps extends cdk.StackProps { + encryptBucket?: boolean; +} + +export class MultistackStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: MultiStackProps) { + super(scope, id, props); + + // The code that defines your stack goes here + } +} +``` + +------ +#### [ JavaScript ] + +File: `lib/multistack-stack.js` + +JavaScript doesn't have an interface feature; we don't need to add any code\. + +``` +const cdk = require('aws-cdk-stack'); + +class MultistackStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + // The code that defines your stack goes here + } +} + +module.exports = { MultistackStack } +``` + +------ +#### [ Python ] + +File: `multistack/multistack_stack.py` + +Python does not have an interface feature, so we'll extend our stack to accept the new property by adding a keyword argument\. + +``` +import aws_cdk as cdk +import Construct from constructs + +class MultistackStack(cdk.Stack): + + # The Stack class doesn't know about our encrypt_bucket parameter, + # so accept it separately and pass along any other keyword arguments. + def __init__(self, scope: Construct, id: str, *, encrypt_bucket=False, + **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + # The code that defines your stack goes here +``` + +------ +#### [ Java ] + +File: `src/main/java/com/myorg/MultistackStack.java` + +It's more complicated than we really want to get into to extend a props type in Java, so we'll simply write our stack's constructor to accept an optional Boolean parameter\. Since `props` is an optional argument, we'll write an additional constructor that allows you to skip it\. It will default to `false`\. + +``` +package com.myorg; + +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.constructs.Construct; + +import software.amazon.awscdk.services.s3.Bucket; + +public class MultistackStack extends Stack { + // additional constructors to allow props and/or encryptBucket to be omitted + public MultistackStack(final Construct scope, final String id, boolean encryptBucket) { + this(scope, id, null, encryptBucket); + } + + public MultistackStack(final Construct scope, final String id) { + this(scope, id, null, false); + } + + public MultistackStack(final Construct scope, final String id, final StackProps props, + final boolean encryptBucket) { + super(scope, id, props); + + // The code that defines your stack goes here + } +} +``` + +------ +#### [ C\# ] + +File: `src/Multistack/MultistackStack.cs` + +``` +using Amazon.CDK; +using constructs; + +namespace Multistack +{ + + + public class MultiStackProps : StackProps + { + public bool? EncryptBucket { get; set; } + } + + + public class MultistackStack : Stack + { + public MultistackStack(Construct scope, string id, MultiStackProps props) : base(scope, id, props) + { + // The code that defines your stack goes here + } + } +} +``` + +------ + +The new property is optional\. If `encryptBucket` \(Python: `encrypt_bucket`\) is not present, its value is `undefined`, or the local equivalent\. The bucket will be unencrypted by default\. + +## Define the stack class + + Now let's define our stack class, using our new property\. Make the code look like the following\. The code you need to add or change is shown in boldface\. + +------ +#### [ TypeScript ] + +File: `lib/multistack-stack.ts` + +``` +import * as cdk from 'aws-cdk-lib'; +import Construct from constructs; +import * as s3 from 'aws-cdk-lib/aws-s3'; + +interface MultistackProps extends cdk.StackProps { + encryptBucket?: boolean; +} + +export class MultistackStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: MultistackProps) { + super(scope, id, props); + + // Add a Boolean property "encryptBucket" to the stack constructor. + // If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. + // Encrypted bucket uses KMS-managed keys (SSE-KMS). + if (props && props.encryptBucket) { + new s3.Bucket(this, "MyGroovyBucket", { + encryption: s3.BucketEncryption.KMS_MANAGED, + removalPolicy: cdk.RemovalPolicy.DESTROY + }); + } else { + new s3.Bucket(this, "MyGroovyBucket", { + removalPolicy: cdk.RemovalPolicy.DESTROY}); + } + } +} +``` + +------ +#### [ JavaScript ] + +File: `lib/multistack-stack.js` + +``` +const cdk = require('aws-cdk-lib'); +const s3 = require('aws-cdk-lib/aws-s3'); + +class MultistackStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + // Add a Boolean property "encryptBucket" to the stack constructor. + // If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. + // Encrypted bucket uses KMS-managed keys (SSE-KMS). + if ( props && props.encryptBucket) { + new s3.Bucket(this, "MyGroovyBucket", { + encryption: s3.BucketEncryption.KMS_MANAGED, + removalPolicy: cdk.RemovalPolicy.DESTROY + }); + } else { + new s3.Bucket(this, "MyGroovyBucket", { + removalPolicy: cdk.RemovalPolicy.DESTROY}); + } + } +} + +module.exports = { MultistackStack } +``` + +------ +#### [ Python ] + +File: `multistack/multistack_stack.py` + +``` +import aws_cdk as cdk +from constructs import Construct +from aws_cdk import aws_s3 as s3 + +class MultistackStack(cdk.Stack): + + # The Stack class doesn't know about our encrypt_bucket parameter, + # so accept it separately and pass along any other keyword arguments. + def __init__(self, scope: Construct, id: str, *, encrypt_bucket=False, + **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + # Add a Boolean property "encryptBucket" to the stack constructor. + # If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. + # Encrypted bucket uses KMS-managed keys (SSE-KMS). + if encrypt_bucket: + s3.Bucket(self, "MyGroovyBucket", + encryption=s3.BucketEncryption.KMS_MANAGED, + removal_policy=cdk.RemovalPolicy.DESTROY) + else: + s3.Bucket(self, "MyGroovyBucket", + removal_policy=cdk.RemovalPolicy.DESTROY) +``` + +------ +#### [ Java ] + +File: `src/main/java/com/myorg/MultistackStack.java` + +``` +package com.myorg; + +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.constructs.Construct; +import software.amazon.awscdk.RemovalPolicy; + +import software.amazon.awscdk.services.s3.Bucket; +import software.amazon.awscdk.services.s3.BucketEncryption; + +public class MultistackStack extends Stack { + // additional constructors to allow props and/or encryptBucket to be omitted + public MultistackStack(final Construct scope, final String id, + boolean encryptBucket) { + this(scope, id, null, encryptBucket); + } + + public MultistackStack(final Construct scope, final String id) { + this(scope, id, null, false); + } + + // main constructor + public MultistackStack(final Construct scope, final String id, + final StackProps props, final boolean encryptBucket) { + super(scope, id, props); + + // Add a Boolean property "encryptBucket" to the stack constructor. + // If true, creates an encrypted bucket. Otherwise, the bucket is + // unencrypted. Encrypted bucket uses KMS-managed keys (SSE-KMS). + if (encryptBucket) { + Bucket.Builder.create(this, "MyGroovyBucket") + .encryption(BucketEncryption.KMS_MANAGED) + .removalPolicy(RemovalPolicy.DESTROY).build(); + } else { + Bucket.Builder.create(this, "MyGroovyBucket") + .removalPolicy(RemovalPolicy.DESTROY).build(); + } + } +} +``` + +------ +#### [ C\# ] + +File: `src/Multistack/MultistackStack.cs` + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +namespace Multistack +{ + + public class MultiStackProps : StackProps + { + public bool? EncryptBucket { get; set; } + } + + public class MultistackStack : Stack + { + public MultistackStack(Construct scope, string id, IMultiStackProps props = null) : base(scope, id, props) + { + // Add a Boolean property "EncryptBucket" to the stack constructor. + // If true, creates an encrypted bucket. Otherwise, the bucket is unencrypted. + // Encrypted bucket uses KMS-managed keys (SSE-KMS). + if (props?.EncryptBucket ?? false) + { + new Bucket(this, "MyGroovyBucket", new BucketProps + { + Encryption = BucketEncryption.KMS_MANAGED, + RemovalPolicy = RemovalPolicy.DESTROY + }); + } + else + { + new Bucket(this, "MyGroovyBucket", new BucketProps + { + RemovalPolicy = RemovalPolicy.DESTROY + }); + } + } + } +} +``` + +------ + +## Create two stack instances + +Now we'll add the code to instantiate two separate stacks\. As before, the lines of code shown in boldface are the ones you need to add\. Delete the existing `MultistackStack` definition\. + +------ +#### [ TypeScript ] + +File: `bin/multistack.ts` + +``` +#!/usr/bin/env node +import 'source-map-support/register'; +import * as cdk from 'aws-cdk-lib'; +import { MultistackStack } from '../lib/multistack-stack'; + +const app = new cdk.App(); + +new MultistackStack(app, "MyWestCdkStack", { + env: {region: "us-west-1"}, + encryptBucket: false +}); + +new MultistackStack(app, "MyEastCdkStack", { + env: {region: "us-east-1"}, + encryptBucket: true +}); +``` + +------ +#### [ JavaScript ] + +File: `bin/multistack.js` + +``` +#!/usr/bin/env node +const cdk = require('aws-cdk-lib'); +const { MultistackStack } = require('../lib/multistack-stack'); + +const app = new cdk.App(); + +new MultistackStack(app, "MyWestCdkStack", { + env: {region: "us-west-1"}, + encryptBucket: false +}); + +new MultistackStack(app, "MyEastCdkStack", { + env: {region: "us-east-1"}, + encryptBucket: true +}); +``` + +------ +#### [ Python ] + +File: `./app.py` + +``` +#!/usr/bin/env python3 + +import aws_cdk as cdk + +from multistack.multistack_stack import MultistackStack + +app = cdk.App() +MultistackStack(app, "MyWestCdkStack", + env=cdk.Environment(region="us-west-1"), + encrypt_bucket=False) + +MultistackStack(app, "MyEastCdkStack", + env=cdk.Environment(region="us-east-1"), + encrypt_bucket=True) +``` + +------ +#### [ Java ] + +File: `src/main/java/com/myorg/MultistackApp.java` + +``` +package com.myorg; + +import software.amazon.awscdk.App; +import software.amazon.awscdk.Environment; +import software.amazon.awscdk.StackProps; + +public class MultistackApp { + public static void main(final String argv[]) { + App app = new App(); + + new MultistackStack(app, "MyWestCdkStack", StackProps.builder() + .env(Environment.builder() + .region("us-west-1") + .build()) + .build(), false); + + new MultistackStack(app, "MyEastCdkStack", StackProps.builder() + .env(Environment.builder() + .region("us-east-1") + .build()) + .build(), true); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +File: src/Multistack/Program\.cs + +``` +using Amazon.CDK; + +namespace Multistack +{ + class Program + { + static void Main(string[] args) + { + var app = new App(); + + new MultistackStack(app, "MyWestCdkStack", new MultiStackProps + { + Env = new Environment { Region = "us-west-1" }, + EncryptBucket = false + }); + + new MultistackStack(app, "MyEastCdkStack", new MultiStackProps + { + Env = new Environment { Region = "us-east-1" }, + EncryptBucket = true + }); + + app.Synth(); + } + } +} +``` + +------ + + This code uses the new `encryptBucket` \(Python: `encrypt_bucket`\) property on the `MultistackStack` class to instantiate the following: ++ One stack with an encrypted Amazon S3 bucket in the `us-east-1` AWS Region\. ++ One stack with an unencrypted Amazon S3 bucket in the `us-west-1` AWS Region\. + +## Synthesize and deploy the stack + +Now you can deploy stacks from the app\. First, synthesize a AWS CloudFormation template for `MyEastCdkStack`—the stack in `us-east-1`\. This is the stack with the encrypted S3 bucket\. + +``` +$ cdk synth MyEastCdkStack +``` + +To deploy this stack to your AWS account, issue one of the following commands\. The first command uses your default AWS profile to obtain the credentials to deploy the stack\. The second uses a profile you specify: for *PROFILE\_NAME*, substitute the name of an AWS CLI profile that contains appropriate credentials for deploying to the `us-east-1` AWS Region\. + +``` +cdk deploy MyEastCdkStack +``` + +``` +cdk deploy MyEastCdkStack --profile=PROFILE_NAME +``` + +## Clean up + +To avoid charges for resources that you deployed, destroy the stack using the following command\. + +``` +cdk destroy MyEastCdkStack +``` + +The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket's contents, but not the bucket itself, using the AWS Management Console or the AWS CLI before destroying the stack\. \ No newline at end of file diff --git a/v2/stacks.md b/v2/stacks.md new file mode 100644 index 00000000..4c6cc09f --- /dev/null +++ b/v2/stacks.md @@ -0,0 +1,377 @@ +# Stacks + +The unit of deployment in the AWS CDK is called a *stack*\. All AWS resources defined within the scope of a stack, either directly or indirectly, are provisioned as a single unit\. + +Because AWS CDK stacks are implemented through AWS CloudFormation stacks, they have the same limitations as in [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html)\. + +You can define any number of stacks in your AWS CDK app\. Any instance of the `Stack` construct represents a stack, and can be either defined directly within the scope of the app, like the `MyFirstStack` example shown previously, or indirectly by any construct within the tree\. + +For example, the following code defines an AWS CDK app with two stacks\. + +------ +#### [ TypeScript ] + +``` +const app = new App(); + +new MyFirstStack(app, 'stack1'); +new MySecondStack(app, 'stack2'); + +app.synth(); +``` + +------ +#### [ JavaScript ] + +``` +const app = new App(); + +new MyFirstStack(app, 'stack1'); +new MySecondStack(app, 'stack2'); + +app.synth(); +``` + +------ +#### [ Python ] + +``` +app = App() + +MyFirstStack(app, 'stack1') +MySecondStack(app, 'stack2') + +app.synth() +``` + +------ +#### [ Java ] + +``` +App app = new App(); + +new MyFirstStack(app, "stack1"); +new MySecondStack(app, "stack2"); + +app.synth(); +``` + +------ +#### [ C\# ] + +``` +var app = new App(); + +new MyFirstStack(app, "stack1"); +new MySecondStack(app, "stack2"); + +app.Synth(); +``` + +------ + +To list all the stacks in an AWS CDK app, run the cdk ls command, which for the previous AWS CDK app would have the following output\. + +``` +stack1 +stack2 +``` + +When you run the cdk synth command for an app with multiple stacks, the cloud assembly includes a separate template for each stack instance\. Even if the two stacks are instances of the same class, the AWS CDK emits them as two individual templates\. + +You can synthesize each template by specifying the stack name in the cdk synth command\. The following example synthesizes the template for **stack1**\. + +``` +cdk synth stack1 +``` + +This approach is conceptually different from how AWS CloudFormation templates are normally used, where a template can be deployed multiple times and parameterized through [AWS CloudFormation parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html)\. Although AWS CloudFormation parameters can be defined in the AWS CDK, they are generally discouraged because AWS CloudFormation parameters are resolved only during deployment\. This means that you cannot determine their value in your code\. For example, to conditionally include a resource in your app based on the value of a parameter, you must set up an [AWS CloudFormation condition](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) and tag the resource with this condition\. Because the AWS CDK takes an approach where concrete templates are resolved at synthesis time, you can use an **if** statement to check the value to determine whether a resource should be defined or some behavior should be applied\. + +**Note** +The AWS CDK provides as much resolution as possible during synthesis time to enable idiomatic and natural usage of your programming language\. + +Like any other construct, stacks can be composed together into groups\. The following code shows an example of a service that consists of three stacks: a control plane, a data plane, and monitoring stacks\. The service construct is defined twice: once for the beta environment and once for the production environment\. + +------ +#### [ TypeScript ] + +``` +import { App, Stack } from 'aws-cdk-lib'; +import { Construct } from 'constructs'; + +interface EnvProps { + prod: boolean; +} + +// imagine these stacks declare a bunch of related resources +class ControlPlane extends Stack {} +class DataPlane extends Stack {} +class Monitoring extends Stack {} + +class MyService extends Construct { + + constructor(scope: Construct, id: string, props?: EnvProps) { + + super(scope, id); + + // we might use the prod argument to change how the service is configured + new ControlPlane(this, "cp"); + new DataPlane(this, "data"); + new Monitoring(this, "mon"); } +} + +const app = new App(); +new MyService(app, "beta"); +new MyService(app, "prod", { prod: true }); + +app.synth(); +``` + +------ +#### [ JavaScript ] + +``` +const { App, Stack } = require('aws-cdk-lib'); +const { Construct } = require('constructs'); + +// imagine these stacks declare a bunch of related resources +class ControlPlane extends Stack {} +class DataPlane extends Stack {} +class Monitoring extends Stack {} + +class MyService extends Construct { + + constructor(scope, id, props) { + + super(scope, id); + + // we might use the prod argument to change how the service is configured + new ControlPlane(this, "cp"); + new DataPlane(this, "data"); + new Monitoring(this, "mon"); + } +} + +const app = new App(); +new MyService(app, "beta"); +new MyService(app, "prod", { prod: true }); + +app.synth(); +``` + +------ +#### [ Python ] + +``` +from aws_cdk import App, Stack +from constructs import Construct + +# imagine these stacks declare a bunch of related resources +class ControlPlane(Stack): pass +class DataPlane(Stack): pass +class Monitoring(Stack): pass + +class MyService(Construct): + + def __init__(self, scope: Construct, id: str, *, prod=False): + + super().__init__(scope, id) + + # we might use the prod argument to change how the service is configured + ControlPlane(self, "cp") + DataPlane(self, "data") + Monitoring(self, "mon") + +app = App(); +MyService(app, "beta") +MyService(app, "prod", prod=True) + +app.synth() +``` + +------ +#### [ Java ] + +``` +package com.myorg; + +import software.amazon.awscdk.App; +import software.amazon.awscdk.Stack; +import software.constructs.Construct; + +public class MyApp { + + // imagine these stacks declare a bunch of related resources + static class ControlPlane extends Stack { + ControlPlane(Construct scope, String id) { + super(scope, id); + } + } + + static class DataPlane extends Stack { + DataPlane(Construct scope, String id) { + super(scope, id); + } + } + + static class Monitoring extends Stack { + Monitoring(Construct scope, String id) { + super(scope, id); + } + } + + static class MyService extends Construct { + MyService(Construct scope, String id) { + this(scope, id, false); + } + + MyService(Construct scope, String id, boolean prod) { + super(scope, id); + + // we might use the prod argument to change how the service is configured + new ControlPlane(this, "cp"); + new DataPlane(this, "data"); + new Monitoring(this, "mon"); + } + } + + public static void main(final String argv[]) { + App app = new App(); + + new MyService(app, "beta"); + new MyService(app, "prod", true); + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Constructs; + +// imagine these stacks declare a bunch of related resources +public class ControlPlane : Stack { + public ControlPlane(Construct scope, string id=null) : base(scope, id) { } +} + +public class DataPlane : Stack { + public DataPlane(Construct scope, string id=null) : base(scope, id) { } +} + +public class Monitoring : Stack +{ + public Monitoring(Construct scope, string id=null) : base(scope, id) { } +} + +public class MyService : Construct +{ + public MyService(Construct scope, string id, Boolean prod=false) : base(scope, id) + { + // we might use the prod argument to change how the service is configured + new ControlPlane(this, "cp"); + new DataPlane(this, "data"); + new Monitoring(this, "mon"); + } +} + +class Program +{ + static void Main(string[] args) + { + + var app = new App(); + new MyService(app, "beta"); + new MyService(app, "prod", prod: true); + app.Synth(); + } +} +``` + +------ + +This AWS CDK app eventually consists of six stacks, three for each environment: + +``` +$ cdk ls + +betacpDA8372D3 +betadataE23DB2BA +betamon632BD457 +prodcp187264CE +proddataF7378CE5 +prodmon631A1083 +``` + +The physical names of the AWS CloudFormation stacks are automatically determined by the AWS CDK based on the stack's construct path in the tree\. By default, a stack's name is derived from the construct ID of the `Stack` object, but you can specify an explicit name using the `stackName` prop \(in Python, `stack_name`\), as follows\. + +------ +#### [ TypeScript ] + +``` +new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name' }); +``` + +------ +#### [ JavaScript ] + +``` +new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name' }); +``` + +------ +#### [ Python ] + +``` +MyStack(self, "not:a:stack:name", stack_name="this-is-stack-name") +``` + +------ +#### [ Java ] + +``` +new MyStack(this, "not:a:stack:name", StackProps.builder() + .StackName("this-is-stack-name").build()); +``` + +------ +#### [ C\# ] + +``` +new MyStack(this, "not:a:stack:name", new StackProps +{ + StackName = "this-is-stack-name" +}); +``` + +------ + +## Stack API + +The [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html) object provides a rich API, including the following: ++ `Stack.of(construct)` – A static method that returns the **Stack** in which a construct is defined\. This is useful if you need to interact with a stack from within a reusable construct\. The call fails if a stack cannot be found in scope\. ++ `stack.stackName` \(Python: `stack_name`\) – Returns the physical name of the stack\. As mentioned previously, all AWS CDK stacks have a physical name that the AWS CDK can resolve during synthesis\. ++ `stack.region` and `stack.account` – Return the AWS Region and account, respectively, into which this stack will be deployed\. These properties return either the account or Region explicitly specified when the stack was defined, or a string\-encoded token that resolves to the AWS CloudFormation pseudo\-parameters for account and Region to indicate that this stack is environment agnostic\. See [Environments](environments.md) for information about how environments are determined for stacks\. ++ `stack.addDependency(stack)` \(Python: `stack.add_dependency(stack)` – Can be used to explicitly define dependency order between two stacks\. This order is respected by the cdk deploy command when deploying multiple stacks at once\. ++ `stack.tags` – Returns a [TagManager](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.TagManager.html) that you can use to add or remove stack\-level tags\. This tag manager tags all resources within the stack, and also tags the stack itself when it's created through AWS CloudFormation\. ++ `stack.partition`, `stack.urlSuffix` \(Python: `url_suffix`\), `stack.stackId` \(Python: `stack_id`\), and `stack.notificationArn` \(Python: `notification_arn`\) – Return tokens that resolve to the respective AWS CloudFormation pseudo\-parameters, such as `{ "Ref": "AWS::Partition" }`\. These tokens are associated with the specific stack object so that the AWS CDK framework can identify cross\-stack references\. ++ `stack.availabilityZones` \(Python: `availability_zones`\) – Returns the set of Availability Zones available in the environment in which this stack is deployed\. For environment\-agnostic stacks, this always returns an array with two Availability Zones, but for environment\-specific stacks, the AWS CDK queries the environment and returns the exact set of Availability Zones available in the region you specified\. ++ `stack.parseArn(arn)` and `stack.formatArn(comps)` \(Python: `parse_arn`, `format_arn`\) – Can be used to work with Amazon Resource Names \(ARNs\)\. ++ `stack.toJsonString(obj)` \(Python: `to_json_string`\) – Can be used to format an arbitrary object as a JSON string that can be embedded in an AWS CloudFormation template\. The object can include tokens, attributes, and references, which are only resolved during deployment\. ++ `stack.templateOptions` \(Python: `template_options`\) – Enables you to specify AWS CloudFormation template options, such as Transform, Description, and Metadata, for your stack\. + +## Nested stacks + +The [NestedStack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.NestedStack.html) construct offers a way around the AWS CloudFormation 500\-resource limit for stacks\. A nested stack counts as only one resource in the stack that contains it, but can itself contain up to 500 resources, including additional nested stacks\. + +The scope of a nested stack must be a `Stack` or `NestedStack` construct\. The nested stack needn't be declared lexically inside its parent stack; it is necessary only to pass the parent stack as the first parameter \(`scope`\) when instantiating the nested stack\. Aside from this restriction, defining constructs in a nested stack works exactly the same as in an ordinary stack\. + +At synthesis time, the nested stack is synthesized to its own AWS CloudFormation template, which is uploaded to the AWS CDK staging bucket at deployment\. Nested stacks are bound to their parent stack and are not treated as independent deployment artifacts; they are not listed by `cdk list` nor can they be deployed by `cdk deploy`\. + +References between parent stacks and nested stacks are automatically translated to stack parameters and outputs in the generated AWS CloudFormation templates, as with any [cross\-stack reference](resources.md#resource_stack)\. + +**Warning** +Changes in security posture are not displayed before deployment for nested stacks\. This information is displayed only for top\-level stacks\. \ No newline at end of file diff --git a/v2/tagging.md b/v2/tagging.md new file mode 100644 index 00000000..5c262efe --- /dev/null +++ b/v2/tagging.md @@ -0,0 +1,413 @@ +# Tagging + +Tags are informational key\-value elements that you can add to constructs in your AWS CDK app\. A tag applied to a given construct also applies to all of its taggable children\. Tags are included in the AWS CloudFormation template synthesized from your app and are applied to the AWS resources it deploys\. You can use tags to identify and categorize resources to simplify management, in cost allocation, and for access control, as well as for any other purposes you devise\. + +**Tip** +For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf)\. + +The [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#addkey-value-props](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#addkey-value-props) applies a new tag to the given construct and all of its children\. ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#removekey-props](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#removekey-props) removes a tag from the given construct and any of its children, including tags a child construct may have applied to itself\. + +**Note** +Tagging is implemented using [Aspects](aspects.md)\. Aspects are a way to apply an operation \(such as tagging\) to all constructs in a given scope\. + +The following example applies the tag **key** with the value **value** to a construct\. + +------ +#### [ TypeScript ] + +``` +Tags.of(myConstruct).add('key', 'value'); +``` + +------ +#### [ JavaScript ] + +``` +Tags.of(myConstruct).add('key', 'value'); +``` + +------ +#### [ Python ] + +``` +Tags.of(my_construct).add("key", "value") +``` + +------ +#### [ Java ] + +``` +Tags.of(myConstruct).add("key", "value"); +``` + +------ +#### [ C\# ] + +``` +Tags.Of(myConstruct).Add("key", "value"); +``` + +------ + +The following example deletes the tag **key** from a construct\. + +------ +#### [ TypeScript ] + +``` +Tags.of(myConstruct).remove('key'); +``` + +------ +#### [ JavaScript ] + +``` +Tags.of(myConstruct).remove('key'); +``` + +------ +#### [ Python ] + +``` +Tags.of(my_construct).remove("key") +``` + +------ +#### [ Java ] + +``` +Tags.of(myConstruct).remove("key"); +``` + +------ +#### [ C\# ] + +``` +Tags.Of(myConstruct).Remove("key"); +``` + +------ + +## Tag priorities + +The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. + +The following applies a tag with a priority of 300 to a construct\. + +------ +#### [ TypeScript ] + +``` +Tags.of(myConstruct).add('key', 'value', { + priority: 300 +}); +``` + +------ +#### [ JavaScript ] + +``` +Tags.of(myConstruct).add('key', 'value', { + priority: 300 +}); +``` + +------ +#### [ Python ] + +``` +Tags.of(my_construct).add("key", "value", priority=300) +``` + +------ +#### [ Java ] + +``` +Tags.of(myConstruct).add("key", "value", TagProps.builder() + .priority(300).build()); +``` + +------ +#### [ C\# ] + +``` +Tags.Of(myConstruct).Add("key", "value", new TagProps { Priority = 300 }); +``` + +------ + +## Optional properties + +Tags support [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.TagProps.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.TagProps.html) that fine\-tune how tags are applied to, or removed from, resources\. All properties are optional\. + +`applyToLaunchedInstances` \(Python: `apply_to_launched_instances`\) +Available for add\(\) only\. By default, tags are applied to instances launched in an Auto Scaling group\. Set this property to **false** to ignore instances launched in an Auto Scaling group\. + +`includeResourceTypes`/`excludeResourceTypes` \(Python: `include_resource_types`/`exclude_resource_types`\) +Use these to manipulate tags only on a subset of resources, based on AWS CloudFormation resource types\. By default, the operation is applied to all resources in the construct subtree, but this can be changed by including or excluding certain resource types\. Exclude takes precedence over include, if both are specified\. + +`priority` +Use this to set the priority of this operation with respect to other `Tags.add()` and `Tags.remove()` operations\. Higher values take precedence over lower values\. The default is 100 for add operations \(50 for tags applied directly to AWS CloudFormation resources\) and 200 for remove operations\. + +The following example applies the tag **tagname** with the value **value** and priority **100** to resources of type **AWS::Xxx::Yyy** in the construct, but not to instances launched in an Amazon EC2 Auto Scaling group or to resources of type **AWS::Xxx::Zzz**\. \(These are placeholders for two arbitrary but different AWS CloudFormation resource types\.\) + +------ +#### [ TypeScript ] + +``` +Tags.of(myConstruct).add('tagname', 'value', { + applyToLaunchedInstances: false, + includeResourceTypes: ['AWS::Xxx::Yyy'], + excludeResourceTypes: ['AWS::Xxx::Zzz'], + priority: 100, +}); +``` + +------ +#### [ JavaScript ] + +``` +Tags.of(myConstruct).add('tagname', 'value', { + applyToLaunchedInstances: false, + includeResourceTypes: ['AWS::Xxx::Yyy'], + excludeResourceTypes: ['AWS::Xxx::Zzz'], + priority: 100 +}); +``` + +------ +#### [ Python ] + +``` +Tags.of(my_construct).add("tagname", "value", + apply_to_launched_instances=False, + include_resource_types=["AWS::Xxx::Yyy"], + exclude_resource_types=["AWS::Xxx::Zzz"], + priority=100) +``` + +------ +#### [ Java ] + +``` +Tags.of(myConstruct).add("key", "value", TagProps.builder() + .applyToLaunchedInstances(false) + .includeResourceTypes(Arrays.asList("AWS::Xxx::Yyy")) + .excludeResourceTypes(Arrays.asList("AWS::Xxx::Zzz")) + .priority(100).build()); +``` + +------ +#### [ C\# ] + +``` +Tags.Of(myConstruct).Add("tagname", "value", new TagProps +{ + ApplyToLaunchedInstances = false, + IncludeResourceTypes = ["AWS::Xxx::Yyy"], + ExcludeResourceTypes = ["AWS::Xxx::Zzz"], + Priority = 100 +}); +``` + +------ + +The following example removes the tag **tagname** with priority **200** from resources of type **AWS::Xxx::Yyy** in the construct, but not from resources of type **AWS::Xxx::Zzz**\. + +------ +#### [ TypeScript ] + +``` +Tags.of(myConstruct).remove('tagname', { + includeResourceTypes: ['AWS::Xxx::Yyy'], + excludeResourceTypes: ['AWS::Xxx::Zzz'], + priority: 200, +}); +``` + +------ +#### [ JavaScript ] + +``` +Tags.of(myConstruct).remove('tagname', { + includeResourceTypes: ['AWS::Xxx::Yyy'], + excludeResourceTypes: ['AWS::Xxx::Zzz'], + priority: 200 +}); +``` + +------ +#### [ Python ] + +``` +Tags.of(my_construct).remove("tagname", + include_resource_types=["AWS::Xxx::Yyy"], + exclude_resource_types=["AWS::Xxx::Zzz"], + priority=200,) +``` + +------ +#### [ Java ] + +``` +Tags.of((myConstruct).remove("tagname", TagProps.builder() + .includeResourceTypes(Arrays.asList("AWS::Xxx::Yyy")) + .excludeResourceTypes(Arrays.asList("AWS::Xxx::Zzz")) + .priority(100).build()); +``` + +------ +#### [ C\# ] + +``` +Tags.Of(myConstruct).Remove("tagname", new TagProps +{ + IncludeResourceTypes = ["AWS::Xxx::Yyy"], + ExcludeResourceTypes = ["AWS::Xxx::Zzz"], + Priority = 100 +}); +``` + +------ + +## Example + +The following example adds the tag key **StackType** with value **TheBest** to any resource created within the Stack named `MarketingSystem`\. Then it removes it again from all resources except Amazon EC2 VPC subnets\. The result is that only the subnets have the tag applied\. + +------ +#### [ TypeScript ] + +``` +import { App, Stack, Tags } from 'aws-cdk-lib'; + +const app = new App(); +const theBestStack = new Stack(app, 'MarketingSystem'); + +// Add a tag to all constructs in the stack +Tags.of(theBestStack).add('StackType', 'TheBest'); + +// Remove the tag from all resources except subnet resources +Tags.of(theBestStack).remove('StackType', { + excludeResourceTypes: ['AWS::EC2::Subnet'] +}); +``` + +------ +#### [ JavaScript ] + +``` +const { App, Stack, Tags } = require('aws-cdk-lib'); + +const app = new App(); +const theBestStack = new Stack(app, 'MarketingSystem'); + +// Add a tag to all constructs in the stack +Tags.of(theBestStack).add('StackType', 'TheBest'); + +// Remove the tag from all resources except subnet resources +Tags.of(theBestStack).remove('StackType', { + excludeResourceTypes: ['AWS::EC2::Subnet'] +}); +``` + +------ +#### [ Python ] + +``` +from aws_cdk import App, Stack, Tags + +app = App(); +the_best_stack = Stack(app, 'MarketingSystem') + +# Add a tag to all constructs in the stack +Tags.of(the_best_stack).add("StackType", "TheBest") + +# Remove the tag from all resources except subnet resources +Tags.of(the_best_stack).remove("StackType", + exclude_resource_types=["AWS::EC2::Subnet"]) +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.App; +import software.amazon.awscdk.Tags; + +// Add a tag to all constructs in the stack +Tags.of(theBestStack).add("StackType", "TheBest"); + +// Remove the tag from all resources except subnet resources +Tags.of(theBestStack).remove("StackType", TagProps.builder() + .excludeResourceTypes(Arrays.asList("AWS::EC2::Subnet")) + .build()); +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; + +var app = new App(); +var theBestStack = new Stack(app, 'MarketingSystem'); + +// Add a tag to all constructs in the stack +Tags.Of(theBestStack).Add("StackType", "TheBest"); + +// Remove the tag from all resources except subnet resources +Tags.Of(theBestStack).Remove("StackType", new TagProps +{ + ExcludeResourceTypes = ["AWS::EC2::Subnet"] +}); +``` + +------ + +The following code achieves the same result\. Consider which approach \(inclusion or exclusion\) makes your intent clearer\. + +------ +#### [ TypeScript ] + +``` +Tags.of(theBestStack).add('StackType', 'TheBest', + { includeResourceTypes: ['AWS::EC2::Subnet']}); +``` + +------ +#### [ JavaScript ] + +``` +Tags.of(theBestStack).add('StackType', 'TheBest', + { includeResourceTypes: ['AWS::EC2::Subnet']}); +``` + +------ +#### [ Python ] + +``` +Tags.of(the_best_stack).add("StackType", "TheBest", + include_resource_types=["AWS::EC2::Subnet"]) +``` + +------ +#### [ Java ] + +``` +Tags.of(theBestStack).add("StackType", "TheBest", TagProps.builder() + .includeResourceTypes(Arrays.asList("AWS::EC2::Subnet")) + .build()); +``` + +------ +#### [ C\# ] + +``` +Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps { + IncludeResourceTypes = ["AWS::EC2::Subnet"] +}); +``` + +------ \ No newline at end of file diff --git a/v2/testing.md b/v2/testing.md new file mode 100644 index 00000000..32a8f523 --- /dev/null +++ b/v2/testing.md @@ -0,0 +1,1531 @@ +# Testing constructs + +With the AWS CDK, your infrastructure can be as testable as any other code you write\. This article illustrates the standard approach to testing AWS CDK apps using the AWS CDK's [assertions](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.assertions-readme.html) module and popular test frameworks such as [Jest](https://jestjs.io/) for TypeScript and JavaScript or [Pytest](https://docs.pytest.org/en/6.2.x/) for Python\. + +There are two categories of tests you can write for AWS CDK apps\. ++ **Fine\-grained assertions** test specific aspects of the generated AWS CloudFormation template, such as "this resource has this property with this value\." These tests can detect regressions, and are also useful when you're developing new features using test\-driven development \(write a test first, then make it pass by writing a correct implementation\)\. Fine\-grained assertions are the tests you'll write the most of\. ++ **Snapshot tests** test the synthesized AWS CloudFormation template against a previously\-stored baseline template or "master\." Snapshot tests let you refactor freely, since you can be sure that the refactored code works exactly the same way as the original\. If the changes were intentional, you can accept a new baseline for future tests\. However, CDK upgrades can also cause synthesized templates to change, so you can't rely only on snapshots to make sure your implementation is correct\. + +**Note** +Complete versions of the TypeScript, Python, and Java apps used as examples in this topic are [available on GitHub](https://github.com/cdklabs/aws-cdk-testing-examples/)\. + +## Getting started + +To illustrate how to write these tests, we'll create a stack that contains an AWS Step Functions state machine and a AWS Lambda function\. The Lambda function is subscribed to an Amazon SNS topic and simply forwards the message to the state machine\. + +First, create an empty CDK application project using the CDK Toolkit and installing the libraries we'll need\. The constructs we'll use are all in the main CDK package, which is a default dependency in projects created with the CDK Toolkit, but you'll need to install your testing framework\. + +------ +#### [ TypeScript ] + +``` +mkdir state-machine && cd state-machine +cdk init --language=typescript +npm install --save-dev jest @types/jest +``` + +Create a directory for your tests\. + +``` +mkdir test +``` + +Edit the project's `package.json` to tell NPM how to run Jest, and to tell Jest what kinds of files to collect\. The necessary changes are as follows\. ++ Add a new `test` key to the `scripts` section ++ Add Jest and its types to the `devDependencies` section ++ Add a new `jest` top\-level key with a `moduleFileExtensions` declaration + +These changes are shown in outline below\. Place the new text where indicated in `package.json`\. The "\.\.\." placeholders indicate existing parts of the file that should not be changed\. + +``` +{ + ... + "scripts": { + ... + "test": "jest" + }, + "devDependencies": { + ... + "@types/jest": "^24.0.18", + "jest": "^24.9.0" + }, + "jest": { + "moduleFileExtensions": ["js"] + } +} +``` + +------ +#### [ JavaScript ] + +``` +mkdir state-machine && cd state-machine +cdk init --language=javascript +npm install --save-dev jest +``` + +Create a directory for your tests\. + +``` +mkdir test +``` + +Edit the project's `package.json` to tell NPM how to run Jest, and to tell Jest what kinds of files to collect\. The necessary changes are as follows\. ++ Add a new `test` key to the `scripts` section ++ Add Jest to the `devDependencies` section ++ Add a new `jest` top\-level key with a `moduleFileExtensions` declaration + +These changes are shown in outline below\. Place the new text where indicated in `package.json`\. The "\.\.\." placeholders indicate existing parts of the file that s\.hould not be changed\. + +``` +{ + ... + "scripts": { + ... + "test": "jest" + }, + "devDependencies": { + ... + "jest": "^24.9.0" + }, + "jest": { + "moduleFileExtensions": ["js"] + } +} +``` + +------ +#### [ Python ] + +``` +mkdir state-machine && cd state-machine +cdk init --language=python +source .venv/bin/activate +python -m pip install -r requirements.txt +python -m pip install -r requirements-dev.txt +``` + +------ +#### [ Java ] + +``` +mkdir state-machine && cd-state-machine +cdk init --language=java +``` + +Open the project in your preferred Java IDE\. \(In Eclipse, use **File** > **Import** > Existing Maven Projects\.\) + +------ +#### [ C\# ] + +``` +mkdir state-machine && cd-state-machine +cdk init --language=csharp +``` + +Open `src\StateMachine.sln` in Visual Studio\. + +Right\-click the solution in Solution Explorer and choose **Add** > **New Project**\. Search for MSTest C\# and add an **MSTest Test Project** for C\#\. \(The default name `TestProject1`is fine\.\) + +Right\-click `TestProject1` and choose **Add** > **Project Reference**, and add the `StateMachine` project as a reference\. + +------ + +## The example stack + +Here's the stack we'll be testing in this topic\. As we've previously described, it contains a Lambda function and a Step Functions state machine, and accepts one or more Amazon SNS topics\. The Lambda function is subscribed to the Amazon SNS topics and forwards them to the state machine\. + +You don't have to do anything special to make the app testable\. In fact, this CDK stack is not different in any important way from the other example stacks in this Guide\. + +------ +#### [ TypeScript ] + +Place the following code in `lib/state-machine-stack.ts`: + +``` +import * as cdk from "aws-cdk-lib"; +import * as sns from "aws-cdk-lib/aws-sns"; +import * as sns_subscriptions from "aws-cdk-lib/aws-sns-subscriptions"; +import * as lambda from "aws-cdk-lib/aws-lambda"; +import * as sfn from "aws-cdk-lib/aws-stepfunctions"; +import { Construct } from "constructs"; + +export interface ProcessorStackProps extends cdk.StackProps { + readonly topics: sns.Topic[]; +} + +export class ProcessorStack extends cdk.Stack { + constructor(scope: Construct, id: string, props: ProcessorStackProps) { + super(scope, id, props); + + // In the future this state machine will do some work... + const stateMachine = new sfn.StateMachine(this, "StateMachine", { + definition: new sfn.Pass(this, "StartState"), + }); + + // This Lambda function starts the state machine. + const func = new lambda.Function(this, "LambdaFunction", { + runtime: lambda.Runtime.NODEJS_14_X, + handler: "handler", + code: lambda.Code.fromAsset("./start-state-machine"), + environment: { + STATE_MACHINE_ARN: stateMachine.stateMachineArn, + }, + }); + stateMachine.grantStartExecution(func); + + const subscription = new sns_subscriptions.LambdaSubscription(func); + for (const topic of props.topics) { + topic.addSubscription(subscription); + } + } +} +``` + +------ +#### [ JavaScript ] + +Place the following code in `lib/state-machine-stack.js`: + +``` +const cdk = require("aws-cdk-lib"); +const sns = require("aws-cdk-lib/aws-sns"); +const sns_subscriptions = require("aws-cdk-lib/aws-sns-subscriptions"); +const lambda = require("aws-cdk-lib/aws-lambda"); +const sfn = require("aws-cdk-lib/aws-stepfunctions"); + +class ProcessorStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + // In the future this state machine will do some work... + const stateMachine = new sfn.StateMachine(this, "StateMachine", { + definition: new sfn.Pass(this, "StartState"), + }); + + // This Lambda function starts the state machine. + const func = new lambda.Function(this, "LambdaFunction", { + runtime: lambda.Runtime.NODEJS_14_X, + handler: "handler", + code: lambda.Code.fromAsset("./start-state-machine"), + environment: { + STATE_MACHINE_ARN: stateMachine.stateMachineArn, + }, + }); + stateMachine.grantStartExecution(func); + + const subscription = new sns_subscriptions.LambdaSubscription(func); + for (const topic of props.topics) { + topic.addSubscription(subscription); + } + } +} + +module.exports = { ProcessorStack } +``` + +------ +#### [ Python ] + +Place the following code in `state_machine/state_machine_stack.py`: + +``` +from typing import List + +import aws-cdk.aws_lambda as lambda_ +import aws-cdk.aws_sns as sns +import aws-cdk.aws_sns_subscriptions as sns_subscriptions +import aws-cdk.aws_stepfunctions as sfn +import aws-cdk as cdk + +class ProcessorStack(cdk.Stack): + def __init__( + self, + scope: cdk.Construct, + construct_id: str, + *, + topics: List[sns.Topic], + **kwargs + ) -> None: + super().__init__(scope, construct_id, **kwargs) + + # In the future this state machine will do some work... + state_machine = sfn.StateMachine( + self, "StateMachine", definition=sfn.Pass(self, "StartState") + ) + + # This Lambda function starts the state machine. + func = lambda_.Function( + self, + "LambdaFunction", + runtime=lambda_.Runtime.NODEJS_14_X, + handler="handler", + code=lambda_.Code.from_asset("./start-state-machine"), + environment={ + "STATE_MACHINE_ARN": state_machine.state_machine_arn, + }, + ) + state_machine.grant_start_execution(func) + + subscription = sns_subscriptions.LambdaSubscription(func) + for topic in topics: + topic.add_subscription(subscription) +``` + +------ +#### [ Java ] + +``` +package software.amazon.samples.awscdkassertionssamples; + +import software.constructs.Construct; +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.services.lambda.Code; +import software.amazon.awscdk.services.lambda.Function; +import software.amazon.awscdk.services.lambda.Runtime; +import software.amazon.awscdk.services.sns.ITopicSubscription; +import software.amazon.awscdk.services.sns.Topic; +import software.amazon.awscdk.services.sns.subscriptions.LambdaSubscription; +import software.amazon.awscdk.services.stepfunctions.Pass; +import software.amazon.awscdk.services.stepfunctions.StateMachine; + +import java.util.Collections; +import java.util.List; + +public class ProcessorStack extends Stack { + public ProcessorStack(final Construct scope, final String id, final List topics) { + this(scope, id, null, topics); + } + + public ProcessorStack(final Construct scope, final String id, final StackProps props, final List topics) { + super(scope, id, props); + + // In the future this state machine will do some work... + final StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine") + .definition(new Pass(this, "StartState")) + .build(); + + // This Lambda function starts the state machine. + final Function func = Function.Builder.create(this, "LambdaFunction") + .runtime(Runtime.NODEJS_14_X) + .handler("handler") + .code(Code.fromAsset("./start-state-machine")) + .environment(Collections.singletonMap("STATE_MACHINE_ARN", stateMachine.getStateMachineArn())) + .build(); + stateMachine.grantStartExecution(func); + + final ITopicSubscription subscription = new LambdaSubscription(func); + for (final Topic topic : topics) { + topic.addSubscription(subscription); + } + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.Lambda; +using Amazon.CDK.AWS.StepFunctions; +using Amazon.CDK.AWS.SNS; +using Amazon.CDK.AWS.SNS.Subscriptions; +using Constructs; + +using System.Collections.Generic; + +namespace AwsCdkAssertionSamples +{ + public class StateMachineStackProps : StackProps + { + public Topic[] Topics; + } + + public class StateMachineStack : Stack + { + + internal StateMachineStack(Construct scope, string id, StateMachineStackProps props = null) : base(scope, id, props) + { + // In the future this state machine will do some work... + var stateMachine = new StateMachine(this, "StateMachine", new StateMachineProps + { + Definition = new Pass(this, "StartState") + }); + + // This Lambda function starts the state machine. + var func = new Function(this, "LambdaFunction", new FunctionProps + { + Runtime = Runtime.NODEJS_14_X, + Handler = "handler", + Code = Code.FromAsset("./start-state-machine"), + Environment = new Dictionary + { + { "STATE_MACHINE_ARN", stateMachine.StateMachineArn } + } + }); + stateMachine.GrantStartExecution(func); + + foreach (Topic topic in props?.Topics ?? new Topic[0]) + { + var subscription = new LambdaSubscription(func); + } + + } + } +} +``` + +------ + +We'll modify the app's main entry point to not actually instantiate our stack, since we don't want to accidentally deploy it\. Our tests will create an app and an instance of the stack for testing\. This is a useful tactic when combined with test\-driven development: make sure the stack passes all tests before you enable deployment\. + +------ +#### [ TypeScript ] + +In `bin/state-machine.ts`: + +``` +#!/usr/bin/env node +import * as cdk from "aws-cdk-lib"; + +const app = new cdk.App(); + +// Stacks are intentionally not created here -- this application isn't meant to +// be deployed. +``` + +------ +#### [ JavaScript ] + +In `bin/state-machine.js`: + +``` +#!/usr/bin/env node +const cdk = require("aws-cdk-lib"); + +const app = new cdk.App(); + +// Stacks are intentionally not created here -- this application isn't meant to +// be deployed. +``` + +------ +#### [ Python ] + +In `app.py`: + +``` +#!/usr/bin/env python3 +import os + +import aws_cdk as cdk + +app = cdk.App() + +# Stacks are intentionally not created here -- this application isn't meant to +# be deployed. + +app.synth() +``` + +------ +#### [ Java ] + +``` +package software.amazon.samples.awscdkassertionssamples; + +import software.amazon.awscdk.App; + +public class SampleApp { + public static void main(final String[] args) { + App app = new App(); + + // Stacks are intentionally not created here -- this application isn't meant to be deployed. + + app.synth(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; + +namespace AwsCdkAssertionSamples +{ + sealed class Program + { + public static void Main(string[] args) + { + var app = new App(); + + // Stacks are intentionally not created here -- this application isn't meant to be deployed. + + app.Synth(); + } + } +} +``` + +------ + +## Running tests + +For reference, here are the commands you use to run tests in your AWS CDK app\. These are the same commands you'd use to run the tests in any project using the same testing framework\. For languages that require a build step, include that to make sure your tests have been compiled\. + +------ +#### [ TypeScript ] + +``` +tsc && npm test +``` + +------ +#### [ JavaScript ] + +``` +npm test +``` + +------ +#### [ Python ] + +``` +python -m pytest +``` + +------ +#### [ Java ] + +``` +mvn compile && mvn test +``` + +------ +#### [ C\# ] + +Build your solution \(F6\) to discover the tests, then run the tests \(**Test** > **Run All Tests**\)\. To choose which tests to run, open Test Explorer \(**Test** > **Test Explorer**\)\. + +Or: + +``` +dotnet test src +``` + +------ + +## Fine\-grained assertions + +The first step for testing a stack with fine\-grained assertions is to synthesize the stack, because we're writing assertions against the generated AWS CloudFormation template\. + +Our `ProcessorStack` requires that we pass it the Amazon SNS topic to be forwarded to the state machine\. So in our test, we'll create a separate stack to contain the topic\. + +Ordinarily, if you were writing a CDK app, you'd subclass `Stack` and instantiate the Amazon SNS topic in the stack's constructor\. In our test, we instantiate `Stack` directly, then pass this stack as the `Topic`'s scope, attaching it to the stack\. This is functionally equivalent, less verbose, and helps make stacks used only in tests "look different" from stacks you intend to deploy\. + +------ +#### [ TypeScript ] + +``` +import { Capture, Match, Template } from "aws-cdk-lib/assertions"; +import * as cdk from "aws-cdk-lib"; +import * as sns from "aws-cdk-lib/aws-sns"; +import { ProcessorStack } from "../lib/processor-stack"; + +describe("ProcessorStack", () => { + test("synthesizes the way we expect", () => { + const app = new cdk.App(); + + // Since the ProcessorStack consumes resources from a separate stack + // (cross-stack references), we create a stack for our SNS topics to live + // in here. These topics can then be passed to the ProcessorStack later, + // creating a cross-stack reference. + const topicsStack = new cdk.Stack(app, "TopicsStack"); + + // Create the topic the stack we're testing will reference. + const topics = [new sns.Topic(topicsStack, "Topic1", {})]; + + // Create the ProcessorStack. + const processorStack = new ProcessorStack(app, "ProcessorStack", { + topics: topics, // Cross-stack reference + }); + + // Prepare the stack for assertions. + const template = Template.fromStack(processorStack); + + +} +``` + +------ +#### [ JavaScript ] + +``` +const { Capture, Match, Template } = require("aws-cdk-lib/assertions"); +const cdk = require("aws-cdk-lib"); +const sns = require("aws-cdk-lib/aws-sns"); +const { ProcessorStack } = require("../lib/processor-stack"); + +describe("ProcessorStack", () => { + test("synthesizes the way we expect", () => { + const app = new cdk.App(); + + // Since the ProcessorStack consumes resources from a separate stack + // (cross-stack references), we create a stack for our SNS topics to live + // in here. These topics can then be passed to the ProcessorStack later, + // creating a cross-stack reference. + const topicsStack = new cdk.Stack(app, "TopicsStack"); + + // Create the topic the stack we're testing will reference. + const topics = [new sns.Topic(topicsStack, "Topic1", {})]; + + // Create the ProcessorStack. + const processorStack = new ProcessorStack(app, "ProcessorStack", { + topics: topics, // Cross-stack reference + }); + + // Prepare the stack for assertions. + const template = Template.fromStack(processorStack); +``` + +------ +#### [ Python ] + +``` +from aws_cdk import aws_sns as sns +import aws_cdk as cdk +from aws_cdk.assertions import Template + +from app.processor_stack import ProcessorStack + +def test_synthesizes_properly(): + app = cdk.App() + + # Since the ProcessorStack consumes resources from a separate stack + # (cross-stack references), we create a stack for our SNS topics to live + # in here. These topics can then be passed to the ProcessorStack later, + # creating a cross-stack reference. + topics_stack = cdk.Stack(app, "TopicsStack") + + # Create the topic the stack we're testing will reference. + topics = [sns.Topic(topics_stack, "Topic1")] + + # Create the ProcessorStack. + processor_stack = ProcessorStack( + app, "ProcessorStack", topics=topics # Cross-stack reference + ) + + # Prepare the stack for assertions. + template = Template.from_stack(processor_stack) +``` + +------ +#### [ Java ] + +``` +package software.amazon.samples.awscdkassertionssamples; + +import org.junit.jupiter.api.Test; +import software.amazon.awscdk.assertions.Capture; +import software.amazon.awscdk.assertions.Match; +import software.amazon.awscdk.assertions.Template; +import software.amazon.awscdk.App; +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.services.sns.Topic; + +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ProcessorStackTest { + @Test + public void testSynthesizesProperly() { + final App app = new App(); + + // Since the ProcessorStack consumes resources from a separate stack (cross-stack references), we create a stack + // for our SNS topics to live in here. These topics can then be passed to the ProcessorStack later, creating a + // cross-stack reference. + final Stack topicsStack = new Stack(app, "TopicsStack"); + + // Create the topic the stack we're testing will reference. + final List topics = Collections.singletonList(Topic.Builder.create(topicsStack, "Topic1").build()); + + // Create the ProcessorStack. + final ProcessorStack processorStack = new ProcessorStack( + app, + "ProcessorStack", + topics // Cross-stack reference + ); + + // Prepare the stack for assertions. + final Template template = Template.fromStack(processorStack) +``` + +------ +#### [ C\# ] + +``` +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Amazon.CDK; +using Amazon.CDK.AWS.SNS; +using Amazon.CDK.Assertions; +using AwsCdkAssertionSamples; + +using ObjectDict = System.Collections.Generic.Dictionary; +using StringDict = System.Collections.Generic.Dictionary; + +namespace TestProject1 +{ + [TestClass] + public class ProcessorStackTest + { + [TestMethod] + public void TestMethod1() + { + var app = new App(); + + // Since the ProcessorStack consumes resources from a separate stack (cross-stack references), we create a stack + // for our SNS topics to live in here. These topics can then be passed to the ProcessorStack later, creating a + // cross-stack reference. + var topicsStack = new Stack(app, "TopicsStack"); + + // Create the topic the stack we're testing will reference. + var topics = new Topic[] { new Topic(topicsStack, "Topic1") }; + + // Create the ProcessorStack. + var processorStack = new StateMachineStack(app, "ProcessorStack", new StateMachineStackProps + { + Topics = topics + }); + + // Prepare the stack for assertions. + var template = Template.FromStack(processorStack); + + // test will go here + } + } +} +``` + +------ + +Now we can assert that the Lambda function and the Amazon SNS subscription were created\. + +------ +#### [ TypeScript ] + +``` + // Assert it creates the function with the correct properties... + template.hasResourceProperties("AWS::Lambda::Function", { + Handler: "handler", + Runtime: "nodejs14.x", + }); + + // Creates the subscription... + template.resourceCountIs("AWS::SNS::Subscription", 1); +``` + +------ +#### [ JavaScript ] + +``` + // Assert it creates the function with the correct properties... + template.hasResourceProperties("AWS::Lambda::Function", { + Handler: "handler", + Runtime: "nodejs14.x", + }); + + // Creates the subscription... + template.resourceCountIs("AWS::SNS::Subscription", 1); +``` + +------ +#### [ Python ] + +``` +# Assert that we have created the function with the correct properties + template.has_resource_properties( + "AWS::Lambda::Function", + { + "Handler": "handler", + "Runtime": "nodejs14.x", + }, + ) + + # Assert that we have created a subscription + template.resource_count_is("AWS::SNS::Subscription", 1) +``` + +------ +#### [ Java ] + +``` + // Assert it creates the function with the correct properties... + template.hasResourceProperties("AWS::Lambda::Function", Map.of( + "Handler", "handler", + "Runtime", "nodejs14.x" + )); + + // Creates the subscription... + template.resourceCountIs("AWS::SNS::Subscription", 1); +``` + +------ +#### [ C\# ] + +``` + // Prepare the stack for assertions. + var template = Template.FromStack(processorStack); + + // Assert it creates the function with the correct properties... + template.HasResourceProperties("AWS::Lambda::Function", new StringDict { + { "Handler", "handler"}, + { "Runtime", "nodejs14x" } + }); + + // Creates the subscription... + template.ResourceCountIs("AWS::SNS::Subscription", 1); +``` + +------ + +Our Lambda function test asserts that two particular properties of the function resource have specific values\. By default, the `hasResourceProperties` method performs a partial match on the resource's properties as given in the synthesized CloudFormation template\. This test requires that the provided properties exist and have the specified values, but the resource can also have other properties, and these are not tested\. + +Our Amazon SNS assertion asserts that the synthesized template contains a subscription, but nothing about the subscription itself\. We included this assertion mainly to illustrate how to assert on resource counts\. The `Template` class offers more specific methods to write assertions against the `Resources`, `Outputs`, and `Mapping` sections of the CloudFormation template\. + +### Matchers + +The default partial matching behavior of `hasResourceProperties` can be changed using *matchers* from the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.assertions.Match.html#methods](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.assertions.Match.html#methods) class\. + +Matchers range from the very lenient \(`Match.anyValue`\) to the quite strict \(`Match.objectEquals`\), and can be nested to apply different matching methods to different parts of the resource properties\. Using `Match.objectEquals` and `Match.anyValue` together, for example, we can test the state machine's IAM role more fully, while not requiring specific values for properties that may change\. + +------ +#### [ TypeScript ] + +``` + // Fully assert on the state machine's IAM role with matchers. + template.hasResourceProperties( + "AWS::IAM::Role", + Match.objectEquals({ + AssumeRolePolicyDocument: { + Version: "2012-10-17", + Statement: [ + { + Action: "sts:AssumeRole", + Effect: "Allow", + Principal: { + Service: { + "Fn::Join": [ + "", + ["states.", Match.anyValue(), ".amazonaws.com"], + ], + }, + }, + }, + ], + }, + }) + ); +``` + +------ +#### [ JavaScript ] + +``` + // Fully assert on the state machine's IAM role with matchers. + template.hasResourceProperties( + "AWS::IAM::Role", + Match.objectEquals({ + AssumeRolePolicyDocument: { + Version: "2012-10-17", + Statement: [ + { + Action: "sts:AssumeRole", + Effect: "Allow", + Principal: { + Service: { + "Fn::Join": [ + "", + ["states.", Match.anyValue(), ".amazonaws.com"], + ], + }, + }, + }, + ], + }, + }) + ); +``` + +------ +#### [ Python ] + +``` +from aws_cdk.assertions import Match + + # Fully assert on the state machine's IAM role with matchers. + template.has_resource_properties( + "AWS::IAM::Role", + Match.object_equals( + { + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": { + "Fn::Join": [ + "", + [ + "states.", + Match.any_value(), + ".amazonaws.com", + ], + ], + }, + }, + }, + ], + }, + } + ), + ) +``` + +------ +#### [ Java ] + +``` + // Fully assert on the state machine's IAM role with matchers. + template.hasResourceProperties("AWS::IAM::Role", Match.objectEquals( + Collections.singletonMap("AssumeRolePolicyDocument", Map.of( + "Version", "2012-10-17", + "Statement", Collections.singletonList(Map.of( + "Action", "sts:AssumeRole", + "Effect", "Allow", + "Principal", Collections.singletonMap( + "Service", Collections.singletonMap( + "Fn::Join", Arrays.asList( + "", + Arrays.asList("states.", Match.anyValue(), ".amazonaws.com") + ) + ) + ) + )) + )) + )); +``` + +------ +#### [ C\# ] + +``` + // Fully assert on the state machine's IAM role with matchers. + template.HasResource("AWS::IAM::Role", Match.ObjectEquals(new ObjectDict + { + { "AssumeRolePolicyDocument", new ObjectDict + { + { "Version", "2012-10-17" }, + { "Action", "sts:AssumeRole" }, + { "Principal", new ObjectDict + { + { "Version", "2012-10-17" }, + { "Statement", new object[] + { + new ObjectDict { + { "Action", "sts:AssumeRole" }, + { "Effect", "Allow" }, + { "Principal", new ObjectDict + { + { "Service", new ObjectDict + { + { "", new object[] + { "states", Match.AnyValue(), ".amazonaws.com" } + } + } + } + } + } + } + } + } + } + } + } + } + })); +``` + +------ + +Many CloudFormation resources include serialized JSON objects represented as strings\. The `Match.serializedJson()` matcher can be used to match properties inside this JSON\. For example, Step Functions state machines are defined using a string in the JSON\-based [Amazon States Language](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html)\. We'll use `Match.serializedJson()` to make sure our initial state is the only step, again using nested matchers to apply different kinds of matching to different parts of the object\. + +------ +#### [ TypeScript ] + +``` + // Assert on the state machine's definition with the Match.serializedJson() + // matcher. + template.hasResourceProperties("AWS::StepFunctions::StateMachine", { + DefinitionString: Match.serializedJson( + // Match.objectEquals() is used implicitly, but we use it explicitly + // here for extra clarity. + Match.objectEquals({ + StartAt: "StartState", + States: { + StartState: { + Type: "Pass", + End: true, + // Make sure this state doesn't provide a next state -- we can't + // provide both Next and set End to true. + Next: Match.absent(), + }, + }, + }) + ), + }); +``` + +------ +#### [ JavaScript ] + +``` + // Assert on the state machine's definition with the Match.serializedJson() + // matcher. + template.hasResourceProperties("AWS::StepFunctions::StateMachine", { + DefinitionString: Match.serializedJson( + // Match.objectEquals() is used implicitly, but we use it explicitly + // here for extra clarity. + Match.objectEquals({ + StartAt: "StartState", + States: { + StartState: { + Type: "Pass", + End: true, + // Make sure this state doesn't provide a next state -- we can't + // provide both Next and set End to true. + Next: Match.absent(), + }, + }, + }) + ), + }); +``` + +------ +#### [ Python ] + +``` + # Assert on the state machine's definition with the serialized_json matcher. + template.has_resource_properties( + "AWS::StepFunctions::StateMachine", + { + "DefinitionString": Match.serialized_json( + # Match.object_equals() is the default, but specify it here for clarity + Match.object_equals( + { + "StartAt": "StartState", + "States": { + "StartState": { + "Type": "Pass", + "End": True, + # Make sure this state doesn't provide a next state -- + # we can't provide both Next and set End to true. + "Next": Match.absent(), + }, + }, + } + ) + ), + }, + ) +``` + +------ +#### [ Java ] + +``` + // Assert on the state machine's definition with the Match.serializedJson() matcher. + template.hasResourceProperties("AWS::StepFunctions::StateMachine", Collections.singletonMap( + "DefinitionString", Match.serializedJson( + // Match.objectEquals() is used implicitly, but we use it explicitly here for extra clarity. + Match.objectEquals(Map.of( + "StartAt", "StartState", + "States", Collections.singletonMap( + "StartState", Map.of( + "Type", "Pass", + "End", true, + // Make sure this state doesn't provide a next state -- we can't provide + // both Next and set End to true. + "Next", Match.absent() + ) + ) + )) + ) + )); +``` + +------ +#### [ C\# ] + +``` + // Assert on the state machine's definition with the Match.serializedJson() matcher + template.HasResourceProperties("AWS::StepFunctions::StateMachine", new ObjectDict + { + { "DefinitionString", Match.SerializedJson( + // Match.objectEquals() is used implicitly, but we use it explicitly here for extra clarity. + Match.ObjectEquals(new ObjectDict { + { "StartAt", "StartState" }, + { "States", new ObjectDict + { + { "StartState", new ObjectDict { + { "Type", "Pass" }, + { "End", "True" }, + // Make sure this state doesn't provide a next state -- we can't provide + // both Next and set End to true. + { "Next", Match.Absent() } + }} + }} + }) + )}}); +``` + +------ + +### Capturing + +It's often useful to test properties to make sure they follow specific formats, or have the same value as another property, without needing to know their exact values ahead of time\. The `assertions` module provides this capability in its [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.assertions.Capture.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.assertions.Capture.html) class\. + +By specifying a `Capture` instance in place of a value in `hasResourceProperties`, that value is retained in the `Capture` object\. The actual captured value can be retrieved using the object's `as` methods, including `asNumber()`, `asString()`, and `asObject`, and subjected to test\. Use `Capture` with a matcher to specify the exact location of the value to be captured within the resource's properties, including serialized JSON properties\. + +For example, this example tests to make sure that the starting state of our state machine has a name beginning with `Start` and also that this state is actually present within the list of states in the machine\. + +------ +#### [ TypeScript ] + +``` + // Capture some data from the state machine's definition. + const startAtCapture = new Capture(); + const statesCapture = new Capture(); + template.hasResourceProperties("AWS::StepFunctions::StateMachine", { + DefinitionString: Match.serializedJson( + Match.objectLike({ + StartAt: startAtCapture, + States: statesCapture, + }) + ), + }); + + // Assert that the start state starts with "Start". + expect(startAtCapture.asString()).toEqual(expect.stringMatching(/^Start/)); + + // Assert that the start state actually exists in the states object of the + // state machine definition. + expect(statesCapture.asObject()).toHaveProperty(startAtCapture.asString()); +``` + +------ +#### [ JavaScript ] + +``` + // Capture some data from the state machine's definition. + const startAtCapture = new Capture(); + const statesCapture = new Capture(); + template.hasResourceProperties("AWS::StepFunctions::StateMachine", { + DefinitionString: Match.serializedJson( + Match.objectLike({ + StartAt: startAtCapture, + States: statesCapture, + }) + ), + }); + + // Assert that the start state starts with "Start". + expect(startAtCapture.asString()).toEqual(expect.stringMatching(/^Start/)); + + // Assert that the start state actually exists in the states object of the + // state machine definition. + expect(statesCapture.asObject()).toHaveProperty(startAtCapture.asString()); +``` + +------ +#### [ Python ] + +``` +import re + + from aws_cdk.assertions import Capture + + # ... + + # Capture some data from the state machine's definition. + start_at_capture = Capture() + states_capture = Capture() + template.has_resource_properties( + "AWS::StepFunctions::StateMachine", + { + "DefinitionString": Match.serialized_json( + Match.object_like( + { + "StartAt": start_at_capture, + "States": states_capture, + } + ) + ), + }, + ) + + # Assert that the start state starts with "Start". + assert re.match("^Start", start_at_capture.as_string()) + + # Assert that the start state actually exists in the states object of the + # state machine definition. + assert start_at_capture.as_string() in states_capture.as_object() +``` + +------ +#### [ Java ] + +``` + // Capture some data from the state machine's definition. + final Capture startAtCapture = new Capture(); + final Capture statesCapture = new Capture(); + template.hasResourceProperties("AWS::StepFunctions::StateMachine", Collections.singletonMap( + "DefinitionString", Match.serializedJson( + Match.objectLike(Map.of( + "StartAt", startAtCapture, + "States", statesCapture + )) + ) + )); + + // Assert that the start state starts with "Start". + assertThat(startAtCapture.asString()).matches("^Start.+"); + + // Assert that the start state actually exists in the states object of the state machine definition. + assertThat(statesCapture.asObject()).containsKey(startAtCapture.asString()); +``` + +------ +#### [ C\# ] + +``` + // Capture some data from the state machine's definition. + var startAtCapture = new Capture(); + var statesCapture = new Capture(); + template.HasResourceProperties("AWS::StepFunctions::StateMachine", new ObjectDict + { + { "DefinitionString", Match.SerializedJson( + new ObjectDict + { + { "StartAt", startAtCapture }, + { "States", statesCapture } + } + )} + }); + + Assert.IsTrue(startAtCapture.ToString().StartsWith("Start")); + Assert.IsTrue(statesCapture.AsObject().ContainsKey(startAtCapture.ToString())); +``` + +------ + +## Snapshot tests + +In *snapshot testing*, you compare the entire synthesized CloudFormation template against a previously\-stored master\. This isn't useful in catching regressions, as fine\-grained assertions are, because it applies to the entire template, and things besides code changes can cause small \(or not\-so\-small\) differences in synthesis results\. For example, we may update a CDK construct to incorporate a new best practice, which can cause changes to the synthesized resources or how they're organized, or we might update the CDK Toolkit to report additional metadata\. Changes to context values can also affect the synthesized template\. + +Snapshot tests can be of great help in refactoring, though, as long as you hold constant all other factors that might affect the synthesized template\. You will know immediately if a change you made has unintentionally changed the template\. If the change is intentional, simply accept a new master and proceed\. + +For example, if we have this `DeadLetterQueue` construct: + +------ +#### [ TypeScript ] + +``` +export class DeadLetterQueue extends sqs.Queue { + public readonly messagesInQueueAlarm: cloudwatch.IAlarm; + + constructor(scope: Construct, id: string) { + super(scope, id); + + // Add the alarm + this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { + alarmDescription: 'There are messages in the Dead Letter Queue', + evaluationPeriods: 1, + threshold: 1, + metric: this.metricApproximateNumberOfMessagesVisible(), + }); + } +} +``` + +------ +#### [ JavaScript ] + +``` +class DeadLetterQueue extends sqs.Queue { + + constructor(scope, id) { + super(scope, id); + + // Add the alarm + this.messagesInQueueAlarm = new cloudwatch.Alarm(this, 'Alarm', { + alarmDescription: 'There are messages in the Dead Letter Queue', + evaluationPeriods: 1, + threshold: 1, + metric: this.metricApproximateNumberOfMessagesVisible(), + }); + } +} + +module.exports = { DeadLetterQueue } +``` + +------ +#### [ Python ] + +``` +class DeadLetterQueue(sqs.Queue): + def __init__(self, scope: Construct, id: str): + super().__init__(scope, id) + + self.messages_in_queue_alarm = cloudwatch.Alarm( + self, + "Alarm", + alarm_description="There are messages in the Dead Letter Queue.", + evaluation_periods=1, + threshold=1, + metric=self.metric_approximate_number_of_messages_visible(), + ) +``` + +------ +#### [ Java ] + +``` +public class DeadLetterQueue extends Queue { + private final IAlarm messagesInQueueAlarm; + + public DeadLetterQueue(@NotNull Construct scope, @NotNull String id) { + super(scope, id); + + this.messagesInQueueAlarm = Alarm.Builder.create(this, "Alarm") + .alarmDescription("There are messages in the Dead Letter Queue.") + .evaluationPeriods(1) + .threshold(1) + .metric(this.metricApproximateNumberOfMessagesVisible()) + .build(); + } + + public IAlarm getMessagesInQueueAlarm() { + return messagesInQueueAlarm; + } +} +``` + +------ +#### [ C\# ] + +``` +namespace AwsCdkAssertionSamples +{ + public class DeadLetterQueue : Queue + { + public IAlarm messagesInQueueAlarm; + + public DeadLetterQueue(Construct scope, string id) : base(scope, id) + { + messagesInQueueAlarm = new Alarm(this, "Alarm", new AlarmProps + { + AlarmDescription = "There are messages in the Dead Letter Queue.", + EvaluationPeriods = 1, + Threshold = 1, + Metric = this.MetricApproximateNumberOfMessagesVisible() + }); + } + } +} +``` + +------ + +We can test it like this: + +------ +#### [ TypeScript ] + +``` +import { Match, Template } from "aws-cdk-lib/assertions"; +import * as cdk from "aws-cdk-lib"; +import { DeadLetterQueue } from "../lib/dead-letter-queue"; + +describe("DeadLetterQueue", () => { + test("creates an alarm", () => { + const stack = new cdk.Stack(); + new DeadLetterQueue(stack, "DeadLetterQueue"); + + const template = Template.fromStack(stack); + template.hasResourceProperties("AWS::CloudWatch::Alarm", { + Namespace: "AWS/SQS", + MetricName: "ApproximateNumberOfMessagesVisible", + Dimensions: [ + { + Name: "QueueName", + Value: Match.anyValue(), + }, + ], + }); + }); +}); +``` + +------ +#### [ JavaScript ] + +``` +const { Match, Template } = require("aws-cdk-lib/assertions"); +const cdk = require("aws-cdk-lib"); +const { DeadLetterQueue } = require("../lib/dead-letter-queue"); + +describe("DeadLetterQueue", () => { + test("creates an alarm", () => { + const stack = new cdk.Stack(); + new DeadLetterQueue(stack, "DeadLetterQueue"); + + const template = Template.fromStack(stack); + template.hasResourceProperties("AWS::CloudWatch::Alarm", { + Namespace: "AWS/SQS", + MetricName: "ApproximateNumberOfMessagesVisible", + Dimensions: [ + { + Name: "QueueName", + Value: Match.anyValue(), + }, + ], + }); + }); +}); +``` + +------ +#### [ Python ] + +``` +import aws_cdk as cdk +from aws_cdk.assertions import Match, Template + +from app.dead_letter_queue import DeadLetterQueue + +def test_creates_alarm(): + stack = cdk.Stack() + DeadLetterQueue(stack, "DeadLetterQueue") + + template = Template.from_stack(stack) + template.has_resource_properties( + "AWS::CloudWatch::Alarm", + { + "Namespace": "AWS/SQS", + "MetricName": "ApproximateNumberOfMessagesVisible", + "Dimensions": [ + { + "Name": "QueueName", + "Value": Match.any_value(), + }, + ], + }, + ) +``` + +------ +#### [ Java ] + +``` +package software.amazon.samples.awscdkassertionssamples; + +import org.junit.jupiter.api.Test; +import software.amazon.awscdk.assertions.Match; +import software.amazon.awscdk.assertions.Template; +import software.amazon.awscdk.Stack; + +import java.util.Collections; +import java.util.Map; + +public class DeadLetterQueueTest { + @Test + public void testCreatesAlarm() { + final Stack stack = new Stack(); + new DeadLetterQueue(stack, "DeadLetterQueue"); + + final Template template = Template.fromStack(stack); + template.hasResourceProperties("AWS::CloudWatch::Alarm", Map.of( + "Namespace", "AWS/SQS", + "MetricName", "ApproximateNumberOfMessagesVisible", + "Dimensions", Collections.singletonList(Map.of( + "Name", "QueueName", + "Value", Match.anyValue() + )) + )); + } +} +``` + +------ +#### [ C\# ] + +``` +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Amazon.CDK; +using Amazon.CDK.Assertions; +using AwsCdkAssertionSamples; + +using ObjectDict = System.Collections.Generic.Dictionary; +using StringDict = System.Collections.Generic.Dictionary; + +namespace TestProject1 +{ + [TestClass] + public class ProcessorStackTest + + [TestClass] + public class DeadLetterQueueTest + { + [TestMethod] + public void TestCreatesAlarm() + { + var stack = new Stack(); + new DeadLetterQueue(stack, "DeadLetterQueue"); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudWatch::Alarm", new ObjectDict + { + { "Namespace", "AWS/SQS" }, + { "MetricName", "ApproximateNumberOfMessagesVisible" }, + { "Dimensions", new object[] + { + new ObjectDict + { + { "Name", "QueueName" }, + { "Value", Match.AnyValue() } + } + } + } + }); + } + } +} +``` + +------ + +## Tips for tests + +Remember, your tests will live just as long as the code they test, and be read and modified just as often, so it pays to take a moment to consider how best to write them\. Don't copy and paste setup lines or common assertions, for example; refactor this logic into fixtures or helper functions\. Use good names that reflect what each test actually tests\. + +Don't try to do too much in one test\. Preferably, a test should test one and only one behavior\. If you accidentally break that behavior, exactly one test should fail, and the name of the test should tell you exactly what failed\. This is more an ideal to be striven for, however; sometimes you will unavoidably \(or inadvertently\) write tests that test more than one behavior\. Snapshot tests are, for reasons we've already described, especially prone to this problem, so use them sparingly\. \ No newline at end of file diff --git a/v2/tokens.md b/v2/tokens.md new file mode 100644 index 00000000..402da9c8 --- /dev/null +++ b/v2/tokens.md @@ -0,0 +1,427 @@ +# Tokens + +Tokens represent values that can only be resolved at a later time in the lifecycle of an app \(see [App lifecycle](apps.md#lifecycle)\)\. For example, the name of an Amazon S3 bucket that you define in your AWS CDK app is only allocated when the AWS CloudFormation template is synthesized\. If you print the `bucket.bucketName` attribute, which is a string, you see it contains something like the following\. + +``` +${TOKEN[Bucket.Name.1234]} +``` + +This is how the AWS CDK encodes a token whose value is not yet known at construction time, but will become available later\. The AWS CDK calls these placeholders *tokens*\. In this case, it's a token encoded as a string\. + +You can pass this string around as if it was the name of the bucket, such as in the following example, where the bucket name is specified as an environment variable to an AWS Lambda function\. + +------ +#### [ TypeScript ] + +``` +const bucket = new s3.Bucket(this, 'MyBucket'); + +const fn = new lambda.Function(stack, 'MyLambda', { + // ... + environment: { + BUCKET_NAME: bucket.bucketName, + } +}); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = new s3.Bucket(this, 'MyBucket'); + +const fn = new lambda.Function(stack, 'MyLambda', { + // ... + environment: { + BUCKET_NAME: bucket.bucketName + } +}); +``` + +------ +#### [ Python ] + +``` +bucket = s3.Bucket(self, "MyBucket") + +fn = lambda_.Function(stack, "MyLambda", + environment=dict(BUCKET_NAME=bucket.bucket_name)) +``` + +------ +#### [ Java ] + +``` +final Bucket bucket = new Bucket(this, "MyBucket"); + +Function fn = Function.Builder.create(this, "MyLambda") + .environment(new HashMap() {{ + put("BUCKET_NAME", bucket.getBucketName()); + }}).build(); +``` + +------ +#### [ C\# ] + +``` +var bucket = new s3.Bucket(this, "MyBucket"); + +var fn = new Function(this, "MyLambda", new FunctionProps { + Environment = new Dictionary + { + ["BUCKET_NAME"] = bucket.BucketName + } +}); +``` + +------ + +When the AWS CloudFormation template is finally synthesized, the token is rendered as the AWS CloudFormation intrinsic `{ "Ref": "MyBucket" }`\. At deployment time, AWS CloudFormation replaces this intrinsic with the actual name of the bucket that was created\. + +## Tokens and token encodings + +Tokens are objects that implement the [IResolvable](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.IResolvable.html) interface, which contains a single `resolve` method\. The AWS CDK calls this method during synthesis to produce the final value for the AWS CloudFormation template\. Tokens participate in the synthesis process to produce arbitrary values of any type\. + +**Note** +You'll hardly ever work directly with the `IResolvable` interface\. You will most likely only see string\-encoded versions of tokens\. + +Other functions typically only accept arguments of basic types, such as `string` or `number`\. To use tokens in these cases, you can encode them into one of three types using static methods on the [cdk\.Token](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html) class\. ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrstringvalue-options](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrstringvalue-options) to generate a string encoding \(or call `.toString()` on the token object\) ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrlistvalue-options](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrlistvalue-options) to generate a list encoding ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrnumbervalue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrnumbervalue) to generate a numeric encoding + +These take an arbitrary value, which can be an `IResolvable`, and encode them into a primitive value of the indicated type\. + +**Important** +Because any one of the previous types can potentially be an encoded token, be careful when you parse or try to read their contents\. For example, if you attempt to parse a string to extract a value from it, and the string is an encoded token, your parsing will fail\. Similarly, if you attempt to query the length of an array, or perform math operations with a number, you must first verify that they are not encoded tokens\. + +To check whether a value has an unresolved token in it, call the `Token.isUnresolved` \(Python: `is_unresolved`\) method\. + +The following example validates that a string value, which could be a token, is no more than 10 characters long\. + +------ +#### [ TypeScript ] + +``` +if (!Token.isUnresolved(name) && name.length > 10) { + throw new Error(`Maximum length for name is 10 characters`); +} +``` + +------ +#### [ JavaScript ] + +``` +if ( !Token.isUnresolved(name) && name.length > 10) { + throw ( new Error(`Maximum length for name is 10 characters`)); +} +``` + +------ +#### [ Python ] + +``` +if not Token.is_unresolved(name) and len(name) > 10: + raise ValueError("Maximum length for name is 10 characters") +``` + +------ +#### [ Java ] + +``` +if (!Token.isUnresolved(name) && name.length() > 10) + throw new IllegalArgumentException("Maximum length for name is 10 characters"); +``` + +------ +#### [ C\# ] + +``` +if (!Token.IsUnresolved(name) && name.Length > 10) + throw new ArgumentException("Maximum length for name is 10 characters"); +``` + +------ + +If **name** is a token, validation isn't performed, and an error could still occur in a later stage in the lifecycle, such as during deployment\. + +**Note** +You can use token encodings to escape the type system\. For example, you could string\-encode a token that produces a number value at synthesis time\. If you use these functions, it's your responsibility to ensure that your template resolves to a usable state after synthesis\. + +## String\-encoded tokens + +String\-encoded tokens look like the following\. + +``` +${TOKEN[Bucket.Name.1234]} +``` + +They can be passed around like regular strings, and can be concatenated, as shown in the following example\. + +------ +#### [ TypeScript ] + +``` +const functionName = bucket.bucketName + 'Function'; +``` + +------ +#### [ JavaScript ] + +``` +const functionName = bucket.bucketName + 'Function'; +``` + +------ +#### [ Python ] + +``` +function_name = bucket.bucket_name + "Function" +``` + +------ +#### [ Java ] + +``` +String functionName = bucket.getBucketName().concat("Function"); +``` + +------ +#### [ C\# ] + +``` +string functionName = bucket.BucketName + "Function"; +``` + +------ + +You can also use string interpolation, if your language supports it, as shown in the following example\. + +------ +#### [ TypeScript ] + +``` +const functionName = `${bucket.bucketName}Function`; +``` + +------ +#### [ JavaScript ] + +``` +const functionName = `${bucket.bucketName}Function`; +``` + +------ +#### [ Python ] + +``` +function_name = f"{bucket.bucket_name}Function" +``` + +------ +#### [ Java ] + +``` +String functionName = String.format("%sFunction". bucket.getBucketName()); +``` + +------ +#### [ C\# ] + +``` +string functionName = $"${bucket.bucketName}Function"; +``` + +------ + +Avoid manipulating the string in other ways\. For example, taking a substring of a string is likely to break the string token\. + +## List\-encoded tokens + +List\-encoded tokens look like the following + +``` +["#{TOKEN[Stack.NotificationArns.1234]}"] +``` + +The only safe thing to do with these lists is pass them directly to other constructs\. Tokens in string list form cannot be concatenated, nor can an element be taken from the token\. The only safe way to manipulate them is by using AWS CloudFormation intrinsic functions like [Fn\.select](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-select.html)\. + +## Number\-encoded tokens + +Number\-encoded tokens are a set of tiny negative floating\-point numbers that look like the following\. + +``` +-1.8881545897087626e+289 +``` + +As with list tokens, you cannot modify the number value, as doing so is likely to break the number token\. The only allowed operation is to pass the value around to another construct\. + +## Lazy values + +In addition to representing deploy\-time values, such as AWS CloudFormation [parameters](parameters.md), Tokens are also commonly used to represent synthesis\-time lazy values\. These are values for which the final value will be determined before synthesis has completed, just not at the point where the value is constructed\. Use tokens to pass a literal string or number value to another construct, while the actual value at synthesis time may depend on some calculation that has yet to occur\. + +You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.string](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Lazy.html#static-stringproducer-options) and [Lazy\.number](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Lazy.html#static-numberproducer)\. These methods accept an object whose `produce` property is a function that accepts a context argument and returns the final value when called\. + +The following example creates an Auto Scaling group whose capacity is determined after its creation\. + +------ +#### [ TypeScript ] + +``` +let actualValue: number; + +new AutoScalingGroup(this, 'Group', { + desiredCapacity: Lazy.numberValue({ + produce(context) { + return actualValue; + } + }) +}); + +// At some later point +actualValue = 10; +``` + +------ +#### [ JavaScript ] + +``` +let actualValue; + +new AutoScalingGroup(this, 'Group', { + desiredCapacity: Lazy.numberValue({ + produce(context) { + return (actualValue); + } + }) +}); + +// At some later point +actualValue = 10; +``` + +------ +#### [ Python ] + +``` +class Producer: + def __init__(self, func): + self.produce = func + +actual_value = None + +AutoScalingGroup(self, "Group", + desired_capacity=Lazy.number_value(Producer(lambda context: actual_value)) +) + +# At some later point +actual_value = 10 +``` + +------ +#### [ Java ] + +``` +double actualValue = 0; + +class ProduceActualValue implements INumberProducer { + + @Override + public Number produce(IResolveContext context) { + return actualValue; + } +} + +AutoScalingGroup.Builder.create(this, "Group") + .desiredCapacity(Lazy.numberValue(new ProduceActualValue())).build(); + +// At some later point +actualValue = 10; +``` + +------ +#### [ C\# ] + +``` +public class NumberProducer : INumberProducer +{ + Func function; + + public NumberProducer(Func function) + { + this.function = function; + } + + public Double Produce(IResolveContext context) + { + return function(); + } +} + +double actualValue = 0; + +new AutoScalingGroup(this, "Group", new AutoScalingGroupProps +{ + DesiredCapacity = Lazy.NumberValue(new NumberProducer(() => actualValue)) +}); + +// At some later point +actualValue = 10; +``` + +------ + +## Converting to JSON + +Sometimes you want to produce a JSON string of arbitrary data, and you may not know whether the data contains tokens\. To properly JSON\-encode any data structure, regardless of whether it contains tokens, use the method [stack\.toJsonString](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#towbrjsonwbrstringobj-space), as shown in the following example\. + +------ +#### [ TypeScript ] + +``` +const stack = Stack.of(this); +const str = stack.toJsonString({ + value: bucket.bucketName +}); +``` + +------ +#### [ JavaScript ] + +``` +const stack = Stack.of(this); +const str = stack.toJsonString({ + value: bucket.bucketName +}); +``` + +------ +#### [ Python ] + +``` +stack = Stack.of(self) +string = stack.to_json_string(dict(value=bucket.bucket_name)) +``` + +------ +#### [ Java ] + +``` +Stack stack = Stack.of(this); +String stringVal = stack.toJsonString(new HashMap() {{ + put("value", bucket.getBucketName()); +}}); +``` + +------ +#### [ C\# ] + +``` +var stack = Stack.Of(this); +var stringVal = stack.ToJsonString(new Dictionary +{ + ["value"] = bucket.BucketName +}); +``` + +------ \ No newline at end of file diff --git a/v2/tools.md b/v2/tools.md new file mode 100644 index 00000000..d0df8f1a --- /dev/null +++ b/v2/tools.md @@ -0,0 +1,8 @@ +# AWS CDK tools + +This section contains information about the AWS CDK tools listed below\. + +**Topics** ++ [AWS CDK Toolkit \(`cdk` command\)](cli.md) ++ [AWS Toolkit for Visual Studio Code](vscode.md) ++ [SAM CLI](sam.md) \ No newline at end of file diff --git a/v2/troubleshooting.md b/v2/troubleshooting.md new file mode 100644 index 00000000..a70b70a8 --- /dev/null +++ b/v2/troubleshooting.md @@ -0,0 +1,254 @@ +# Troubleshooting common AWS CDK issues + +This topic describes how to troubleshoot the following issues with the AWS CDK\. ++ [After updating the AWS CDK, the AWS CDK Toolkit \(CLI\) reports a mismatch with the AWS Construct Library](#troubleshooting_toolkit) ++ [When deploying my AWS CDK stack, I receive a `NoSuchBucket` error](#troubleshooting_nobucket) ++ [When deploying my AWS CDK stack, I receive a `forbidden: null` message](#troubleshooting_forbidden_null) ++ [When synthesizing an AWS CDK stack, I get the message `--app is required either in command-line, in cdk.json or in ~/.cdk.json`](#troubleshooting_app_required) ++ [When synthesizing an AWS CDK stack, I receive an error because the AWS CloudFormation template contains too many resources](#troubleshooting_resource_count) ++ [I specified three \(or more\) Availability Zones for my EC2 Auto\-Scaling Group or Virtual Private Cloud, but it was only deployed in two](#troubleshooting_availability_zones) ++ [My S3 bucket, DynamoDB table, or other resource is not deleted when I issue `cdk destroy`](#troubleshooting_resource_not_deleted) + +**After updating the AWS CDK, the AWS CDK Toolkit \(CLI\) reports a mismatch with the AWS Construct Library** +The version of the AWS CDK Toolkit \(which provides the `cdk` command\) must be at least equal to the version of the main AWS Construct Library module, `aws-cdk-lib`\. The Toolkit is intended to be backward compatible; the latest 2\.x version of the toolkit can be used with any 1\.x or 2\.x release of the library\. For this reason, we recommend you install this component globally and keep it up\-to\-date\. + +``` +npm update -g aws-cdk +``` + +If, for some reason, you need to work with multiple versions of the AWS CDK Toolkit, you can install a specific version of the toolkit locally in your project folder\. + +If you are using TypeScript or JavaScript, your project directory already contains a versioned local copy of the CDK Toolkit\. + +If you are using another language, use `npm` to install the AWS CDK Toolkit, omitting the `-g` flag and specifying the desired version\. For example: + +``` +npm install aws-cdk@2.0 +``` + +To run a locally\-installed AWS CDK Toolkit, use the command `npx aws-cdk` rather than just `cdk`\. For example: + +``` +npx aws-cdk deploy MyStack +``` + +`npx aws-cdk` runs the local version of the AWS CDK Toolkit if one exists, and falls back to the global version when a project doesn't have a local installation\. You may find it convenient to set up a shell alias to make sure `cdk` is always invoked this way\. + +------ +#### [ macOS/Linux ] + +``` +alias cdk=npx aws-cdk +``` + +------ +#### [ Windows ] + +``` +doskey cdk=npx aws-cdk $* +``` + +------ + +\([back to list](#troubleshooting_top)\) + +**When deploying my AWS CDK stack, I receive a `NoSuchBucket` error** +Your AWS environment has not been bootstrapped, and so does not have an Amazon S3 bucket to hold resources during deployment\. Stacks require this bucket if they contain [Assets](assets.md) or synthesize to AWS CloudFormation templates larger than 50 kilobytes or if they contain assets such as Lambda function code or container images\. You can create the staging bucket with the following command: + +``` +cdk bootstrap aws://ACCOUNT-NUMBER/REGION +``` + +To avoid generating unexpected AWS charges, the AWS CDK does not automatically boostrap any environment\. You must bootstrap each environment into which you will deploy explicitly\. + +By default, the boostrap resources are created in the region\(s\) used by stacks in the current AWS CDK application, or the region specified in your local AWS profile \(set by `aws configure`\), using that profile's account\. You can specify a different account and region on the command line as follows\. \(You must specify the account and region if you are not in an app's directory\.\) + +``` +cdk bootstrap aws://ACCOUNT-NUMBER/REGION +``` + +For more information, see [Bootstrapping](bootstrapping.md) + +\([back to list](#troubleshooting_top)\) + +**When deploying my AWS CDK stack, I receive a `forbidden: null` message** +You are deploying a stack that requires boostrap resources, but are using an IAM role or account that lacks permission to write to it\. \(The staging bucket is used when deploying stacks that contain assets or that synthesize an AWS CloudFormation template larger than 50K\.\) Use an account or role that has permission to perform the action `s3:*` against the bucket mentioned in the error message\. + +\([back to list](#troubleshooting_top)\) + +**When synthesizing an AWS CDK stack, I get the message `--app is required either in command-line, in cdk.json or in ~/.cdk.json`** +This message usually means that you aren't in the main directory of your AWS CDK project when you issue `cdk synth`\. The file `cdk.json` in this directory, created by the `cdk init` command, contains the command line needed to run \(and thereby synthesize\) your AWS CDK app\. For a TypeScript app, for example, the default `cdk.json` looks something like this: + +``` +{ + "app": "npx ts-node bin/my-cdk-app.ts" +} +``` + + We recommend issuing `cdk` commands only in your project's main directory, so the AWS CDK toolkit can find `cdk.json` there and successfully run your app\. + + If this isn't practical for some reason, the AWS CDK Toolkit looks for the app's command line in two other locations: ++ in `cdk.json` in your home directory ++ on the `cdk synth` command itself using the `-a` option + +For example, you might synthesize a stack from a TypeScript app as follows\. + +``` +cdk synth --app "npx ts-node my-cdk-app.ts" MyStack +``` + +\([back to list](#troubleshooting_top)\) + +**When synthesizing an AWS CDK stack, I receive an error because the AWS CloudFormation template contains too many resources** +The AWS CDK generates and deploys AWS CloudFormation templates\. AWS CloudFormation has a hard limit on the number of resources a stack can contain\. With the AWS CDK, you can run up against this limit more quickly than you might expect\. + +**Note** +The AWS CloudFormation resource limit is 500 at this writing\. See [AWS CloudFormation quotas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html) for the current resource limit\. + +The AWS Construct Library's higher\-level, intent\-based constructs automatically provision any auxiliary resources that are needed for logging, key management, authorization, and other purposes\. For example, granting one resource access to another generates any IAM objects needed for the relevant services to communicate\. + +In our experience, real\-world use of intent\-based constructs results in 1–5 AWS CloudFormation resources per construct, though this can vary\. For serverless applications, 5–8 AWS resources per API endpoint is typical\. + +Patterns, which represent a higher level of abstraction, let you define even more AWS resources with even less code\. The AWS CDK code in [Creating an AWS Fargate service using the AWS CDK](ecs_example.md), for example, generates more than fifty AWS CloudFormation resources while defining only three constructs\! + +Exceeding the AWS CloudFormation resource limit is an error during AWS CloudFormation synthesis\. The AWS CDK issues a warning if your stack exceeds 80% of the limit\. You can use a different limit by setting the `maxResources` property on your stack, or disable validation by setting `maxResources` to 0\. + +**Tip** +You can get an exact count of the resources in your synthesized output using the following utility script\. \(Since every AWS CDK developer needs Node\.js, the script is written in JavaScript\.\) + +``` +// rescount.js - count the resources defined in a stack +// invoke with: node rescount.js +// e.g. node rescount.js cdk.out/MyStack.template.json + +import * as fs from 'fs'; +const path = process.argv[2]; + +if (path) fs.readFile(path, 'utf8', function(err, contents) { + console.log(err ? `${err}` : + `${Object.keys(JSON.parse(contents).Resources).length} resources defined in ${path}`); +}); else console.log("Please specify the path to the stack's output .json file"); +``` + +As your stack's resource count approaches the limit, consider re\-architecting to reduce the number of resources your stack contains: for example, by combining some Lambda functions, or by breaking your stack into multiple stacks\. The CDK supports [references between stacks](resources.md#resource_stack), so it is straightforward to separate your app's functionality into different stacks in whatever way makes the most sense to you\. + +**Note** +AWS CloudFormation experts often suggest the use of nested stacks as a solution to the resource limit\. The AWS CDK supports this approach via the [`NestedStack`](stacks.md#stack_nesting) construct\. + +\([back to list](#troubleshooting_top)\) + +**I specified three \(or more\) Availability Zones for my EC2 Auto\-Scaling Group or Virtual Private Cloud, but it was only deployed in two** +To get the number of Availability Zones you requested, specify the account and region in the stack's `env` property\. If you do not specify both, the AWS CDK, by default, synthesizes the stack as environment\-agnostic, such that it can be deployed to any region\. You can then deploy the stack to a specific region using AWS CloudFormation\. Because some regions have only two availability zones, an environment\-agnostic template never uses more than two\. + +**Note** +In the past, regions have occasionally launched with only one availability zone\. Environment\-agnostic AWS CDK stacks cannot be deployed to such regions\. At this writing, however, all AWS regions have at least two AZs\. + +You can change this behavior by overriding your stack's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones) \(Python: `availability_zones`\) property to explicitly specify the zones you want to use\. + +For more information about specifying a stack's account and region at synthesis time, while retaining the flexibility to deploy to any region, see [Environments](environments.md)\. + +\([back to list](#troubleshooting_top)\) + +**My S3 bucket, DynamoDB table, or other resource is not deleted when I issue `cdk destroy`** +By default, resources that can contain user data have a `removalPolicy` \(Python: `removal_policy`\) property of `RETAIN`, and the resource is not deleted when the stack is destroyed\. Instead, the resource is orphaned from the stack\. You must then delete the resource manually after the stack is destroyed\. Until you do, redeploying the stack fails, because the name of the new resource being created during deployment conflicts with the name of the orphaned resource\. + +If you set a resource's removal policy to `DESTROY`, that resource will be deleted when the stack is destroyed\. + +------ +#### [ TypeScript ] + +``` +import * as cdk from 'aws-cdk-lib'; +import { Construct } from 'constructs'; +import * as s3 from 'aws-cdk-lib/aws-s3'; + +export class CdkTestStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const bucket = new s3.Bucket(this, 'Bucket', { + removalPolicy: cdk.RemovalPolicy.DESTROY, + }); + } +} +``` + +------ +#### [ JavaScript ] + +``` +const cdk = require('aws-cdk-lib'); +const s3 = require('aws-cdk-lib/aws-s3'); + +class CdkTestStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const bucket = new s3.Bucket(this, 'Bucket', { + removalPolicy: cdk.RemovalPolicy.DESTROY + }); + } +} + +module.exports = { CdkTestStack } +``` + +------ +#### [ Python ] + +``` +import aws_cdk as cdk +from constructs import Constroct +import aws_cdk.aws_s3 as s3 + +class CdkTestStack(cdk.stack): + def __init__(self, scope: Construct, id: str, **kwargs): + super().__init__(scope, id, **kwargs) + + bucket = s3.Bucket(self, "Bucket", + removal_policy=cdk.RemovalPolicy.DESTROY) +``` + +------ +#### [ Java ] + +``` +software.amazon.awscdk.*; +import software.amazon.awscdk.services.s3.*; +import software.constructs; + +public class CdkTestStack extends Stack { + public CdkTestStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public CdkTestStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + Bucket.Builder.create(this, "Bucket") + .removalPolicy(RemovalPolicy.DESTROY).build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Amazon.CDK.AWS.S3; + +public CdkTestStack(Construct scope, string id, IStackProps props) : base(scope, id, props) +{ + new Bucket(this, "Bucket", new BucketProps { + RemovalPolicy = RemovalPolicy.DESTROY + }); +} +``` + +------ + +**Note** +AWS CloudFormation cannot delete a non\-empty Amazon S3 bucket\. If you set an Amazon S3 bucket's removal policy to `DESTROY`, and it contains data, attempting to destroy the stack will fail because the bucket cannot be deleted\. You can have the AWS CDK delete the objects in the bucket before attempting to destroy it by setting the bucket's `autoDeleteObjects` prop to `true`\. + +\([back to list](#troubleshooting_top)\) \ No newline at end of file diff --git a/v2/use_cfn_public_registry.md b/v2/use_cfn_public_registry.md new file mode 100644 index 00000000..363aba4b --- /dev/null +++ b/v2/use_cfn_public_registry.md @@ -0,0 +1,112 @@ +# Using resources from the AWS CloudFormation Public Registry + + The AWS CloudFormation Public Registry is a collection of AWS CloudFormation extensions from both AWS and third parties that are available for use by all AWS customers\. You can also publish your own extension for others to use\. Extensions are of two types: resources and modules\. You can use public resource extensions in your AWS CDK app using the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html) construct\. + +All public extensions published by AWS are available to all accounts in all regions without any action on your part\. On the other hand, you must activate each third\-party extension you want to use, in each account and region where you want to use it\. + +**Note** +When you use AWS CloudFormation with third\-party resource types, you will incur charges based on the number of handler operations you run per month and handler operation duration\. See [CloudFormation pricing](http://aws.amazon.com/cloudformation/pricing/) for complete details\. + +See [Using public extensions in CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry-public.html) for complete documentation of this feature from the AWS CloudFormation side\. + +## Activating a third\-party resource in your account and region + +Extensions published by AWS do not require activation; they are always available in every account and region\. You can activate a third\-party extension through the AWS Management Console, via the AWS Command Line Interface, or by deploying a special AWS CloudFormation resource\. + +To activate a third\-party extension through the AWS Management Console, or to simply see what resources are available, follow these steps\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/activate-cfn-extension.png) + +1. Log in to the AWS account in which you want to use the extension, then switch to the region where you want to use it\. + +1. Navigate to the CloudFormation console via the **Services** menu\. + +1. Click **Public extensions** on the navigation bar, then activate the **Third party** radio button under **Publisher**\. A list of the available third\-party public extensions appears\. \(You may also choose **AWS** to see a list of the public extensions published by AWS, though you don't need to activate them\.\) + +1. Browse the list and find the extension you want to activate, or search for it, then activate the radio button in the upper right corner of the extension's card\. + +1. Click the **Activate** button at the top of the list to activate the selected extension\. The extension's **Activate** page appears\. + +1. In the **Activate** page, you may override the extension's default name, specify an execution role and logging configuration, and choose whether to automatically update the extension when a new version is released\. When you have set these options as you like, click **Activate extension** at the bottom of the page\. + +To activate a third\-party extension using the AWS CLI, use the `activate-type `command, substituting the ARN of the custom type you want to use for the one given\. + +``` +aws cloudformation activate-type --public-type-arn public_extension_ARN --auto-update-activated +``` + +To activate an extension through CloudFormation or the CDK, deploy a resource of type `AWS::CloudFormation::TypeActivation`, specifying the following properties\. ++ `TypeName` \- The name of the type, such as `AWSQS::EKS::Cluster`\. ++ `MajorVersion` \- The major version number of the extension that you want; omit if you want the latest version\. ++ `AutoUpdate` \- Whether to automatically update this extension when a new minor version is released by the publisher\. \(Major version updates require explicitly changing the `MajorVersion` property\.\) ++ `ExecutionRoleArn` \- The ARN of the IAM role under which this extension will run\. ++ `LoggingConfig` \- The logging configuration for the extension\. + +The `TypeActivation` resource can be deployed by the CDK using the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html) construct, as shown below for the actual extensions\. + +## Adding a resource from the AWS CloudFormation Public Registry to your CDK app + + Use the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html) construct to include a resource from the AWS CloudFormation Public Registry in your application\. This construct is in the CDK's `aws-cdk-lib` module\. + +For example, suppose there is a public resource named `MY::S5::UltimateBucket` that you want to use in your AWS CDK application\. This resource takes one property: the bucket name\. The corresponding `CfnResource` instantiation looks like this\. + +------ +#### [ TypeScript ] + +``` +const ubucket = new CfnResource(this, 'MyUltimateBucket', { + type: 'MY::S5::UltimateBucket::MODULE', + properties: { + BucketName: 'UltimateBucket' + } +}); +``` + +------ +#### [ JavaScript ] + +``` +const ubucket = new CfnResource(this, 'MyUltimateBucket', { + type: 'MY::S5::UltimateBucket::MODULE', + properties: { + BucketName: 'UltimateBucket' + } +}); +``` + +------ +#### [ Python ] + +``` +ubucket = CfnResource(self, "MyUltimateBucket", + type="MY::S5::UltimateBucket::MODULE", + properties=dict( + BucketName="UltimateBucket")) +``` + +------ +#### [ Java ] + +``` +CfnResource.Builder.create(this, "MyUltimateBucket") + .type("MY::S5::UltimateBucket::MODULE") + .properties(new HashMap() {{ + put("BucketName", "UltimateBucket"); + }}); +``` + +------ +#### [ C\# ] + +``` +new CfnResource(this, "MyUltimateBucket", new CfnResourceProps +{ + Type = "MY::S5::UltimateBucket::MODULE", + Properties = new Dictionary + { + ["BucketName"] = "UltimateBucket" + } +}); +``` + +------ \ No newline at end of file diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md new file mode 100644 index 00000000..8a291530 --- /dev/null +++ b/v2/use_cfn_template.md @@ -0,0 +1,666 @@ +# Import or migrate an existing AWS CloudFormation template + +The [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include-readme.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include-readme.html) construct converts the resources in an imported AWS CloudFormation template to AWS CDK L1 constructs\. You can work with these in your app just as if they were defined in AWS CDK code, even using them within higher\-level AWS CDK constructs, letting you use \(for example\) the L2 permission grant methods with the resources they define\. + +This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\. + +**Note** +The AWS CDK also includes [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. + +## Importing an AWS CloudFormation template + + Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. + +**Tip** +You can use either a JSON or YAML template\. We recommend JSON if available, since YAML parsers can vary slightly in what they accept\. + +``` +{ + "MyBucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": "MyBucket", + } + } +} +``` + +And here's how you import it into your stack using `cloudformation-include`\. + +------ +#### [ TypeScript ] + +``` +import * as cdk from 'aws-cdk-lib'; +import * as cfninc from 'aws-cdk-lib/cloudformation-include'; +import { Construct } from 'constructs'; + +export class MyStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const template = new cfninc.CfnInclude(this, 'Template', { + templateFile: 'my-template.json', + }); + } +} +``` + +------ +#### [ JavaScript ] + +``` +const cdk = require('aws-cdk-lib'); +const cfninc = require('aws-cdk-lib/cloudformation-include'); + +class MyStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + + const template = new cfninc.CfnInclude(this, 'Template', { + templateFile: 'my-template.json', + }); + } +} + +module.exports = { MyStack } +``` + +------ +#### [ Python ] + +``` +import aws_cdk as cdk +from aws_cdk import cloudformation_include as cfn_inc +from constructs import Construct + +class MyStack(cdk.Stack): + + def __init__(self, scope: Construct, id: str, **kwargs) -> None: + super().__init__(scope, id, **kwargs) + + template = cfn_inc.CfnInclude(self, "Template", + template_file="my-template.json") +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.StackProps; +import software.amazon.awscdk.cloudformation.include.CfnInclude; +import software.constructs.Construct; + +public class MyStack extends Stack { + public MyStack(final Construct scope, final String id) { + this(scope, id, null); + } + + public MyStack(final Construct scope, final String id, final StackProps props) { + super(scope, id, props); + + CfnInclude template = CfnInclude.Builder.create(this, "Template") + .templateFile("my-template.json") + .build(); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; +using Constructs; +using cfnInc = Amazon.CDK.CloudFormation.Include; + +namespace MyApp +{ + public class MyStack : Stack + { + internal MyStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) + { + var template = new cfnInc.CfnInclude(this, "Template", new cfnInc.CfnIncludeProps + { + TemplateFile = "my-template.json" + }); + } + } +} +``` + +------ + +By default, importing a resource preserves the resource's original logical ID from the template\. This behavior is suitable for migrating an AWS CloudFormation template to the AWS CDK, where the logical IDs must be retained for AWS CloudFormation to recognize these as the same resources from the AWS CloudFormation template\. + +If you are instead developing an AWS CDK construct wrapper for the template so it can be used by AWS CDK developers \("vending"\), have the AWS CDK generate new resource IDs instead, so the construct can be used multiple times in a stack without name conflicts\. To do this, set the `preserveLogicalIds` property to false when importing the template\. + +------ +#### [ TypeScript ] + +``` +const template = new cfninc.CfnInclude(this, 'MyConstruct', { + templateFile: 'my-template.json', + preserveLogicalIds: false +}); +``` + +------ +#### [ JavaScript ] + +``` +const template = new cfninc.CfnInclude(this, 'MyConstruct', { + templateFile: 'my-template.json', + preserveLogicalIds: false +}); +``` + +------ +#### [ Python ] + +``` +template = cfn_inc.CfnInclude(self, "Template", + template_file="my-template.json", + preserve_logical_ids=False) +``` + +------ +#### [ Java ] + +``` +CfnInclude template = CfnInclude.Builder.create(this, "Template") + .templateFile("my-template.json") + .preserveLogicalIds(false) + .build(); +``` + +------ +#### [ C\# ] + +``` +var template = new cfnInc.CfnInclude(this, "Template", new cfn_inc.CfnIncludeProps +{ + TemplateFile = "my-template.json", + PreserveLogicalIds = false +}); +``` + +------ + +To put the imported resources under the control of your AWS CDK app, add the stack to the `App` as usual\. + +------ +#### [ TypeScript ] + +``` +import * as cdk from 'aws-cdk-lib'; +import { MyStack } from '../lib/my-stack'; + +const app = new cdk.App(); +new MyStack(app, 'MyStack'); +``` + +------ +#### [ JavaScript ] + +``` +const cdk = require('aws-cdk-lib'); +const { MyStack } = require('../lib/my-stack'); + +const app = new cdk.App(); +new MyStack(app, 'MyStack'); +``` + +------ +#### [ Python ] + +``` +import aws_cdk as cdk +from mystack.my_stack import MyStack + +app = cdk.App() +MyStack(app, "MyStack") +``` + +------ +#### [ Java ] + +``` +import software.amazon.awscdk.App; + +public class MyApp { + public static void main(final String[] args) { + App app = new App(); + + new MyStack(app, "MyStack"); + } +} +``` + +------ +#### [ C\# ] + +``` +using Amazon.CDK; + +namespace CdkApp +{ + sealed class Program + { + public static void Main(string[] args) + { + var app = new App(); + new MyStack(app, "MyStack"); + } + } +} +``` + +------ + +To verify that there will be no unintended changes to the AWS resources in the stack, perform a diff, omitting the AWS CDK\-specific metadata\. + +``` +cdk diff --no-version-reporting --no-path-metadata --no-asset-metadata +``` + +When you `cdk deploy` the stack, your AWS CDK app becomes the source of truth for the stack\. Going forward, make changes to the AWS CDK app, not to the AWS CloudFormation template\. + +## Accessing imported resources + +The name `template` in the example code represents the imported AWS CloudFormation template\. To access a resource from it, use this object's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrresourcelogicalid](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrresourcelogicalid) method\. To access the returned resource as a specific kind of resource, cast the result to the desired type\. \(Casting is not necessary in Python and JavaScript\.\) + +------ +#### [ TypeScript ] + +``` +const cfnBucket = template.getResource('MyBucket') as s3.CfnBucket; +``` + +------ +#### [ JavaScript ] + +``` +const cfnBucket = template.getResource('MyBucket') as s3.CfnBucket; +``` + +------ +#### [ Python ] + +``` +cfn_bucket = template.get_resource("MyBucket") +``` + +------ +#### [ Java ] + +``` +CfnBucket cfnBucket = (CfnBucket)template.getResource("MyBucket"); +``` + +------ +#### [ C\# ] + +``` +var cfnBucket = (CfnBucket)template.GetResource("MyBucket"); +``` + +------ + +In our example, `cfnBucket` is now an instance of the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) class, a L1 construct that exactly represents the corresponding AWS CloudFormation resource\. You can treat it like any other resource of its type, for example getting its ARN by way of the `bucket.attrArn` property\. + +To wrap the L1 `CfnBucket` resource in a L2 [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) instance instead, use the static methods [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#static-fromwbrbucketwbrarnscope-id-bucketarn](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#static-fromwbrbucketwbrarnscope-id-bucketarn), [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#static-fromwbrbucketwbrattributesscope-id-attrs](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#static-fromwbrbucketwbrattributesscope-id-attrs), or [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#static-fromwbrbucketwbrnamescope-id-bucketname](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#static-fromwbrbucketwbrnamescope-id-bucketname)\. Usually the `fromBucketName()` method is the most convenient\. For example: + +------ +#### [ TypeScript ] + +``` +const bucket = s3.Bucket.fromBucketName(this, 'Bucket', cfnBucket.ref); +``` + +------ +#### [ JavaScript ] + +``` +const bucket = s3.Bucket.fromBucketName(this, 'Bucket', cfnBucket.ref); +``` + +------ +#### [ Python ] + +``` +bucket = s3.Bucket.from_bucket_name(self, "Bucket", cfn_bucket.ref) +``` + +------ +#### [ Java ] + +``` +Bucket bucket = (Bucket)Bucket.fromBucketName(this, "Bucket", cfnBucket.getRef()); +``` + +------ +#### [ C\# ] + +``` +var bucket = (Bucket)Bucket.FromBucketName(this, "Bucket", cfnBucket.Ref); +``` + +------ + +Other L2 constructs have similar methods for creating the construct from an existing resource\. + +Constructing the `Bucket` this way doesn't create a second Amazon S3 bucket; instead, the new `Bucket` instance encapsulates the existing `CfnBucket`\. + +In the example, `bucket` is now an L2 `Bucket` construct that you can use as you would one you declared yourself\. For example, if `lambdaFunc` is an AWS Lambda function, and you wish to grant it write access to the bucket, you can do so using the bucket's convenient [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrwriteidentity-objectskeypattern](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrwriteidentity-objectskeypattern) method, without needing to construct the necessary IAM policy yourself\. + +------ +#### [ TypeScript ] + +``` +bucket.grantWrite(lambdaFunc); +``` + +------ +#### [ JavaScript ] + +``` +bucket.grantWrite(lambdaFunc); +``` + +------ +#### [ Python ] + +``` +bucket.grant_write(lambda_func) +``` + +------ +#### [ Java ] + +``` +bucket.grantWrite(lambdaFunc); +``` + +------ +#### [ C\# ] + +``` +bucket.GrantWrite(lambdaFunc); +``` + +------ + +## Replacing parameters + +If your included AWS CloudFormation template has parameters, you can replace these with build\-time values when you import the template, using the `parameters` property\. In the example below, we replace the `UploadBucket` parameter with the ARN of a bucket defined elsewhere in our AWS CDK code\. + +------ +#### [ TypeScript ] + +``` +const template = new cfninc.CfnInclude(this, 'Template', { + templateFile: 'my-template.json', + parameters: { + 'UploadBucket': bucket.bucketArn, + }, +}); +``` + +------ +#### [ JavaScript ] + +``` +const template = new cfninc.CfnInclude(this, 'Template', { + templateFile: 'my-template.json', + parameters: { + 'UploadBucket': bucket.bucketArn, + }, +}); +``` + +------ +#### [ Python ] + +``` +template = cfn_inc.CfnInclude(self, "Template", + template_file="my-template.json", + parameters=dict(UploadBucket=bucket.bucket_arn) +) +``` + +------ +#### [ Java ] + +``` +CfnInclude template = CfnInclude.Builder.create(this, "Template") + .templateFile("my-template.json") + .parameters(new HashMap() {{ + put("UploadBucket", bucket.getBucketArn()); + }}) + .build(); +``` + +------ +#### [ C\# ] + +``` +var template = new cfnInc.CfnInclude(this, "Template", new cfnInc.CfnIncludeProps +{ + TemplateFile = "my-template.json", + Parameters = new Dictionary + { + { "UploadBucket", bucket.BucketArn } + } +}); +``` + +------ + +## Other template elements + +You can import any AWS CloudFormation template element, not just resources\. The imported elements become part of the AWS CDK stack\. To import these elements, use the following methods of the `CfnInclude` object\. ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrconditionconditionname](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrconditionconditionname) \- AWS CloudFormation [conditions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrhookhooklogicalid](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrhookhooklogicalid) \- AWS CloudFormation [hooks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/blue-green.html) for blue\-green deployments ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrmappingmappingname](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrmappingmappingname) \- AWS CloudFormation [mappings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbroutputlogicalid](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbroutputlogicalid) \- AWS CloudFormation [outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrparameterparametername](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrparameterparametername) \- AWS CloudFormation [parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrrulerulename](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrrulerulename) \- AWS CloudFormation [rules](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/reference-template_constraint_rules.html) for Service Catalog templates + +Each of these methods returns an instance of a class representing the specific type of AWS CloudFormation element\. These objects are mutable; changes you make to them will appear in the template generated from the AWS CDK stack\. The code below, for example, imports a parameter from the template and modifies its default\. + +------ +#### [ TypeScript ] + +``` +const param = template.getParameter('MyParameter'); +param.default = "AWS CDK" +``` + +------ +#### [ JavaScript ] + +``` +const param = template.getParameter('MyParameter'); +param.default = "AWS CDK" +``` + +------ +#### [ Python ] + +``` +param = template.get_parameter("MyParameter") +param.default = "AWS CDK" +``` + +------ +#### [ Java ] + +``` +CfnParameter param = template.getParameter("MyParameter"); +param.setDefaultValue("AWS CDK") +``` + +------ +#### [ C\# ] + +``` +var cfnBucket = (CfnBucket)template.GetResource("MyBucket"); +var param = template.GetParameter("MyParameter"); +param.Default = "AWS CDK"; +``` + +------ + +## Nested stacks + +You may import [nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html) by specifying them either when you import their main template, or at some later point\. The nested template must be stored in a local file, but referenced as a `NestedStack` resource in the main template, and the resource name used in the AWS CDK code must match the name used for the nested stack in the main template\. + +Given this resource definition in the main template, the following code shows how to import the referenced nested stack both ways\. + +``` +"NestedStack": { + "Type": "AWS::CloudFormation::Stack", + "Properties": { + "TemplateURL": "https://my-s3-template-source.s3.amazonaws.com/nested-stack.json" + } +``` + +------ +#### [ TypeScript ] + +``` +// include nested stack when importing main stack +const mainTemplate = new cfninc.CfnInclude(this, 'MainStack', { + templateFile: 'main-template.json', + loadNestedStacks: { + 'NestedStack': { + templateFile: 'nested-template.json', + }, + }, +}); + +// or add it some time after importing the main stack +const nestedTemplate = mainTemplate.loadNestedStack('NestedTemplate', { + templateFile: 'nested-template.json', +}); +``` + +------ +#### [ JavaScript ] + +``` +// include nested stack when importing main stack +const mainTemplate = new cfninc.CfnInclude(this, 'MainStack', { + templateFile: 'main-template.json', + loadNestedStacks: { + 'NestedStack': { + templateFile: 'nested-template.json', + }, + }, +}); + +// or add it some time after importing the main stack +const nestedTemplate = mainTemplate.loadNestedStack('NestedStack', { + templateFile: 'my-nested-template.json', +}); +``` + +------ +#### [ Python ] + +``` +# include nested stack when importing main stack +main_template = cfn_inc.CfnInclude(self, "MainStack", + template_file="main-template.json", + load_nested_stacks=dict(NestedStack= + cfn_inc.CfnIncludeProps(template_file="nested-template.json"))) + +# or add it some time after importing the main stack +nested_template = main_template.load_nested_stack("NestedStack", + template_file="nested-template.json") +``` + +------ +#### [ Java ] + +``` +CfnInclude mainTemplate = CfnInclude.Builder.create(this, "MainStack") + .templateFile("main-template.json") + .loadNestedStacks(new HashMap() {{ + put("NestedStack", CfnIncludeProps.builder() + .templateFile("nested-template.json").build()); + }}) + .build(); + +// or add it some time after importing the main stack +IncludedNestedStack nestedTemplate = mainTemplate.loadNestedStack("NestedTemplate", CfnIncludeProps.builder() + .templateFile("nested-template.json") + .build()); +``` + +------ +#### [ C\# ] + +``` +// include nested stack when importing main stack +var mainTemplate = new cfnInc.CfnInclude(this, "MainStack", new cfnInc.CfnIncludeProps +{ + TemplateFile = "main-template.json", + LoadNestedStacks = new Dictionary + { + { "NestedStack", new cfnInc.CfnIncludeProps { TemplateFile = "nested-template.json" } } + } +}); + +// or add it some time after importing the main stack +var nestedTemplate = mainTemplate.LoadNestedStack("NestedTemplate", new cfnInc.CfnIncludeProps { + TemplateFile = 'nested-template.json' +}); +``` + +------ + +You can import multiple nested stacks with either or both methods\. When importing the main template, you provide a mapping between the resource name of each nested stack and its template file, and this mapping can contain any number of entries\. To do it after the initial import, call `loadNestedStack()` once for each nested stack\. + +After importing a nested stack, you can access it using the main template's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrnestedwbrstacklogicalid](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrnestedwbrstacklogicalid) method\. + +------ +#### [ TypeScript ] + +``` +const nestedStack = mainTemplate.getNestedStack('NestedStack').stack; +``` + +------ +#### [ JavaScript ] + +``` +const nestedStack = mainTemplate.getNestedStack('NestedStack').stack; +``` + +------ +#### [ Python ] + +``` +nested_stack = main_template.get_nested_stack("NestedStack").stack +``` + +------ +#### [ Java ] + +``` +NestedStack nestedStack = mainTemplate.getNestedStack("NestedStack").getStack(); +``` + +------ +#### [ C\# ] + +``` +var nestedStack = mainTemplate.GetNestedStack("NestedStack").Stack; +``` + +------ + +The `getNestedStack()` method returns an [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrnestedwbrstacklogicalid](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrnestedwbrstacklogicalid) instance, from which you can access the AWS CDK [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.NestedStack.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.NestedStack.html) instance via the `stack` property \(as shown in the example\) or the original AWS CloudFormation template object via `includedTemplate`, from which you can load resources and other AWS CloudFormation elements\. \ No newline at end of file diff --git a/v2/videos.md b/v2/videos.md new file mode 100644 index 00000000..61b0dd42 --- /dev/null +++ b/v2/videos.md @@ -0,0 +1,16 @@ +# Videos + +Enjoy these videos presented by members of the AWS CDK team\. + +**Note** +Since the AWS CDK is always evolving, some of the code presented in these videos may not work quite the same way it did when the video was recorded\. This is especially true for modules that were under active development at the time\. It's also possible that we've since added a better way to achieve the same result\. Consult this Developer Guide and the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) for up\-to\-date information\. + +## Infrastructure *is* Code with the AWS CDK + +## Deep dive into AWS Cloud Development Kit \(AWS CDK\) + +## Contributing to the AWS Construct Library + +## Faster deployments with CDK Pipelines + +## How to contribute to the AWS CDK using GitPod \ No newline at end of file diff --git a/v2/vscode.md b/v2/vscode.md new file mode 100644 index 00000000..3c089740 --- /dev/null +++ b/v2/vscode.md @@ -0,0 +1,3 @@ +# AWS Toolkit for Visual Studio Code + +The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the AWS Toolkit](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. \ No newline at end of file diff --git a/v2/work-with-cdk-csharp.md b/v2/work-with-cdk-csharp.md new file mode 100644 index 00000000..dd5dbc0f --- /dev/null +++ b/v2/work-with-cdk-csharp.md @@ -0,0 +1,173 @@ +# Working with the AWS CDK in C\# + +\.NET is a fully\-supported client platform for the AWS CDK and is considered stable\. C\# is the main \.NET language for which we provide examples and support\. You can choose to write AWS CDK applications in other \.NET languages, such as Visual Basic or F\#, but AWS offers limited support for using these languages with the CDK\. + +You can develop AWS CDK applications in C\# using familiar tools including Visual Studio, Visual Studio Code, the `dotnet` command, and the NuGet package manager\. The modules comprising the AWS Construct Library are distributed via [nuget\.org](https://www.nuget.org/packages?q=amazon.cdk.aws)\. + +We suggest using [Visual Studio 2019](https://visualstudio.microsoft.com/downloads/) \(any edition\) on Windows to develop AWS CDK apps in C\#\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +C\# AWS CDK applications require \.NET Core v3\.1 or later, [available here](https://dotnet.microsoft.com/download/dotnet-core/3.1)\. + +The \.NET toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if you work mainly in Visual Studio, this command can be useful for batch operations and for installing AWS Construct Library packages\. + +## Creating a project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language csharp +``` + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +The resulting project includes a reference to the `Amazon.CDK.Lib` NuGet package\. It and its dependencies are installed automatically by NuGet\. + +## Managing AWS Construct Library modules + +The \.NET ecosystem uses the NuGet package manager\. The main CDK package, which contains the core classes and all stable service constructs, is `Amazon.CDK.Lib`\. Experimental modules, where new functionality is under active development, are named like `Amazon.CDK.AWS.SERVICE-NAME.Alpha`, where the service name is a short name without an AWS or Amazon prefix\. For example, the NuGet package name for the AWS IoT module is `Amazon.CDK.AWS.IoT.Alpha`\. If you can't find a package you want, [search Nuget\.org](https://www.nuget.org/packages?q=amazon.cdk.aws)\. + +**Note** +The [\.NET edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/dotnet/api/index.html) also shows the package names\. + +Some services' AWS Construct Library support is in more than one module\. For example, AWS IoT has a second module named `Amazon.CDK.AWS.IoT.Actions.Alpha`\. + +The AWS CDK's main module, which you'll need in most AWS CDK apps, is imported in C\# code as `Amazon.CDK`\. Modules for the various services in the AWS Construct Library live under `Amazon.CDK.AWS`\. For example, the Amazon S3 module's namespace is `Amazon.CDK.AWS.S3`\. + +We recommend writing C\# `using` directives for the CDK core constructs and for each AWS service you use in each of your C\# source files\. You may find it convenient to use an alias for a namespace or type to help resolve name conflicts\. You can always use a type's fully\-qualfiied name \(including its namespace\) without a `using` statement\. + +NuGet has four standard, mostly\-equivalent interfaces; you can use the one that suits your needs and working style\. You can also use compatible tools, such as [Paket](https://fsprojects.github.io/Paket/) or [MyGet](https://fsprojects.github.io/Paket/)\. + +### The Visual Studio NuGet GUI + +Visual Studio's NuGet tools are accessible from **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution**\. Use the **Browse** tab to find the AWS Construct Library packages you want to install\. You can choose the desired version, including pre\-release versions of your modules and add them to any of the open projects\. + +**Note** +All AWS Construct Library modules deemed "experimental" \(see [Versioning](reference.md#versioning)\) are flagged as pre\-release in NuGet and have an `alpha` name suffix\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/visual-studio-nuget.png) + +Look on the **Updates** page to install new versions of your packages\. + +### The NuGet console + +The NuGet console is a PowerShell\-based interface to NuGet that works in the context of a Visual Studio project\. You can open it in Visual Studio by choosing **Tools** > **NuGet Package Manager** > **Package Manager Console**\. For more information about using this tool, see [Install and Manage Packages with the Package Manager Console in Visual Studio](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-powershell)\. + +### The `dotnet` command + +The `dotnet` command is the primary command\-line tool for working with Visual Studio C\# projects\. You can invoke it from any Windows command prompt\. Among its many capabilities, `dotnet` can add NuGet dependencies to a Visual Studio project\. + +Assuming you're in the same directory as the Visual Studio project \(`.csproj`\) file, issue a command like the following to install a package\. Note that since the main CDK library is included when you create a project, you should ever only need to explictly install experimental modules\. Experimental modules require you to specify an explicit version number\. + +``` +dotnet add package Amazon.CDK.AWS.IoT.Alpha -v VERSION-NUMBER +``` + +You may issue the command from another directory by including the path to the project file, or to the directory that contains it, after the `add` keyword\. The following example assumes that you are in your AWS CDK project's main directory\. + +``` +dotnet add src/PROJECT-DIR package Amazon.CDK.AWS.IoT.Alpha -v VERSION-NUMBER +``` + +To install a specific version of a package, include the `-v` flag and the desired version\. + +To update a package, issue the same `dotnet add` command you used to install it\. For experimental modules, again, you must specify an explicit version number\. + +For more information about managing packages using the `dotnet` command, see [Install and Manage Packages Using the dotnet CLI](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli)\. + +### The `nuget` command + +The `nuget` command line tool can install and update NuGet packages\. However, it requires your Visual Studio project to be set up differently from the way `cdk init` sets up projects\. \(Technical details: `nuget` works with `Packages.config` projects, while `cdk init` creates a newer\-style `PackageReference` project\.\) + +We do not recommend the use of the `nuget` tool with AWS CDK projects created by `cdk init`\. If you are using another type of project, and want to use `nuget`, see the [NuGet CLI Reference](https://docs.microsoft.com/en-us/nuget/reference/nuget-exe-cli-reference)\. + +## AWS CDK idioms in C\# + +### Props + +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. + +In C\#, props are expressed using a props type\. In idiomatic C\# fashion, we can use an object initializer to set the various properties\. Here we're creating an Amazon S3 bucket using the `Bucket` construct; its corresponding props type is `BucketProps`\. + +``` +var bucket = new Bucket(this, "MyBucket", new BucketProps { + Versioned = true +}); +``` + +**Tip** +Add the package `Amazon.JSII.Analyzers` to your project to get required\-values checking in your props definitions inside Visual Studio\. + +When extending a class or overriding a method, you may want to accept additional props for your own purposes that are not understood by the parent class\. To do this, subclass the appropriate props type and add the new attributes\. + +``` +// extend BucketProps for use with MimeBucket +class MimeBucketProps : BucketProps { + public string MimeType { get; set; } +} + +// hypothetical bucket that enforces MIME type of objects inside it +class MimeBucket : Bucket { + public MimeBucket( readonly Construct scope, readonly string id, readonly MimeBucketProps props=null) : base(scope, id, props) { + // ... + } +} + +// instantiate our MyBucket class +var bucket = new MyBucket(this, "MyBucket", new MimeBucketProps { + Versioned = true, + MimeType = "image/jpeg" +}); +``` + +When calling the parent class's initializer or overridden method, you can generally pass the props you received\. The new type is compatible with its parent, and extra props you added are ignored\. + +A future release of the AWS CDK could coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues using your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion for your construct's users\. You can avoid this potential problem by naming your properties so they clearly belong to your construct\. If there are many new properties, bundle them into an appropriately\-named class and pass them as a single property\. + +### Generic structures + +In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html) method\.\) In C\#, these objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` array types in C\#\. + +### Missing values + +In C\#, missing values in AWS CDK objects such as props are represented by `null`\. The null\-conditional member access operator `?.` and the null coalescing operator `??` are convenient for working with these values\. + +``` +// mimeType is null if props is null or if props.MimeType is null +string mimeType = props?.MimeType; + +// mimeType defaults to text/plain. either props or props.MimeType can be null +string MimeType = props?.MimeType ?? "text/plain"; +``` + +## Building, synthesizing, and deploying + +The AWS CDK automatically compiles your app before running it\. However, it can be useful to build your app manually to check for errors and run tests\. You can do this by pressing F6 in Visual Studio or by issuing `dotnet build src` from the command line, where `src` is the directory in your project directory that contains the Visual Studio Solution \(`.sln`\) file\. + +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. + +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. + +``` +cdk synth "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. +``` + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file diff --git a/v2/work-with-cdk-go.md b/v2/work-with-cdk-go.md new file mode 100644 index 00000000..eb4e80a5 --- /dev/null +++ b/v2/work-with-cdk-go.md @@ -0,0 +1,123 @@ +# Working with the AWS CDK in Go + +The Go language binding for the AWS CDK is now available as a Developer Preview\. It is not suitable for production use and may undergo significant changes before being designated stable\. To follow development, see the [Project Board](https://github.com/aws/jsii/projects/3) on GitHub\. Please [report any issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. + +Unlike the other languages the CDK supports, Go is not a traditional object\-oriented programming language\. Go uses composition where other languages often leverage inheritance\. We have tried to employ idiomatic Go approaches as much as possible, but there are places where the CDK charts its own course\. + +This topic explains the ins and outs of working with the AWS CDK in Go\. See the [announcement blog post](https://aws.amazon.com/blogs/developer/getting-started-with-the-aws-cloud-development-kit-and-go/) for a walkthrough of a simple Go project for the AWS CDK\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +The Go bindings for the AWS CDK use the standard [Go toolchain](https://golang.org/dl/), v1\.16 or later\. You can use the editor of your choice\. + +## Creating a project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language go +``` + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +The resulting project includes a reference to the AWS CDK Go module, `github.com/aws/aws-cdk-go/awscdk/v2`, in `go.mod`\. The CDK and its dependencies are automatically installed when you build your app\. + +## Managing AWS Construct Library modules + +In most AWS CDK documentation and examples, the word "module" is often used to refer to AWS Construct Library modules, one or more per AWS service, which differs from idiomatic Go usage of the term\. The CDK Construct Library is provided in one Go module with the individual Construct Library modules, which support the various AWS services, provided as Go packages within that module\. + +Some services' AWS Construct Library support is in more than one Construct Library module \(Go package\)\. For example, Amazon Route 53 has three Construct Library modules in addition to the main `awsroute53` package, named `awsroute53patterns`, `awsroute53resolver`, and `awsroute53targets`\. + +The AWS CDK's core package, which you'll need in most AWS CDK apps, is imported in Go code as `github.com/aws/aws-cdk-go/awscdk/v2`\. Packages for the various services in the AWS Construct Library live under `github.com/aws/aws-cdk-go/awscdk/v2`\. For example, the Amazon S3 module's namespace is `github.com/aws/aws-cdk-go/awscdk/v2/awss3`\. + +``` +import ( + "github.com/aws/aws-cdk-go/awscdk/v2/awss3" + // ... +) +``` + +Once you have imported the Construct Library modules \(Go packages\) for the services you want to use in your app, you access constructs in that module using, for example, `awss3.Bucket`\. + +## AWS CDK idioms in Go + +### Field and method names + +Field and method names use camel casing \(`likeThis`\) in TypeScript, the CDK's language of origin\. In Go, these follow Go conventions, so are Pascal\-cased \(`LikeThis`\)\. + +### Missing values and pointer conversion + +In Go, missing values in AWS CDK objects such as property bundles are represented by `nil`\. Go doesn't have nullable types; the only type that can contain `nil` is a pointer\. To allow values to be optional, then, all CDK properties, arguments, and return values are pointers, even for primitive types\. This applies to required values as well as optional ones, so if a required value later becomes optional, no breaking change in type is needed\. + +When passing literal values or expressions, use the following helper functions to create pointers to the values\. ++ `jsii.String` ++ `jsii.Number` ++ `jsii.Bool` ++ `jsii.Time` + +For consistency, we recommend that you use pointers similarly when defining your own constructs, even though it may seem more convenient to, for example, receive your construct's `id` as a string rather than a pointer to a string\. + +When dealing with optional AWS CDK values, including primitive values as well as complex types, you should explicitly test pointers to make sure they are not `nil` before doing anything with them\. Go does not have "syntactic sugar" to help handle empty or missing values as some other languages do\. However, required values in property bundles and similar structures are guaranteed to exist \(construction fails otherwise\), so these values need not be `nil`\-checked\. + +### Constructs and Props + +Constructs, which represent one or more AWS resources and their associated attributes, are represented in Go as interfaces\. For example, `awss3.Bucket` is an interface\. Every construct has a factory function, such as `awss3.NewBucket`, to return a struct that implements the corresponding interface\. + +All factory functions take three arguments: the `scope` in which the construct is being defined \(its parent in the construct tree\), an `id`, and `props`, a bundle of key/value pairs that the construct uses to configure the resources it creates\. The "bundle of attributes" pattern is also used elsewhere in the AWS CDK\. + +In Go, props are represented by a specific struct type for each construct\. For example, an `awss3.Bucket` takes a props argument of type `awss3.BucketProps`\. Use a struct literal to write props arguments\. + +``` +var bucket = awss3.NewBucket(stack, jsii.String("MyBucket"), &awss3.BucketProps{ + Versioned: jsii.Bool(true), +}) +``` + +### Generic structures + +In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html#static-fromwbrobjectvalue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html#static-fromwbrobjectvalue) method\.\) In Go, these objects are represented as slices and an empty interface, respectively\. + +The CDK provides variadic helper functions such as `jsii.Strings` for building slices containing primitive types\. + +``` +jsii.Strings("One", "Two", "Three") +``` + +### Developing custom constructs + +In Go, it is usually more straightforward to write a new construct than to extend an existing one\. First, define a new struct type, anonymously embedding one or more existing types if extension\-like semantics are desired\. Write methods for any new functionality you're adding and the fields necessary to hold the data they need\. Define a props interface if your construct needs one\. Finally, write a factory function `NewMyConstruct()` to return an instance of your construct\. + +If you are simply changing some default values on an existing construct or adding a simple behavior at instantiation, you don't need all that plumbing\. Instead, write a factory function that calls the factory function of the construct you're "extending\." In other CDK languages, for example, you might create a `TypedBucket` construct that enforces the type of objects in an Amazon S3 bucket by overriding the `s3.Bucket` type and, in your new type's initializer, adding a bucket policy that allows only specified filename extensions to be added to the bucket\. In Go, it is easier to simply write a `NewTypedBucket` that returns an `s3.Bucket` \(instantiated using `s3.NewBucket`\) to which you have added an appropriate bucket policy\. No new construct type is necessary because the functionality is already available in the standard bucket construct; the new "construct" just provides a simpler way to configure it\. + +## Building, synthesizing, and deploying + +The AWS CDK automatically compiles your app before running it\. However, it can be useful to build your app manually to check for errors and to run tests\. You can do this by issuing `go build` at a command prompt while in your project's root directory\. + +Run any tests you've written by running `go test` at a command prompt\. + +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. + +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. + +``` +cdk synth "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. +``` + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file diff --git a/v2/work-with-cdk-java.md b/v2/work-with-cdk-java.md new file mode 100644 index 00000000..418845c3 --- /dev/null +++ b/v2/work-with-cdk-java.md @@ -0,0 +1,136 @@ +# Working with the AWS CDK in Java + +Java is a fully\-supported client platform for the AWS CDK and is considered stable\. You can develop AWS CDK applications in Java using familiar tools, including the JDK \(Oracle's, or an OpenJDK distribution such as Amazon Corretto\) and Apache Maven\. The modules comprising the AWS Construct Library are distributed via the [Maven Central Repository](https://search.maven.org/search?q=g:software.amazon.awscdk)\. + +You can use any text editor, or a Java IDE that can read Maven projects, to work on your AWS CDK apps\. We provide [Eclipse](https://www.eclipse.org/downloads/) hints in this Guide, but IntelliJ IDEA, NetBeans, and other IDEs can import Maven projects and will work fine for developing AWS CDK applications in Java\. + +It is possible to write AWS CDK applications in JVM\-hosted languages other than Java \(for example, Kotlin, Groovy, Clojure, or Scala\), but we are unable to provide support for these languages\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +Java AWS CDK applications require Java 8 \(v1\.8\) or later\. We recommend [Amazon Corretto](https://aws.amazon.com/corretto/), but you can use any OpenJDK distribution or [Oracle's JDK](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)\. You will also need [Apache Maven](https://maven.apache.org/download.cgi) 3\.5 or later\. You can also use tools such as Gradle, but the application skeletons generated by the AWS CDK Toolkit are Maven projects\. + +## Creating a project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language java +``` + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +The resulting project includes a reference to the `software.amazon.awscdk` Maven package\. It and its dependencies are automatically installed by Maven\. + +If you are using an IDE, you can now open or import the project\. In Eclipse, for example, choose **File** > **Import** > **Maven** > **Existing Maven Projects**\. Make sure that the project settings are set to use Java 8 \(1\.8\)\. + +## Managing AWS Construct Library modules + +Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk`\. Most constructs are in the artifact `aws-cdk-lib`\. Modules for services whose higher\-level CDK support is still being developed are in separate "experimental" packages, named with a short version \(no AWS or Amazon prefix\) of their service's name\. [Search the Maven Central Repository](https://search.maven.org/search?q=sg:oftware.amazon.awscdk) to find the names of all AWS CDK and AWS Construct Module libraries\. + +**Note** +The [Java edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/java/index.html) also shows the package names\. + +Some services' AWS Construct Library support is in more than one namespace\. For example, Amazon Route 53 has its functionality divided into `software.amazon.awscdk.route53`, `route53-patterns`, `route53resolver`, and `route53-targets`\. + +The main AWS CDK package is imported in Java code as `software.amazon.awscdk`\. Modules for the various services in the AWS Construct Library live under `software.amazon.awscdk.services` and are named similarly to their Maven package name\. For example, the Amazon S3 module's namespace is `software.amazon.awscdk.services.s3`\. + +We recommend writing a separate Java `import` statement for each AWS Construct Library class you use in each of your Java source files, and avoiding wildcard imports\. You can always use a type's fully\-qualified name \(including its namespace\) without an `import` statement\. + +If your application depends on an experimental package, edit your project's `pom.xml` and add a new `` element in the `` container\. For example, the following `` element specifies the CodeStar experimental construct library module: + +``` + + software.amazon.awscdk + codestar-alpha + 2.0.0-alpha.10 + +``` + +**Tip** +If you use a Java IDE, it probably has features for managing Maven dependencies\. We recommend editing `pom.xml` directly, however, unless you are absolutely sure the IDE's functionality matches what you'd do by hand\. + +## AWS CDK idioms in Java + +### Props + +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. + +In Java, props are expressed using the [Builder pattern](https://en.wikipedia.org/wiki/Builder_pattern)\. Each construct type has a corresponding props type; for example, the `Bucket` construct \(which represents an Amazon S3 bucket\) takes as its props an instance of `BucketProps`\. + +The `BucketProps` class \(like every AWS Construct Library props class\) has an inner class called `Builder`\. The `BucketProps.Builder` type offers methods to set the various properties of a `BucketProps` instance\. Each method returns the `Builder` instance, so the method calls can be chained to set multiple properties\. At the end of the chain, you call `build()` to actually produce the `BucketProps` object\. + +``` +Bucket bucket = new Bucket(this, "MyBucket", new BucketProps.Builder() + .versioned(true) + .encryption(BucketEncryption.KMS_MANAGED) + .build()); +``` + +Constructs, and other classes that take a props\-like object as their final argument, offer a shortcut\. The class has a `Builder` of its own that instantiates it and its props object in one step\. This way, you don't need to explicitly instantiate \(for example\) both `BucketProps` and a `Bucket`—and you don't need an import for the props type\. + +``` +Bucket bucket = Bucket.Builder.create(this, "MyBucket") + .versioned(true) + .encryption(BucketEncryption.KMS_MANAGED) + .build(); +``` + +When deriving your own construct from an existing construct, you may want to accept additional properties\. We recommend that you follow these builder patterns\. However, this isn't as simple as subclassing a construct class\. You must provide the moving parts of the two new `Builder` classes yourself\. You may prefer to simply have your construct accept one or more additional arguments\. You should provide additional constructors when an argument is optional\. + +### Generic structures + +In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html#static-fromwbrobjectvalue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html#static-fromwbrobjectvalue) method\.\) In Java, these objects are represented as `java.util.Map`\. In cases where the values are all strings, you can use `Map`\. It is convenient to use double braces to define `HashMap`s\. + +``` +new HashMap() {{ + put("base-directory", "dist"); + put("files", "LambdaStack.template.json"); +}}; +``` + +**Note** +The double\-brace notation \(which technically declares an anonymous inner class\) is sometimes considered an anti\-pattern\. However, its disadvantages are not very relevant to using it in CDK apps\. It is a reasonable substitute for what would be object or dictionary literals in other languages\. + +JavaScript arrays are represented as `List` or `List` in Java\. The method `java.util.Arrays.asList` is convenient for defining short `ArrayList`s\. + +``` +String[] cmds = Arrays.asList("cd lambda", "npm install", "npm install typescript") +``` + +### Missing values + +In Java, missing values in AWS CDK objects such as props are represented by `null`\. You must explicitly test any value that could be `null` to make sure it contains a value before doing anything with it\. Java does not have "syntactic sugar" to help handle null values as some other languages do\. You may find Apache ObjectUtil's [defaultIfNull](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#defaultIfNull-T-T-) and [firstNonNull](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#firstNonNull-T...-) useful in some situations\. Alternatively, write your own static helper methods to make it easier to handle potentially null values and make your code more readable\. + +## Building, synthesizing, and deploying + +The AWS CDK automatically compiles your app before running it\. However, it can be useful to build your app manually to check for errors and to run tests\. You can do this in your IDE \(for example, press Control\-B in Eclipse\) or by issuing `mvn compile` at a command prompt while in your project's root directory\. + +Run any tests you've written by running `mvn test` at a command prompt\. + +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. + +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. + +``` +cdk synth "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. +``` + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file diff --git a/v2/work-with-cdk-javascript.md b/v2/work-with-cdk-javascript.md new file mode 100644 index 00000000..434585e1 --- /dev/null +++ b/v2/work-with-cdk-javascript.md @@ -0,0 +1,288 @@ +# Working with the AWS CDK in JavaScript + +JavaScript is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in JavaScript uses familiar tools, including [Node\.js](https://nodejs.org/) and the Node Package Manager \(`npm`\)\. You may also use [Yarn](https://yarnpkg.com/) if you prefer, though the examples in this Guide use NPM\. The modules comprising the AWS Construct Library are distributed via the NPM repository, [npmjs\.org](https://www.npmjs.com/)\. + +You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://vscodium.com/)\), which has good support for JavaScript\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +JavaScript AWS CDK applications require no additional prerequisites beyond these\. + +## Creating a project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language javascript +``` + +Creating a project also installs the [ `aws-cdk-lib`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html) module and its dependencies\. + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +## Using local `cdk` + +For the most part, this guide assumes you install the CDK Toolkit globally \(`npm install -g aws-cdk`\), and the provided command examples \(such as `cdk synth`\) follow this assumption\. This approach makes it easy to keep the CDK Toolkit up to date, and since the CDK takes a strict approach to backward compatibility, there is generally little risk in always using the latest version\. + +Some teams prefer to specify all dependencies within each project, including tools like the CDK Toolkit\. This practice lets you pin such components to specific versions and ensure that all developers on your team \(and your CI/CD environment\) use exactly those versions\. This eliminates a possible source of change, helping to make builds and deployments more consistent and repeatable\. + +The CDK includes a dependency for the CDK Toolkit in the JavaScript project template's `package.json`, so if you want to use this approach, you don't need to make any changes to your project\. All you need to do is use slightly different commands for building your app and for issuing `cdk` commands\. + +| Operation | Use global CDK Toolkit | Use local CDK Toolkit | +| --- |--- |--- | +| Initialize project | `cdk init --language javascript` | `npx aws-cdk init --language javascript` | +| --- |--- |--- | +| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx aws-cdk ...` | +| --- |--- |--- | + +`npx aws-cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@1.120 --version` prints `1.120.0`\. + +**Tip** +Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. + +``` +alias cdk=npx aws-cdk +``` + +``` +doskey cdk=npx aws-cdk $* +``` + +## Managing AWS Construct Library modules + +Use the Node Package Manager \(`npm`\) to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. + +Most AWS CDK constructs are in the main CDK package, named `aws-cdk-lib`, which is a default dependency in new projects created by cdk init\. "Experimental" AWS Construct Library modules, where higher\-level constructs are still under development, are named like `aws-cdk-lib/SERVICE-NAME-alpha`\. The service name has an *aws\-* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. + +**Note** +The [CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) also shows the package names\. + +For example, the command below installs the experimental module for AWS CodeStar\. + +``` +npm install @aws-cdk/aws-codestar-alpha +``` + +Some services' Construct Library support is in more than one namespace\. For example, besides `aws-route53`, there are three additional Amazon Route 53 namespaces, `aws-route53-targets`, `aws-route53-patterns`, and `aws-route53resolver`\. + +Your project's dependencies are maintained in `package.json`\. You can edit this file to lock some or all of your dependencies to a specific version or to allow them to be updated to newer versions under certain criteria\. To update your project's NPM dependencies to the latest permitted version according to the rules you specified in `package.json`: + +``` +npm update +``` + +In JavaScript, you import modules into your code under the same name you use to install them using NPM\. We recommend the following practices when importing AWS CDK classes and AWS Construct Library modules in your applications\. Following these guidelines will help make your code consistent with other AWS CDK applications as well as easier to understand\. ++ Use `require()`, not ES6\-style `import` directives\. Older versions of Node\.js do not support ES6 imports, so using the older syntax is more widely compatible\. \(If you really want to use ES6 imports, use [esm](https://www.npmjs.com/package/esm) to ensure your project is compatible with all supported versions of Node\.js\.\) ++ Generally, import individual classes from `aws-cdk-lib`\. + + ``` + const { App, Stack } = require('aws-cdk-lib'); + ``` ++ If you need many classes from `aws-cdk-lib`, you may use a namespace alias of `cdk` instead of importing the individual classes\. Avoid doing both\. + + ``` + const cdk = require('aws-cdk-lib'); + ``` ++ Generally, import AWS Construct Libraries using short namespace aliases\. + + ``` + const { s3 } = require('aws-cdk-lib/aws-s3'); + ``` + +## AWS CDK idioms in JavaScript + +### Props + +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the AWS resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. + +Using an IDE or editor that has good JavaScript autocomplete will help avoid misspelling property names\. If a construct is expecting an `encryptionKeys` property, and you spell it `encryptionkeys`, when instantiating the construct, you haven't passed the value you intended\. This can cause an error at synthesis time if the property is required, or cause the property to be silently ignored if it is optional\. In the latter case, you may get a default behavior you intended to override\. Take special care here\. + +When subclassing an AWS Construct Library class \(or overriding a method that takes a props\-like argument\), you may want to accept additional properties for your own use\. These values will be ignored by the parent class or overridden method, because they are never accessed in that code, so you can generally pass on all the props you received\. + +A future release of the AWS CDK could coincidentally add a new property with a name you used for your own property\. Passing the value you receive up the inheritance chain can then cause unexpected behavior\. It's safer to pass a shallow copy of the props you received with your property removed or set to `undefined`\. For example: + +``` +super(scope, name, {...props, encryptionKeys: undefined}); +``` + +Alternatively, name your properties so that it is clear that they belong to your construct\. This way, it is unlikely they will collide with properties in future AWS CDK releases\. If there are many of them, use a single appropriately\-named object to hold them\. + +### Missing values + +Missing values in an object \(such as `props`\) have the value `undefined` in JavaScript\. The usual techniques apply for dealing with these\. For example, a common idiom for accessing a property of a value that may be undefined is as follows: + +``` +// a may be undefined, but if it is not, it may have an attribute b +// c is undefined if a is undefined, OR if a doesn't have an attribute b +let c = a && a.b; +``` + +However, if `a` could have some other "falsy" value besides `undefined`, it is better to make the test more explicit\. Here, we'll take advantage of the fact that `null` and `undefined` are equal to test for them both at once: + +``` +let c = a == null ? a : a.b; +``` + +**Tip** +Node\.js 14\.0 and later support new operators that can simplify the handling of undefined values\. For more information, see the [optional chaining](https://github.com/tc39/proposal-optional-chaining/blob/master/README.md) and [nullish coalescing](https://github.com/tc39/proposal-nullish-coalescing/blob/master/README.md) proposals\. + +## Synthesizing and deploying + +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. + +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. + +``` +cdk synth "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. +``` + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. + +## Using TypeScript examples with JavaScript + +[TypeScript](https://www.typescriptlang.org/) is the language we use to develop the AWS CDK, and it was the first language supported for developing applications, so many available AWS CDK code examples are written in TypeScript\. These code examples can be a good resource for JavaScript developers; you just need to remove the TypeScript\-specific parts of the code\. + +TypeScript snippets often use the newer ECMAScript `import` and `export` keywords to import objects from other modules and to declare the objects to be made available outside the current module\. Node\.js has just begun supporting these keywords in its latest releases\. Depending on the version of Node\.js you're using \(or wish to support\), you might rewrite imports and exports to use the older syntax\. + +Imports can be replaced with calls to the `require()` function\. + +------ +#### [ TypeScript ] + +``` +import * as cdk from 'aws-cdk-lib'; +import { Bucket, BucketPolicy } from 'aws-cdk-lib/aws-s3'; +``` + +------ +#### [ JavaScript ] + +``` +const cdk = require('aws-cdk-lib'); +const { Bucket, BucketPolicy } = require('aws-cdk-lib/aws-s3'); +``` + +------ + +Exports can be assigned to the `module.exports` object\. + +------ +#### [ TypeScript ] + +``` +export class Stack1 extends cdk.Stack { + // ... +} + +export class Stack2 extends cdk.Stack { + // ... +} +``` + +------ +#### [ JavaScript ] + +``` +class Stack1 extends cdk.Stack { + // ... +} + +class Stack2 extends cdk.Stack { + // ... +} + +module.exports = { Stack1, Stack2 } +``` + +------ + +**Note** +An alternative to using the old\-style imports and exports is to use the [https://www.npmjs.com/package/esm](https://www.npmjs.com/package/esm) module\. + +Once you've got the imports and exports sorted, you can dig into the actual code\. You may run into these commonly\-used TypeScript features: ++ Type annotations ++ Interface definitions ++ Type conversions/casts ++ Access modifiers + +Type annotations may be provided for variables, class members, function parameters, and function return types\. For variables, parameters, and members, types are specified by following the identifier with a colon and the type\. Function return values follow the function signature and consist of a colon and the type\. + +To convert type\-annotated code to JavaScript, remove the colon and the type\. Class members must have some value in JavaScript; set them to `undefined` if they only have a type annotation in TypeScript\. + +------ +#### [ TypeScript ] + +``` +var encrypted: boolean = true; + +class myStack extends cdk.Stack { + bucket: s3.Bucket; + // ... +} + +function makeEnv(account: string, region: string) : object { + // ... +} +``` + +------ +#### [ JavaScript ] + +``` +var encrypted = true; + +class myStack extends cdk.Stack { + bucket = undefined; + // ... +} + +function makeEnv(account, region) { + // ... +} +``` + +------ + +In TypeScript, interfaces are used to give bundles of required and optional properties, and their types, a name\. You can then use the interface name as a type annotation\. TypeScript will make sure that the object you use as, for example, an argument to a function has the required properties of the right types\. + +``` +interface myFuncProps { + code: lambda.Code, + handler?: string +} +``` + +JavaScript does not have an interface feature, so once you've removed the type annotations, delete the interface declarations entirely\. + +When a function or method returns a general\-purpose type \(such as `object`\), but you want to treat that value as a more specific child type to access properties or methods that are not part of the more general type's interface, TypeScript lets you *cast* the value using `as` followed by a type or interface name\. JavaScript doesn't support \(or need\) this, so simply remove `as` and the following identifier\. A less\-common cast syntax is to use a type name in brackets, ``; these casts, too, must be removed\. + +Finally, TypeScript supports the access modifiers `public`, `protected`, and `private` for members of classes\. All class members in JavaScript are public\. Simply remove these modifiers wherever you see them\. + +Knowing how to identify and remove these TypeScript features goes a long way toward adapting short TypeScript snippets to JavaScript\. But it may be impractical to convert longer TypeScript examples in this fashion, since they are more likely to use other TypeScript features\. For these situations, we recommend [Sucrase](https://github.com/alangpierce/sucrase)\. Sucrase won't complain if code uses an undefined variable, for example, as `tsc` would\. If it is syntactically valid, then with few exceptions, Sucrase can translate it to JavaScript\. This makes it particularly valuable for converting snippets that may not be runnable on their own\. + +## Migrating to TypeScript + +Many JavaScript developers move to [TypeScript](https://www.typescriptlang.org/) as their projects get larger and more complex\. TypeScript is a superset of JavaScript—all JavaScript code is valid TypeScript code, so no changes to your code are required—and it is also a supported AWS CDK language\. Type annotations and other TypeScript features are optional and can be added to your AWS CDK app as you find value in them\. TypeScript also gives you early access to new JavaScript features, such as optional chaining and nullish coalescing, before they're finalized—and without requiring that you upgrade Node\.js\. + +TypeScript's "shape\-based" interfaces, which define bundles of required and optional properties \(and their types\) within an object, allow common mistakes to be caught while you're writing the code, and make it easier for your IDE to provide robust autocomplete and other real\-time coding advice\. + +Coding in TypeScript does involve an additional step: compiling your app with the TypeScript compiler, `tsc`\. For typical AWS CDK apps, compilation requires a few seconds at most\. + +The easiest way to migrate an existing JavaScript AWS CDK app to TypeScript is to create a new TypeScript project using `cdk init app --language typescript`, then copy your source files \(and any other necessary files, such as assets like AWS Lambda function source code\) to the new project\. Rename your JavaScript files to end in `.ts` and begin developing in TypeScript\. \ No newline at end of file diff --git a/v2/work-with-cdk-python.md b/v2/work-with-cdk-python.md new file mode 100644 index 00000000..4e8798d0 --- /dev/null +++ b/v2/work-with-cdk-python.md @@ -0,0 +1,212 @@ +# Working with the AWS CDK in Python + +Python is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in Python uses familiar tools, including the standard Python implementation \(CPython\), virtual environments with `virtualenv`, and the Python package installer `pip`\. The modules comprising the AWS Construct Library are distributed via [pypi\.org](https://pypi.org/search/?q=aws-cdk)\. The Python version of the AWS CDK even uses Python\-style identifiers \(for example, `snake_case` method names\)\. + +You can use any editor or IDE\. Many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://vscodium.com/)\), which has good support for Python via an [official extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python)\. The IDLE editor included with Python will suffice to get started\. The Python modules for the AWS CDK do have type hints, which are useful for a linting tool or an IDE that supports type validation\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +Python AWS CDK applications require Python 3\.6 or later\. If you don't already have it installed, [download a compatible version](https://www.python.org/downloads/) for your platform at [python\.org](https://www.python.org/)\. If you run Linux, your system may have come with a compatible version, or you may install it using your distro's package manager \(`yum`, `apt`, etc\.\)\. Mac users may be interested in [Homebrew](https://brew.sh/), a Linux\-style package manager for macOS\. + +The Python package installer, `pip`, and virtual environment manager, `virtualenv`, are also required\. Windows installations of compatible Python versions include these tools\. On Linux, `pip` and `virtualenv` may be provided as separate packages in your package manager\. Alternatively, you may install them with the following commands: + +``` +python -m ensurepip --upgrade +python -m pip install --upgrade pip +python -m pip install --upgrade virtualenv +``` + +If you encounter a permission error, run the above commands with the `--user` flag so that the modules are installed in your user directory, or use `sudo` to obtain the permissions to install the modules system\-wide\. + +**Note** +It is common for Linux distros to use the executable name `python3` for Python 3\.x, and have `python` refer to a Python 2\.x installation\. Some distros have an optional package you can install that makes the `python` command refer to Python 3\. Failing that, you can adjust the command used to run your application by editing `cdk.json` in the project's main directory\. + +## Creating a project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language python +``` + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +To work with the new project, activate its virtual environment\. This allows the project's dependencies to be installed locally in the project folder, instead of globally\. + +``` +source .venv/bin/activate +``` + +**Note** +You may recognize this as the Mac/Linux command to activate a virtual environment\. The Python templates include a batch file, `source.bat`, that allows the same command to be used on Windows\. The traditional Windows command, `.venv\Scripts\activate.bat`, works, too\. +If you initialized your AWS CDK project using CDK Toolkit v1\.70\.0 or earlier, your virtual environment is in the `.env` directory instead of `.venv`\. + +**Important** +Activate the project's virtual environment whenever you start working on it\. Otherwise, you won't have access to the modules installed there, and modules you install will go in the Python global module directory \(or will result in a permission error\)\. + +After activating your virtual environment for the first time, install the app's standard dependencies: + +``` +python -m pip install -r requirements.txt +``` + +## Managing AWS Construct Library modules + +Use the Python package installer, pip, to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. pip also installs the dependencies for those modules automatically\. If your system does not recognize pip as a standalone command, invoke pip as a Python module, like this: + +``` +python -m pip PIP-COMMAND +``` + +Most AWS CDK constructs are in `aws-cdk-lib`\. Experimental modules are in separate modules named like `aws-cdk.SERVICE-NAME.alpha`\. The service name includes an *aws* prefix\. If you're unsure of a module's name, [search for it at PyPI](https://pypi.org/search/?q=aws-cdk)\. For example, the command below installs the AWS CodeStar library\. + +``` +python -m pip install aws-cdk.aws-codestar-alpha +``` + +Some services' constructs are in more than one namespace\. For example, besides `aws-cdk.aws-route53`, there are three additional Amazon Route 53 namespaces, named `aws-route53-targets`, `aws-route53-patterns`, and `aws-route53resolver`\. + +**Note** +The [Python edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/python/index.html) also shows the package names\. + +The names used for importing AWS Construct Library modules into your Python code look like the following\. + +``` +import aws_cdk.aws_s3 as s3 +import aws_cdk.aws_lambda as lambda_ +``` + +We recommend the following practices when importing AWS CDK classes and AWS Construct Library modules in your applications\. Following these guidelines will help make your code consistent with other AWS CDK applications as well as easier to understand\. ++ Generally, import individual classes from top\-level `aws_cdk`\. + + ``` + from aws_cdk import App, Construct + ``` ++ If you need many classes from the `aws_cdk`, you may use a namespace alias of `cdk` instead of importing individual classes\. Avoid doing both\. + + ``` + import aws_cdk as cdk + ``` ++ Generally, import AWS Construct Libraries using short namespace aliases\. + + ``` + import aws_cdk.aws_s3 as s3 + ``` + +After installing a module, update your project's `requirements.txt` file, which lists your project's dependencies\. It is best to do this manually rather than using `pip freeze`\. `pip freeze` captures the current versions of all modules installed in your Python virtual environment, which can be useful when bundling up a project to be run elsewhere\. + +Usually, though, your `requirements.txt` should list only top\-level dependencies \(modules that your app depends on directly\) and not the dependencies of those libraries\. This strategy makes updating your dependencies simpler\. + +You can edit `requirements.txt` to allow upgrades; simply replace the `==` preceding a version number with `~=` to allow upgrades to a higher compatible version, or remove the version requirement entirely to specify the latest available version of the module\. + +With `requirements.txt` edited appropriately to allow upgrades, issue this command to upgrade your project's installed modules at any time: + +``` +pip install --upgrade -r requirements.txt +``` + +## AWS CDK idioms in Python + +### Language conflicts + +In Python, `lambda` is a language keyword, so you cannot use it as a name for the AWS Lambda construct library module or Lambda functions\. The Python convention for such conflicts is to use a trailing underscore, as in `lambda_`, in the variable name\. + +By convention, the second argument to AWS CDK constructs is named `id`\. When writing your own stacks and constructs, calling a parameter `id` "shadows" the Python built\-in function `id()`, which returns an object's unique identifier\. This function isn't used very often, but if you should happen to need it in your construct, rename the argument, for example `construct_id`\. + +### Arguments and properties + +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. + +*scope* and *id* should always be passed as positional arguments, not keyword arguments, because their names change if the construct accepts a property named *scope* or *id*\. + +In Python, props are expressed as keyword arguments\. If an argument contains nested data structures, these are expressed using a class which takes its own keyword arguments at instantiation\. The same pattern is applied to other method calls that take a structured argument\. + +For example, in a Amazon S3 bucket's `add_lifecycle_rule` method, the `transitions` property is a list of `Transition` instances\. + +``` +bucket.add_lifecycle_rule( + transitions=[ + Transition( + storage_class=StorageClass.GLACIER, + transition_after=Duration.days(10) + ) + ] +) +``` + +When extending a class or overriding a method, you may want to accept additional arguments for your own purposes that are not understood by the parent class\. In this case you should accept the arguments you don't care about using the `**kwargs` idiom, and use keyword\-only arguments to accept the arguments you're interested in\. When calling the parent's constructor or the overridden method, pass only the arguments it is expecting \(often just `**kwargs`\)\. Passing arguments that the parent class or method doesn't expect results in an error\. + +``` +class MyConstruct(Construct): + def __init__(self, id, *, MyProperty=42, **kwargs): + super().__init__(self, id, **kwargs) + # ... +``` + +A future release of the AWS CDK could coincidentally add a new property with a name you used for your own property\. This won't cause any technical issues for users of your construct or method \(since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value\) but it may cause confusion\. You can avoid this potential problem by naming your properties so they clearly belong to your construct\. If there are many new properties, bundle them into an appropriately\-named class and pass it as a single keyword argument\. + +### Missing values + +The AWS CDK uses `None` to represent missing or undefined values\. When working with `**kwargs`, use the dictionary's `get()` method to provide a default value if a property is not provided\. Avoid using `kwargs[...]`, as this raises `KeyError` for missing values\. + +``` +encrypted = kwargs.get("encrypted") # None if no property "encrypted" exists +encrypted = kwargs.get("encrypted", False) # specify default of False if property is missing +``` + +Some AWS CDK methods \(such as `tryGetContext()` to get a runtime context value\) may return `None`, which you will need to check explicitly\. + +### Using interfaces + +Python doesn't have an interface feature as some other languages do, though it does have [abstract base classes](https://docs.python.org/3/library/abc.html), which are similar\. \(If you're not familiar with interfaces, Wikipedia has [a good introduction](https://en.wikipedia.org/wiki/Interface_(computing)#In_object-oriented_languages)\.\) TypeScript, the language in which the AWS CDK is implemented, does provide interfaces, and constructs and other AWS CDK objects often require an object that adheres to a particular interface, rather than inheriting from a particular class\. So the AWS CDK provides its own interface feature as part of the [JSII](https://github.com/aws/jsii) layer\. + +To indicate that a class implements a particular interface, you can use the `@jsii.implements` decorator: + +``` +from aws_cdk import IAspect, IConstruct +import jsii + +@jsii.implements(IAspect) +class MyAspect(): + def visit(self, node: IConstruct) -> None: + print("Visited", node.node.path) +``` + +### Type pitfalls + +Python uses dynamic typing, where all variables may refer to a value of any type\. Parameters and return values may be annotated with types, but these are "hints" and are not enforced\. This means that in Python, it is easy to pass the incorrect type of value to a AWS CDK construct\. Instead of getting a type error during build, as you would from a statically\-typed language, you may instead get a runtime error when the JSII layer \(which translates between Python and the AWS CDK's TypeScript core\) is unable to deal with the unexpected type\. + +In our experience, the type errors Python programmers make tend to fall into these categories\. ++ Passing a single value where a construct expects a container \(Python list or dictionary\) or vice versa\. ++ Passing a value of a type associated with a layer 1 \(`CfnXxxxxx`\) construct to a L2 or L3 construct, or vice versa\. + +The AWS CDK Python modules do include type annotations, so you can use tools that support them to help with types\. If you are not using an IDE that supports these, such as [PyCharm](https://www.jetbrains.com/pycharm/), you might want to call the [MyPy](http://mypy-lang.org/) type validator as a step in your build process\. There are also runtime type checkers that can improve error messages for type\-related errors\. + +## Synthesizing and deploying + +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. + +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. + +``` +cdk synth "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. +``` + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file diff --git a/v2/work-with-cdk-typescript.md b/v2/work-with-cdk-typescript.md new file mode 100644 index 00000000..4bd62de5 --- /dev/null +++ b/v2/work-with-cdk-typescript.md @@ -0,0 +1,160 @@ +# Working with the AWS CDK in TypeScript + +TypeScript is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in TypeScript uses familiar tools, including Microsoft's TypeScript compiler \(`tsc`\), [Node\.js](https://nodejs.org/) and the Node Package Manager \(`npm`\)\. You may also use [Yarn](https://yarnpkg.com/) if you prefer, though the examples in this Guide use NPM\. The modules comprising the AWS Construct Library are distributed via the NPM repository, [npmjs\.org](https://www.npmjs.com/)\. + +You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://vscodium.com/)\), which has excellent support for TypeScript\. + +## Prerequisites + +To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. + +You also need TypeScript itself \(version 3\.8 or later\)\. If you don't already have it, you can install it using `npm`\. + +``` +npm install -g typescript +``` + +**Note** +If you get a permission error, and have administrator access on your system, try `sudo npm install -g typescript`\. + +Keep TypeScript up to date with a regular `npm update -g typescript`\. + +## Creating a project + +You create a new AWS CDK project by invoking `cdk init` in an empty directory\. + +``` +mkdir my-project +cd my-project +cdk init app --language typescript +``` + +Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html) module and its dependencies\. + +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. + +## Using local `tsc` and `cdk` + +For the most part, this guide assumes you install TypeScript and the CDK Toolkit globally \(`npm install -g typescript aws-cdk`\), and the provided command examples \(such as `cdk synth`\) follow this assumption\. This approach makes it easy to keep both components up to date, and since both take a strict approach to backward compatibility, there is generally little risk in always using the latest versions\. + +Some teams prefer to specify all dependencies within each project, including tools like the TypeScript compiler and the CDK Toolkit\. This practice lets you pin these components to specific versions and ensure that all developers on your team \(and your CI/CD environment\) use exactly those versions\. This eliminates a possible source of change, helping to make builds and deployments more consistent and repeatable\. + +The CDK includes dependencies for both TypeScript and the CDK Toolkit in the TypeScript project template's `package.json`, so if you want to use this approach, you don't need to make any changes to your project\. All you need to do is use slightly different commands for building your app and for issuing `cdk` commands\. + +| Operation | Use global tools | Use local tools | +| --- |--- |--- | +| Initialize project | `cdk init --language typescript` | `npx aws-cdk init --language typescript` | +| --- |--- |--- | +| Build | `tsc` | `npm run build` | +| --- |--- |--- | +| Run CDK Toolkit command | `cdk ...` | `npm run cdk ...` or `npx aws-cdk ...` | +| --- |--- |--- | + +`npx aws-cdk` runs the version of the CDK Toolkit installed locally in the current project, if one exists, falling back to the global installation, if any\. If no global installation exists, `npx` downloads a temporary copy of the CDK Toolkit and runs that\. You may specify an arbitrary version of the CDK Toolkit using the `@` syntax: `npx aws-cdk@2.0 --version` prints `2.0.0`\. + +**Tip** +Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. + +``` +alias cdk=npx aws-cdk +``` + +``` +doskey cdk=npx aws-cdk $* +``` + +## Managing AWS Construct Library modules + +Use the Node Package Manager \(`npm`\) to install and update AWS Construct Library modules for use by your apps, as well as other packages you need\. \(You may use `yarn` instead of `npm` if you prefer\.\) `npm` also installs the dependencies for those modules automatically\. + +Most AWS CDK constructs are in the main CDK package, named `aws-cdk-lib`, which is a default dependency in new projects created by cdk init\. "Experimental" AWS Construct Library modules, where higher\-level constructs are still under development, are named like `@aws-cdk/SERVICE-NAME-alpha`\. The service name has an *aws\-* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. + +**Note** +The [CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) also shows the package names\. + +For example, the command below installs the experimental module for AWS CodeStar\. + +``` +npm install @aws-cdk/aws-codestar-alpha +``` + +Some services' Construct Library support is in more than one namespace\. For example, besides `aws-route53`, there are three additional Amazon Route 53 namespaces, `aws-route53-targets`, `aws-route53-patterns`, and `aws-route53resolver`\. + +Your project's dependencies are maintained in `package.json`\. You can edit this file to lock some or all of your dependencies to a specific version or to allow them to be updated to newer versions under certain criteria\. To update your project's NPM dependencies to the latest permitted version according to the rules you specified in `package.json`: + +``` +npm update +``` + +In TypeScript, you import modules into your code under the same name you use to install them using NPM\. We recommend the following practices when importing AWS CDK classes and AWS Construct Library modules in your applications\. Following these guidelines will help make your code consistent with other AWS CDK applications as well as easier to understand\. ++ Use ES6\-style `import` directives, not `require()`\. ++ Generally, import individual classes from `aws-cdk-lib`\. + + ``` + import { App, Stack } from 'aws-cdk-lib'; + ``` ++ If you need many classes from `aws-cdk-lib`, you may use a namespace alias of `cdk` instead of importing the individual classes\. Avoid doing both\. + + ``` + import * as cdk from 'aws-cdk-lib'; + ``` ++ Generally, import AWS service constructs using short namespace aliases\. + + ``` + import { aws_s3 as s3 } from 'aws-cdk-lib'; + ``` + +## AWS CDK idioms in TypeScript + +### Props + +All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the AWS resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. + +In TypeScript, the shape of `props` is defined using an interface that tells you the required and optional arguments and their types\. Such an interface is defined for each kind of `props` argument, usually specific to a single construct or method\. For example, the [Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) construct \(in the `aws-cdk-lib/aws-s3 module`\) specifies a `props` argument conforming to the [BucketProps](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.BucketProps.html) interface\. + +If a property is itself an object, for example the [websiteRedirect](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.BucketProps.html#websiteredirect) property of `BucketProps`, that object will have its own interface to which its shape must conform, in this case [RedirectTarget](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.RedirectTarget.html)\. + +If you are subclassing an AWS Construct Library class \(or overriding a method that takes a props\-like argument\), you can inherit from the existing interface to create a new one that specifies any new props your code requires\. When calling the parent class or base method, generally you can pass the entire props argument you received, since any attributes provided in the object but not specified in the interface will be ignored\. + +A future release of the AWS CDK could coincidentally add a new property with a name you used for your own property\. Passing the value you receive up the inheritance chain can then cause unexpected behavior\. It's safer to pass a shallow copy of the props you received with your property removed or set to `undefined`\. For example: + +``` +super(scope, name, {...props, encryptionKeys: undefined}); +``` + +Alternatively, name your properties so that it is clear that they belong to your construct\. This way, it is unlikely they will collide with properties in future AWS CDK releases\. If there are many of them, use a single appropriately\-named object to hold them\. + +### Missing values + +Missing values in an object \(such as props\) have the value `undefined` in TypeScript\. Version 3\.7 of the language introduced operators that simplify working with these values, making it easier to specify defaults and "short\-circuit" chaining when an undefined value is reached\. For more information about these features, see the [TypeScript 3\.7 Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html), specifically the first two features, Optional Chaining and Nullish Coalescing\. + +## Building, synthesizing, and deploying + +Generally, you should be in the project's root directory when building and running your application\. + +Node\.js cannot run TypeScript directly; instead, your application is converted to JavaScript using the TypeScript compiler, `tsc`\. The resulting JavaScript code is then executed\. + +The AWS CDK automatically does this whenever it needs to run your app\. However, it can be useful to compile manually to check for errors and to run tests\. To compile your TypeScript app manually, issue `npm run build`\. You may also issue `npm run watch` to enter watch mode, in which the TypeScript compiler automatically rebuilds your app whenever you save changes to a source file\. + +The [stacks](stacks.md) defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below\. Generally, you should be in your project's main directory when you issue them\. ++ `cdk synth`: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app\. ++ `cdk deploy`: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS\. + +You can specify the names of multiple stacks to be synthesized or deployed in a single command\. If your app defines only one stack, you do not need to specify it\. + +``` +cdk synth # app defines single stack +cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed +``` + +You may also use the wildcards \* \(any number of characters\) and ? \(any single character\) to identify stacks by pattern\. When using wildcards, enclose the pattern in quotes\. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit\. + +``` +cdk synth "Stack?" # Stack1, StackA, etc. +cdk deploy "*Stack" # PipeStack, LambdaStack, etc. +``` + +**Tip** +You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. + +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file diff --git a/v2/work-with.md b/v2/work-with.md new file mode 100644 index 00000000..156e5e53 --- /dev/null +++ b/v2/work-with.md @@ -0,0 +1,118 @@ +# Working with the AWS CDK + +The AWS Cloud Development Kit \(AWS CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and \(in developer preview\) Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. + +**Note** +This Guide does not currently include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. Go support is currently in developer preview\. + +We develop the AWS CDK in TypeScript and use [JSII](https://github.com/aws/jsii) to provide a "native" experience in other supported languages\. For example, we distribute AWS Construct Library modules using your preferred language's standard repository, and you install them using the language's standard package manager\. Methods and properties are even named using your language's recommended naming patterns\. + +## AWS CDK prerequisites + +To use the AWS CDK, you need an AWS account and a corresponding access key\. If you don't have an AWS account yet, see [Create and Activate an AWS Account](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)\. To find out how to obtain an access key ID and secret access key for your AWS account, see [Understanding and Getting Your Security Credentials](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html)\. To find out how to configure your workstation so the AWS CDK uses your credentials, see [Setting Credentials in Node\.js](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html)\. + +**Tip** +If you have the [AWS CLI](https://aws.amazon.com/cli/) installed, the simplest way to set up your workstation with your AWS credentials is to open a command prompt and type: + +``` +aws configure +``` + +All AWS CDK applications require Node\.js 10\.13 or later, even if you work in Python, Java, or C\#\. You may download a compatible version at [nodejs\.org](https://nodejs.org/)\. We recommend the [active LTS version](https://nodejs.org/en/about/releases/) \(at this writing, the latest 16\.x release\)\. Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. + +After installing Node\.js, install the AWS CDK Toolkit \(the `cdk` command\): + +``` +npm install -g aws-cdk +``` + +**Note** +If you get a permission error, and have administrator access on your system, try `sudo npm install -g aws-cdk`\. + +Test the installation by issuing `cdk --version`\. + +If you get an error message at this point, try uninstalling \(`npm uninstall -g aws-cdk`\) and reinstalling\. As a last resort, delete the `node-modules` folder from the current project as well as the global `node-modules` folder\. To figure out where this folder is, issue `npm config get prefix`\. + +### Language\-specific prerequisites + +The specific language you work in also has its own prerequisites, described in the corresponding topic listed here\. ++ [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) ++ [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) ++ [Working with the AWS CDK in Python](work-with-cdk-python.md) ++ [Working with the AWS CDK in Java](work-with-cdk-java.md) ++ [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) ++ [Working with the AWS CDK in Go](work-with-cdk-go.md) + +## AWS Construct Library + +The AWS CDK includes the AWS Construct Library, a collection of constructs organized by AWS service\. The library's constructs are mainly in a single module, colloquially called `aws-cdk-lib` because that's its name in TypeScript\. The actual package name of the main CDK package varies by language\. + +------ +#### [ TypeScript ] + +| Install | `npm install aws-cdk-lib` | +| --- |--- | +| Import | `const cdk = require('aws-cdk-lib');` | +| --- |--- | + +------ +#### [ JavaScript ] + +| Install | `npm install aws-cdk-lib` | +| --- |--- | +| Import | `const cdk = require('aws-cdk-lib');` | +| --- |--- | + +------ +#### [ Python ] + +| Install | `python -m pip install aws-cdk-lib` | +| --- |--- | +| Import | `import aws_cdk as cdk` | +| --- |--- | + +------ +#### [ Java ] + +| Add to `pom.xml` | Group `software.amazon.awscdk`; artifact `aws-cdk-lib` | +| --- |--- | +| Import | `import software.amazon.awscdk.App;` \(for example\) | +| --- |--- | + +------ +#### [ C\# ] + +| Install | `dotnet add package Amazon.CDK.Lib` | +| --- |--- | +| Import | `using Amazon.CDK;` | +| --- |--- | + +------ + +**Note** +Experimental constructs are provided as separate modules\. + +The [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) provides detailed documentation of the constructs \(and other components\) in the library\. A version of the API Reference is provided for each supported programming language\. + +Each module's reference material is broken into the following sections\. ++ *Overview*: Introductory material you'll need to know to work with the service in the AWS CDK, including concepts and examples\. ++ *Constructs*: Library classes that represent one or more concrete AWS resources\. These are the "curated" \(L2\) resources or patterns \(L3 resources\) that provide a high\-level interface with sane defaults\. ++ *Classes*: Non\-construct classes that provide functionality used by constructs in the module\. ++ *Structs*: Data structures \(attribute bundles\) that define the structure of composite values such as properties \(the `props` argument of constructs\) and options\. ++ *Interfaces*: Interfaces, whose names all begin with "I", define the absolute minimum functionality for the corresponding construct or other class\. The CDK uses construct interfaces to represent AWS resources that are defined outside your AWS CDK app and imported by methods such as `Bucket.fromBucketArn()`\. ++ *Enums*: Collections of named values for use in specifying \*certain construct parameters\. Using an enumerated value allows the CDK to check these values for validity during synthesis\. ++ *CloudFormation Resources*: These L1 constructs, whose names begin with "Cfn", represent exactly the resources defined in the CloudFormation specification\. They are automatically generated from that specification with each CDK release\. Each L2 or L3 construct encapsulates one or more CloudFormation resources\. ++ *CloudFormation Property Types*: The collection of named values that define the properties for each CloudFormation Resource\. + +### Interfaces vs\. construct classes + +The AWS CDK uses interfaces in a specific way that might not be obvious even if you are familiar with interfaces as a programming concept\. + +The AWS CDK supports importing resources defined outside CDK applications using methods such as `Bucket.fromBucketArn()`\. Imported resources cannot be modified and may not have all the functionality available with resources defined in your CDK app using e\.g\. the `Bucket` class\. Interfaces, then, represent the bare minimum functionality available in the CDK for a given AWS resource type, *including imported resources\.* + +When instantiating resources in your CDK app, then, you should always use concrete classes such as `Bucket`\. When specifying the type of an argument you are accepting in one of your own constructs, use the interface type such as `IBucket` if you are prepared to deal with imported resources \(that is, you won't need to change them\)\. If you require a CDK\-defined construct, specify the most general type you can use\. + +Some interfaces are minimum versions of properties or options bundles \(shown in the AWS CDK API Reference as Structs\) that are associated with specific constructs\. For example, `IBucketProps` is the smallest set of properties required to instantiate a bucket\. Such interfaces can be useful when subclassing constructs to accept arguments that you'll pass on to your parent class\. If you require one or more additional properties, you'll want to implement or derive from this interface, or from a more specific type such as `BucketProps`\. + +**Note** +Some programming languages supported by the AWS CDK don't have an interface feature\. In these languages, interfaces are just ordinary classes\. You can identify them by their names, which follow the pattern of an initial "I" followed by the name of some other construct \(e\.g\. `IBucket`\)\. The same rules apply\. \ No newline at end of file From 67c2c9e0ff3090844a20b9c66b26ed43332c6101 Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Thu, 2 Dec 2021 10:05:44 -0800 Subject: [PATCH 472/655] add info on folders --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index d5e75146..e21b5683 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,9 @@ This is the GitHub repository for the [AWS CDK Developer Guide](https://docs.aws.amazon.com/cdk/latest/guide/home.html). You're welcome to [report issues](https://github.com/awsdocs/aws-cdk-guide/issues/new) with the documentation here or, if you have a moment, to submit a Pull Request with your suggested changes. PRs should target the main branch, not master, which has been deprecated. +* `doc_source` - contains the Markdown files for the CDK v1 Developer Guide +* `v2` - contains the Markdown files for the CDK v2 Developer Guide + Issues reported through the Feedback link at the bottom of the individual pages of the AWS CDK Developer Guide go to an internal Amazon issue tracker and may not appear here. However, we try to track most substantive AWS CDK Developer Guide work on GitHub so the community can see, comment, and contribute. From 32613b9a67f4ca39a146cefe3bb000ae7324f41f Mon Sep 17 00:00:00 2001 From: danielconnor Date: Sat, 4 Dec 2021 21:03:45 +0000 Subject: [PATCH 473/655] Fix "Migrating to AWS CDK v2" link (#366) Change the link to be `../../v2/guide/migrating-v2.html` instead of `../../v2/migrating_v2.html` --- doc_source/work-with-cdk-v2.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index 3cd592a8..021a19af 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -4,7 +4,7 @@ Version 2 of the AWS CDK, now Generally Available, provides an improved developm CDK v1 will continue to be fully supported until June 2, 2022, at which time it will enter maintenance\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 2, 2023, support will end entirely for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. -For information on migrating your apps to AWS CDK v2, see [Migrating to AWS CDK v2](../../v2/migrating_v2.html)\. +For information on migrating your apps to AWS CDK v2, see [Migrating to AWS CDK v2](../../v2/guide/migrating-v2.html)\. ## CDK Toolkit v2 compatibility From c647b9f4ad35fc937e183224da995fb3134c55bb Mon Sep 17 00:00:00 2001 From: Philipp <6516667+psperber@users.noreply.github.com> Date: Sat, 4 Dec 2021 22:04:20 +0100 Subject: [PATCH 474/655] FIx init command in migrating-v2.md (#367) --- v2/migrating-v2.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 9f67b745..585255cf 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -111,8 +111,8 @@ CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compa If you need to create both v1 and v2 CDK projects, **do not install CDK Toolkit v2 globally\.** \(Remove it if you already have it installed: `npm remove -g aws-cdk`\.\) To invoke the CDK Toolkit, use npx to run v1 or v2 of the CDK Toolkit as desired\. ``` -npx aws-cdk init@1.x app --language typescript -npx aws-cdk init@2.x app --language typescript +npx aws-cdk@1.x init app --language typescript +npx aws-cdk@2.x init app --language typescript ``` **Tip** @@ -342,4 +342,4 @@ Expected changes include but are not limited to: Unexpected changes are typically not caused by upgrading to AWS CDK v2 in itself, but are usually the result of deprecated behavior that was previously changed by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, removing feature flags, revising your code as necessary, deploying, and then upgrading to v2\. -If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. \ No newline at end of file +If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. From 9398b511122f487e208056ab37545b0bbd5c6516 Mon Sep 17 00:00:00 2001 From: "Sean W. Lawrence" Date: Sat, 4 Dec 2021 15:05:19 -0600 Subject: [PATCH 475/655] Typo in init commands (#369) --- doc_source/work-with-cdk-v2.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index 021a19af..00aeacfe 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -13,8 +13,8 @@ CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compa If you need to create both v1 and v2 CDK projects, **do not install CDK Toolkit v2 globally\.** \(Remove it if you already have it installed: `npm remove -g aws-cdk`\.\) To invoke the CDK Toolkit, use npx to run v1 or v2 of the CDK Toolkit as desired\. ``` -npx cdk init@1.x app --language typescript -npx cdk init@2.x app --language typescript +npx cdk@1.x init app --language typescript +npx cdk@2.x init app --language typescript ``` **Tip** @@ -28,4 +28,4 @@ alias cdk2=npx aws-cdk@2.x ``` doskey cdk=npx aws-cdk@1.x $* doskey cdk2=npx aws-cdk@2.x $* -``` \ No newline at end of file +``` From 602a8df15aed4899c3123704cc2c37a8d3e8597a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thiago=20P=C3=A1dua?= Date: Sat, 4 Dec 2021 21:39:23 -0300 Subject: [PATCH 476/655] fix: s3 lib import on javascript (#368) --- v2/hello_world.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v2/hello_world.md b/v2/hello_world.md index a499f711..56171a08 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -184,7 +184,7 @@ In `lib/hello-cdk-stack.js`: ``` const cdk = require('aws-cdk-lib'); -const { aws_s3 as s3 } = require('aws-cdk-lib'); +const s3 = require('aws-cdk-lib/aws-s3'); class HelloCdkStack extends cdk.Stack { constructor(scope, id, props) { @@ -533,4 +533,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) to discover constructs created by AWS and others\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? From 0e7d0d5efed4567a51f00a26ba7e53f1e3327e4c Mon Sep 17 00:00:00 2001 From: Ryan Batchelder Date: Wed, 8 Dec 2021 17:09:58 -0500 Subject: [PATCH 477/655] Add quotes to CDK alias commands on Mac/Linux (#370) --- doc_source/work-with-cdk-v2.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index 00aeacfe..a52cb157 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -21,8 +21,8 @@ npx cdk@2.x init app --language typescript Set up command line aliases so you can use cdk and cdk2 commands to invoke the desired version of the CDK Toolkit\. ``` -alias cdk=npx aws-cdk@1.x -alias cdk2=npx aws-cdk@2.x +alias cdk="npx aws-cdk@1.x" +alias cdk2="npx aws-cdk@2.x" ``` ``` From f746cbe1f5901637af37aa6664f2f3ae193fc70b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 9 Dec 2021 01:52:57 +0000 Subject: [PATCH 478/655] tweaks --- doc_source/cli.md | 2 +- doc_source/getting_started.md | 2 +- doc_source/home.md | 6 +++--- doc_source/index.md | 2 +- doc_source/resources.md | 2 +- doc_source/sam.md | 2 +- doc_source/troubleshooting.md | 2 +- doc_source/videos.md | 2 +- doc_source/work-with-cdk-javascript.md | 2 +- doc_source/work-with-cdk-typescript.md | 2 +- doc_source/work-with-cdk-v2.md | 12 ++++++------ doc_source/work-with.md | 2 +- v2/cli.md | 2 +- v2/constructs.md | 2 +- v2/getting_started.md | 2 +- v2/hello_world.md | 2 +- v2/home.md | 4 ++-- v2/index.md | 2 +- v2/migrating-v2.md | 16 ++++++++-------- v2/resources.md | 2 +- v2/sam.md | 2 +- v2/troubleshooting.md | 2 +- v2/videos.md | 2 +- v2/work-with-cdk-javascript.md | 2 +- v2/work-with-cdk-typescript.md | 2 +- v2/work-with.md | 2 +- 26 files changed, 41 insertions(+), 41 deletions(-) diff --git a/doc_source/cli.md b/doc_source/cli.md index 05e094e4..05300d2b 100644 --- a/doc_source/cli.md +++ b/doc_source/cli.md @@ -412,7 +412,7 @@ For this reason, the CDK Toolkit; allows you to disable rollback by adding `--no Use the `--hotswap` flag with `cdk deploy` to attempt to update your AWS resources directly instead of generating a AWS CloudFormation changeset and deploying it\. Deployment falls back to AWS CloudFormation deployment if hot swapping is not possible\. -Currently hot swapping supports only Lambda functions\. The `--hotswap` flag also disables rollback \(i\.e\., implies `--no-rollback`\)\. +Currently hot swapping supports Lambda functions, Step Functions state machines, and Amazon ECS container images\. The `--hotswap` flag also disables rollback \(i\.e\., implies `--no-rollback`\)\. **Important** Hot\-swapping is not recommended for production deployments\. diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 5049376f..1bda9421 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -4,7 +4,7 @@ This topic introduces you to important AWS CDK concepts and describes how to ins ## Your background -The AWS Cloud Development Kit \(AWS CDK\) lets you define your cloud infrastructure as code in one of its supported programming languages\. It is intended for moderately to highly experienced AWS users\. +The AWS Cloud Development Kit \(CDK\) lets you define your cloud infrastructure as code in one of its supported programming languages\. It is intended for moderately to highly experienced AWS users\. Ideally, you already have experience with popular AWS services, particularly [AWS Identity and Access Management](https://aws.amazon.com/iam/) \(IAM\)\. You might already have AWS credentials on your workstation for use with an AWS SDK or the AWS CLI and experience working with AWS resources programmatically\. diff --git a/doc_source/home.md b/doc_source/home.md index 72784188..0c1737ea 100644 --- a/doc_source/home.md +++ b/doc_source/home.md @@ -1,10 +1,10 @@ # What is the AWS CDK? -Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. +Welcome to the *AWS Cloud Development Kit \(CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. **Important** The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v1\. -CDK v1 will continue to be fully supported until June 2, 2022, at which time it will enter maintenance\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 2, 2023, support will end for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. +CDK v1 will continue to be fully supported until June 1, 2022, at which time it will enter maintenance\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 1, 2023, support will end for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. The AWS CDK lets you build reliable, scalable, cost\-effective applications in the cloud with the considerable expressive power of a programming language\. This approach yields many benefits, including: + Build with high\-level constructs that automatically provide sensible, secure defaults for your AWS resources, defining more infrastructure with less code\. @@ -198,7 +198,7 @@ This class produces an AWS CloudFormation [template of more than 500 lines](http + [AWS::IAM::Role](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html) + [AWS::Logs::LogGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html) -And lest we forget\.\.\. code completion within your IDE or editor\! +And let's not forget\.\.\. code completion within your IDE or editor\! ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/CodeCompletion.png) diff --git a/doc_source/index.md b/doc_source/index.md index 2cec9a4d..ee4a81d1 100644 --- a/doc_source/index.md +++ b/doc_source/index.md @@ -1,4 +1,4 @@ -# AWS Cloud Development Kit (AWS CDK) v1 Developer Guide +# AWS Cloud Development Kit (CDK) v1 Developer Guide ----- *****Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** diff --git a/doc_source/resources.md b/doc_source/resources.md index f44e0acd..540d5ae2 100644 --- a/doc_source/resources.md +++ b/doc_source/resources.md @@ -1227,7 +1227,7 @@ public CdkTestStack(Construct scope, string id, IStackProps props) : base(scope, ------ -You can also apply a removal policy directly to the underlying AWS CloudFormation resource via the `applyRemovalPolicy()` method\. This method is available on some stateful resources that do not have a `removalPolicy` property in their L2 resource's props, including AWS CloudFormation stacks, Amazon Cognito user pools, Amazon DocumentDB database instances, Amazon EC2 volumes, Amazon Elasticsearch Service domains, Amazon FSx file systems, and Amazon SQS queues\. +You can also apply a removal policy directly to the underlying AWS CloudFormation resource via the `applyRemovalPolicy()` method\. This method is available on some stateful resources that do not have a `removalPolicy` property in their L2 resource's props, including AWS CloudFormation stacks, Amazon Cognito user pools, Amazon DocumentDB database instances, Amazon EC2 volumes, Amazon OpenSearch Service domains, Amazon FSx file systems, and Amazon SQS queues\. ------ #### [ TypeScript ] diff --git a/doc_source/sam.md b/doc_source/sam.md index 0d5ac967..ac93efb2 100644 --- a/doc_source/sam.md +++ b/doc_source/sam.md @@ -3,7 +3,7 @@ This topic describes how to use the AWS SAM CLI with the AWS CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. **Note** -Full AWS CDK integration with the AWS SAM CLI is currently in public preview\. This integration allows you to locally test and build serverless application defined using the CDK\. For more information, see [AWS Cloud Development Kit \(AWS CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. +Full AWS CDK integration with the AWS SAM CLI is currently in public preview\. This integration allows you to locally test and build serverless application defined using the CDK\. For more information, see [AWS Cloud Development Kit \(CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. The instructions here apply to the current \(non\-preview\) version of the AWS SAM CLI\. 1. The first step is to create a AWS CDK application and add the Lambda package\. diff --git a/doc_source/troubleshooting.md b/doc_source/troubleshooting.md index c3856839..0d5fa3de 100644 --- a/doc_source/troubleshooting.md +++ b/doc_source/troubleshooting.md @@ -149,7 +149,7 @@ npx aws-cdk deploy MyStack `npx aws-cdk` runs the local version of the AWS CDK Toolkit if one exists, and falls back to the global version when a project doesn't have a local installation\. You may find it convenient to set up a shell alias or batch file to make sure `cdk` is always invoked this way\. For example, Linux users might add the following statement to their `.bash_profile` file\. ``` -alias cdk=npx aws-cdk +alias cdk="npx aws-cdk" ``` \([back to list](#troubleshooting_top)\) diff --git a/doc_source/videos.md b/doc_source/videos.md index f2c160f9..e986b2fc 100644 --- a/doc_source/videos.md +++ b/doc_source/videos.md @@ -7,7 +7,7 @@ Since the AWS CDK is always evolving, some of the code presented in these videos ## Infrastructure *is* Code with the AWS CDK -## Deep dive into AWS Cloud Development Kit \(AWS CDK\) +## Deep dive into AWS Cloud Development Kit \(CDK\) ## Contributing to the AWS Construct Library diff --git a/doc_source/work-with-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md index 4868cccd..13fa8db7 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/doc_source/work-with-cdk-javascript.md @@ -45,7 +45,7 @@ The CDK includes a dependency for the CDK Toolkit in the JavaScript project temp Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. ``` -alias cdk=npx aws-cdk +alias cdk="npx aws-cdk" ``` ``` diff --git a/doc_source/work-with-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md index 54fff852..371cc824 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/doc_source/work-with-cdk-typescript.md @@ -56,7 +56,7 @@ The CDK includes dependencies for both TypeScript and the CDK Toolkit in the Typ Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. ``` -alias cdk=npx aws-cdk +alias cdk="npx aws-cdk" ``` ``` diff --git a/doc_source/work-with-cdk-v2.md b/doc_source/work-with-cdk-v2.md index a52cb157..cab61f83 100644 --- a/doc_source/work-with-cdk-v2.md +++ b/doc_source/work-with-cdk-v2.md @@ -1,10 +1,10 @@ # Migrating to AWS CDK v2 -Version 2 of the AWS CDK, now Generally Available, provides an improved development experience that aims to make Infrastructure as Code \(IAC\) even simpler\. See [Migrating to AWS CDK v2](../../v2/guide/migrating-v2.html) in the CDK v1 Developer Guide to learn how to migrate to CDK v2\. +Version 2 of the AWS CDK, now Generally Available, provides an improved development experience that aims to make Infrastructure as Code \(IAC\) even simpler\. -CDK v1 will continue to be fully supported until June 2, 2022, at which time it will enter maintenance\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 2, 2023, support will end entirely for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. +CDK v1 will continue to be fully supported until June 1, 2022, at which time it will enter maintenance\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 1, 2023, support will end entirely for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. -For information on migrating your apps to AWS CDK v2, see [Migrating to AWS CDK v2](../../v2/guide/migrating-v2.html)\. +For information on migrating your apps to AWS CDK v2, see [Migrating to AWS CDK v2](../../v2/guide/migrating-v2.html) in the AWS CDK v2 Developer Guide\. ## CDK Toolkit v2 compatibility @@ -13,8 +13,8 @@ CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compa If you need to create both v1 and v2 CDK projects, **do not install CDK Toolkit v2 globally\.** \(Remove it if you already have it installed: `npm remove -g aws-cdk`\.\) To invoke the CDK Toolkit, use npx to run v1 or v2 of the CDK Toolkit as desired\. ``` -npx cdk@1.x init app --language typescript -npx cdk@2.x init app --language typescript +npx aws-cdk@1.x init app --language typescript +npx aws-cdk@2.x init app --language typescript ``` **Tip** @@ -28,4 +28,4 @@ alias cdk2="npx aws-cdk@2.x" ``` doskey cdk=npx aws-cdk@1.x $* doskey cdk2=npx aws-cdk@2.x $* -``` +``` \ No newline at end of file diff --git a/doc_source/work-with.md b/doc_source/work-with.md index bbf536e2..906b3d1d 100644 --- a/doc_source/work-with.md +++ b/doc_source/work-with.md @@ -1,6 +1,6 @@ # Working with the AWS CDK -The AWS Cloud Development Kit \(AWS CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and \(in developer preview\) Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. +The AWS Cloud Development Kit \(CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and \(in developer preview\) Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. **Note** This Guide does not currently include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. Go support is currently in developer preview\. diff --git a/v2/cli.md b/v2/cli.md index a030077a..d914e6b3 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -404,7 +404,7 @@ For this reason, the CDK Toolkit; allows you to disable rollback by adding `--no Use the `--hotswap` flag with `cdk deploy` to attempt to update your AWS resources directly instead of generating a AWS CloudFormation changeset and deploying it\. Deployment falls back to AWS CloudFormation deployment if hot swapping is not possible\. -Currently hot swapping supports only Lambda functions\. The `--hotswap` flag also disables rollback \(i\.e\., implies `--no-rollback`\)\. +Currently hot swapping supports Lambda functions, Step Functions state machines, and Amazon ECS container images\. The `--hotswap` flag also disables rollback \(i\.e\., implies `--no-rollback`\)\. **Important** Hot\-swapping is not recommended for production deployments\. diff --git a/v2/constructs.md b/v2/constructs.md index 1d0c3f2d..a937d72e 100644 --- a/v2/constructs.md +++ b/v2/constructs.md @@ -22,7 +22,7 @@ There are three different levels of constructs in this library, beginning with l The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#addwbrlifecyclewbrrulerule), which adds a lifecycle rule to the bucket\. -Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. +Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns* or L3\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. For more information about how to navigate the library and discover constructs that can help you build your apps, see the [API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html)\. diff --git a/v2/getting_started.md b/v2/getting_started.md index 1d4993ad..5adffa90 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -4,7 +4,7 @@ This topic introduces you to important AWS CDK concepts and describes how to ins ## Your background -The AWS Cloud Development Kit \(AWS CDK\) lets you define your cloud infrastructure as code in one of its supported programming languages\. It is intended for moderately to highly experienced AWS users\. +The AWS Cloud Development Kit \(CDK\) lets you define your cloud infrastructure as code in one of its supported programming languages\. It is intended for moderately to highly experienced AWS users\. Ideally, you already have experience with popular AWS services, particularly [AWS Identity and Access Management](https://aws.amazon.com/iam/) \(IAM\)\. You might already have AWS credentials on your workstation for use with an AWS SDK or the AWS CLI and experience working with AWS resources programmatically\. diff --git a/v2/hello_world.md b/v2/hello_world.md index 56171a08..6fab48db 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -533,4 +533,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) to discover constructs created by AWS and others\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/v2/home.md b/v2/home.md index a2bf6154..db15ec55 100644 --- a/v2/home.md +++ b/v2/home.md @@ -1,6 +1,6 @@ # What is the AWS CDK? -Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. +Welcome to the *AWS Cloud Development Kit \(CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. **Note** The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v2\. @@ -197,7 +197,7 @@ This class produces an AWS CloudFormation [template of more than 500 lines](http + [AWS::IAM::Role](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html) + [AWS::Logs::LogGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html) -And lest we forget\.\.\. code completion within your IDE or editor\! +And let's not forget\.\.\. code completion within your IDE or editor\! ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/CodeCompletion.png) diff --git a/v2/index.md b/v2/index.md index b8cc898d..cd077823 100644 --- a/v2/index.md +++ b/v2/index.md @@ -1,4 +1,4 @@ -# AWS Cloud Development Kit (AWS CDK) v2 Developer Guide +# AWS Cloud Development Kit (CDK) v2 Developer Guide ----- *****Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 585255cf..933f1af0 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -1,12 +1,12 @@ # Migrating to AWS CDK v2 -Version 2 of the AWS Cloud Development Kit \(AWS CDK\) is designed to make writing infrastructure as code in your preferred programming language even easier\. +Version 2 of the AWS Cloud Development Kit \(CDK\) is designed to make writing infrastructure as code in your preferred programming language even easier\. The main changes from AWS CDK v1 to CDK v2 are as follows\. + AWS CDK v2 consolidates the stable parts of the AWS Construct Library, including the core library, into a single package, `aws-cdk-lib`\. Developers no longer need to install additional packages for the individual AWS services they use\. This single\-package approach also eliminates the need to synchronize the versions of the various CDK library packages\. L1 \(CfnXXXX\) constructs, which represent the exact resources available in AWS CloudFormation, are always considered stable and so are included in `aws-cdk-lib`\. -+ Experimental modules, where we're still working with the community to develop new L2 or L3 constructs, are not included in `aws-cdk-lib`; they are instead distributed as individual packages\. Experimental packages are named with an `alpha` suffix and a semantic version number that matches the first version of the AWS Construct Library with which they are compatible, also with an `alpha` suffix\. Constructs move into `aws-cdk-lib` after being designated stable, permitting the main Construct Library to adhere to strict semantic versioning\. ++ Experimental modules, where we're still working with the community to develop new [L2 or L3 constructs](constructs.md#constructs_lib), are not included in `aws-cdk-lib`; they are instead distributed as individual packages\. Experimental packages are named with an `alpha` suffix and a semantic version number that matches the first version of the AWS Construct Library with which they are compatible, also with an `alpha` suffix\. Constructs move into `aws-cdk-lib` after being designated stable, permitting the main Construct Library to adhere to strict semantic versioning\. Stability is specified at the service level\. For example, if we begin creating one or more L2 constructs for Amazon AppFlow, which at this writing has only L1 constructs, they would first appear in a module named `@aws-cdk/aws-appflow-alpha`, then move to `aws-cdk-lib` when we feel the new constructs meet the fundamental needs of customers\. @@ -99,7 +99,7 @@ The syntax for reverting these flags in `cdk.json` is shown here\. "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": false, "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": false, "@aws-cdk/aws-rds:lowercaseDbIdentifier": false, - "@aws-cdk/core:stackRelativeExports": false, + "@aws-cdk/core:stackRelativeExports": false } } ``` @@ -119,8 +119,8 @@ npx aws-cdk@2.x init app --language typescript Set up command line aliases so you can use the cdk and cdk1 commands to invoke the desired version of the CDK Toolkit\. ``` -alias cdk1=npx aws-cdk@1.x -alias cdk=npx aws-cdk@2.x +alias cdk1="npx aws-cdk@1.x" +alias cdk="npx aws-cdk@2.x" ``` ``` @@ -136,7 +136,7 @@ Update your app's dependencies, then install the new packages\. Finally, update #### [ TypeScript ] **Applications** -For CDK apps, `package.json` as follows\. Remove dependencies on v1\-style individual stable modules and establish the lowest version of `aws-cdk-lib` you require for your application \(2\.0\.0 here\)\. +For CDK apps, update `package.json` as follows\. Remove dependencies on v1\-style individual stable modules and establish the lowest version of `aws-cdk-lib` you require for your application \(2\.0\.0 here\)\. Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` with which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. @@ -171,7 +171,7 @@ Note that `aws-cdk-lib` appears both as a peer dependency and a dev dependency\. **Note** You should perform a major version bump on your library's version number when releasing a v2\-compatible library, as this will be a breaking change for consumers of the library\. It is not possible to support both CDK v1 and v2 with a single library\. To continue to support customers who are still using v1, you could maintain the older release in parallel, or create a new package for v2\. -It's up to you how long you want to continue supporting AWS CDK v1 customers, but you could take your cue from the lifecycle of CDK v1 itself, and continue supporting v1 until AWS CDK v1 enters maintenance \(June 2, 2022\) or end\-of\-life \(June 2, 2023\)\. For full details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy) +It's up to you how long you want to continue supporting AWS CDK v1 customers, but you could take your cue from the lifecycle of CDK v1 itself, and continue supporting v1 until AWS CDK v1 enters maintenance \(June 1, 2022\) or end\-of\-life \(June 1, 2023\)\. For full details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy) **Both libraries and apps** Install the new dependencies by running `npm install` or `yarn install`\. @@ -342,4 +342,4 @@ Expected changes include but are not limited to: Unexpected changes are typically not caused by upgrading to AWS CDK v2 in itself, but are usually the result of deprecated behavior that was previously changed by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, removing feature flags, revising your code as necessary, deploying, and then upgrading to v2\. -If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. +If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. \ No newline at end of file diff --git a/v2/resources.md b/v2/resources.md index ecb5e207..519a86a2 100644 --- a/v2/resources.md +++ b/v2/resources.md @@ -1233,7 +1233,7 @@ public CdkTestStack(Construct scope, string id, IStackProps props) : base(scope, ------ -You can also apply a removal policy directly to the underlying AWS CloudFormation resource via the `applyRemovalPolicy()` method\. This method is available on some stateful resources that do not have a `removalPolicy` property in their L2 resource's props, including AWS CloudFormation stacks, Amazon Cognito user pools, Amazon DocumentDB database instances, Amazon EC2 volumes, Amazon Elasticsearch Service domains, Amazon FSx file systems, and Amazon SQS queues\. +You can also apply a removal policy directly to the underlying AWS CloudFormation resource via the `applyRemovalPolicy()` method\. This method is available on some stateful resources that do not have a `removalPolicy` property in their L2 resource's props, including AWS CloudFormation stacks, Amazon Cognito user pools, Amazon DocumentDB database instances, Amazon EC2 volumes, Amazon OpenSearch Service domains, Amazon FSx file systems, and Amazon SQS queues\. ------ #### [ TypeScript ] diff --git a/v2/sam.md b/v2/sam.md index 67eb635c..f6910462 100644 --- a/v2/sam.md +++ b/v2/sam.md @@ -3,7 +3,7 @@ This topic describes how to use the AWS SAM CLI with the AWS CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. **Note** -Full AWS CDK integration with the AWS SAM CLI is currently in public preview\. This integration allows you to locally test and build serverless application defined using the CDK\. For more information, see [AWS Cloud Development Kit \(AWS CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. +Full AWS CDK integration with the AWS SAM CLI is currently in public preview\. This integration allows you to locally test and build serverless application defined using the CDK\. For more information, see [AWS Cloud Development Kit \(CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. The instructions here apply to the current \(non\-preview\) version of the AWS SAM CLI\. 1. The first step is to create a AWS CDK application and add the Lambda package\. diff --git a/v2/troubleshooting.md b/v2/troubleshooting.md index a70b70a8..35d7dc30 100644 --- a/v2/troubleshooting.md +++ b/v2/troubleshooting.md @@ -38,7 +38,7 @@ npx aws-cdk deploy MyStack #### [ macOS/Linux ] ``` -alias cdk=npx aws-cdk +alias cdk="npx aws-cdk" ``` ------ diff --git a/v2/videos.md b/v2/videos.md index 61b0dd42..3735eda2 100644 --- a/v2/videos.md +++ b/v2/videos.md @@ -7,7 +7,7 @@ Since the AWS CDK is always evolving, some of the code presented in these videos ## Infrastructure *is* Code with the AWS CDK -## Deep dive into AWS Cloud Development Kit \(AWS CDK\) +## Deep dive into AWS Cloud Development Kit \(CDK\) ## Contributing to the AWS Construct Library diff --git a/v2/work-with-cdk-javascript.md b/v2/work-with-cdk-javascript.md index 434585e1..90bf9658 100644 --- a/v2/work-with-cdk-javascript.md +++ b/v2/work-with-cdk-javascript.md @@ -45,7 +45,7 @@ The CDK includes a dependency for the CDK Toolkit in the JavaScript project temp Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. ``` -alias cdk=npx aws-cdk +alias cdk="npx aws-cdk" ``` ``` diff --git a/v2/work-with-cdk-typescript.md b/v2/work-with-cdk-typescript.md index 4bd62de5..e61056c4 100644 --- a/v2/work-with-cdk-typescript.md +++ b/v2/work-with-cdk-typescript.md @@ -56,7 +56,7 @@ The CDK includes dependencies for both TypeScript and the CDK Toolkit in the Typ Set up an alias so you can use the `cdk` command with a local CDK Toolkit installation\. ``` -alias cdk=npx aws-cdk +alias cdk="npx aws-cdk" ``` ``` diff --git a/v2/work-with.md b/v2/work-with.md index 156e5e53..3adf6468 100644 --- a/v2/work-with.md +++ b/v2/work-with.md @@ -1,6 +1,6 @@ # Working with the AWS CDK -The AWS Cloud Development Kit \(AWS CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and \(in developer preview\) Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. +The AWS Cloud Development Kit \(CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and \(in developer preview\) Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. **Note** This Guide does not currently include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. Go support is currently in developer preview\. From 104ebfa2f890e96b7d63fa85a0fcd83f14550351 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 11 Dec 2021 00:03:14 +0000 Subject: [PATCH 479/655] typo --- v2/serverless_example.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/serverless_example.md b/v2/serverless_example.md index 4bff3769..18d957d1 100644 --- a/v2/serverless_example.md +++ b/v2/serverless_example.md @@ -209,7 +209,7 @@ File: `lib/widget_service.ts` ``` import * as cdk from "aws-cdk-lib"; -import { Construct ) from "constructs"; +import { Construct } from "constructs"; import * as apigateway from "aws-cdk-lib/aws-apigateway"; import * as lambda from "aws-cdk-lib/aws-lambda"; import * as s3 from "aws-cdk-lib/aws-s3"; From 43cfcaf430da6ce78b9b942c97f3943564e8243e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 11 Dec 2021 00:05:40 +0000 Subject: [PATCH 480/655] typo --- doc_source/getting_started.md | 2 +- v2/getting_started.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc_source/getting_started.md b/doc_source/getting_started.md index 1bda9421..8d3a92d5 100644 --- a/doc_source/getting_started.md +++ b/doc_source/getting_started.md @@ -42,7 +42,7 @@ Numerous third parties have also published constructs compatible with the AWS CD ## Supported programming languages -The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) Go support is available as a Develper Preview\. +The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) Go support is available as a Developer Preview\. To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. diff --git a/v2/getting_started.md b/v2/getting_started.md index 5adffa90..afc4f42c 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -92,7 +92,7 @@ Numerous third parties have also published constructs compatible with the AWS CD ## Supported programming languages -The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) Go support is available as a Develper Preview\. +The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) Go support is available as a Developer Preview\. To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. From 1ec14dc8a64e39683d18c71e67b0192e41c1dbcb Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 11 Dec 2021 18:13:13 +0000 Subject: [PATCH 481/655] fix import --- v2/cdk_pipeline.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index 01ffab5d..1aeb3a69 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -449,7 +449,7 @@ Create the new file `lib/my-pipeline-app-stage.ts` to hold our stage\. ``` import * as cdk from 'aws-cdk-lib'; -import Construct from constructs; +import { Construct } from "constructs"; import { MyLambdaStack } from './my-pipeline-lambda-stack'; export class MyPipelineAppStage extends cdk.Stage { From 4801c4181d5a6bec7fca2be9ee89f98622cdf801 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 21 Dec 2021 22:12:49 +0000 Subject: [PATCH 482/655] update some links for /latest/ to /v1/ migration --- v2/doc-history.md | 2 +- v2/use_cfn_template.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v2/doc-history.md b/v2/doc-history.md index 3e2a6708..bc4d93ce 100644 --- a/v2/doc-history.md +++ b/v2/doc-history.md @@ -7,4 +7,4 @@ The table below represents significant documentation milestones\. We fix errors | Change | Description | Date | | --- |--- |--- | -| [AWS CDK v2 release](#doc-history) | Version 2 of the AWS CDK Developer Guide is released\. [Document history](../../latest/guide/doc-history.html) for CDK v1\. | December 4, 2021 | \ No newline at end of file +| [AWS CDK v2 release](#doc-history) | Version 2 of the AWS CDK Developer Guide is released\. [Document history](../../v1/guide/doc-history.html) for CDK v1\. | December 4, 2021 | \ No newline at end of file diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 8a291530..0241a652 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -5,7 +5,7 @@ The [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_incl This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\. **Note** -The AWS CDK also includes [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. +AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. ## Importing an AWS CloudFormation template From cfa95492415e7e70840a3c7d963819361fcc2e16 Mon Sep 17 00:00:00 2001 From: Kevin Formsma Date: Tue, 21 Dec 2021 17:37:55 -0500 Subject: [PATCH 483/655] Fix python comments (#373) --- v2/bootstrapping.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index bb6b3530..aebb2824 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -419,11 +419,11 @@ DefaultStackSynthesizer( # ARN of the role passed to CloudFormation to execute the deployments cloud_formation_execution_role="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" - - // Name of the SSM parameter which describes the bootstrap stack version number + + # Name of the SSM parameter which describes the bootstrap stack version number bootstrap_stack_version_ssm_parameter="/cdk-bootstrap/${Qualifier}/version", - // Add a rule to every template which verifies the required bootstrap stack version + # Add a rule to every template which verifies the required bootstrap stack version generate_bootstrap_version_rule=True, ) ``` @@ -554,4 +554,4 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 6 | 1\.108\.0 | Add lookup role separate from deployment role\. | | 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | -| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | \ No newline at end of file +| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | From 841c156dfedb3f1cb9e28cd071e8e0aa055af921 Mon Sep 17 00:00:00 2001 From: Kevin Formsma Date: Tue, 21 Dec 2021 17:40:57 -0500 Subject: [PATCH 484/655] Fix minor typo in python example (#372) --- v2/bootstrapping.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index aebb2824..10c60e74 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -410,7 +410,7 @@ DefaultStackSynthesizer( deploy_role_external_id="", # ARN of the role used for file asset publishing (assumed from the deploy role) - file_sset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", + file_asset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", file_asset_publishing_external_id="", # ARN of the role used for Docker asset publishing (assumed from the deploy role) From 26bd9def5432d59a8e943ddd6db625e78d8b7db6 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 21 Dec 2021 22:49:56 +0000 Subject: [PATCH 485/655] move doc_source to v1 --- README.md | 4 +- doc_source/my_ecs_construct-stack.yaml | 516 ------------------ snippets/test-1.txt | 1 - snippets/test-2.txt | 1 - {doc_source => v1}/about_examples.md | 0 {doc_source => v1}/apps.md | 8 +- {doc_source => v1}/aspects.md | 2 +- {doc_source => v1}/assets.md | 16 +- {doc_source => v1}/best-practices.md | 12 +- {doc_source => v1}/bootstrapping.md | 8 +- {doc_source => v1}/cdk_pipeline.md | 14 +- {doc_source => v1}/cfn_layer.md | 0 {doc_source => v1}/cli.md | 2 +- {doc_source => v1}/compliance-validation.md | 0 {doc_source => v1}/constructs.md | 38 +- {doc_source => v1}/context.md | 12 +- {doc_source => v1}/core_concepts.md | 2 +- .../disaster-recovery-resiliency.md | 0 {doc_source => v1}/doc-history.md | 0 {doc_source => v1}/ecs_example.md | 2 +- {doc_source => v1}/environments.md | 2 +- {doc_source => v1}/examples.md | 0 {doc_source => v1}/featureflags.md | 0 {doc_source => v1}/get_cfn_param.md | 0 {doc_source => v1}/get_context_var.md | 0 {doc_source => v1}/get_env_var.md | 0 .../get_secrets_manager_value.md | 2 +- {doc_source => v1}/get_ssm_value.md | 4 +- {doc_source => v1}/getting_started.md | 4 +- {doc_source => v1}/hello_world.md | 4 +- {doc_source => v1}/home.md | 6 +- {doc_source => v1}/how_to_set_cw_alarm.md | 8 +- {doc_source => v1}/how_tos.md | 0 {doc_source => v1}/identifiers.md | 0 {doc_source => v1}/index.md | 0 {doc_source => v1}/infrastructure-security.md | 0 {doc_source => v1}/multiple_languages.md | 0 {doc_source => v1}/parameters.md | 4 +- {doc_source => v1}/permissions.md | 32 +- {doc_source => v1}/pgp-keys.md | 0 {doc_source => v1}/reference.md | 6 +- {doc_source => v1}/resources.md | 10 +- {doc_source => v1}/sam.md | 0 {doc_source => v1}/security-iam.md | 0 {doc_source => v1}/security.md | 0 {doc_source => v1}/serverless_example.md | 2 +- .../stack_how_to_create_multiple_stacks.md | 0 {doc_source => v1}/stacks.md | 6 +- {doc_source => v1}/tagging.md | 8 +- {doc_source => v1}/testing.md | 6 +- {doc_source => v1}/tokens.md | 14 +- {doc_source => v1}/tools.md | 0 {doc_source => v1}/troubleshooting.md | 2 +- {doc_source => v1}/use_cfn_public_registry.md | 8 +- {doc_source => v1}/use_cfn_template.md | 28 +- {doc_source => v1}/videos.md | 2 +- {doc_source => v1}/vscode.md | 0 {doc_source => v1}/work-with-cdk-csharp.md | 6 +- {doc_source => v1}/work-with-cdk-go.md | 2 +- {doc_source => v1}/work-with-cdk-java.md | 4 +- .../work-with-cdk-javascript.md | 4 +- {doc_source => v1}/work-with-cdk-python.md | 2 +- .../work-with-cdk-typescript.md | 8 +- {doc_source => v1}/work-with-cdk-v2.md | 0 {doc_source => v1}/work-with.md | 2 +- v2/bootstrapping.md | 4 +- 66 files changed, 156 insertions(+), 672 deletions(-) delete mode 100644 doc_source/my_ecs_construct-stack.yaml delete mode 100644 snippets/test-1.txt delete mode 100644 snippets/test-2.txt rename {doc_source => v1}/about_examples.md (100%) rename {doc_source => v1}/apps.md (94%) rename {doc_source => v1}/aspects.md (95%) rename {doc_source => v1}/assets.md (90%) rename {doc_source => v1}/best-practices.md (95%) rename {doc_source => v1}/bootstrapping.md (98%) rename {doc_source => v1}/cdk_pipeline.md (95%) rename {doc_source => v1}/cfn_layer.md (100%) rename {doc_source => v1}/cli.md (98%) rename {doc_source => v1}/compliance-validation.md (100%) rename {doc_source => v1}/constructs.md (88%) rename {doc_source => v1}/context.md (94%) rename {doc_source => v1}/core_concepts.md (65%) rename {doc_source => v1}/disaster-recovery-resiliency.md (100%) rename {doc_source => v1}/doc-history.md (100%) rename {doc_source => v1}/ecs_example.md (99%) rename {doc_source => v1}/environments.md (97%) rename {doc_source => v1}/examples.md (100%) rename {doc_source => v1}/featureflags.md (100%) rename {doc_source => v1}/get_cfn_param.md (100%) rename {doc_source => v1}/get_context_var.md (100%) rename {doc_source => v1}/get_env_var.md (100%) rename {doc_source => v1}/get_secrets_manager_value.md (93%) rename {doc_source => v1}/get_ssm_value.md (86%) rename {doc_source => v1}/getting_started.md (98%) rename {doc_source => v1}/hello_world.md (99%) rename {doc_source => v1}/home.md (98%) rename {doc_source => v1}/how_to_set_cw_alarm.md (83%) rename {doc_source => v1}/how_tos.md (100%) rename {doc_source => v1}/identifiers.md (100%) rename {doc_source => v1}/index.md (100%) rename {doc_source => v1}/infrastructure-security.md (100%) rename {doc_source => v1}/multiple_languages.md (100%) rename {doc_source => v1}/parameters.md (89%) rename {doc_source => v1}/permissions.md (78%) rename {doc_source => v1}/pgp-keys.md (100%) rename {doc_source => v1}/reference.md (93%) rename {doc_source => v1}/resources.md (97%) rename {doc_source => v1}/sam.md (100%) rename {doc_source => v1}/security-iam.md (100%) rename {doc_source => v1}/security.md (100%) rename {doc_source => v1}/serverless_example.md (98%) rename {doc_source => v1}/stack_how_to_create_multiple_stacks.md (100%) rename {doc_source => v1}/stacks.md (94%) rename {doc_source => v1}/tagging.md (90%) rename {doc_source => v1}/testing.md (98%) rename {doc_source => v1}/tokens.md (86%) rename {doc_source => v1}/tools.md (100%) rename {doc_source => v1}/troubleshooting.md (98%) rename {doc_source => v1}/use_cfn_public_registry.md (87%) rename {doc_source => v1}/use_cfn_template.md (69%) rename {doc_source => v1}/videos.md (89%) rename {doc_source => v1}/vscode.md (100%) rename {doc_source => v1}/work-with-cdk-csharp.md (94%) rename {doc_source => v1}/work-with-cdk-go.md (96%) rename {doc_source => v1}/work-with-cdk-java.md (95%) rename {doc_source => v1}/work-with-cdk-javascript.md (98%) rename {doc_source => v1}/work-with-cdk-python.md (99%) rename {doc_source => v1}/work-with-cdk-typescript.md (92%) rename {doc_source => v1}/work-with-cdk-v2.md (100%) rename {doc_source => v1}/work-with.md (96%) diff --git a/README.md b/README.md index e21b5683..d7cc26b2 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,11 @@ This is the GitHub repository for the [AWS CDK Developer Guide](https://docs.aws.amazon.com/cdk/latest/guide/home.html). You're welcome to [report issues](https://github.com/awsdocs/aws-cdk-guide/issues/new) with the documentation here or, if you have a moment, to submit a Pull Request with your suggested changes. PRs should target the main branch, not master, which has been deprecated. -* `doc_source` - contains the Markdown files for the CDK v1 Developer Guide +* `v1` - contains the Markdown files for the CDK v1 Developer Guide * `v2` - contains the Markdown files for the CDK v2 Developer Guide +Feel free to make a Pull Request against only one of these content sets (we'll make sure it gets into both). + Issues reported through the Feedback link at the bottom of the individual pages of the AWS CDK Developer Guide go to an internal Amazon issue tracker and may not appear here. However, we try to track most substantive AWS CDK Developer Guide work on GitHub so the community can see, comment, and contribute. diff --git a/doc_source/my_ecs_construct-stack.yaml b/doc_source/my_ecs_construct-stack.yaml deleted file mode 100644 index 5dd8b29d..00000000 --- a/doc_source/my_ecs_construct-stack.yaml +++ /dev/null @@ -1,516 +0,0 @@ -Resources: - MyVpcF9F0CA6F: - Type: AWS::EC2::VPC - Properties: - CidrBlock: 10.0.0.0/16 - EnableDnsHostnames: true - EnableDnsSupport: true - InstanceTenancy: default - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/Resource - MyVpcPublicSubnet1SubnetF6608456: - Type: AWS::EC2::Subnet - Properties: - CidrBlock: 10.0.0.0/18 - VpcId: - Ref: MyVpcF9F0CA6F - AvailabilityZone: - Fn::Select: - - 0 - - Fn::GetAZs: "" - MapPublicIpOnLaunch: true - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PublicSubnet1 - - Key: aws-cdk:subnet-name - Value: Public - - Key: aws-cdk:subnet-type - Value: Public - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/Subnet - MyVpcPublicSubnet1RouteTableC46AB2F4: - Type: AWS::EC2::RouteTable - Properties: - VpcId: - Ref: MyVpcF9F0CA6F - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PublicSubnet1 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/RouteTable - MyVpcPublicSubnet1RouteTableAssociation2ECEE1CB: - Type: AWS::EC2::SubnetRouteTableAssociation - Properties: - RouteTableId: - Ref: MyVpcPublicSubnet1RouteTableC46AB2F4 - SubnetId: - Ref: MyVpcPublicSubnet1SubnetF6608456 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/RouteTableAssociation - MyVpcPublicSubnet1DefaultRoute95FDF9EB: - Type: AWS::EC2::Route - Properties: - RouteTableId: - Ref: MyVpcPublicSubnet1RouteTableC46AB2F4 - DestinationCidrBlock: 0.0.0.0/0 - GatewayId: - Ref: MyVpcIGW5C4A4F63 - DependsOn: - - MyVpcVPCGW488ACE0D - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/DefaultRoute - MyVpcPublicSubnet1EIP096967CB: - Type: AWS::EC2::EIP - Properties: - Domain: vpc - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/EIP - MyVpcPublicSubnet1NATGatewayAD3400C1: - Type: AWS::EC2::NatGateway - Properties: - AllocationId: - Fn::GetAtt: - - MyVpcPublicSubnet1EIP096967CB - - AllocationId - SubnetId: - Ref: MyVpcPublicSubnet1SubnetF6608456 - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PublicSubnet1 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/NATGateway - MyVpcPublicSubnet2Subnet492B6BFB: - Type: AWS::EC2::Subnet - Properties: - CidrBlock: 10.0.64.0/18 - VpcId: - Ref: MyVpcF9F0CA6F - AvailabilityZone: - Fn::Select: - - 1 - - Fn::GetAZs: "" - MapPublicIpOnLaunch: true - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PublicSubnet2 - - Key: aws-cdk:subnet-name - Value: Public - - Key: aws-cdk:subnet-type - Value: Public - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/Subnet - MyVpcPublicSubnet2RouteTable1DF17386: - Type: AWS::EC2::RouteTable - Properties: - VpcId: - Ref: MyVpcF9F0CA6F - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PublicSubnet2 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/RouteTable - MyVpcPublicSubnet2RouteTableAssociation227DE78D: - Type: AWS::EC2::SubnetRouteTableAssociation - Properties: - RouteTableId: - Ref: MyVpcPublicSubnet2RouteTable1DF17386 - SubnetId: - Ref: MyVpcPublicSubnet2Subnet492B6BFB - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/RouteTableAssociation - MyVpcPublicSubnet2DefaultRoute052936F6: - Type: AWS::EC2::Route - Properties: - RouteTableId: - Ref: MyVpcPublicSubnet2RouteTable1DF17386 - DestinationCidrBlock: 0.0.0.0/0 - GatewayId: - Ref: MyVpcIGW5C4A4F63 - DependsOn: - - MyVpcVPCGW488ACE0D - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/DefaultRoute - MyVpcPublicSubnet2EIP8CCBA239: - Type: AWS::EC2::EIP - Properties: - Domain: vpc - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/EIP - MyVpcPublicSubnet2NATGateway91BFBEC9: - Type: AWS::EC2::NatGateway - Properties: - AllocationId: - Fn::GetAtt: - - MyVpcPublicSubnet2EIP8CCBA239 - - AllocationId - SubnetId: - Ref: MyVpcPublicSubnet2Subnet492B6BFB - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PublicSubnet2 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/NATGateway - MyVpcPrivateSubnet1Subnet5057CF7E: - Type: AWS::EC2::Subnet - Properties: - CidrBlock: 10.0.128.0/18 - VpcId: - Ref: MyVpcF9F0CA6F - AvailabilityZone: - Fn::Select: - - 0 - - Fn::GetAZs: "" - MapPublicIpOnLaunch: false - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PrivateSubnet1 - - Key: aws-cdk:subnet-name - Value: Private - - Key: aws-cdk:subnet-type - Value: Private - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/Subnet - MyVpcPrivateSubnet1RouteTable8819E6E2: - Type: AWS::EC2::RouteTable - Properties: - VpcId: - Ref: MyVpcF9F0CA6F - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PrivateSubnet1 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/RouteTable - MyVpcPrivateSubnet1RouteTableAssociation56D38C7E: - Type: AWS::EC2::SubnetRouteTableAssociation - Properties: - RouteTableId: - Ref: MyVpcPrivateSubnet1RouteTable8819E6E2 - SubnetId: - Ref: MyVpcPrivateSubnet1Subnet5057CF7E - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/RouteTableAssociation - MyVpcPrivateSubnet1DefaultRouteA8CDE2FA: - Type: AWS::EC2::Route - Properties: - RouteTableId: - Ref: MyVpcPrivateSubnet1RouteTable8819E6E2 - DestinationCidrBlock: 0.0.0.0/0 - NatGatewayId: - Ref: MyVpcPublicSubnet1NATGatewayAD3400C1 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/DefaultRoute - MyVpcPrivateSubnet2Subnet0040C983: - Type: AWS::EC2::Subnet - Properties: - CidrBlock: 10.0.192.0/18 - VpcId: - Ref: MyVpcF9F0CA6F - AvailabilityZone: - Fn::Select: - - 1 - - Fn::GetAZs: "" - MapPublicIpOnLaunch: false - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PrivateSubnet2 - - Key: aws-cdk:subnet-name - Value: Private - - Key: aws-cdk:subnet-type - Value: Private - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/Subnet - MyVpcPrivateSubnet2RouteTableCEDCEECE: - Type: AWS::EC2::RouteTable - Properties: - VpcId: - Ref: MyVpcF9F0CA6F - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc/PrivateSubnet2 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/RouteTable - MyVpcPrivateSubnet2RouteTableAssociation86A610DA: - Type: AWS::EC2::SubnetRouteTableAssociation - Properties: - RouteTableId: - Ref: MyVpcPrivateSubnet2RouteTableCEDCEECE - SubnetId: - Ref: MyVpcPrivateSubnet2Subnet0040C983 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/RouteTableAssociation - MyVpcPrivateSubnet2DefaultRoute9CE96294: - Type: AWS::EC2::Route - Properties: - RouteTableId: - Ref: MyVpcPrivateSubnet2RouteTableCEDCEECE - DestinationCidrBlock: 0.0.0.0/0 - NatGatewayId: - Ref: MyVpcPublicSubnet2NATGateway91BFBEC9 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/DefaultRoute - MyVpcIGW5C4A4F63: - Type: AWS::EC2::InternetGateway - Properties: - Tags: - - Key: Name - Value: MyEcsConstruct/MyVpc - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/IGW - MyVpcVPCGW488ACE0D: - Type: AWS::EC2::VPCGatewayAttachment - Properties: - VpcId: - Ref: MyVpcF9F0CA6F - InternetGatewayId: - Ref: MyVpcIGW5C4A4F63 - Metadata: - aws:cdk:path: MyEcsConstruct/MyVpc/VPCGW - MyCluster4C1BA579: - Type: AWS::ECS::Cluster - Metadata: - aws:cdk:path: MyEcsConstruct/MyCluster/Resource - MyFargateServiceLBDE830E97: - Type: AWS::ElasticLoadBalancingV2::LoadBalancer - Properties: - LoadBalancerAttributes: [] - Scheme: internet-facing - SecurityGroups: - - Fn::GetAtt: - - MyFargateServiceLBSecurityGroup6FBF16F1 - - GroupId - Subnets: - - Ref: MyVpcPublicSubnet1SubnetF6608456 - - Ref: MyVpcPublicSubnet2Subnet492B6BFB - Type: application - DependsOn: - - MyVpcPublicSubnet1DefaultRoute95FDF9EB - - MyVpcPublicSubnet2DefaultRoute052936F6 - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/LB/Resource - MyFargateServiceLBSecurityGroup6FBF16F1: - Type: AWS::EC2::SecurityGroup - Properties: - GroupDescription: Automatically created Security Group for ELB MyEcsConstructMyFargateServiceLB5E4E9AE3 - SecurityGroupEgress: [] - SecurityGroupIngress: - - CidrIp: 0.0.0.0/0 - Description: Allow from anyone on port 80 - FromPort: 80 - IpProtocol: tcp - ToPort: 80 - VpcId: - Ref: MyVpcF9F0CA6F - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/LB/SecurityGroup/Resource - MyFargateServiceLBSecurityGrouptoMyEcsConstructMyFargateServiceSecurityGroup67F71DB380B308A4F1: - Type: AWS::EC2::SecurityGroupEgress - Properties: - GroupId: - Fn::GetAtt: - - MyFargateServiceLBSecurityGroup6FBF16F1 - - GroupId - IpProtocol: tcp - Description: Load balancer to target - DestinationSecurityGroupId: - Fn::GetAtt: - - MyFargateServiceSecurityGroup7016792A - - GroupId - FromPort: 80 - ToPort: 80 - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/LB/SecurityGroup/to MyEcsConstructMyFargateServiceSecurityGroup67F71DB3:80 - MyFargateServiceLBPublicListener61A1042F: - Type: AWS::ElasticLoadBalancingV2::Listener - Properties: - DefaultActions: - - TargetGroupArn: - Ref: MyFargateServiceLBPublicListenerECSGroup4A3EDF05 - Type: forward - LoadBalancerArn: - Ref: MyFargateServiceLBDE830E97 - Port: 80 - Protocol: HTTP - Certificates: [] - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/LB/PublicListener/Resource - MyFargateServiceLBPublicListenerECSGroup4A3EDF05: - Type: AWS::ElasticLoadBalancingV2::TargetGroup - Properties: - Port: 80 - Protocol: HTTP - TargetGroupAttributes: [] - Targets: [] - TargetType: ip - VpcId: - Ref: MyVpcF9F0CA6F - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/LB/PublicListener/ECSGroup/Resource - MyFargateServiceTaskDefTaskRole62C7D397: - Type: AWS::IAM::Role - Properties: - AssumeRolePolicyDocument: - Statement: - - Action: sts:AssumeRole - Effect: Allow - Principal: - Service: - Fn::Join: - - "" - - - ecs-tasks. - - Ref: AWS::URLSuffix - Version: "2012-10-17" - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/TaskRole/Resource - MyFargateServiceTaskDef5DA17B39: - Type: AWS::ECS::TaskDefinition - Properties: - ContainerDefinitions: - - Essential: true - Image: amazon/amazon-ecs-sample - Links: [] - LogConfiguration: - LogDriver: awslogs - Options: - awslogs-group: - Ref: MyFargateServiceTaskDefwebLogGroup4A6C44E8 - awslogs-stream-prefix: MyFargateService - awslogs-region: - Ref: AWS::Region - MountPoints: [] - Name: web - PortMappings: - - ContainerPort: 80 - Protocol: tcp - Ulimits: [] - VolumesFrom: [] - Cpu: "512" - ExecutionRoleArn: - Fn::GetAtt: - - MyFargateServiceTaskDefExecutionRoleD6305504 - - Arn - Family: MyEcsConstructMyFargateServiceTaskDef164AB9B9 - Memory: "2048" - NetworkMode: awsvpc - RequiresCompatibilities: - - FARGATE - TaskRoleArn: - Fn::GetAtt: - - MyFargateServiceTaskDefTaskRole62C7D397 - - Arn - Volumes: [] - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/Resource - MyFargateServiceTaskDefwebLogGroup4A6C44E8: - Type: AWS::Logs::LogGroup - DeletionPolicy: Retain - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/web/LogGroup/Resource - MyFargateServiceTaskDefExecutionRoleD6305504: - Type: AWS::IAM::Role - Properties: - AssumeRolePolicyDocument: - Statement: - - Action: sts:AssumeRole - Effect: Allow - Principal: - Service: - Fn::Join: - - "" - - - ecs-tasks. - - Ref: AWS::URLSuffix - Version: "2012-10-17" - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/ExecutionRole/Resource - MyFargateServiceTaskDefExecutionRoleDefaultPolicyEC22B20F: - Type: AWS::IAM::Policy - Properties: - PolicyDocument: - Statement: - - Action: - - logs:CreateLogStream - - logs:PutLogEvents - Effect: Allow - Resource: - Fn::GetAtt: - - MyFargateServiceTaskDefwebLogGroup4A6C44E8 - - Arn - Version: "2012-10-17" - PolicyName: MyFargateServiceTaskDefExecutionRoleDefaultPolicyEC22B20F - Roles: - - Ref: MyFargateServiceTaskDefExecutionRoleD6305504 - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/ExecutionRole/DefaultPolicy/Resource - MyFargateServiceF490C034: - Type: AWS::ECS::Service - Properties: - TaskDefinition: - Ref: MyFargateServiceTaskDef5DA17B39 - Cluster: - Ref: MyCluster4C1BA579 - DeploymentConfiguration: - MaximumPercent: 200 - MinimumHealthyPercent: 50 - DesiredCount: 6 - HealthCheckGracePeriodSeconds: 60 - LaunchType: FARGATE - LoadBalancers: - - ContainerName: web - ContainerPort: 80 - TargetGroupArn: - Ref: MyFargateServiceLBPublicListenerECSGroup4A3EDF05 - NetworkConfiguration: - AwsvpcConfiguration: - AssignPublicIp: DISABLED - SecurityGroups: - - Fn::GetAtt: - - MyFargateServiceSecurityGroup7016792A - - GroupId - Subnets: - - Ref: MyVpcPrivateSubnet1Subnet5057CF7E - - Ref: MyVpcPrivateSubnet2Subnet0040C983 - ServiceRegistries: [] - DependsOn: - - MyFargateServiceLBPublicListenerECSGroup4A3EDF05 - - MyFargateServiceLBPublicListener61A1042F - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/Service/Service - MyFargateServiceSecurityGroup7016792A: - Type: AWS::EC2::SecurityGroup - Properties: - GroupDescription: MyEcsConstruct/MyFargateService/Service/SecurityGroup - SecurityGroupEgress: - - CidrIp: 0.0.0.0/0 - Description: Allow all outbound traffic by default - IpProtocol: "-1" - SecurityGroupIngress: [] - VpcId: - Ref: MyVpcF9F0CA6F - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/Service/SecurityGroup/Resource - MyFargateServiceSecurityGroupfromMyEcsConstructMyFargateServiceLBSecurityGroup8793A2F780B3ABD3C6: - Type: AWS::EC2::SecurityGroupIngress - Properties: - IpProtocol: tcp - Description: Load balancer to target - FromPort: 80 - GroupId: - Fn::GetAtt: - - MyFargateServiceSecurityGroup7016792A - - GroupId - SourceSecurityGroupId: - Fn::GetAtt: - - MyFargateServiceLBSecurityGroup6FBF16F1 - - GroupId - ToPort: 80 - Metadata: - aws:cdk:path: MyEcsConstruct/MyFargateService/Service/SecurityGroup/from MyEcsConstructMyFargateServiceLBSecurityGroup8793A2F7:80 -Outputs: - MyFargateServiceLoadBalancerDNS704F6391: - Value: - Fn::GetAtt: - - MyFargateServiceLBDE830E97 - - DNSName - diff --git a/snippets/test-1.txt b/snippets/test-1.txt deleted file mode 100644 index ae6fc483..00000000 --- a/snippets/test-1.txt +++ /dev/null @@ -1 +0,0 @@ -// this is a test code snippet diff --git a/snippets/test-2.txt b/snippets/test-2.txt deleted file mode 100644 index ae6fc483..00000000 --- a/snippets/test-2.txt +++ /dev/null @@ -1 +0,0 @@ -// this is a test code snippet diff --git a/doc_source/about_examples.md b/v1/about_examples.md similarity index 100% rename from doc_source/about_examples.md rename to v1/about_examples.md diff --git a/doc_source/apps.md b/v1/apps.md similarity index 94% rename from doc_source/apps.md rename to v1/apps.md index 4e7db550..1beffaac 100644 --- a/doc_source/apps.md +++ b/v1/apps.md @@ -1,6 +1,6 @@ # Apps -As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/docs/core/stack.html) construct\. +As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/v1/docs/core/stack.html) construct\. The following example declares a stack class named `MyFirstStack` that includes a single Amazon S3 bucket\. However, this only declares a stack\. You still need to define \(also known as to instantiate\) it in some scope to deploy it\. @@ -76,7 +76,7 @@ public class MyFirstStack : Stack ## The app construct -To define the previous stack within the scope of an application, use the [App](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.App.html) construct\. The following example app instantiates a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. +To define the previous stack within the scope of an application, use the [App](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.App.html) construct\. The following example app instantiates a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. ------ #### [ TypeScript ] @@ -221,7 +221,7 @@ These two methods are equivalent\. The following diagram shows the phases that the AWS CDK goes through when you call the cdk deploy\. This command deploys the resources that your app defines\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/Lifecycle.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v1/guide/images/Lifecycle.png) An AWS CDK app goes through the following phases in its lifecycle\. @@ -241,7 +241,7 @@ This is the final stage of the execution of your AWS CDK app\. It's triggered by In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: -+ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1/typescript/custom-resource/) example\. ++ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1/typescript/custom-resource/) example\. + The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)` \(Python: `is_token`\)\. See [Tokens](tokens.md) for details\. ## Cloud assemblies diff --git a/doc_source/aspects.md b/v1/aspects.md similarity index 95% rename from doc_source/aspects.md rename to v1/aspects.md index e7ef209d..074004be 100644 --- a/doc_source/aspects.md +++ b/v1/aspects.md @@ -2,7 +2,7 @@ Aspects are a way to apply an operation to all constructs in a given scope\. The aspect could modify the constructs, such as by adding tags, or it could verify something about the state of the constructs, such as ensuring that all buckets are encrypted\. -To apply an aspect to a construct and all constructs in the same scope, call [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Aspects.html#static-ofscope](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Aspects.html#static-ofscope)`.of(SCOPE).add()` with a new aspect, as shown in the following example\. +To apply an aspect to a construct and all constructs in the same scope, call [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Aspects.html#static-ofscope](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Aspects.html#static-ofscope)`.of(SCOPE).add()` with a new aspect, as shown in the following example\. ------ #### [ TypeScript ] diff --git a/doc_source/assets.md b/v1/assets.md similarity index 90% rename from doc_source/assets.md rename to v1/assets.md index 3bc5b04a..d9cc2728 100644 --- a/doc_source/assets.md +++ b/v1/assets.md @@ -2,7 +2,7 @@ Assets are local files, directories, or Docker images that can be bundled into AWS CDK libraries and apps; for example, a directory that contains the handler code for an AWS Lambda function\. Assets can represent any artifact that the app needs to operate\. -You add assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html#code) property lets you pass an [asset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-fromassetpath) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function's code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-assetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. +You add assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-lambda.Function.html#code) property lets you pass an [asset](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-lambda.Code.html#static-fromassetpath) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function's code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-assetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. ## Assets in detail @@ -32,7 +32,7 @@ These asset types are explained in the following sections\. ### Amazon S3 assets -You can define local files and directories as assets, and the AWS CDK packages and uploads them to Amazon S3 through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-assets-readme.html) module\. +You can define local files and directories as assets, and the AWS CDK packages and uploads them to Amazon S3 through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-s3-assets-readme.html) module\. The following example defines a local directory asset and a file asset\. @@ -132,7 +132,7 @@ var fileAsset = new Asset(this, "SampleSingleFileAsset", new AssetProps ------ -In most cases, you don't need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods that enable you to use assets\. For Lambda functions, the [fromAsset\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) static method enables you to specify a directory or a \.zip file in the local file system\. +In most cases, you don't need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods that enable you to use assets\. For Lambda functions, the [fromAsset\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-lambda.Code.html#static-assetpath) static method enables you to specify a directory or a \.zip file in the local file system\. #### Lambda function example @@ -413,7 +413,7 @@ new Function(this, "myLambdaFunction", new FunctionProps #### Permissions -If you use Amazon S3 assets directly through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-assets-readme.html) module, IAM roles, users, or groups, and need to read assets in runtime, grant those assets IAM permissions through the [asset\.grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3-assets.Asset.html#grant-readgrantee) method\. +If you use Amazon S3 assets directly through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-s3-assets-readme.html) module, IAM roles, users, or groups, and need to read assets in runtime, grant those assets IAM permissions through the [asset\.grantRead](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3-assets.Asset.html#grant-readgrantee) method\. The following example grants an IAM group read permissions on a file asset\. @@ -510,7 +510,7 @@ asset.GrantRead(group); ### Docker image assets -The AWS CDK supports bundling local Docker images as assets through the [aws\-ecr\-assets](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecr-assets-readme.html) module\. +The AWS CDK supports bundling local Docker images as assets through the [aws\-ecr\-assets](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-ecr-assets-readme.html) module\. The following example defines a docker image that is built locally and pushed to Amazon ECR\. Images are built from a local Docker context directory \(with a Dockerfile\) and uploaded to Amazon ECR by the AWS CDK CLI or your app's CI/CD pipeline, and can be naturally referenced in your AWS CDK app\. @@ -580,7 +580,7 @@ The `my-image` directory must include a Dockerfile\. The AWS CDK CLI builds a Do #### Amazon ECS task definition example -A common use case is to create an Amazon ECS [TaskDefinition](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.TaskDefinition.html) to run docker containers\. The following example specifies the location of a Docker image asset that the AWS CDK builds locally and pushes to Amazon ECR\. +A common use case is to create an Amazon ECS [TaskDefinition](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.TaskDefinition.html) to run docker containers\. The following example specifies the location of a Docker image asset that the AWS CDK builds locally and pushes to Amazon ECR\. ------ #### [ TypeScript ] @@ -865,9 +865,9 @@ var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps #### Permissions -If you use a module that supports Docker image assets, such as [aws\-ecs](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html), the AWS CDK manages permissions for you when you use assets directly or through [ContainerImage\.fromEcrRepository](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-ecr-repositoryrepository-tag) \(Python: `from_ecr_repository`\)\. If you use Docker image assets directly, you need to ensure that the consuming principal has permissions to pull the image\. +If you use a module that supports Docker image assets, such as [aws\-ecs](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-ecs-readme.html), the AWS CDK manages permissions for you when you use assets directly or through [ContainerImage\.fromEcrRepository](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.ContainerImage.html#static-from-ecr-repositoryrepository-tag) \(Python: `from_ecr_repository`\)\. If you use Docker image assets directly, you need to ensure that the consuming principal has permissions to pull the image\. -In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecr.Repository.html#grant-pullgrantee) method \(Python: `grant_pull`\. This modifies the IAM policy of the principal to enable it to pull images from this repository\. If the principal that is pulling the image is not in the same account or is an AWS service, such as AWS CodeBuild, that does not assume a role in your account, you must grant pull permissions on the resource policy and not on the principal's policy\. Use the [asset\.repository\.addToResourcePolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecr.Repository.html#add-to-resource-policystatement) method \(Python: `add_to_resource_policy`\) to grant the appropriate principal permissions\. +In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecr.Repository.html#grant-pullgrantee) method \(Python: `grant_pull`\. This modifies the IAM policy of the principal to enable it to pull images from this repository\. If the principal that is pulling the image is not in the same account or is an AWS service, such as AWS CodeBuild, that does not assume a role in your account, you must grant pull permissions on the resource policy and not on the principal's policy\. Use the [asset\.repository\.addToResourcePolicy](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecr.Repository.html#add-to-resource-policystatement) method \(Python: `add_to_resource_policy`\) to grant the appropriate principal permissions\. ## AWS CloudFormation resource metadata diff --git a/doc_source/best-practices.md b/v1/best-practices.md similarity index 95% rename from doc_source/best-practices.md rename to v1/best-practices.md index 074ecc72..84700e33 100644 --- a/doc_source/best-practices.md +++ b/v1/best-practices.md @@ -4,7 +4,7 @@ The AWS CDK allows developers or administrators to define their cloud infrastruc The AWS CDK reflects careful consideration of the needs of our customers and internal teams and of the failure patterns that often arise during the deployment and ongoing maintenance of complex cloud applications\. We discovered that failures are often related to "out\-of\-band" changes to an application, such as configuration changes, that were not fully tested\. Therefore, we developed the AWS CDK around a model in which your entire application, not just business logic but also infrastructure and configuration, is defined in code\. That way, proposed changes can be carefully reviewed, comprehensively tested in environments resembling production to varying degrees, and fully rolled back if something goes wrong\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/all-in-one.jpg) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v1/guide/images/all-in-one.jpg) At deployment time, the AWS CDK synthesizes a cloud assembly that contains not only AWS CloudFormation templates describing your infrastructure in all target environments, but file assets containing your runtime code and their supporting files\. With the CDK, every commit in your application's main version control branch can represent a complete, consistent, deployable version of your application\. Your application can then be deployed automatically whenever a change is made\. @@ -27,13 +27,13 @@ The CCoE also creates a "landing zone" that defines your organizational units wi Development teams should be able use their own accounts for testing and have the ability to deploy new resources in these accounts as needed\. Individual developers can treat these resources as extensions of their own development workstation\. Using [CDK Pipelines](cdk_pipeline.md), the AWS CDK applications can then be deployed via a CI/CD account to testing, integration, and production environments \(each isolated in its own AWS region and/or account\) by merging the developers' code into your organization's canonical repository\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/best-practice-deploy-to-multiple-accounts.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v1/guide/images/best-practice-deploy-to-multiple-accounts.png) ## Coding best practices This section presents best practices for organizing your AWS CDK code\. The diagram below shows the relationship between a team and that team's code repositories, packages, applications, and construct libraries\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/code-organization.jpg) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v1/guide/images/code-organization.jpg) ### Start simple and add complexity only when you need it @@ -79,7 +79,7 @@ A construct that is self\-contained, in other words that completely describes a ### Model your app through constructs, not stacks -When breaking down your application into logical units, represent each unit as a descendant of [https://docs.aws.amazon.com/cdk/api/latest/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/latest/docs/constructs.Construct.html) and not of [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html)\. Stacks are a unit of deployment, and so tend to be oriented to specific applications\. By using constructs instead of stacks, you give yourself and your users the flexibility to build stacks in the way that makes the most sense for each deployment scenario\. For example, you could compose multiple constructs into a `DevStack` with some configuration for development environments and then have a different composition for your `ProdStack`\. +When breaking down your application into logical units, represent each unit as a descendant of [https://docs.aws.amazon.com/cdk/api/v1/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v1/docs/constructs.Construct.html) and not of [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html)\. Stacks are a unit of deployment, and so tend to be oriented to specific applications\. By using constructs instead of stacks, you give yourself and your users the flexibility to build stacks in the way that makes the most sense for each deployment scenario\. For example, you could compose multiple constructs into a `DevStack` with some configuration for development environments and then have a different composition for your `ProdStack`\. ### Configure with properties and methods, not environment variables @@ -146,7 +146,7 @@ Determinism is key to successful AWS CDK deployments\. A AWS CDK app should have Since your AWS CDK app is written in a general\-purpose programming language, it can execute arbitrary code, use arbitrary libraries, and make arbitrary network calls\. For example, you could use an AWS SDK to retrieve some information from your AWS account while synthesizing your app\. Recognize that doing so will result in additional credential setup requirements, increased latency, and a chance, however small, of failure every time you run `cdk synth`\. -You should never modify your AWS account or resources during synthesis; synthesizing an app should not have side effects\. Changes to your infrastructure should happen only in the deployment phase, after the AWS CloudFormation template has been generated\. This way, if there's a problem, AWS CloudFormation will automatically roll back the change\. To make changes that can't be easily made within the AWS CDK framework, use [custom resources](https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html) to execute arbitrary code at deployment time\. +You should never modify your AWS account or resources during synthesis; synthesizing an app should not have side effects\. Changes to your infrastructure should happen only in the deployment phase, after the AWS CloudFormation template has been generated\. This way, if there's a problem, AWS CloudFormation will automatically roll back the change\. To make changes that can't be easily made within the AWS CDK framework, use [custom resources](https://docs.aws.amazon.com/cdk/api/v1/docs/custom-resources-readme.html) to execute arbitrary code at deployment time\. Even strictly read\-only calls are not necessarily safe\. Consider what happens if the value returned by a network call changes\. What part of your infrastructure will that impact? What will happen to already\-deployed resources? Here are just two of the situations in which a sudden change in values might cause a problem\. + If you provision an Amazon VPC to all available Availability Zones in a specified region, and the number of AZs is two on deployment day, your IP space gets split in half\. If AWS launches a new Availability Zone the next day, the next deployment after that tries to split your IP space into thirds, requiring all subnets to be recreated\. This probably won't be possible because your Amazon EC2 instances are still running, and you'll have to clean this up manually\. @@ -178,4 +178,4 @@ If you require developers to always use predefined roles that were created by a ### Measure everything -Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html) class\. \ No newline at end of file +Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-dynamodb.Table.html) class\. \ No newline at end of file diff --git a/doc_source/bootstrapping.md b/v1/bootstrapping.md similarity index 98% rename from doc_source/bootstrapping.md rename to v1/bootstrapping.md index 3dc69845..cc423830 100644 --- a/doc_source/bootstrapping.md +++ b/v1/bootstrapping.md @@ -117,7 +117,7 @@ The legacy template is still fully supported by the AWS CDK and is in fact the t The main differences between the templates are as follows\. -[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) +[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/v1/guide/bootstrapping.html) \* *We will add additional resources to the modern template as needed\.* @@ -482,7 +482,7 @@ DefaultStackSynthesizer( deploy_role_external_id="", # ARN of the role used for file asset publishing (assumed from the deploy role) - file_sset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", + file_asset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", file_asset_publishing_external_id="", # ARN of the role used for Docker asset publishing (assumed from the deploy role) @@ -492,10 +492,10 @@ DefaultStackSynthesizer( # ARN of the role passed to CloudFormation to execute the deployments cloud_formation_execution_role="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" - // Name of the SSM parameter which describes the bootstrap stack version number + # Name of the SSM parameter which describes the bootstrap stack version number bootstrap_stack_version_ssm_parameter="/cdk-bootstrap/${Qualifier}/version", - // Add a rule to every template which verifies the required bootstrap stack version + # Add a rule to every template which verifies the required bootstrap stack version generate_bootstrap_version_rule=True, ) ``` diff --git a/doc_source/cdk_pipeline.md b/v1/cdk_pipeline.md similarity index 95% rename from doc_source/cdk_pipeline.md rename to v1/cdk_pipeline.md index 214cf1df..a10b25c1 100644 --- a/doc_source/cdk_pipeline.md +++ b/v1/cdk_pipeline.md @@ -1,6 +1,6 @@ # Continuous integration and delivery \(CI/CD\) using CDK Pipelines -[CDK Pipelines](https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html) is a construct library module for painless continuous delivery of AWS CDK applications\. Whenever you check your AWS CDK app's source code in to AWS CodeCommit, GitHub, or CodeStar, CDK Pipelines can automatically build, test, and deploy your new version\. +[CDK Pipelines](https://docs.aws.amazon.com/cdk/api/v1/docs/pipelines-readme.html) is a construct library module for painless continuous delivery of AWS CDK applications\. Whenever you check your AWS CDK app's source code in to AWS CodeCommit, GitHub, or CodeStar, CDK Pipelines can automatically build, test, and deploy your new version\. CDK Pipelines are self\-updating: if you add application stages or stacks, the pipeline automatically reconfigures itself to deploy those new stages and/or stacks\. @@ -231,7 +231,7 @@ In a future release of the AWS CDK, "new style" stack synthesis will become the Your CDK Pipelines application will include at least two stacks: one that represents the pipeline itself, and one or more stacks that represent the application deployed through it\. Stacks can also be grouped into *stages*, which you can use to deploy copies of infrastructure stacks to different environments\. For now, we'll consider the pipeline, and later delve into the application it will deploy\. -The construct [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CodePipeline.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CodePipeline.html) is the construct that represents a CDK Pipeline that uses AWS CodePipeline as its deployment engine\. When you instantiate `CodePipeline` in a stack, you define the source location for the pipeline \(e\.g\. a GitHub repository\) and the commands to build the app\. For example, the following defines a pipeline whose source is stored in a GitHub repository, and includes a build step for a TypeScript CDK application\. Fill in the information about your GitHub repo where indicated\. +The construct [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_pipelines.CodePipeline.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_pipelines.CodePipeline.html) is the construct that represents a CDK Pipeline that uses AWS CodePipeline as its deployment engine\. When you instantiate `CodePipeline` in a stack, you define the source location for the pipeline \(e\.g\. a GitHub repository\) and the commands to build the app\. For example, the following defines a pipeline whose source is stored in a GitHub repository, and includes a build step for a TypeScript CDK application\. Fill in the information about your GitHub repo where indicated\. **Note** By default, the pipeline authenticates to GitHub using a personal access token stored in Secrets Manager under the name `github-token`\. @@ -495,13 +495,13 @@ Now that you've done the initial deployment, your local AWS account no longer ne ## Application stages -To define a multi\-stack AWS application that can be added to the pipeline all at once, define a subclass of `[Stage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stage.html)` \(not to be confused with `CdkStage` in the CDK Pipelines module\)\. +To define a multi\-stack AWS application that can be added to the pipeline all at once, define a subclass of `[Stage](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stage.html)` \(not to be confused with `CdkStage` in the CDK Pipelines module\)\. The stage contains the stacks that make up your application\. If there are dependencies between the stacks, the stacks are automatically added to the pipeline in the right order\. Stacks that don't depend on each other are deployed in parallel\. You can add a dependency relationship between stacks by calling `stack1.addDependency(stack2)`\. Stages accept a default `env` argument, which becomes the default environment for the stacks inside it\. \(Stacks can still have their own environment specified\.\)\. -An application is added to the pipeline by calling `[addStage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.CodePipeline.html#addwbrstagestage-options)()` with instances of `Stage`\. A stage can be instantiated and added to the pipeline multiple times to define different stages of your DTAP or multi\-region application pipeline: +An application is added to the pipeline by calling `[addStage](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_pipelines.CodePipeline.html#addwbrstagestage-options)()` with instances of `Stage`\. A stage can be instantiated and added to the pipeline multiple times to define different stages of your DTAP or multi\-region application pipeline: We will create a stack containing a simple Lambda function and place that stack in a stage\. Then we will add the stage to the pipeline so it can be deployed\. @@ -876,7 +876,7 @@ namespace MyPipeline ------ -Every application stage added by `addStage()` results in the addition of a corresponding pipeline stage, represented by a [StageDeployment](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.StageDeployment.html) instance returned by the `addStage()` call\. You can add pre\-deployment or post\-deployment actions to the stage by calling its `addPre()` or `addPost()` method\. +Every application stage added by `addStage()` results in the addition of a corresponding pipeline stage, represented by a [StageDeployment](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_pipelines.StageDeployment.html) instance returned by the `addStage()` call\. You can add pre\-deployment or post\-deployment actions to the stage by calling its `addPre()` or `addPost()` method\. ------ #### [ TypeScript ] @@ -951,7 +951,7 @@ testingStage.AddPost(new ManualApprovalStep("approval")); ------ -You can add stages to a [Wave](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.Wave.html) to deploy them in parallel, for example when deploying a stage to multiple accounts or regions\. +You can add stages to a [Wave](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_pipelines.Wave.html) to deploy them in parallel, for example when deploying a stage to multiple accounts or regions\. ------ #### [ TypeScript ] @@ -1035,7 +1035,7 @@ wave.AddStage(new MyPipelineAppStage(this, "MyAppUS", new StageProps ## Testing deployments -You can add steps to a CDK Pipeline to validate the deployments you are performing\. Using the CDK Pipeline library's `[ShellStep](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_pipelines.ShellStep.html)`, you can try to access a just\-deployed Amazon API Gateway backed by a Lambda function, for example, or issue an AWS CLI command to check some setting of a deployed resource\. +You can add steps to a CDK Pipeline to validate the deployments you are performing\. Using the CDK Pipeline library's `[ShellStep](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_pipelines.ShellStep.html)`, you can try to access a just\-deployed Amazon API Gateway backed by a Lambda function, for example, or issue an AWS CLI command to check some setting of a deployed resource\. In its simplest form, adding validation actions looks like this: diff --git a/doc_source/cfn_layer.md b/v1/cfn_layer.md similarity index 100% rename from doc_source/cfn_layer.md rename to v1/cfn_layer.md diff --git a/doc_source/cli.md b/v1/cli.md similarity index 98% rename from doc_source/cli.md rename to v1/cli.md index 05300d2b..f4d3fc58 100644 --- a/doc_source/cli.md +++ b/v1/cli.md @@ -251,7 +251,7 @@ cdk synth 'PipelineStack/Prod/**' # All stacks in Prod stage in a CDK Pipeline ``` **Note** -The order in which you specify the stacks is not necessarily the order in which they will be processed\. The AWS CDK Toolkit takes into account dependencies between stacks when deciding the order in which to process them\. For example, if one stack uses a value produced by another \(such as the ARN of a resource defined in the second stack\), the second stack is synthesized before the first one because of this dependency\. You can add dependencies between stacks manually using the stack's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#addwbrdependencytarget-reason](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#addwbrdependencytarget-reason) method\. +The order in which you specify the stacks is not necessarily the order in which they will be processed\. The AWS CDK Toolkit takes into account dependencies between stacks when deciding the order in which to process them\. For example, if one stack uses a value produced by another \(such as the ARN of a resource defined in the second stack\), the second stack is synthesized before the first one because of this dependency\. You can add dependencies between stacks manually using the stack's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html#addwbrdependencytarget-reason](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html#addwbrdependencytarget-reason) method\. ## Bootstrapping your AWS environment diff --git a/doc_source/compliance-validation.md b/v1/compliance-validation.md similarity index 100% rename from doc_source/compliance-validation.md rename to v1/compliance-validation.md diff --git a/doc_source/constructs.md b/v1/constructs.md similarity index 88% rename from doc_source/constructs.md rename to v1/constructs.md index a7d4e676..10ad8a64 100644 --- a/doc_source/constructs.md +++ b/v1/constructs.md @@ -11,17 +11,17 @@ The AWS CDK includes a collection of constructs called the AWS Construct Library ## AWS Construct library -The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html), which contains constructs representing AWS resources\. +The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html), which contains constructs representing AWS resources\. -This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-dynamodb.Table.html)` class represents an Amazon DynamoDB table\. +This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-dynamodb.Table.html)` class represents an Amazon DynamoDB table\. -There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "layer 1"\) or Cfn \(short for CloudFormation\) resources\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. +There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "layer 1"\) or Cfn \(short for CloudFormation\) resources\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. -The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#add-wbr-lifecycle-wbr-rulerule), which adds a lifecycle rule to the bucket\. +The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#add-wbr-lifecycle-wbr-rulerule), which adds a lifecycle rule to the bucket\. -Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs-patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. +Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs-patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. -For more information about how to navigate the library and discover constructs that can help you build your apps, see the [API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html)\. +For more information about how to navigate the library and discover constructs that can help you build your apps, see the [API Reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html)\. ## Composition @@ -31,16 +31,16 @@ Composition lets you define reusable components and share them like any other co ## Initialization -Constructs are implemented in classes that extend the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html) base class\. You define a construct by instantiating the class\. All constructs take three parameters when they are initialized: +Constructs are implemented in classes that extend the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html) base class\. You define a construct by instantiating the class\. All constructs take three parameters when they are initialized: + **Scope** – The construct within which this construct is defined\. You should usually pass `this` for the scope, because it represents the current scope in which you are defining the construct\. + **id** – An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to allocate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. + **Props** – A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. -Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tag.html) or for specifying where the constructs will be deployed\. +Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tag.html) or for specifying where the constructs will be deployed\. ## Apps and stacks -We call your CDK application an *app*, which is represented by the AWS CDK class [App](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.App.html)\. The following example defines an app with a single stack that contains a single Amazon S3 bucket with versioning enabled: +We call your CDK application an *app*, which is represented by the AWS CDK class [App](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.App.html)\. The following example defines an app with a single stack that contains a single Amazon S3 bucket with versioning enabled: ------ #### [ TypeScript ] @@ -154,7 +154,7 @@ namespace HelloCdkApp ------ -As you can see, you need a scope within which to define your bucket\. Since resources eventually need to be deployed as part of a AWS CloudFormation stack into an *AWS [environment](environments.md)*, which covers a specific AWS account and AWS region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/latest/docs/core/stack.html)\. +As you can see, you need a scope within which to define your bucket\. Since resources eventually need to be deployed as part of a AWS CloudFormation stack into an *AWS [environment](environments.md)*, which covers a specific AWS account and AWS region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/v1/docs/core/stack.html)\. Stacks in AWS CDK apps extend the **Stack** base class, as shown in the previous example\. This is a common pattern when creating a stack within your AWS CDK app: extend the **Stack** class, define a constructor that accepts **scope**, **id**, and **props**, and invoke the base class constructor via `super` with the received **scope**, **id**, and **props**, as shown in the following example\. @@ -367,7 +367,7 @@ Some of our language\-specific API references currently have errors in the paths ## Using L2 constructs -The following example defines an Amazon S3 bucket by creating an instance of the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) class, an L2 construct\. +The following example defines an Amazon S3 bucket by creating an instance of the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html) class, an L2 construct\. ------ #### [ TypeScript ] @@ -438,10 +438,10 @@ new Bucket(this, "MyFirstBucket", new BucketProps ------ -The [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) includes constructs that represent many AWS resources\. +The [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) includes constructs that represent many AWS resources\. **Note** -`MyFirstBucket` is not the name of the bucket that AWS CloudFormation creates\. It is a logical identifier given to the new construct\. See [Physical Names](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Resource.html#physicalname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) for details\. +`MyFirstBucket` is not the name of the bucket that AWS CloudFormation creates\. It is a logical identifier given to the new construct\. See [Physical Names](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Resource.html#physicalname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) for details\. ## Configuration @@ -501,7 +501,7 @@ new Bucket(this, "MyEncryptedBucket", new BucketProps ## Interacting with constructs -Constructs are classes that extend the base [Construct](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html) class\. After you instantiate a construct, the construct object exposes a set of methods and properties that enable you to interact with the construct and pass it around as a reference to other parts of the system\. The AWS CDK framework doesn't put any restrictions on the APIs of constructs; authors can define any API they wish\. However, the AWS constructs that are included with the AWS Construct Library, such as `s3.Bucket`, follow guidelines and common patterns in order to provide a consistent experience across all AWS resources\. +Constructs are classes that extend the base [Construct](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html) class\. After you instantiate a construct, the construct object exposes a set of methods and properties that enable you to interact with the construct and pass it around as a reference to other parts of the system\. The AWS CDK framework doesn't put any restrictions on the APIs of constructs; authors can define any API they wish\. However, the AWS constructs that are included with the AWS Construct Library, such as `s3.Bucket`, follow guidelines and common patterns in order to provide a consistent experience across all AWS resources\. For example, almost all AWS constructs have a set of [grant](permissions.md#permissions_grants) methods that you can use to grant AWS Identity and Access Management \(IAM\) permissions on that construct to a principal\. The following example grants the IAM group `data-science` permission to read from the Amazon S3 bucket `raw-data`\. @@ -637,7 +637,7 @@ For information about the most common API patterns in the AWS Construct Library, In addition to using existing constructs like `s3.Bucket`, you can also write your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct imported from a third\-party library that someone published via NPM or Maven or PyPI—or to your company's internal package repository\. -To declare a new construct, create a class that extends the [Construct](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html) base class, then follow the pattern for initializer arguments\. +To declare a new construct, create a class that extends the [Construct](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html) base class, then follow the pattern for initializer arguments\. For example, you could declare a construct that represents an Amazon S3 bucket which sends an Amazon Simple Notification Service \(Amazon SNS\) notification every time someone uploads a file into it: @@ -987,16 +987,16 @@ As we've already seen, in AWS CDK apps, you define constructs "inside" other con The root of this tree is your app—that is, an instance of the `App` class\. Within the app, you instantiate one or more stacks\. Within stacks, you instantiate either AWS CloudFormation resources or higher\-level constructs, which may themselves instantiate resources or other constructs, and so on down the tree\. -Constructs are *always* explicitly defined within the scope of another construct, so there is never any doubt about the relationships between constructs\. Almost always, you should pass `this` \(in Python, `self`\) as the scope, indicating that the new construct is a child of the current construct\. The intended pattern is that you derive your construct from [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html), then instantiate the constructs it uses in its constructor\. +Constructs are *always* explicitly defined within the scope of another construct, so there is never any doubt about the relationships between constructs\. Almost always, you should pass `this` \(in Python, `self`\) as the scope, indicating that the new construct is a child of the current construct\. The intended pattern is that you derive your construct from [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html), then instantiate the constructs it uses in its constructor\. -Passing the scope explicitly allows each construct to add itself to the tree, with this behavior entirely contained within the [`Construct` base class](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Construct.html)\. It works the same way in every language supported by the AWS CDK and does not require introspection or other "magic\." +Passing the scope explicitly allows each construct to add itself to the tree, with this behavior entirely contained within the [`Construct` base class](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html)\. It works the same way in every language supported by the AWS CDK and does not require introspection or other "magic\." **Important** Technically, it's possible to pass some scope other than `this` when instantiating a construct, which allows you to add constructs anywhere in the tree, even in another stack entirely\. For example, you could write a mixin\-style function that adds constructs to a scope passed in as an argument\. The practical difficulty here is that you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope\. The practice also makes your code more difficult to understand, maintain, and reuse\. It is virtually always better to find a way to express your intent without resorting to abusing the `scope` argument\. The AWS CDK uses the IDs of all constructs in the path from the tree's root to each child construct to generate the unique IDs required by AWS CloudFormation\. This approach means that construct IDs need be unique only within their scope, rather than within the entire stack as in native AWS CloudFormation\. It does, however, mean that if you move a construct to a different scope, its generated stack\-unique ID will change, and AWS CloudFormation will no longer consider it the same resource\. -The construct tree is separate from the constructs you define in your AWS CDK code, but it is accessible through any construct's `node` attribute, which is a reference to the node that represents that construct in the tree\. Each node is a [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.ConstructNode.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.ConstructNode.html) instance, the attributes of which provide access to the tree's root and to the node's parent scopes and children\. +The construct tree is separate from the constructs you define in your AWS CDK code, but it is accessible through any construct's `node` attribute, which is a reference to the node that represents that construct in the tree\. Each node is a [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.ConstructNode.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.ConstructNode.html) instance, the attributes of which provide access to the tree's root and to the node's parent scopes and children\. + `node.children` – The direct children of the construct\. + `node.id` – The identifier of the construct within its scope\. + `node.path` – The full path of the construct including the IDs of all of its parents\. @@ -1005,6 +1005,6 @@ The construct tree is separate from the constructs you define in your AWS CDK co + `node.scopes` – All parents of the construct, up to the root\. + `node.uniqueId` – The unique alphanumeric identifier for this construct within the tree \(by default, generated from `node.path` and a hash\)\. -The construct tree defines an implicit order in which constructs are synthesized to resources in the final AWS CloudFormation template\. Where one resource must be created before another, AWS CloudFormation or the AWS Construct Library will generally infer the dependency and make sure the resources are created in the right order\. You can also add an explicit dependency between two nodes using `node.addDependency()`; see [Dependencies](https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html#dependencies) in the AWS CDK API Reference\. +The construct tree defines an implicit order in which constructs are synthesized to resources in the final AWS CloudFormation template\. Where one resource must be created before another, AWS CloudFormation or the AWS Construct Library will generally infer the dependency and make sure the resources are created in the right order\. You can also add an explicit dependency between two nodes using `node.addDependency()`; see [Dependencies](https://docs.aws.amazon.com/cdk/api/v1/docs/core-readme.html#dependencies) in the AWS CDK API Reference\. The AWS CDK provides a simple way to visit every node in the construct tree and perform an operation on each one\. See [Aspects](aspects.md)\. \ No newline at end of file diff --git a/doc_source/context.md b/v1/context.md similarity index 94% rename from doc_source/context.md rename to v1/context.md index 1913e445..1c86688a 100644 --- a/doc_source/context.md +++ b/v1/context.md @@ -27,23 +27,23 @@ You can get a context value using the `construct.node.tryGetContext` method\. If ## Context methods -The AWS CDK supports several context methods that enable AWS CDK apps to get contextual information\. For example, you can get a list of Availability Zones that are available in a given AWS account and region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) method\. +The AWS CDK supports several context methods that enable AWS CDK apps to get contextual information\. For example, you can get a list of Availability Zones that are available in a given AWS account and region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html#availabilityzones) method\. The following are the context methods: -[HostedZone\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-route53.HostedZone.html#static-from-wbr-lookupscope-id-query) +[HostedZone\.fromLookup](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-route53.HostedZone.html#static-from-wbr-lookupscope-id-query) Gets the hosted zones in your account\. -[stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) +[stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html#availabilityzones) Gets the supported Availability Zones\. -[StringParameter\.valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) +[StringParameter\.valueFromLookup](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) Gets a value from the current Region's Amazon EC2 Systems Manager Parameter Store\. -[Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options) +[Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options) Gets the existing Amazon Virtual Private Clouds in your accounts\. -[LookupMachineImage](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.LookupMachineImage.html) +[LookupMachineImage](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.LookupMachineImage.html) Looks up a machine image for use with a NAT instance in an Amazon Virtual Private Cloud\. If a required context value isn't available, the AWS CDK app notifies the AWS CDK CLI that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. diff --git a/doc_source/core_concepts.md b/v1/core_concepts.md similarity index 65% rename from doc_source/core_concepts.md rename to v1/core_concepts.md index acecfa92..d9e45d36 100644 --- a/doc_source/core_concepts.md +++ b/v1/core_concepts.md @@ -2,4 +2,4 @@ This topic describes some of the concepts \(the why and how\) behind the AWS CDK\. It also discusses the AWS Construct Library\. -AWS CDK apps are composed of building blocks known as [Constructs](constructs.md), which are composed together to form [stacks](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html) and [apps](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.App.html)\. \ No newline at end of file +AWS CDK apps are composed of building blocks known as [Constructs](constructs.md), which are composed together to form [stacks](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html) and [apps](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.App.html)\. \ No newline at end of file diff --git a/doc_source/disaster-recovery-resiliency.md b/v1/disaster-recovery-resiliency.md similarity index 100% rename from doc_source/disaster-recovery-resiliency.md rename to v1/disaster-recovery-resiliency.md diff --git a/doc_source/doc-history.md b/v1/doc-history.md similarity index 100% rename from doc_source/doc-history.md rename to v1/doc-history.md diff --git a/doc_source/ecs_example.md b/v1/ecs_example.md similarity index 99% rename from doc_source/ecs_example.md rename to v1/ecs_example.md index fa7c774f..5471f6bd 100644 --- a/doc_source/ecs_example.md +++ b/v1/ecs_example.md @@ -25,7 +25,7 @@ The Amazon ECS construct used in this tutorial helps you use AWS services by pro Previously, you had to create a Lambda function to have this functionality\. + Provides asset support, so that you can deploy a source from your machine to Amazon ECS in one step\. Previously, to use an application source you had to perform several manual steps, such as uploading to Amazon ECR and creating a Docker image\. -See [ECS](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html) for details\. +See [ECS](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-ecs-readme.html) for details\. ## Creating the directory and initializing the AWS CDK diff --git a/doc_source/environments.md b/v1/environments.md similarity index 97% rename from doc_source/environments.md rename to v1/environments.md index 6c672ae6..10dc4205 100644 --- a/doc_source/environments.md +++ b/v1/environments.md @@ -210,7 +210,7 @@ new MyDevStack(app, "dev", new StackProps { Env = makeEnv() }); ------ -The AWS CDK distinguishes between not specifying the `env` property at all and specifying it using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. Constructs that are defined in such a stack cannot use any information about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options) \(Python: `from_lookup`\), which need to query your AWS account\. These features do not work at all without an explicit environment specified; to use them, you must specify `env`\. +The AWS CDK distinguishes between not specifying the `env` property at all and specifying it using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. Constructs that are defined in such a stack cannot use any information about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options) \(Python: `from_lookup`\), which need to query your AWS account\. These features do not work at all without an explicit environment specified; to use them, you must specify `env`\. When you pass in your environment using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, the stack will be deployed in the account and Region determined by the AWS CDK CLI at the time of synthesis\. This allows environment\-dependent code to work, but it also means that the synthesized template could be different based on the machine, user, or session under which it is synthesized\. This behavior is often acceptable or even desirable during development, but it would probably be an anti\-pattern for production use\. diff --git a/doc_source/examples.md b/v1/examples.md similarity index 100% rename from doc_source/examples.md rename to v1/examples.md diff --git a/doc_source/featureflags.md b/v1/featureflags.md similarity index 100% rename from doc_source/featureflags.md rename to v1/featureflags.md diff --git a/doc_source/get_cfn_param.md b/v1/get_cfn_param.md similarity index 100% rename from doc_source/get_cfn_param.md rename to v1/get_cfn_param.md diff --git a/doc_source/get_context_var.md b/v1/get_context_var.md similarity index 100% rename from doc_source/get_context_var.md rename to v1/get_context_var.md diff --git a/doc_source/get_env_var.md b/v1/get_env_var.md similarity index 100% rename from doc_source/get_env_var.md rename to v1/get_env_var.md diff --git a/doc_source/get_secrets_manager_value.md b/v1/get_secrets_manager_value.md similarity index 93% rename from doc_source/get_secrets_manager_value.md rename to v1/get_secrets_manager_value.md index 3b17c81d..a4b19c3b 100644 --- a/doc_source/get_secrets_manager_value.md +++ b/v1/get_secrets_manager_value.md @@ -1,6 +1,6 @@ # Get a value from AWS Secrets Manager -To use values from AWS Secrets Manager in your AWS CDK app, use the [fromSecretAttributes](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-secretsmanager/secret.html#aws_secretsmanager_Secret_fromSecretAttributes) method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. +To use values from AWS Secrets Manager in your AWS CDK app, use the [fromSecretAttributes](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-secretsmanager/secret.html#aws_secretsmanager_Secret_fromSecretAttributes) method\. It represents a value that is retrieved from Secrets Manager and used at AWS CloudFormation deployment time\. ------ #### [ TypeScript ] diff --git a/doc_source/get_ssm_value.md b/v1/get_ssm_value.md similarity index 86% rename from doc_source/get_ssm_value.md rename to v1/get_ssm_value.md index e8229b46..6f70386e 100644 --- a/doc_source/get_ssm_value.md +++ b/v1/get_ssm_value.md @@ -9,7 +9,7 @@ This topic shows how to read attributes from the AWS Systems Manager Parameter S ## Reading Systems Manager values at deployment time -To read values from the Systems Manager Parameter Store, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-string-parameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-secure-string-parameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md), not the actual value\. The value is resolved by AWS CloudFormation during deployment\. +To read values from the Systems Manager Parameter Store, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-string-parameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-secure-string-parameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md), not the actual value\. The value is resolved by AWS CloudFormation during deployment\. A [limited number of AWS services](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#template-parameters-dynamic-patterns-resources) currently support this feature\. @@ -104,7 +104,7 @@ var secureStringToken = StringParameter.ValueForSecureStringParameter( It is sometimes useful to "bake in" a parameter at synthesis time, so that the resulting AWS CloudFormation template always uses the same value, rather than resolving the value during deployment\. -To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. +To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. diff --git a/doc_source/getting_started.md b/v1/getting_started.md similarity index 98% rename from doc_source/getting_started.md rename to v1/getting_started.md index 8d3a92d5..277542be 100644 --- a/doc_source/getting_started.md +++ b/v1/getting_started.md @@ -105,7 +105,7 @@ var bucket = new Bucket(this, "MyBucket", new BucketProps { **Note** These code snippets are intended for illustration only\. They are incomplete and won't run as they are\. -The AWS Construct Library is distributed using each language's standard package management tools, including NPM, PyPi, Maven, and NuGet\. There's even a version of the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) for each language\. +The AWS Construct Library is distributed using each language's standard package management tools, including NPM, PyPi, Maven, and NuGet\. There's even a version of the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) for each language\. To help you use the AWS CDK in your favorite language, this Guide includes topics that explain how to use the AWS CDK in all supported languages\. + [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) @@ -238,7 +238,7 @@ The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode Where do you go now that you've dipped your toes in the AWS CDK? + Come on in; the water's fine\! Build [your first AWS CDK app](hello_world.md)\. + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. -+ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the provided constructs available for your favorite AWS services\. ++ See the [API reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) to begin exploring the provided constructs available for your favorite AWS services\. + Visit the [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=1&sort=downloadsDesc&offset=0) to find constructs from the CDK community as well as from AWS\. + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1) of using the AWS CDK\. diff --git a/doc_source/hello_world.md b/v1/hello_world.md similarity index 99% rename from doc_source/hello_world.md rename to v1/hello_world.md index 9654ee47..42055e94 100644 --- a/doc_source/hello_world.md +++ b/v1/hello_world.md @@ -207,7 +207,7 @@ Or **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution* ------ -Next, define an Amazon S3 bucket in the stack using the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) construct\. +Next, define an Amazon S3 bucket in the stack using the [Bucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html) construct\. ------ #### [ TypeScript ] @@ -585,7 +585,7 @@ If we hadn't changed the bucket's `RemovalPolicy`, the stack deletion would comp Where do you go now that you've dipped your toes in the AWS CDK? + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. -+ See the [API reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite AWS services\. ++ See the [API reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite AWS services\. + Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=1&sort=downloadsDesc&offset=0) to discover constructs created by AWS and others\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1) of using the AWS CDK\. diff --git a/doc_source/home.md b/v1/home.md similarity index 98% rename from doc_source/home.md rename to v1/home.md index 0c1737ea..508e92fa 100644 --- a/doc_source/home.md +++ b/v1/home.md @@ -18,7 +18,7 @@ The AWS CDK lets you build reliable, scalable, cost\-effective applications in t The AWS CDK supports TypeScript, JavaScript, Python, Java, C\#/\.Net, and \(in developer preview\) Go\. Developers can use one of these supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/AppStacks.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v1/guide/images/AppStacks.png) ## Why use the AWS CDK? @@ -200,7 +200,7 @@ This class produces an AWS CloudFormation [template of more than 500 lines](http And let's not forget\.\.\. code completion within your IDE or editor\! -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/CodeCompletion.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v1/guide/images/CodeCompletion.png) ## Developing with the AWS CDK @@ -225,7 +225,7 @@ The Construct Programming Model \(CPM\) extends the concepts behind the AWS CDK ## Additional documentation and resources In addition to this guide, the following other resources are available to AWS CDK users: -+ [API Reference](https://docs.aws.amazon.com/cdk/api/latest) ++ [API Reference](https://docs.aws.amazon.com/cdk/api/v1) + [AWS CDK Workshop](https://cdkworkshop.com/) + [cdk\.dev](https://cdk.dev/) community hub, including a Slack channel + [AWS CDK Examples](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1) diff --git a/doc_source/how_to_set_cw_alarm.md b/v1/how_to_set_cw_alarm.md similarity index 83% rename from doc_source/how_to_set_cw_alarm.md rename to v1/how_to_set_cw_alarm.md index 5e6a1fb6..c3be2bd1 100644 --- a/doc_source/how_to_set_cw_alarm.md +++ b/v1/how_to_set_cw_alarm.md @@ -1,10 +1,10 @@ # Set a CloudWatch alarm -The [aws\-cloudwatch](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudwatch-readme.html) package supports setting CloudWatch alarms on CloudWatch metrics\. So the first thing you need is a metric\. You can use a predefined metric or you can create your own\. +The [aws\-cloudwatch](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-cloudwatch-readme.html) package supports setting CloudWatch alarms on CloudWatch metrics\. So the first thing you need is a metric\. You can use a predefined metric or you can create your own\. ## Using an existing metric -Many AWS Construct Library modules let you set an alarm on an existing metric by passing the metric's name to a convenience method on an instance of an object that has metrics\. For example, given an Amazon SQS queue, you can get the metric **ApproximateNumberOfMessagesVisible** from the queue's [metric\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-sqs.Queue.html#metricmetricname-props) method\. +Many AWS Construct Library modules let you set an alarm on an existing metric by passing the metric's name to a convenience method on an instance of an object that has metrics\. For example, given an Amazon SQS queue, you can get the metric **ApproximateNumberOfMessagesVisible** from the queue's [metric\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-sqs.Queue.html#metricmetricname-props) method\. ------ #### [ TypeScript ] @@ -45,7 +45,7 @@ var metric = queue.Metric("ApproximateNumberOfMessagesVisible"); ## Creating your own metric -Create your own [metric](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudwatch.Metric.html) as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. You also need to specify your metric's name and dimension\. +Create your own [metric](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-cloudwatch.Metric.html) as follows, where the *namespace* value should be something like **AWS/SQS** for an Amazon SQS queue\. You also need to specify your metric's name and dimension\. ------ #### [ TypeScript ] @@ -180,7 +180,7 @@ var alarm = new Alarm(this, "Alarm", new AlarmProps ------ -An alternative way to create an alarm is using the metric's [createAlarm\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudwatch.Metric.html#create-wbr-alarmscope-id-props) method, which takes essentially the same properties as the `Alarm` constructor; you just don't need to pass in the metric, since it's already known\. +An alternative way to create an alarm is using the metric's [createAlarm\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-cloudwatch.Metric.html#create-wbr-alarmscope-id-props) method, which takes essentially the same properties as the `Alarm` constructor; you just don't need to pass in the metric, since it's already known\. ------ #### [ TypeScript ] diff --git a/doc_source/how_tos.md b/v1/how_tos.md similarity index 100% rename from doc_source/how_tos.md rename to v1/how_tos.md diff --git a/doc_source/identifiers.md b/v1/identifiers.md similarity index 100% rename from doc_source/identifiers.md rename to v1/identifiers.md diff --git a/doc_source/index.md b/v1/index.md similarity index 100% rename from doc_source/index.md rename to v1/index.md diff --git a/doc_source/infrastructure-security.md b/v1/infrastructure-security.md similarity index 100% rename from doc_source/infrastructure-security.md rename to v1/infrastructure-security.md diff --git a/doc_source/multiple_languages.md b/v1/multiple_languages.md similarity index 100% rename from doc_source/multiple_languages.md rename to v1/multiple_languages.md diff --git a/doc_source/parameters.md b/v1/parameters.md similarity index 89% rename from doc_source/parameters.md rename to v1/parameters.md index a90b4814..45b5675e 100644 --- a/doc_source/parameters.md +++ b/v1/parameters.md @@ -9,7 +9,7 @@ When deploying the AWS CloudFormation template using the AWS CDK Toolkit, you pr In general, we recommend against using AWS CloudFormation parameters with the AWS CDK\. Unlike [context values](context.md) or environment variables, the usual way to pass values into your AWS CDK apps without hard\-coding them, parameter values are not available at synthesis time, and thus cannot be easily used in other parts of your AWS CDK app, particularly for control flow\. **Note** -To do control flow with parameters, you can use [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnCondition.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnCondition.html) constructs, although this is awkward compared to native `if` statements\. +To do control flow with parameters, you can use [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnCondition.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnCondition.html) constructs, although this is awkward compared to native `if` statements\. Using parameters requires you to be mindful of how the code you're writing behaves at deployment time, as well as at synthesis time\. This makes it harder to understand and reason about your AWS CDK application, in many cases for little benefit\. @@ -19,7 +19,7 @@ There are, however, use cases to which AWS CloudFormation parameters are uniquel ## Defining parameters -Use the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnParameter.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnParameter.html) class to define a parameter\. You'll want to specify at least a type and a description for most parameters, though both are technically optional\. The description appears when the user is prompted to enter the parameter's value in the AWS CloudFormation console\. For more information on the available types, see [Types](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#parameters-section-structure-properties-type)\. +Use the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnParameter.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnParameter.html) class to define a parameter\. You'll want to specify at least a type and a description for most parameters, though both are technically optional\. The description appears when the user is prompted to enter the parameter's value in the AWS CloudFormation console\. For more information on the available types, see [Types](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#parameters-section-structure-properties-type)\. **Note** You can define parameters in any scope, but we recommend defining parameters at the stack level so that their logical ID does not change when you refactor your code\. diff --git a/doc_source/permissions.md b/v1/permissions.md similarity index 78% rename from doc_source/permissions.md rename to v1/permissions.md index ee5e0c69..6c8e0755 100644 --- a/doc_source/permissions.md +++ b/v1/permissions.md @@ -6,31 +6,31 @@ The AWS Construct Library uses a few common, widely\-implemented idioms to manag An IAM principal is an entity that can be authenticated in order to access AWS resources, such as a user, a service, or an application\. The AWS Construct Library supports many types of principals, including: -1. IAM resources such as `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)` +1. IAM resources such as `[Role](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Group.html)` -1. Service principals \(`new iam.[ServicePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ServicePrincipal.html)('service.amazonaws.com')`\) +1. Service principals \(`new iam.[ServicePrincipal](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ServicePrincipal.html)('service.amazonaws.com')`\) -1. Federated principals \(`new iam.[FederatedPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.FederatedPrincipal.html)('cognito-identity.amazonaws.com')`\) +1. Federated principals \(`new iam.[FederatedPrincipal](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.FederatedPrincipal.html)('cognito-identity.amazonaws.com')`\) -1. Account principals \(`new iam.[AccountPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.AccountPrincipal.html)('0123456789012'))` +1. Account principals \(`new iam.[AccountPrincipal](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.AccountPrincipal.html)('0123456789012'))` -1. Canonical user principals \(`new iam.[CanonicalUserPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CanonicalUserPrincipal.html)('79a59d[...]7ef2be')`\) +1. Canonical user principals \(`new iam.[CanonicalUserPrincipal](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.CanonicalUserPrincipal.html)('79a59d[...]7ef2be')`\) -1. AWS organizations principals \(`new iam.[OrganizationPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.OrganizationPrincipal.html)('org-id')`\) +1. AWS organizations principals \(`new iam.[OrganizationPrincipal](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.OrganizationPrincipal.html)('org-id')`\) -1. Arbitrary ARN principals \(`new iam.[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.ArnPrincipal.html)(res.arn)`\) +1. Arbitrary ARN principals \(`new iam.[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ArnPrincipal.html)(res.arn)`\) -1. An `iam.[CompositePrincipal](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.CompositePrincipal.html)(principal1, principal2, ...)` to trust multiple principals +1. An `iam.[CompositePrincipal](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.CompositePrincipal.html)(principal1, principal2, ...)` to trust multiple principals ## Grants -Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` \(Python: `grant_read`, `grant_read_write`\) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. +Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#grant-readidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#grant-read-writeidentity-objectskeypattern)` \(Python: `grant_read`, `grant_read_write`\) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. -The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Group.html)`\. +The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Group.html)`\. Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other entities that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. -Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly instead of granting access to their role\. For example, if `bucket` is an Amazon S3 bucket, and `function` is a Lambda function, the code below grants the function read access to the bucket\. +Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly instead of granting access to their role\. For example, if `bucket` is an Amazon S3 bucket, and `function` is a Lambda function, the code below grants the function read access to the bucket\. ------ #### [ TypeScript ] @@ -122,7 +122,7 @@ custom.node.AddDependency(grant); ## Roles -The IAM package contains a `[Role](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html)` construct that represents IAM roles\. The following code creates a new role, trusting the Amazon EC2 service\. +The IAM package contains a `[Role](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html)` construct that represents IAM roles\. The following code creates a new role, trusting the Amazon EC2 service\. ------ #### [ TypeScript ] @@ -181,7 +181,7 @@ var role = new Role(this, "Role", new RoleProps ------ -You can add permissions to a role by calling the role's `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` method \(Python: `add_to_policy`\), passing in a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. +You can add permissions to a role by calling the role's `[addToPolicy](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` method \(Python: `add_to_policy`\), passing in a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.PolicyStatement.html)` that defines the rule to be added\. The statement is added to the role's default policy; if it has none, one is created\. The following example adds a `Deny` policy statement to the role for the actions `ec2:SomeAction` and `s3:AnotherAction` on the resources `bucket` and `otherRole` \(Python: `other_role`\), under the condition that the authorized service is AWS CodeBuild\. @@ -260,7 +260,7 @@ role.AddToPolicy(new PolicyStatement(new PolicyStatementProps ------ - In our example above, we've created a new `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` inline with the `[addToPolicy](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` \(Python: `add_to_policy`\) call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. + In our example above, we've created a new `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.PolicyStatement.html)` inline with the `[addToPolicy](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html#add-to-policystatement)` \(Python: `add_to_policy`\) call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. If you're using a construct that requires a role to function correctly, you can either pass in an existing role when instantiating the construct object, or let the construct create a new role for you, trusting the appropriate service principal\. The following example uses such a construct: a CodeBuild project\. @@ -423,9 +423,9 @@ project.AddToRolePolicy(new PolicyStatement(new PolicyStatementProps ## Resource policies -A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. These constructs have an `addToResourcePolicy` method \(Python: `add_to_resource_policy`\), which takes a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.PolicyStatement.html)` as its argument\. Every policy statement added to a resource policy must specify at least one principal\. +A few resources in AWS, such as Amazon S3 buckets and IAM roles, also have a resource policy\. These constructs have an `addToResourcePolicy` method \(Python: `add_to_resource_policy`\), which takes a `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.PolicyStatement.html)` as its argument\. Every policy statement added to a resource policy must specify at least one principal\. -In the following example, the [Amazon S3 bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) `bucket` grants a role with the `s3:SomeAction` permission to itself\. +In the following example, the [Amazon S3 bucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html) `bucket` grants a role with the `s3:SomeAction` permission to itself\. ------ #### [ TypeScript ] diff --git a/doc_source/pgp-keys.md b/v1/pgp-keys.md similarity index 100% rename from doc_source/pgp-keys.md rename to v1/pgp-keys.md diff --git a/doc_source/reference.md b/v1/reference.md similarity index 93% rename from doc_source/reference.md rename to v1/reference.md index 60f07191..0aa959e1 100644 --- a/doc_source/reference.md +++ b/v1/reference.md @@ -1,8 +1,8 @@ # API reference -The [API Reference](https://docs.aws.amazon.com/cdk/api/latest) contains information about the AWS Construct Library and other APIs provided by the AWS CDK\. It is organized by module\. +The [API Reference](https://docs.aws.amazon.com/cdk/api/v1) contains information about the AWS Construct Library and other APIs provided by the AWS CDK\. It is organized by module\. -Each module has an overview that includes information about how to use its APIs\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html) overview demonstrates how to set default encryption on an Amazon S3 bucket\. +Each module has an overview that includes information about how to use its APIs\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-s3-readme.html) overview demonstrates how to set default encryption on an Amazon S3 bucket\. Separate versions of the API Reference are provided for TypeScript/JavaScript, Python, Java, and C\#/\.NET\. @@ -52,7 +52,7 @@ Stage 3: General availability \(GA\) The module is generally available with a compatibility guarantee across minor versions\. We will only make backward\-compatible changes to the API, so that your existing apps will continue to work until the next major AWS CDK release\. In some cases, we may use [feature flags](featureflags.md) to optionally enable new behavior while retaining the previous behavior to support existing apps\. -Each module's Overview in the [API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) describes its stability level\. +Each module's Overview in the [API Reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) describes its stability level\. For more information about these maturity stages, see [AWS Construct Library Module Lifecycle](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0107-construct-library-module-lifecycle.md)\. diff --git a/doc_source/resources.md b/v1/resources.md similarity index 97% rename from doc_source/resources.md rename to v1/resources.md index 540d5ae2..1db83d28 100644 --- a/doc_source/resources.md +++ b/v1/resources.md @@ -2,7 +2,7 @@ As described in [Constructs](constructs.md), the AWS CDK provides a rich class library of constructs, called *AWS constructs*, that represent all AWS resources\. This section describes some common patterns and best practices for how to use these constructs\. -Defining AWS resources in your CDK app is exactly like defining any other construct\. You create an instance of the construct class, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here's how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. +Defining AWS resources in your CDK app is exactly like defining any other construct\. You create an instance of the construct class, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here's how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. ------ #### [ TypeScript ] @@ -265,7 +265,7 @@ If the AWS CDK determines that the resource is in the same account and Region, b Referencing a resource from one stack in a different stack creates a dependency between the two stacks\. Once this dependency is established, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure if the AWS CDK Toolkit deploys the producing stack before the consuming stack\. This happens if there is another dependency between the two stacks, but it can also happen that the producing stack is chosen by the AWS CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it is no longer needed, but the exported resource is still being used in the consuming stack because its update has not yet been deployed, so deploying the producer stack fails\. -To break this deadlock, remove the use of the shared resource from the consuming stack \(which will remove the automatic export from the producing stack\), then manually add the same export to the producing stack using exactly the same logical ID as the automatically\-generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then remove the manual export \(and the shared resource if it is no longer needed\), and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#exportwbrvalueexportedvalue-options)` method is a convenient way to create the manual export for this purpose \(see the example in the linked method reference\)\. +To break this deadlock, remove the use of the shared resource from the consuming stack \(which will remove the automatic export from the producing stack\), then manually add the same export to the producing stack using exactly the same logical ID as the automatically\-generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then remove the manual export \(and the shared resource if it is no longer needed\), and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html#exportwbrvalueexportedvalue-options)` method is a convenient way to create the manual export for this purpose \(see the example in the linked method reference\)\. ## Physical names @@ -773,7 +773,7 @@ table.Grant(func, "dynamodb:CreateBackup"); Many resources, such as Lambda functions, require a role to be assumed when executing code\. A configuration property enables you to specify an `iam.IRole`\. If no role is specified, the function automatically creates a role specifically for this use\. You can then use grant methods on the resources to add statements to the role\. -The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-iam-readme.html) objects\. Add statements directly to roles \(or a construct's attached role\) using the `addToRolePolicy` method \(Python: `add_to_role_policy`\), or to a resource's policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` \(Python: `add_to_resource_policy`\) method\. +The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-iam-readme.html) objects\. Add statements directly to roles \(or a construct's attached role\) using the `addToRolePolicy` method \(Python: `add_to_role_policy`\), or to a resource's policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` \(Python: `add_to_resource_policy`\) method\. ## Metrics and alarms @@ -898,13 +898,13 @@ metric.CreateAlarm(this, "TooManyMessagesAlarm", new cw.CreateAlarmOptions If there is no method for a particular metric, you can use the general metric method to specify the metric name manually\. -Metrics can also be added to CloudWatch dashboards\. See [CloudWatch](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudwatch-readme.html)\. +Metrics can also be added to CloudWatch dashboards\. See [CloudWatch](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-cloudwatch-readme.html)\. ## Network traffic In many cases, you must enable permissions on a network for an application to work, such as when the compute infrastructure needs to access the persistence layer\. Resources that establish or listen for connections expose methods that enable traffic flows, including setting security group rules or network ACLs\. -[IConnectable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.IConnectable.html) resources have a `connections` property that is the gateway to network traffic rules configuration\. +[IConnectable](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.IConnectable.html) resources have a `connections` property that is the gateway to network traffic rules configuration\. You enable data to flow on a given network path by using `allow` methods\. The following example enables HTTPS connections to the web and incoming connections from the Amazon EC2 Auto Scaling group `fleet2`\. diff --git a/doc_source/sam.md b/v1/sam.md similarity index 100% rename from doc_source/sam.md rename to v1/sam.md diff --git a/doc_source/security-iam.md b/v1/security-iam.md similarity index 100% rename from doc_source/security-iam.md rename to v1/security-iam.md diff --git a/doc_source/security.md b/v1/security.md similarity index 100% rename from doc_source/security.md rename to v1/security.md diff --git a/doc_source/serverless_example.md b/v1/serverless_example.md similarity index 98% rename from doc_source/serverless_example.md rename to v1/serverless_example.md index 2720efed..61837e04 100644 --- a/doc_source/serverless_example.md +++ b/v1/serverless_example.md @@ -499,7 +499,7 @@ namespace MyWidgetService ------ **Tip** -We're using a `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Function.html)` in to deploy this function because it supports a wide variety of programming languages\. For JavaScript and TypeScript specifically, you might consider a `[lambda\-nodejs\.NodejsFunction](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda-nodejs.NodejsFunction.html)`\. The latter uses esbuild to bundle up the script and converts code written in TypeScript automatically\. +We're using a `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-lambda.Function.html)` in to deploy this function because it supports a wide variety of programming languages\. For JavaScript and TypeScript specifically, you might consider a `[lambda\-nodejs\.NodejsFunction](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-lambda-nodejs.NodejsFunction.html)`\. The latter uses esbuild to bundle up the script and converts code written in TypeScript automatically\. Save the app and make sure it still synthesizes an empty stack\. diff --git a/doc_source/stack_how_to_create_multiple_stacks.md b/v1/stack_how_to_create_multiple_stacks.md similarity index 100% rename from doc_source/stack_how_to_create_multiple_stacks.md rename to v1/stack_how_to_create_multiple_stacks.md diff --git a/doc_source/stacks.md b/v1/stacks.md similarity index 94% rename from doc_source/stacks.md rename to v1/stacks.md index a6cf8a3b..aff226d1 100644 --- a/doc_source/stacks.md +++ b/v1/stacks.md @@ -347,12 +347,12 @@ new MyStack(this, "not:a:stack:name", new StackProps ## Stack API -The [Stack](https://docs.aws.amazon.com/cdk/api/latest/docs/core/stack.html) object provides a rich API, including the following: +The [Stack](https://docs.aws.amazon.com/cdk/api/v1/docs/core/stack.html) object provides a rich API, including the following: + `Stack.of(construct)` – A static method that returns the **Stack** in which a construct is defined\. This is useful if you need to interact with a stack from within a reusable construct\. The call fails if a stack cannot be found in scope\. + `stack.stackName` \(Python: `stack_name`\) – Returns the physical name of the stack\. As mentioned previously, all AWS CDK stacks have a physical name that the AWS CDK can resolve during synthesis\. + `stack.region` and `stack.account` – Return the AWS Region and account, respectively, into which this stack will be deployed\. These properties return either the account or Region explicitly specified when the stack was defined, or a string\-encoded token that resolves to the AWS CloudFormation pseudo\-parameters for account and Region to indicate that this stack is environment agnostic\. See [Environments](environments.md) for information about how environments are determined for stacks\. + `stack.addDependency(stack)` \(Python: `stack.add_dependency(stack)` – Can be used to explicitly define dependency order between two stacks\. This order is respected by the cdk deploy command when deploying multiple stacks at once\. -+ `stack.tags` – Returns a [TagManager](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.TagManager.html) that you can use to add or remove stack\-level tags\. This tag manager tags all resources within the stack, and also tags the stack itself when it's created through AWS CloudFormation\. ++ `stack.tags` – Returns a [TagManager](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.TagManager.html) that you can use to add or remove stack\-level tags\. This tag manager tags all resources within the stack, and also tags the stack itself when it's created through AWS CloudFormation\. + `stack.partition`, `stack.urlSuffix` \(Python: `url_suffix`\), `stack.stackId` \(Python: `stack_id`\), and `stack.notificationArn` \(Python: `notification_arn`\) – Return tokens that resolve to the respective AWS CloudFormation pseudo\-parameters, such as `{ "Ref": "AWS::Partition" }`\. These tokens are associated with the specific stack object so that the AWS CDK framework can identify cross\-stack references\. + `stack.availabilityZones` \(Python: `availability_zones`\) – Returns the set of Availability Zones available in the environment in which this stack is deployed\. For environment\-agnostic stacks, this always returns an array with two Availability Zones, but for environment\-specific stacks, the AWS CDK queries the environment and returns the exact set of Availability Zones available in the region you specified\. + `stack.parseArn(arn)` and `stack.formatArn(comps)` \(Python: `parse_arn`, `format_arn`\) – Can be used to work with Amazon Resource Names \(ARNs\)\. @@ -361,7 +361,7 @@ The [Stack](https://docs.aws.amazon.com/cdk/api/latest/docs/core/stack.html) obj ## Nested stacks -The [NestedStack](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.NestedStack.html) construct offers a way around the AWS CloudFormation 500\-resource limit for stacks\. A nested stack counts as only one resource in the stack that contains it, but can itself contain up to 500 resources, including additional nested stacks\. +The [NestedStack](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.NestedStack.html) construct offers a way around the AWS CloudFormation 500\-resource limit for stacks\. A nested stack counts as only one resource in the stack that contains it, but can itself contain up to 500 resources, including additional nested stacks\. The scope of a nested stack must be a `Stack` or `NestedStack` construct\. The nested stack needn't be declared lexically inside its parent stack; it is necessary only to pass the parent stack as the first parameter \(`scope`\) when instantiating the nested stack\. Aside from this restriction, defining constructs in a nested stack works exactly the same as in an ordinary stack\. diff --git a/doc_source/tagging.md b/v1/tagging.md similarity index 90% rename from doc_source/tagging.md rename to v1/tagging.md index 56d25711..9d65d01b 100644 --- a/doc_source/tagging.md +++ b/v1/tagging.md @@ -5,9 +5,9 @@ Tags are informational key\-value elements that you can add to constructs in you **Tip** For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf)\. -The [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#addkey-value-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#addkey-value-props) applies a new tag to the given construct and all of its children\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#removekey-props](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Tags.html#removekey-props) removes a tag from the given construct and any of its children, including tags a child construct may have applied to itself\. +The [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. ++ [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html#addkey-value-props](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html#addkey-value-props) applies a new tag to the given construct and all of its children\. ++ [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html#removekey-props](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html#removekey-props) removes a tag from the given construct and any of its children, including tags a child construct may have applied to itself\. **Note** Tagging is implemented using [Aspects](aspects.md)\. Aspects are a way to apply an operation \(such as tagging\) to all constructs in a given scope\. @@ -140,7 +140,7 @@ Tags.Of(myConstruct).Add("key", "value", new TagProps { Priority = 300 }); ## Optional properties -Tags support [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.TagProps.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.TagProps.html) that fine\-tune how tags are applied to, or removed from, resources\. All properties are optional\. +Tags support [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.TagProps.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.TagProps.html) that fine\-tune how tags are applied to, or removed from, resources\. All properties are optional\. `applyToLaunchedInstances` \(Python: `apply_to_launched_instances`\) Available for add\(\) only\. By default, tags are applied to instances launched in an Auto Scaling group\. Set this property to **false** to ignore instances launched in an Auto Scaling group\. diff --git a/doc_source/testing.md b/v1/testing.md similarity index 98% rename from doc_source/testing.md rename to v1/testing.md index f595ff6d..88557cfa 100644 --- a/doc_source/testing.md +++ b/v1/testing.md @@ -1,6 +1,6 @@ # Testing constructs -With the AWS CDK, your infrastructure can be as testable as any other code you write\. This article illustrates the standard approach to testing AWS CDK apps using the AWS CDK's [assertions](https://docs.aws.amazon.com/cdk/api/latest/docs/assertions-readme.html) module and popular test frameworks such as [Jest](https://jestjs.io/) for TypeScript and JavaScript or [Pytest](https://docs.pytest.org/en/6.2.x/) for Python\. +With the AWS CDK, your infrastructure can be as testable as any other code you write\. This article illustrates the standard approach to testing AWS CDK apps using the AWS CDK's [assertions](https://docs.aws.amazon.com/cdk/api/v1/docs/assertions-readme.html) module and popular test frameworks such as [Jest](https://jestjs.io/) for TypeScript and JavaScript or [Pytest](https://docs.pytest.org/en/6.2.x/) for Python\. There are two categories of tests you can write for AWS CDK apps\. + **Fine\-grained assertions** test specific aspects of the generated AWS CloudFormation template, such as "this resource has this property with this value\." These tests can detect regressions, and are also useful when you're developing new features using test\-driven development \(write a test first, then make it pass by writing a correct implementation\)\. Fine\-grained assertions are the tests you'll write the most of\. @@ -873,7 +873,7 @@ Our Amazon SNS assertion asserts that the synthesized template contains a subscr ### Matchers -The default partial matching behavior of `hasResourceProperties` can be changed using *matchers* from the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_assertions.Match.html#methods](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_assertions.Match.html#methods) class\. +The default partial matching behavior of `hasResourceProperties` can be changed using *matchers* from the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_assertions.Match.html#methods](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_assertions.Match.html#methods) class\. Matchers range from the very lenient \(`Match.anyValue`\) to the quite strict \(`Match.objectEquals`\), and can be nested to apply different matching methods to different parts of the resource properties\. Using `Match.objectEquals` and `Match.anyValue` together, for example, we can test the state machine's IAM role more fully, while not requiring specific values for properties that may change\. @@ -1174,7 +1174,7 @@ Many CloudFormation resources include serialized JSON objects represented as str ### Capturing -It's often useful to test properties to make sure they follow specific formats, or have the same value as another property, without needing to know their exact values ahead of time\. The `assertions` module provides this capability in its [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_assertions.Capture.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_assertions.Capture.html) class\. +It's often useful to test properties to make sure they follow specific formats, or have the same value as another property, without needing to know their exact values ahead of time\. The `assertions` module provides this capability in its [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_assertions.Capture.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_assertions.Capture.html) class\. By specifying a `Capture` instance in place of a value in `hasResourceProperties`, that value is retained in the `Capture` object\. The actual captured value can be retrieved using the object's `as` methods, including `asNumber()`, `asString()`, and `asObject`, and subjected to test\. Use `Capture` with a matcher to specify the exact location of the value to be captured within the resource's properties, including serialized JSON properties\. diff --git a/doc_source/tokens.md b/v1/tokens.md similarity index 86% rename from doc_source/tokens.md rename to v1/tokens.md index a6017e44..0403e6b6 100644 --- a/doc_source/tokens.md +++ b/v1/tokens.md @@ -80,15 +80,15 @@ When the AWS CloudFormation template is finally synthesized, the token is render ## Tokens and token encodings -Tokens are objects that implement the [IResolvable](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.IResolvable.html) interface, which contains a single `resolve` method\. The AWS CDK calls this method during synthesis to produce the final value for the AWS CloudFormation template\. Tokens participate in the synthesis process to produce arbitrary values of any type\. +Tokens are objects that implement the [IResolvable](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.IResolvable.html) interface, which contains a single `resolve` method\. The AWS CDK calls this method during synthesis to produce the final value for the AWS CloudFormation template\. Tokens participate in the synthesis process to produce arbitrary values of any type\. **Note** You'll hardly ever work directly with the `IResolvable` interface\. You will most likely only see string\-encoded versions of tokens\. -Other functions typically only accept arguments of basic types, such as `string` or `number`\. To use tokens in these cases, you can encode them into one of three types using static methods on the [core\.Token](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html) class\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) to generate a string encoding \(or call `.toString()` on the token object\) -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) to generate a list encoding -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Token.html#static-as-numbervalue) to generate a numeric encoding +Other functions typically only accept arguments of basic types, such as `string` or `number`\. To use tokens in these cases, you can encode them into one of three types using static methods on the [core\.Token](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Token.html) class\. ++ [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Token.html#static-as-stringvalue-options) to generate a string encoding \(or call `.toString()` on the token object\) ++ [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Token.html#static-as-listvalue-options](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Token.html#static-as-listvalue-options) to generate a list encoding ++ [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Token.html#static-as-numbervalue](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Token.html#static-as-numbervalue) to generate a numeric encoding These take an arbitrary value, which can be an `IResolvable`, and encode them into a primitive value of the indicated type\. @@ -260,7 +260,7 @@ As with list tokens, you cannot modify the number value, as doing so is likely t In addition to representing deploy\-time values, such as AWS CloudFormation [parameters](parameters.md), Tokens are also commonly used to represent synthesis\-time lazy values\. These are values for which the final value will be determined before synthesis has completed, just not at the point where the value is constructed\. Use tokens to pass a literal string or number value to another construct, while the actual value at synthesis time may depend on some calculation that has yet to occur\. -You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.string](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-stringproducer-options) and [Lazy\.number](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Lazy.html#static-numberproducer)\. These methods accept an object whose `produce` property is a function that accepts a context argument and returns the final value when called\. +You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.string](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Lazy.html#static-stringproducer-options) and [Lazy\.number](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Lazy.html#static-numberproducer)\. These methods accept an object whose `produce` property is a function that accepts a context argument and returns the final value when called\. The following example creates an Auto Scaling group whose capacity is determined after its creation\. @@ -373,7 +373,7 @@ actualValue = 10; ## Converting to JSON -Sometimes you want to produce a JSON string of arbitrary data, and you may not know whether the data contains tokens\. To properly JSON\-encode any data structure, regardless of whether it contains tokens, use the method [stack\.toJsonString](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#to-json-stringobj-space), as shown in the following example\. +Sometimes you want to produce a JSON string of arbitrary data, and you may not know whether the data contains tokens\. To properly JSON\-encode any data structure, regardless of whether it contains tokens, use the method [stack\.toJsonString](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html#to-json-stringobj-space), as shown in the following example\. ------ #### [ TypeScript ] diff --git a/doc_source/tools.md b/v1/tools.md similarity index 100% rename from doc_source/tools.md rename to v1/tools.md diff --git a/doc_source/troubleshooting.md b/v1/troubleshooting.md similarity index 98% rename from doc_source/troubleshooting.md rename to v1/troubleshooting.md index 0d5fa3de..7e22f89e 100644 --- a/doc_source/troubleshooting.md +++ b/v1/troubleshooting.md @@ -247,7 +247,7 @@ To get the number of Availability Zones you requested, specify the account and r **Note** In the past, regions have occasionally launched with only one availability zone\. Environment\-agnostic AWS CDK stacks cannot be deployed to such regions\. At this writing, however, all AWS regions have at least two AZs\. -You can change this behavior by overriding your stack's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html#availabilityzones) \(Python: `availability_zones`\) property to explicitly specify the zones you want to use\. +You can change this behavior by overriding your stack's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html#availabilityzones](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html#availabilityzones) \(Python: `availability_zones`\) property to explicitly specify the zones you want to use\. For more information about specifying a stack's account and region at synthesis time, while retaining the flexibility to deploy to any region, see [Environments](environments.md)\. diff --git a/doc_source/use_cfn_public_registry.md b/v1/use_cfn_public_registry.md similarity index 87% rename from doc_source/use_cfn_public_registry.md rename to v1/use_cfn_public_registry.md index cc3071f5..2f4c8458 100644 --- a/doc_source/use_cfn_public_registry.md +++ b/v1/use_cfn_public_registry.md @@ -1,6 +1,6 @@ # Using resources from the AWS CloudFormation Public Registry - The AWS CloudFormation Public Registry is a collection of AWS CloudFormation extensions from both AWS and third parties that are available for use by all AWS customers\. You can also publish your own extension for others to use\. Extensions are of two types: resources and modules\. You can use public resource extensions in your AWS CDK app using the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html) construct\. + The AWS CloudFormation Public Registry is a collection of AWS CloudFormation extensions from both AWS and third parties that are available for use by all AWS customers\. You can also publish your own extension for others to use\. Extensions are of two types: resources and modules\. You can use public resource extensions in your AWS CDK app using the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnResource.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnResource.html) construct\. All public extensions published by AWS are available to all accounts in all regions without any action on your part\. On the other hand, you must activate each third\-party extension you want to use, in each account and region where you want to use it\. @@ -15,7 +15,7 @@ Extensions published by AWS do not require activation; they are always available To activate a third\-party extension through the AWS Management Console, or to simply see what resources are available, follow these steps\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/activate-cfn-extension.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v1/guide/images/activate-cfn-extension.png) 1. Log in to the AWS account in which you want to use the extension, then switch to the region where you want to use it\. @@ -42,11 +42,11 @@ To activate an extension through CloudFormation or the CDK, deploy a resource of + `ExecutionRoleArn` \- The ARN of the IAM role under which this extension will run\. + `LoggingConfig` \- The logging configuration for the extension\. -The `TypeActivation` resource can be deployed by the CDK using the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html) construct, as shown below for the actual extensions\. +The `TypeActivation` resource can be deployed by the CDK using the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnResource.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnResource.html) construct, as shown below for the actual extensions\. ## Adding a resource from the AWS CloudFormation Public Registry to your CDK app - Use the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnResource.html) construct to include a resource from the AWS CloudFormation Public Registry in your application\. This construct is in the CDK's `core` module\. + Use the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnResource.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnResource.html) construct to include a resource from the AWS CloudFormation Public Registry in your application\. This construct is in the CDK's `core` module\. For example, suppose there is a public resource named `MY::S5::UltimateBucket` that you want to use in your AWS CDK application\. This resource takes one property: the bucket name\. The corresponding `CfnResource` instantiation looks like this\. diff --git a/doc_source/use_cfn_template.md b/v1/use_cfn_template.md similarity index 69% rename from doc_source/use_cfn_template.md rename to v1/use_cfn_template.md index 098dc2ad..eb79b7d7 100644 --- a/doc_source/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -1,11 +1,11 @@ # Import or migrate an existing AWS CloudFormation template -The [https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-readme.html](https://docs.aws.amazon.com/cdk/api/latest/docs/cloudformation-include-readme.html) construct converts the resources in an imported AWS CloudFormation template to AWS CDK L1 constructs\. You can work with these in your app just as if they were defined in AWS CDK code, even using them within higher\-level AWS CDK constructs, letting you use \(for example\) the L2 permission grant methods with the resources they define\. +The [https://docs.aws.amazon.com/cdk/api/v1/docs/cloudformation-include-readme.html](https://docs.aws.amazon.com/cdk/api/v1/docs/cloudformation-include-readme.html) construct converts the resources in an imported AWS CloudFormation template to AWS CDK L1 constructs\. You can work with these in your app just as if they were defined in AWS CDK code, even using them within higher\-level AWS CDK constructs, letting you use \(for example\) the L2 permission grant methods with the resources they define\. This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\. **Note** -The AWS CDK also includes [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. +The AWS CDK also includes [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. ## Install the `cloudformation-include` module @@ -315,7 +315,7 @@ When you `cdk deploy` the stack, your AWS CDK app becomes the source of truth fo ## Accessing imported resources -The name `template` in the example code represents the imported AWS CloudFormation template\. To access a resource from it, use this object's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) method\. To access the returned resource as a specific kind of resource, cast the result to the desired type\. \(Casting is not necessary in Python and JavaScript\.\) +The name `template` in the example code represents the imported AWS CloudFormation template\. To access a resource from it, use this object's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-resourcelogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) method\. To access the returned resource as a specific kind of resource, cast the result to the desired type\. \(Casting is not necessary in Python and JavaScript\.\) ------ #### [ TypeScript ] @@ -354,9 +354,9 @@ var cfnBucket = (CfnBucket)template.GetResource("MyBucket"); ------ -In our example, `cfnBucket` is now an instance of the [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.CfnBucket.html) class, a L1 construct that exactly represents the corresponding AWS CloudFormation resource\. You can treat it like any other resource of its type, for example getting its ARN by way of the `bucket.attrArn` property\. +In our example, `cfnBucket` is now an instance of the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.CfnBucket.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.CfnBucket.html) class, a L1 construct that exactly represents the corresponding AWS CloudFormation resource\. You can treat it like any other resource of its type, for example getting its ARN by way of the `bucket.attrArn` property\. -To wrap the L1 `CfnBucket` resource in a L2 [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) instance instead, use the static methods [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-arnscope-id-bucketarn](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-arnscope-id-bucketarn), [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-attributesscope-id-attrs](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-attributesscope-id-attrs), or [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-namescope-id-bucketname](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-namescope-id-bucketname)\. Usually the `fromBucketName()` method is the most convenient\. For example: +To wrap the L1 `CfnBucket` resource in a L2 [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html) instance instead, use the static methods [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-arnscope-id-bucketarn](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-arnscope-id-bucketarn), [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-attributesscope-id-attrs](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-attributesscope-id-attrs), or [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-namescope-id-bucketname](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#static-from-wbr-bucket-wbr-namescope-id-bucketname)\. Usually the `fromBucketName()` method is the most convenient\. For example: ------ #### [ TypeScript ] @@ -399,7 +399,7 @@ Other L2 constructs have similar methods for creating the construct from an exis Constructing the `Bucket` this way doesn't create a second Amazon S3 bucket; instead, the new `Bucket` instance encapsulates the existing `CfnBucket`\. -In the example, `bucket` is now an L2 `Bucket` construct that you can use as you would one you declared yourself\. For example, if `lambdaFunc` is an AWS Lambda function, and you wish to grant it write access to the bucket, you can do so using the bucket's convenient [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-wbr-read-wbr-writeidentity-objectskeypattern](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#grant-wbr-read-wbr-writeidentity-objectskeypattern) method, without needing to construct the necessary IAM policy yourself\. +In the example, `bucket` is now an L2 `Bucket` construct that you can use as you would one you declared yourself\. For example, if `lambdaFunc` is an AWS Lambda function, and you wish to grant it write access to the bucket, you can do so using the bucket's convenient [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#grant-wbr-read-wbr-writeidentity-objectskeypattern](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#grant-wbr-read-wbr-writeidentity-objectskeypattern) method, without needing to construct the necessary IAM policy yourself\. ------ #### [ TypeScript ] @@ -507,12 +507,12 @@ var template = new cfnInc.CfnInclude(this, "Template", new cfnInc.CfnIncludeProp ## Other template elements You can import any AWS CloudFormation template element, not just resources\. The imported elements become part of the AWS CDK stack\. To import these elements, use the following methods of the `CfnInclude` object\. -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-conditionconditionname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-conditionconditionname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [conditions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-hookhooklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-hookhooklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [hooks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/blue-green.html) for blue\-green deployments -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-mappingmappingname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-mappingmappingname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [mappings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html) -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-outputlogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-outputlogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html) -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-parameterparametername-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-parameterparametername-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) -+ [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-rulerulename-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-rulerulename-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [rules](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/reference-template_constraint_rules.html) for Service Catalog templates ++ [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-conditionconditionname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-conditionconditionname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [conditions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-hookhooklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-hookhooklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [hooks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/blue-green.html) for blue\-green deployments ++ [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-mappingmappingname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-mappingmappingname-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [mappings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-outputlogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-outputlogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-parameterparametername-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-parameterparametername-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) ++ [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-rulerulename-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-rulerulename-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) \- AWS CloudFormation [rules](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/reference-template_constraint_rules.html) for Service Catalog templates Each of these methods returns an instance of a class representing the specific type of AWS CloudFormation element\. These objects are mutable; changes you make to them will appear in the template generated from the AWS CDK stack\. The code below, for example, imports a parameter from the template and modifies its default\. @@ -670,7 +670,7 @@ var nestedTemplate = mainTemplate.LoadNestedStack("NestedTemplate", new cfnInc.C You can import multiple nested stacks with either or both methods\. When importing the main template, you provide a mapping between the resource name of each nested stack and its template file, and this mapping can contain any number of entries\. To do it after the initial import, call `loadNestedStack()` once for each nested stack\. -After importing a nested stack, you can access it using the main template's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-nested-wbr-stacklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-nested-wbr-stacklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) method\. +After importing a nested stack, you can access it using the main template's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-nested-wbr-stacklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.CfnInclude.html#get-wbr-nested-wbr-stacklogicalid-span-class-api-icon-api-icon-experimental-title-this-api-element-is-experimental-it-may-change-without-notice-span) method\. ------ #### [ TypeScript ] @@ -709,4 +709,4 @@ var nestedStack = mainTemplate.GetNestedStack("NestedStack").Stack; ------ -The `getNestedStack()` method returns an [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.IncludedNestedStack.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_cloudformation-include.IncludedNestedStack.html) instance, from which you can access the AWS CDK [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.NestedStack.html](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.NestedStack.html) instance via the `stack` property \(as shown in the example\) or the original AWS CloudFormation template object via `includedTemplate`, from which you can load resources and other AWS CloudFormation elements\. \ No newline at end of file +The `getNestedStack()` method returns an [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.IncludedNestedStack.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_cloudformation-include.IncludedNestedStack.html) instance, from which you can access the AWS CDK [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.NestedStack.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.NestedStack.html) instance via the `stack` property \(as shown in the example\) or the original AWS CloudFormation template object via `includedTemplate`, from which you can load resources and other AWS CloudFormation elements\. \ No newline at end of file diff --git a/doc_source/videos.md b/v1/videos.md similarity index 89% rename from doc_source/videos.md rename to v1/videos.md index e986b2fc..795a00db 100644 --- a/doc_source/videos.md +++ b/v1/videos.md @@ -3,7 +3,7 @@ Enjoy these videos presented by members of the AWS CDK team\. **Note** -Since the AWS CDK is always evolving, some of the code presented in these videos may not work quite the same way it did when the video was recorded\. This is especially true for modules that were under active development at the time\. It's also possible that we've since added a better way to achieve the same result\. Consult this Developer Guide and the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) for up\-to\-date information\. +Since the AWS CDK is always evolving, some of the code presented in these videos may not work quite the same way it did when the video was recorded\. This is especially true for modules that were under active development at the time\. It's also possible that we've since added a better way to achieve the same result\. Consult this Developer Guide and the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) for up\-to\-date information\. ## Infrastructure *is* Code with the AWS CDK diff --git a/doc_source/vscode.md b/v1/vscode.md similarity index 100% rename from doc_source/vscode.md rename to v1/vscode.md diff --git a/doc_source/work-with-cdk-csharp.md b/v1/work-with-cdk-csharp.md similarity index 94% rename from doc_source/work-with-cdk-csharp.md rename to v1/work-with-cdk-csharp.md index 7eacbcd6..e232c77f 100644 --- a/doc_source/work-with-cdk-csharp.md +++ b/v1/work-with-cdk-csharp.md @@ -33,7 +33,7 @@ The resulting project includes a reference to the `Amazon.CDK` NuGet package\. I The \.NET ecosystem uses the NuGet package manager\. AWS Construct Library modules are named like `Amazon.CDK.AWS.SERVICE-NAME` where the service name is a short name without an AWS or Amazon prefix\. For example, the NuGet package name for the Amazon S3 module is `Amazon.CDK.AWS.S3`\. If you can't find a package you want, [search Nuget\.org](https://www.nuget.org/packages?q=amazon.cdk.aws)\. **Note** -The [\.NET edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/dotnet/api/index.html) also shows the package names\. +The [\.NET edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/v1/dotnet/api/index.html) also shows the package names\. Some services' AWS Construct Library support is in more than one module\. For example, Amazon Route 53 has the three modules in addition to the main `Amazon.CDK.AWS.Route53` module, named `Route53.Patterns`, `Route53.Resolver`, and `Route53.Targets`\. @@ -53,7 +53,7 @@ Visual Studio's NuGet tools are accessible from **Tools** > **NuGet Package Mana **Note** All AWS Construct Library modules deemed "experimental" \(see [Versioning](reference.md#versioning)\) are flagged as pre\-release in NuGet\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/latest/guide/images/visual-studio-nuget.png) +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v1/guide/images/visual-studio-nuget.png) Look on the **Updates** page to install new versions of your packages\. @@ -138,7 +138,7 @@ A future release of the AWS CDK could coincidentally add a new property with a n ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In C\#, these objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` in C\#\. +In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In C\#, these objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` in C\#\. ### Missing values diff --git a/doc_source/work-with-cdk-go.md b/v1/work-with-cdk-go.md similarity index 96% rename from doc_source/work-with-cdk-go.md rename to v1/work-with-cdk-go.md index 9cbea934..b6f38a38 100644 --- a/doc_source/work-with-cdk-go.md +++ b/v1/work-with-cdk-go.md @@ -79,7 +79,7 @@ var bucket = awss3.NewBucket(stack, jsii.String("MyBucket"), &awss3.BucketProps{ ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Go, these objects are represented as slices and an empty interface, respectively\. +In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Go, these objects are represented as slices and an empty interface, respectively\. The CDK provides variadic helper functions such as `jsii.Strings` for building slices containing primitive types\. diff --git a/doc_source/work-with-cdk-java.md b/v1/work-with-cdk-java.md similarity index 95% rename from doc_source/work-with-cdk-java.md rename to v1/work-with-cdk-java.md index f993a3db..1747189e 100644 --- a/doc_source/work-with-cdk-java.md +++ b/v1/work-with-cdk-java.md @@ -33,7 +33,7 @@ If you are using an IDE, you can now open or import the project\. In Eclipse, fo Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk` and named with a short version \(no AWS or Amazon prefix\) of their service's name\. For example, the Maven artifact ID for Amazon S3 is `s3`\. [Search the Maven Central Repository](https://search.maven.org/search?q=sg:oftware.amazon.awscdk) to find the names of all AWS CDK and AWS Construct Module libraries\. **Note** -The [Java edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/java/index.html) also shows the package names\. +The [Java edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/v1/java/index.html) also shows the package names\. Some services' AWS Construct Library support is in more than one module\. For example, Amazon Route 53 has the three modules in addition to the main `software.amazon.awscdk.route53` module, named `route53-patterns`, `route53resolver`, and `route53-targets`\. @@ -95,7 +95,7 @@ When deriving your own construct from an existing construct, you may want to acc ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Java, these objects are represented as `java.util.Map`\. In cases where the values are all strings, you can use `Map`\. It is convenient to use double braces to define `HashMap`s\. +In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Java, these objects are represented as `java.util.Map`\. In cases where the values are all strings, you can use `Map`\. It is convenient to use double braces to define `HashMap`s\. ``` new HashMap() {{ diff --git a/doc_source/work-with-cdk-javascript.md b/v1/work-with-cdk-javascript.md similarity index 98% rename from doc_source/work-with-cdk-javascript.md rename to v1/work-with-cdk-javascript.md index 13fa8db7..b669e9f9 100644 --- a/doc_source/work-with-cdk-javascript.md +++ b/v1/work-with-cdk-javascript.md @@ -20,7 +20,7 @@ cd my-project cdk init app --language javascript ``` -Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html](https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html) module and its dependencies\. +Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/v1/docs/core-readme.html](https://docs.aws.amazon.com/cdk/api/v1/docs/core-readme.html) module and its dependencies\. `cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. @@ -59,7 +59,7 @@ Use the Node Package Manager \(`npm`\) to install and update AWS Construct Libra The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an *aws\-* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. **Note** -The [CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) also shows the package names\. +The [CDK API Reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) also shows the package names\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. diff --git a/doc_source/work-with-cdk-python.md b/v1/work-with-cdk-python.md similarity index 99% rename from doc_source/work-with-cdk-python.md rename to v1/work-with-cdk-python.md index f61b0856..dfce4439 100644 --- a/doc_source/work-with-cdk-python.md +++ b/v1/work-with-cdk-python.md @@ -71,7 +71,7 @@ python -m pip install aws-cdk.aws-s3 aws-cdk.aws-lambda Some services' Construct Library support is in more than one module\. For example, besides the `aws-cdk.aws-route53` module, there are three additional Amazon Route 53 modules, named `aws-route53-targets`, `aws-route53-patterns`, and `aws-route53resolver`\. **Note** -The [Python edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/python/index.html) also shows the package names\. +The [Python edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/v1/python/index.html) also shows the package names\. The names used for importing AWS Construct Library modules into your Python code are similar to their package names\. Simply replace the hyphens with underscores\. diff --git a/doc_source/work-with-cdk-typescript.md b/v1/work-with-cdk-typescript.md similarity index 92% rename from doc_source/work-with-cdk-typescript.md rename to v1/work-with-cdk-typescript.md index 371cc824..696f22b6 100644 --- a/doc_source/work-with-cdk-typescript.md +++ b/v1/work-with-cdk-typescript.md @@ -29,7 +29,7 @@ cd my-project cdk init app --language typescript ``` -Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html](https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html) module and its dependencies\. +Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/v1/docs/core-readme.html](https://docs.aws.amazon.com/cdk/api/v1/docs/core-readme.html) module and its dependencies\. `cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. @@ -70,7 +70,7 @@ Use the Node Package Manager \(`npm`\) to install and update AWS Construct Libra The AWS CDK core module is named `@aws-cdk/core`\. AWS Construct Library modules are named like `@aws-cdk/SERVICE-NAME`\. The service name has an *aws* prefix\. If you're unsure of a module's name, [search for it on NPM](https://www.npmjs.com/search?q=%40aws-cdk)\. **Note** -The [CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) also shows the package names\. +The [CDK API Reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) also shows the package names\. For example, the command below installs the modules for Amazon S3 and AWS Lambda\. @@ -113,9 +113,9 @@ All AWS Construct Library modules used in your project must be the same version\ All AWS Construct Library classes are instantiated using three arguments: the *scope* in which the construct is being defined \(its parent in the construct tree\), an *id*, and *props*, a bundle of key/value pairs that the construct uses to configure the AWS resources it creates\. Other classes and methods also use the "bundle of attributes" pattern for arguments\. -In TypeScript, the shape of `props` is defined using an interface that tells you the required and optional arguments and their types\. Such an interface is defined for each kind of `props` argument, usually specific to a single construct or method\. For example, the [Bucket](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html) construct \(in the `@aws-cdk/aws-s3 module`\) specifies a `props` argument conforming to the [BucketProps](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.BucketProps.html) interface\. +In TypeScript, the shape of `props` is defined using an interface that tells you the required and optional arguments and their types\. Such an interface is defined for each kind of `props` argument, usually specific to a single construct or method\. For example, the [Bucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html) construct \(in the `@aws-cdk/aws-s3 module`\) specifies a `props` argument conforming to the [BucketProps](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.BucketProps.html) interface\. -If a property is itself an object, for example the [websiteRedirect](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.BucketProps.html#websiteredirect) property of `BucketProps`, that object will have its own interface to which its shape must conform, in this case [RedirectTarget](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.RedirectTarget.html)\. +If a property is itself an object, for example the [websiteRedirect](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.BucketProps.html#websiteredirect) property of `BucketProps`, that object will have its own interface to which its shape must conform, in this case [RedirectTarget](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.RedirectTarget.html)\. If you are subclassing an AWS Construct Library class \(or overriding a method that takes a props\-like argument\), you can inherit from the existing interface to create a new one that specifies any new props your code requires\. When calling the parent class or base method, generally you can pass the entire props argument you received, since any attributes provided in the object but not specified in the interface will be ignored\. diff --git a/doc_source/work-with-cdk-v2.md b/v1/work-with-cdk-v2.md similarity index 100% rename from doc_source/work-with-cdk-v2.md rename to v1/work-with-cdk-v2.md diff --git a/doc_source/work-with.md b/v1/work-with.md similarity index 96% rename from doc_source/work-with.md rename to v1/work-with.md index 906b3d1d..477c555b 100644 --- a/doc_source/work-with.md +++ b/v1/work-with.md @@ -45,7 +45,7 @@ The specific language you work in also has its own prerequisites, described in t ## AWS Construct Library -The AWS CDK includes the AWS Construct Library, a collection of construct modules organized by AWS service\. The [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html) provides detailed documentation of the constructs \(and other components\) in the library\. A version of the API Reference is provided for each supported programming language\. +The AWS CDK includes the AWS Construct Library, a collection of construct modules organized by AWS service\. The [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) provides detailed documentation of the constructs \(and other components\) in the library\. A version of the API Reference is provided for each supported programming language\. Each module's reference material is broken into the following sections\. + *Overview*: Introductory material you'll need to know to work with the service in the AWS CDK, including concepts and examples\. diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index 10c60e74..094f2d38 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -419,7 +419,7 @@ DefaultStackSynthesizer( # ARN of the role passed to CloudFormation to execute the deployments cloud_formation_execution_role="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" - + # Name of the SSM parameter which describes the bootstrap stack version number bootstrap_stack_version_ssm_parameter="/cdk-bootstrap/${Qualifier}/version", @@ -554,4 +554,4 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 6 | 1\.108\.0 | Add lookup role separate from deployment role\. | | 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | -| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | +| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | \ No newline at end of file From 73bb608270f842bc34082e7185fd1832293a58d2 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 22 Dec 2021 19:58:53 +0000 Subject: [PATCH 486/655] recent doc changes --- v1/best-practices.md | 16 ++++++++++------ v1/cli.md | 6 ++++-- v1/constructs.md | 7 +++++-- v1/context.md | 16 +++++++++++++--- v1/work-with-cdk-java.md | 2 +- v2/best-practices.md | 16 ++++++++++------ v2/cli.md | 6 ++++-- v2/constructs.md | 7 +++++-- v2/context.md | 16 +++++++++++++--- v2/work-with-cdk-java.md | 2 +- 10 files changed, 66 insertions(+), 28 deletions(-) diff --git a/v1/best-practices.md b/v1/best-practices.md index 84700e33..e96964cc 100644 --- a/v1/best-practices.md +++ b/v1/best-practices.md @@ -31,7 +31,7 @@ Development teams should be able use their own accounts for testing and have the ## Coding best practices - This section presents best practices for organizing your AWS CDK code\. The diagram below shows the relationship between a team and that team's code repositories, packages, applications, and construct libraries\. +This section presents best practices for organizing your AWS CDK code\. The diagram below shows the relationship between a team and that team's code repositories, packages, applications, and construct libraries\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v1/guide/images/code-organization.jpg) @@ -75,11 +75,15 @@ A construct that is self\-contained, in other words that completely describes a ## Construct best practices - This section contains best practices for developing constructs\. Constructs are reusable, composable modules that encapsulate resources, and the building blocks of AWS CDK apps\. +This section contains best practices for developing constructs\. Constructs are reusable, composable modules that encapsulate resources, and the building blocks of AWS CDK apps\. -### Model your app through constructs, not stacks +### Model with constructs, deploy with stacks -When breaking down your application into logical units, represent each unit as a descendant of [https://docs.aws.amazon.com/cdk/api/v1/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v1/docs/constructs.Construct.html) and not of [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html)\. Stacks are a unit of deployment, and so tend to be oriented to specific applications\. By using constructs instead of stacks, you give yourself and your users the flexibility to build stacks in the way that makes the most sense for each deployment scenario\. For example, you could compose multiple constructs into a `DevStack` with some configuration for development environments and then have a different composition for your `ProdStack`\. +Stacks are the unit of deployment: everything in a stack is deployed together\. So when building your application's higher\-level logical units from multiple AWS resources, represent each logical unit as a [https://docs.aws.amazon.com/cdk/api/v1/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v1/docs/constructs.Construct.html), not as a [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html)\. Use stacks only to describe how your constructs should be composed and connected for your various deployment scenarios\. + +If one of your logical units is a Web site, for example, the constructs that make it up \(Amazon S3 bucket, API Gateway, Lambda functions, Amazon RDS tables, etc\.\) should be composed into a single high\-level construct, and then that construct should be instantiated in one or more stacks for deployment\. + +By using constructs for building and stacks for deploying, you improve reuse potential of your infrastructure and give yourself more flexibility in how it is deployed\. ### Configure with properties and methods, not environment variables @@ -172,9 +176,9 @@ If you require developers to always use predefined roles that were created by a ### Model all production stages in code - In traditional AWS CloudFormation scenarios, your goal is to produce a single artifact that is parameterized so that it can be deployed to various target environments after applying configuration values specific to those environments\. In the CDK, you can, and should, build that configuration right into your source code\. Create a stack for your production environment, and a separate one for each of your other stages, and put the configuration values for each right there in the code\. Use services like [Secrets Manager](https://aws.amazon.com/secrets-manager/) and [Systems Manager](https://aws.amazon.com/systems-manager/) Parameter Store for sensitive values that you don't want to check in to source control, using the names or ARNs of those resources\. +In traditional AWS CloudFormation scenarios, your goal is to produce a single artifact that is parameterized so that it can be deployed to various target environments after applying configuration values specific to those environments\. In the CDK, you can, and should, build that configuration right into your source code\. Create a stack for your production environment, and a separate one for each of your other stages, and put the configuration values for each right there in the code\. Use services like [Secrets Manager](https://aws.amazon.com/secrets-manager/) and [Systems Manager](https://aws.amazon.com/systems-manager/) Parameter Store for sensitive values that you don't want to check in to source control, using the names or ARNs of those resources\. - When you synthesize your application, the cloud assembly created in the `cdk.out` folder contains a separate template for each environment\. Your entire build is deterministic: there are no out\-of\-band changes to your application, and any given commit always yields the exact same AWS CloudFormation template and accompanying assets, which makes unit testing much more reliable\. +When you synthesize your application, the cloud assembly created in the `cdk.out` folder contains a separate template for each environment\. Your entire build is deterministic: there are no out\-of\-band changes to your application, and any given commit always yields the exact same AWS CloudFormation template and accompanying assets, which makes unit testing much more reliable\. ### Measure everything diff --git a/v1/cli.md b/v1/cli.md index f4d3fc58..5d52e798 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -728,8 +728,10 @@ Options: permissions, modern bootstrapping only) [boolean] - --qualifier Unique string to distinguish - multiple bootstrap stacks [string] + --qualifier String which must be unique for each + bootstrap stack. You must configure + it on your CDK app if you change + this from the default. [string] --public-access-block-configuration Block public access configuration on CDK toolkit bucket (enabled by diff --git a/v1/constructs.md b/v1/constructs.md index 10ad8a64..8762b924 100644 --- a/v1/constructs.md +++ b/v1/constructs.md @@ -19,7 +19,7 @@ There are three different levels of constructs in this library, beginning with l The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#add-wbr-lifecycle-wbr-rulerule), which adds a lifecycle rule to the bucket\. -Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs-patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. +Finally, the AWS Construct Library includes L3 constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs-patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. For more information about how to navigate the library and discover constructs that can help you build your apps, see the [API Reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html)\. @@ -746,6 +746,9 @@ public class NotifyingBucket : Construct ------ +**Note** +Our `NotifyingBucket` construct inherits not from `Bucket` but rather from `Construct`\. We are using composition, not inheritance, to bundle an Amazon S3 bucket and an Amazon SNS topic together\. In general, composition is preferred over inheritance when developing AWS CDK constructs\. + The `NotifyingBucket` constructor has a typical construct signature: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. \(The base `Construct` class does not take a `props`argument\.\) You could define an instance of this construct in your app without `props`, for example: ------ @@ -880,7 +883,7 @@ class NotifyingBucket(core.Construct): #### [ Java ] ``` -public class NotifyingBucket extends Bucket { +public class NotifyingBucket extends Construct { public Topic topic = null; diff --git a/v1/context.md b/v1/context.md index 1c86688a..b68fe94a 100644 --- a/v1/context.md +++ b/v1/context.md @@ -1,11 +1,21 @@ # Runtime context -Context values are key\-value pairs that can be associated with a stack or construct\. The AWS CDK uses context to cache information from your AWS account, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs used to start your instances\. [Feature flags](featureflags.md) are also context values\. You can create your own context values for use by your apps or constructs\. +Context values are key\-value pairs that can be associated with an app, stack, or construct\. The AWS CDK uses context to cache information from your AWS account, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs used to start your instances\. [Feature flags](featureflags.md) are also context values\. You can create your own context values for use by your apps or constructs\. Context keys are strings, and values may be any type supported by JSON: numbers, strings, arrays, or objects\. +If your constructs create their own context values, incorporate your library's package name in its keys so they won't conflict with other package's context values\. + +Since most context values are associated with a particular AWS environment, and a given CDK app can be deployed in more than one environment, it is important to be able to set context values for each environment\. This is achieved by including the AWS account and region in the context key, so that values from different environments do not conflict\. + +The context key below illustrates the format used by the AWS CDK, including the account and region\. + +``` +availability-zones:account=123456789012:region=eu-central-1 +``` + **Important** -Context values are managed by the AWS CDK and its constructs, including constructs you may write\. You should not attempt to add context values manually\. It is useful to review `cdk.context.json` to see what values are being cached; by convention, the keys start with the name of the CDK package that set them\. You should follow this convention when setting your own values\. +Context values are managed by the AWS CDK and its constructs, including constructs you may write\. In general, you should not add or change context values by manually editing files\. It can be useful to review `cdk.context.json` to see what values are being cached\. ## Construct context @@ -19,7 +29,7 @@ Context values can be provided to your AWS CDK app in six different ways: The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, changing your Auto Scaling group\. The AWS CDK does not write context data to any of the other files listed\. -We recommend that your project's context files be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. It is also critical to successful automated deployment of stacks that rely on context values \(for example, using [CDK Pipelines](cdk_pipeline.md)\)\. +We recommend that `cdk.context.json` be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. It is also critical to successful automated deployment of stacks that rely on context values \(for example, using [CDK Pipelines](cdk_pipeline.md)\)\. Context values are scoped to the construct that created them; they are visible to child constructs, but not to siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), whether automatically, from a file, or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in the app\. diff --git a/v1/work-with-cdk-java.md b/v1/work-with-cdk-java.md index 1747189e..25db10e7 100644 --- a/v1/work-with-cdk-java.md +++ b/v1/work-with-cdk-java.md @@ -30,7 +30,7 @@ If you are using an IDE, you can now open or import the project\. In Eclipse, fo ## Managing AWS Construct Library modules -Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk` and named with a short version \(no AWS or Amazon prefix\) of their service's name\. For example, the Maven artifact ID for Amazon S3 is `s3`\. [Search the Maven Central Repository](https://search.maven.org/search?q=sg:oftware.amazon.awscdk) to find the names of all AWS CDK and AWS Construct Module libraries\. +Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk` and named with a short version \(no AWS or Amazon prefix\) of their service's name\. For example, the Maven artifact ID for Amazon S3 is `s3`\. [Search the Maven Central Repository](https://search.maven.org/search?q=software.amazon.awscdk) to find the names of all AWS CDK and AWS Construct Module libraries\. **Note** The [Java edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/v1/java/index.html) also shows the package names\. diff --git a/v2/best-practices.md b/v2/best-practices.md index 5a001455..dbe776f7 100644 --- a/v2/best-practices.md +++ b/v2/best-practices.md @@ -31,7 +31,7 @@ Development teams should be able use their own accounts for testing and have the ## Coding best practices - This section presents best practices for organizing your AWS CDK code\. The diagram below shows the relationship between a team and that team's code repositories, packages, applications, and construct libraries\. +This section presents best practices for organizing your AWS CDK code\. The diagram below shows the relationship between a team and that team's code repositories, packages, applications, and construct libraries\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/code-organization.jpg) @@ -75,11 +75,15 @@ A construct that is self\-contained, in other words that completely describes a ## Construct best practices - This section contains best practices for developing constructs\. Constructs are reusable, composable modules that encapsulate resources, and the building blocks of AWS CDK apps\. +This section contains best practices for developing constructs\. Constructs are reusable, composable modules that encapsulate resources, and the building blocks of AWS CDK apps\. -### Model your app through constructs, not stacks +### Model with constructs, deploy with stacks -When breaking down your application into logical units, represent each unit as a descendant of [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) and not of [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html)\. Stacks are a unit of deployment, and so tend to be oriented to specific applications\. By using constructs instead of stacks, you give yourself and your users the flexibility to build stacks in the way that makes the most sense for each deployment scenario\. For example, you could compose multiple constructs into a `DevStack` with some configuration for development environments and then have a different composition for your `ProdStack`\. +Stacks are the unit of deployment: everything in a stack is deployed together\. So when building your application's higher\-level logical units from multiple AWS resources, represent each logical unit as a [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html), not as a [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html)\. Use stacks only to describe how your constructs should be composed and connected for your various deployment scenarios\. + +If one of your logical units is a Web site, for example, the constructs that make it up \(Amazon S3 bucket, API Gateway, Lambda functions, Amazon RDS tables, etc\.\) should be composed into a single high\-level construct, and then that construct should be instantiated in one or more stacks for deployment\. + +By using constructs for building and stacks for deploying, you improve reuse potential of your infrastructure and give yourself more flexibility in how it is deployed\. ### Configure with properties and methods, not environment variables @@ -172,9 +176,9 @@ If you require developers to always use predefined roles that were created by a ### Model all production stages in code - In traditional AWS CloudFormation scenarios, your goal is to produce a single artifact that is parameterized so that it can be deployed to various target environments after applying configuration values specific to those environments\. In the CDK, you can, and should, build that configuration right into your source code\. Create a stack for your production environment, and a separate one for each of your other stages, and put the configuration values for each right there in the code\. Use services like [Secrets Manager](https://aws.amazon.com/secrets-manager/) and [Systems Manager](https://aws.amazon.com/systems-manager/) Parameter Store for sensitive values that you don't want to check in to source control, using the names or ARNs of those resources\. +In traditional AWS CloudFormation scenarios, your goal is to produce a single artifact that is parameterized so that it can be deployed to various target environments after applying configuration values specific to those environments\. In the CDK, you can, and should, build that configuration right into your source code\. Create a stack for your production environment, and a separate one for each of your other stages, and put the configuration values for each right there in the code\. Use services like [Secrets Manager](https://aws.amazon.com/secrets-manager/) and [Systems Manager](https://aws.amazon.com/systems-manager/) Parameter Store for sensitive values that you don't want to check in to source control, using the names or ARNs of those resources\. - When you synthesize your application, the cloud assembly created in the `cdk.out` folder contains a separate template for each environment\. Your entire build is deterministic: there are no out\-of\-band changes to your application, and any given commit always yields the exact same AWS CloudFormation template and accompanying assets, which makes unit testing much more reliable\. +When you synthesize your application, the cloud assembly created in the `cdk.out` folder contains a separate template for each environment\. Your entire build is deterministic: there are no out\-of\-band changes to your application, and any given commit always yields the exact same AWS CloudFormation template and accompanying assets, which makes unit testing much more reliable\. ### Measure everything diff --git a/v2/cli.md b/v2/cli.md index d914e6b3..53f28544 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -720,8 +720,10 @@ Options: permissions, modern bootstrapping only) [boolean] - --qualifier Unique string to distinguish - multiple bootstrap stacks [string] + --qualifier String which must be unique for each + bootstrap stack. You must configure + it on your CDK app if you change + this from the default. [string] --public-access-block-configuration Block public access configuration on CDK toolkit bucket (enabled by diff --git a/v2/constructs.md b/v2/constructs.md index a937d72e..ea97c474 100644 --- a/v2/constructs.md +++ b/v2/constructs.md @@ -22,7 +22,7 @@ There are three different levels of constructs in this library, beginning with l The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#addwbrlifecyclewbrrulerule), which adds a lifecycle rule to the bucket\. -Finally, the AWS Construct Library includes even higher\-level constructs, which we call *patterns* or L3\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. +Finally, the AWS Construct Library includes L3 constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. For more information about how to navigate the library and discover constructs that can help you build your apps, see the [API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html)\. @@ -750,6 +750,9 @@ public class NotifyingBucket : Construct ------ +**Note** +Our `NotifyingBucket` construct inherits not from `Bucket` but rather from `Construct`\. We are using composition, not inheritance, to bundle an Amazon S3 bucket and an Amazon SNS topic together\. In general, composition is preferred over inheritance when developing AWS CDK constructs\. + The `NotifyingBucket` constructor has a typical construct signature: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. \(The base `Construct` class does not take a `props`argument\.\) You could define an instance of this construct in your app without `props`, for example: ------ @@ -884,7 +887,7 @@ class NotifyingBucket(Construct): #### [ Java ] ``` -public class NotifyingBucket extends Bucket { +public class NotifyingBucket extends Construct { public Topic topic = null; diff --git a/v2/context.md b/v2/context.md index acb7e2f8..77b471aa 100644 --- a/v2/context.md +++ b/v2/context.md @@ -1,11 +1,21 @@ # Runtime context -Context values are key\-value pairs that can be associated with a stack or construct\. The AWS CDK uses context to cache information from your AWS account, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs used to start your instances\. [Feature flags](featureflags.md) are also context values\. You can create your own context values for use by your apps or constructs\. +Context values are key\-value pairs that can be associated with an app, stack, or construct\. The AWS CDK uses context to cache information from your AWS account, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs used to start your instances\. [Feature flags](featureflags.md) are also context values\. You can create your own context values for use by your apps or constructs\. Context keys are strings, and values may be any type supported by JSON: numbers, strings, arrays, or objects\. +If your constructs create their own context values, incorporate your library's package name in its keys so they won't conflict with other package's context values\. + +Since most context values are associated with a particular AWS environment, and a given CDK app can be deployed in more than one environment, it is important to be able to set context values for each environment\. This is achieved by including the AWS account and region in the context key, so that values from different environments do not conflict\. + +The context key below illustrates the format used by the AWS CDK, including the account and region\. + +``` +availability-zones:account=123456789012:region=eu-central-1 +``` + **Important** -Context values are managed by the AWS CDK and its constructs, including constructs you may write\. You should not attempt to add context values manually\. It is useful to review `cdk.context.json` to see what values are being cached; by convention, the keys start with the name of the CDK package that set them\. You should follow this convention when setting your own values\. +Context values are managed by the AWS CDK and its constructs, including constructs you may write\. In general, you should not add or change context values by manually editing files\. It can be useful to review `cdk.context.json` to see what values are being cached\. ## Construct context @@ -19,7 +29,7 @@ Context values can be provided to your AWS CDK app in six different ways: The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, changing your Auto Scaling group\. The AWS CDK does not write context data to any of the other files listed\. -We recommend that your project's context files be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. It is also critical to successful automated deployment of stacks that rely on context values \(for example, using [CDK Pipelines](cdk_pipeline.md)\)\. +We recommend that `cdk.context.json` be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. It is also critical to successful automated deployment of stacks that rely on context values \(for example, using [CDK Pipelines](cdk_pipeline.md)\)\. Context values are scoped to the construct that created them; they are visible to child constructs, but not to siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), whether automatically, from a file, or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in the app\. diff --git a/v2/work-with-cdk-java.md b/v2/work-with-cdk-java.md index 418845c3..a1155a8e 100644 --- a/v2/work-with-cdk-java.md +++ b/v2/work-with-cdk-java.md @@ -30,7 +30,7 @@ If you are using an IDE, you can now open or import the project\. In Eclipse, fo ## Managing AWS Construct Library modules -Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk`\. Most constructs are in the artifact `aws-cdk-lib`\. Modules for services whose higher\-level CDK support is still being developed are in separate "experimental" packages, named with a short version \(no AWS or Amazon prefix\) of their service's name\. [Search the Maven Central Repository](https://search.maven.org/search?q=sg:oftware.amazon.awscdk) to find the names of all AWS CDK and AWS Construct Module libraries\. +Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk`\. Most constructs are in the artifact `aws-cdk-lib`\. Modules for services whose higher\-level CDK support is still being developed are in separate "experimental" packages, named with a short version \(no AWS or Amazon prefix\) of their service's name\. [Search the Maven Central Repository](https://search.maven.org/search?q=software.amazon.awscdk) to find the names of all AWS CDK and AWS Construct Module libraries\. **Note** The [Java edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/java/index.html) also shows the package names\. From 04bb13fd9da5123ead976c43097145eb776eb522 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 27 Jan 2022 19:19:58 +0000 Subject: [PATCH 487/655] recent changes --- doc_source/my_ecs_construct-stack.yaml | 515 +++++++++++++++++++++++++ v1/aspects.md | 10 +- v1/constructs.md | 2 +- v1/tagging.md | 14 +- v1/work-with-cdk-csharp.md | 10 +- v1/work-with-cdk-java.md | 26 +- v2/aspects.md | 10 +- v2/constructs.md | 2 +- v2/tagging.md | 14 +- v2/work-with-cdk-csharp.md | 10 +- v2/work-with-cdk-java.md | 26 +- 11 files changed, 597 insertions(+), 42 deletions(-) create mode 100644 doc_source/my_ecs_construct-stack.yaml diff --git a/doc_source/my_ecs_construct-stack.yaml b/doc_source/my_ecs_construct-stack.yaml new file mode 100644 index 00000000..29d6b889 --- /dev/null +++ b/doc_source/my_ecs_construct-stack.yaml @@ -0,0 +1,515 @@ +Resources: + MyVpcF9F0CA6F: + Type: AWS::EC2::VPC + Properties: + CidrBlock: 10.0.0.0/16 + EnableDnsHostnames: true + EnableDnsSupport: true + InstanceTenancy: default + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/Resource + MyVpcPublicSubnet1SubnetF6608456: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: 10.0.0.0/18 + VpcId: + Ref: MyVpcF9F0CA6F + AvailabilityZone: + Fn::Select: + - 0 + - Fn::GetAZs: "" + MapPublicIpOnLaunch: true + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet1 + - Key: aws-cdk:subnet-name + Value: Public + - Key: aws-cdk:subnet-type + Value: Public + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/Subnet + MyVpcPublicSubnet1RouteTableC46AB2F4: + Type: AWS::EC2::RouteTable + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet1 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/RouteTable + MyVpcPublicSubnet1RouteTableAssociation2ECEE1CB: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: + Ref: MyVpcPublicSubnet1RouteTableC46AB2F4 + SubnetId: + Ref: MyVpcPublicSubnet1SubnetF6608456 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/RouteTableAssociation + MyVpcPublicSubnet1DefaultRoute95FDF9EB: + Type: AWS::EC2::Route + Properties: + RouteTableId: + Ref: MyVpcPublicSubnet1RouteTableC46AB2F4 + DestinationCidrBlock: 0.0.0.0/0 + GatewayId: + Ref: MyVpcIGW5C4A4F63 + DependsOn: + - MyVpcVPCGW488ACE0D + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/DefaultRoute + MyVpcPublicSubnet1EIP096967CB: + Type: AWS::EC2::EIP + Properties: + Domain: vpc + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/EIP + MyVpcPublicSubnet1NATGatewayAD3400C1: + Type: AWS::EC2::NatGateway + Properties: + AllocationId: + Fn::GetAtt: + - MyVpcPublicSubnet1EIP096967CB + - AllocationId + SubnetId: + Ref: MyVpcPublicSubnet1SubnetF6608456 + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet1 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet1/NATGateway + MyVpcPublicSubnet2Subnet492B6BFB: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: 10.0.64.0/18 + VpcId: + Ref: MyVpcF9F0CA6F + AvailabilityZone: + Fn::Select: + - 1 + - Fn::GetAZs: "" + MapPublicIpOnLaunch: true + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet2 + - Key: aws-cdk:subnet-name + Value: Public + - Key: aws-cdk:subnet-type + Value: Public + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/Subnet + MyVpcPublicSubnet2RouteTable1DF17386: + Type: AWS::EC2::RouteTable + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet2 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/RouteTable + MyVpcPublicSubnet2RouteTableAssociation227DE78D: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: + Ref: MyVpcPublicSubnet2RouteTable1DF17386 + SubnetId: + Ref: MyVpcPublicSubnet2Subnet492B6BFB + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/RouteTableAssociation + MyVpcPublicSubnet2DefaultRoute052936F6: + Type: AWS::EC2::Route + Properties: + RouteTableId: + Ref: MyVpcPublicSubnet2RouteTable1DF17386 + DestinationCidrBlock: 0.0.0.0/0 + GatewayId: + Ref: MyVpcIGW5C4A4F63 + DependsOn: + - MyVpcVPCGW488ACE0D + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/DefaultRoute + MyVpcPublicSubnet2EIP8CCBA239: + Type: AWS::EC2::EIP + Properties: + Domain: vpc + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/EIP + MyVpcPublicSubnet2NATGateway91BFBEC9: + Type: AWS::EC2::NatGateway + Properties: + AllocationId: + Fn::GetAtt: + - MyVpcPublicSubnet2EIP8CCBA239 + - AllocationId + SubnetId: + Ref: MyVpcPublicSubnet2Subnet492B6BFB + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PublicSubnet2 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PublicSubnet2/NATGateway + MyVpcPrivateSubnet1Subnet5057CF7E: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: 10.0.128.0/18 + VpcId: + Ref: MyVpcF9F0CA6F + AvailabilityZone: + Fn::Select: + - 0 + - Fn::GetAZs: "" + MapPublicIpOnLaunch: false + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PrivateSubnet1 + - Key: aws-cdk:subnet-name + Value: Private + - Key: aws-cdk:subnet-type + Value: Private + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/Subnet + MyVpcPrivateSubnet1RouteTable8819E6E2: + Type: AWS::EC2::RouteTable + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PrivateSubnet1 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/RouteTable + MyVpcPrivateSubnet1RouteTableAssociation56D38C7E: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: + Ref: MyVpcPrivateSubnet1RouteTable8819E6E2 + SubnetId: + Ref: MyVpcPrivateSubnet1Subnet5057CF7E + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/RouteTableAssociation + MyVpcPrivateSubnet1DefaultRouteA8CDE2FA: + Type: AWS::EC2::Route + Properties: + RouteTableId: + Ref: MyVpcPrivateSubnet1RouteTable8819E6E2 + DestinationCidrBlock: 0.0.0.0/0 + NatGatewayId: + Ref: MyVpcPublicSubnet1NATGatewayAD3400C1 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet1/DefaultRoute + MyVpcPrivateSubnet2Subnet0040C983: + Type: AWS::EC2::Subnet + Properties: + CidrBlock: 10.0.192.0/18 + VpcId: + Ref: MyVpcF9F0CA6F + AvailabilityZone: + Fn::Select: + - 1 + - Fn::GetAZs: "" + MapPublicIpOnLaunch: false + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PrivateSubnet2 + - Key: aws-cdk:subnet-name + Value: Private + - Key: aws-cdk:subnet-type + Value: Private + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/Subnet + MyVpcPrivateSubnet2RouteTableCEDCEECE: + Type: AWS::EC2::RouteTable + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc/PrivateSubnet2 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/RouteTable + MyVpcPrivateSubnet2RouteTableAssociation86A610DA: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: + Ref: MyVpcPrivateSubnet2RouteTableCEDCEECE + SubnetId: + Ref: MyVpcPrivateSubnet2Subnet0040C983 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/RouteTableAssociation + MyVpcPrivateSubnet2DefaultRoute9CE96294: + Type: AWS::EC2::Route + Properties: + RouteTableId: + Ref: MyVpcPrivateSubnet2RouteTableCEDCEECE + DestinationCidrBlock: 0.0.0.0/0 + NatGatewayId: + Ref: MyVpcPublicSubnet2NATGateway91BFBEC9 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/PrivateSubnet2/DefaultRoute + MyVpcIGW5C4A4F63: + Type: AWS::EC2::InternetGateway + Properties: + Tags: + - Key: Name + Value: MyEcsConstruct/MyVpc + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/IGW + MyVpcVPCGW488ACE0D: + Type: AWS::EC2::VPCGatewayAttachment + Properties: + VpcId: + Ref: MyVpcF9F0CA6F + InternetGatewayId: + Ref: MyVpcIGW5C4A4F63 + Metadata: + aws:cdk:path: MyEcsConstruct/MyVpc/VPCGW + MyCluster4C1BA579: + Type: AWS::ECS::Cluster + Metadata: + aws:cdk:path: MyEcsConstruct/MyCluster/Resource + MyFargateServiceLBDE830E97: + Type: AWS::ElasticLoadBalancingV2::LoadBalancer + Properties: + LoadBalancerAttributes: [] + Scheme: internet-facing + SecurityGroups: + - Fn::GetAtt: + - MyFargateServiceLBSecurityGroup6FBF16F1 + - GroupId + Subnets: + - Ref: MyVpcPublicSubnet1SubnetF6608456 + - Ref: MyVpcPublicSubnet2Subnet492B6BFB + Type: application + DependsOn: + - MyVpcPublicSubnet1DefaultRoute95FDF9EB + - MyVpcPublicSubnet2DefaultRoute052936F6 + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/LB/Resource + MyFargateServiceLBSecurityGroup6FBF16F1: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: Automatically created Security Group for ELB MyEcsConstructMyFargateServiceLB5E4E9AE3 + SecurityGroupEgress: [] + SecurityGroupIngress: + - CidrIp: 0.0.0.0/0 + Description: Allow from anyone on port 80 + FromPort: 80 + IpProtocol: tcp + ToPort: 80 + VpcId: + Ref: MyVpcF9F0CA6F + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/LB/SecurityGroup/Resource + MyFargateServiceLBSecurityGrouptoMyEcsConstructMyFargateServiceSecurityGroup67F71DB380B308A4F1: + Type: AWS::EC2::SecurityGroupEgress + Properties: + GroupId: + Fn::GetAtt: + - MyFargateServiceLBSecurityGroup6FBF16F1 + - GroupId + IpProtocol: tcp + Description: Load balancer to target + DestinationSecurityGroupId: + Fn::GetAtt: + - MyFargateServiceSecurityGroup7016792A + - GroupId + FromPort: 80 + ToPort: 80 + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/LB/SecurityGroup/to MyEcsConstructMyFargateServiceSecurityGroup67F71DB3:80 + MyFargateServiceLBPublicListener61A1042F: + Type: AWS::ElasticLoadBalancingV2::Listener + Properties: + DefaultActions: + - TargetGroupArn: + Ref: MyFargateServiceLBPublicListenerECSGroup4A3EDF05 + Type: forward + LoadBalancerArn: + Ref: MyFargateServiceLBDE830E97 + Port: 80 + Protocol: HTTP + Certificates: [] + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/LB/PublicListener/Resource + MyFargateServiceLBPublicListenerECSGroup4A3EDF05: + Type: AWS::ElasticLoadBalancingV2::TargetGroup + Properties: + Port: 80 + Protocol: HTTP + TargetGroupAttributes: [] + Targets: [] + TargetType: ip + VpcId: + Ref: MyVpcF9F0CA6F + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/LB/PublicListener/ECSGroup/Resource + MyFargateServiceTaskDefTaskRole62C7D397: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Action: sts:AssumeRole + Effect: Allow + Principal: + Service: + Fn::Join: + - "" + - - ecs-tasks. + - Ref: AWS::URLSuffix + Version: "2012-10-17" + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/TaskRole/Resource + MyFargateServiceTaskDef5DA17B39: + Type: AWS::ECS::TaskDefinition + Properties: + ContainerDefinitions: + - Essential: true + Image: amazon/amazon-ecs-sample + Links: [] + LogConfiguration: + LogDriver: awslogs + Options: + awslogs-group: + Ref: MyFargateServiceTaskDefwebLogGroup4A6C44E8 + awslogs-stream-prefix: MyFargateService + awslogs-region: + Ref: AWS::Region + MountPoints: [] + Name: web + PortMappings: + - ContainerPort: 80 + Protocol: tcp + Ulimits: [] + VolumesFrom: [] + Cpu: "512" + ExecutionRoleArn: + Fn::GetAtt: + - MyFargateServiceTaskDefExecutionRoleD6305504 + - Arn + Family: MyEcsConstructMyFargateServiceTaskDef164AB9B9 + Memory: "2048" + NetworkMode: awsvpc + RequiresCompatibilities: + - FARGATE + TaskRoleArn: + Fn::GetAtt: + - MyFargateServiceTaskDefTaskRole62C7D397 + - Arn + Volumes: [] + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/Resource + MyFargateServiceTaskDefwebLogGroup4A6C44E8: + Type: AWS::Logs::LogGroup + DeletionPolicy: Retain + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/web/LogGroup/Resource + MyFargateServiceTaskDefExecutionRoleD6305504: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Action: sts:AssumeRole + Effect: Allow + Principal: + Service: + Fn::Join: + - "" + - - ecs-tasks. + - Ref: AWS::URLSuffix + Version: "2012-10-17" + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/ExecutionRole/Resource + MyFargateServiceTaskDefExecutionRoleDefaultPolicyEC22B20F: + Type: AWS::IAM::Policy + Properties: + PolicyDocument: + Statement: + - Action: + - logs:CreateLogStream + - logs:PutLogEvents + Effect: Allow + Resource: + Fn::GetAtt: + - MyFargateServiceTaskDefwebLogGroup4A6C44E8 + - Arn + Version: "2012-10-17" + PolicyName: MyFargateServiceTaskDefExecutionRoleDefaultPolicyEC22B20F + Roles: + - Ref: MyFargateServiceTaskDefExecutionRoleD6305504 + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/TaskDef/ExecutionRole/DefaultPolicy/Resource + MyFargateServiceF490C034: + Type: AWS::ECS::Service + Properties: + TaskDefinition: + Ref: MyFargateServiceTaskDef5DA17B39 + Cluster: + Ref: MyCluster4C1BA579 + DeploymentConfiguration: + MaximumPercent: 200 + MinimumHealthyPercent: 50 + DesiredCount: 6 + HealthCheckGracePeriodSeconds: 60 + LaunchType: FARGATE + LoadBalancers: + - ContainerName: web + ContainerPort: 80 + TargetGroupArn: + Ref: MyFargateServiceLBPublicListenerECSGroup4A3EDF05 + NetworkConfiguration: + AwsvpcConfiguration: + AssignPublicIp: DISABLED + SecurityGroups: + - Fn::GetAtt: + - MyFargateServiceSecurityGroup7016792A + - GroupId + Subnets: + - Ref: MyVpcPrivateSubnet1Subnet5057CF7E + - Ref: MyVpcPrivateSubnet2Subnet0040C983 + ServiceRegistries: [] + DependsOn: + - MyFargateServiceLBPublicListenerECSGroup4A3EDF05 + - MyFargateServiceLBPublicListener61A1042F + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/Service/Service + MyFargateServiceSecurityGroup7016792A: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: MyEcsConstruct/MyFargateService/Service/SecurityGroup + SecurityGroupEgress: + - CidrIp: 0.0.0.0/0 + Description: Allow all outbound traffic by default + IpProtocol: "-1" + SecurityGroupIngress: [] + VpcId: + Ref: MyVpcF9F0CA6F + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/Service/SecurityGroup/Resource + MyFargateServiceSecurityGroupfromMyEcsConstructMyFargateServiceLBSecurityGroup8793A2F780B3ABD3C6: + Type: AWS::EC2::SecurityGroupIngress + Properties: + IpProtocol: tcp + Description: Load balancer to target + FromPort: 80 + GroupId: + Fn::GetAtt: + - MyFargateServiceSecurityGroup7016792A + - GroupId + SourceSecurityGroupId: + Fn::GetAtt: + - MyFargateServiceLBSecurityGroup6FBF16F1 + - GroupId + ToPort: 80 + Metadata: + aws:cdk:path: MyEcsConstruct/MyFargateService/Service/SecurityGroup/from MyEcsConstructMyFargateServiceLBSecurityGroup8793A2F7:80 +Outputs: + MyFargateServiceLoadBalancerDNS704F6391: + Value: + Fn::GetAtt: + - MyFargateServiceLBDE830E97 + - DNSName diff --git a/v1/aspects.md b/v1/aspects.md index 074004be..9e13f8de 100644 --- a/v1/aspects.md +++ b/v1/aspects.md @@ -92,6 +92,8 @@ During the [prepare phase](apps.md#lifecycle), the AWS CDK calls the `visit` met The `visit` method is free to change anything in the construct\. In strongly\-typed languages, cast the received construct to a more specific type before accessing construct\-specific properties or methods\. +Aspects don't propagate across `Stage` construct boundaries, because `Stages` are self\-contained and immutable after definition\. Apply aspects on the `Stage` construct itself \(or lower\) if you want them to visit constructs inside the `Stage`\. + ## Example The following example validates that all buckets created in the stack have versioning enabled\. The aspect adds an error annotation to the constructs that fail the validation, which results in the synth operation failing and prevents deploying the resulting cloud assembly\. @@ -107,7 +109,7 @@ class BucketVersioningChecker implements IAspect { // Check for versioning property, exclude the case where the property // can be a token (IResolvable). - if (!node.versioningConfiguration + if (!node.versioningConfiguration || (!Tokenization.isResolvable(node.versioningConfiguration) && node.versioningConfiguration.status !== 'Enabled')) { Annotations.of(node).addError('Bucket versioning is not enabled'); @@ -131,7 +133,7 @@ class BucketVersioningChecker { // Check for versioning property, exclude the case where the property // can be a token (IResolvable). - if (!node.versioningConfiguration + if (!node.versioningConfiguration || !Tokenization.isResolvable(node.versioningConfiguration) && node.versioningConfiguration.status !== 'Enabled') { Annotations.of(node).addError('Bucket versioning is not enabled'); @@ -150,7 +152,7 @@ Aspects.of(stack).add(new BucketVersioningChecker()); ``` @jsii.implements(core.IAspect) class BucketVersioningChecker: - + def visit(self, node): # See that we're dealing with a CfnBucket if isinstance(node, s3.CfnBucket): @@ -159,7 +161,7 @@ class BucketVersioningChecker: # can be a token (IResolvable). if (not node.versioning_configuration or not Tokenization.is_resolvable(node.versioning_configuration) - and node.versioning_configuration.status != "Enabled"): + and node.versioning_configuration.status != "Enabled"): Annotations.of(node).add_error('Bucket versioning is not enabled') # Later, apply to the stack diff --git a/v1/constructs.md b/v1/constructs.md index 8762b924..a4bb9ba2 100644 --- a/v1/constructs.md +++ b/v1/constructs.md @@ -749,7 +749,7 @@ public class NotifyingBucket : Construct **Note** Our `NotifyingBucket` construct inherits not from `Bucket` but rather from `Construct`\. We are using composition, not inheritance, to bundle an Amazon S3 bucket and an Amazon SNS topic together\. In general, composition is preferred over inheritance when developing AWS CDK constructs\. -The `NotifyingBucket` constructor has a typical construct signature: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. \(The base `Construct` class does not take a `props`argument\.\) You could define an instance of this construct in your app without `props`, for example: +The `NotifyingBucket` constructor has a typical construct signature: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. \(The base `Construct` class does not take a `props` argument\.\) You could define an instance of this construct in your app without `props`, for example: ------ #### [ TypeScript ] diff --git a/v1/tagging.md b/v1/tagging.md index 9d65d01b..af22785c 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -90,7 +90,9 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. + +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. @@ -325,7 +327,7 @@ the_best_stack = Stack(app, 'MarketingSystem') Tags.of(the_best_stack).add("StackType", "TheBest") # Remove the tag from all resources except subnet resources -Tags.of(the_best_stack).remove("StackType", +Tags.of(the_best_stack).remove("StackType", exclude_resource_types=["AWS::EC2::Subnet"]) ``` @@ -358,7 +360,7 @@ var theBestStack = new Stack(app, 'MarketingSystem'); Tags.Of(theBestStack).Add("StackType", "TheBest"); // Remove the tag from all resources except subnet resources -Tags.Of(theBestStack).Remove("StackType", new TagProps +Tags.Of(theBestStack).Remove("StackType", new TagProps { ExcludeResourceTypes = ["AWS::EC2::Subnet"] }); @@ -372,7 +374,7 @@ The following code achieves the same result\. Consider which approach \(inclusio #### [ TypeScript ] ``` -Tags.of(theBestStack).add('StackType', 'TheBest', +Tags.of(theBestStack).add('StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet']}); ``` @@ -380,7 +382,7 @@ Tags.of(theBestStack).add('StackType', 'TheBest', #### [ JavaScript ] ``` -Tags.of(theBestStack).add('StackType', 'TheBest', +Tags.of(theBestStack).add('StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet']}); ``` @@ -388,7 +390,7 @@ Tags.of(theBestStack).add('StackType', 'TheBest', #### [ Python ] ``` -Tags.of(the_best_stack).add("StackType", "TheBest", +Tags.of(the_best_stack).add("StackType", "TheBest", include_resource_types=["AWS::EC2::Subnet"]) ``` diff --git a/v1/work-with-cdk-csharp.md b/v1/work-with-cdk-csharp.md index e232c77f..55b93d8c 100644 --- a/v1/work-with-cdk-csharp.md +++ b/v1/work-with-cdk-csharp.md @@ -138,7 +138,15 @@ A future release of the AWS CDK could coincidentally add a new property with a n ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In C\#, these objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` in C\#\. +In some APIs, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In C\#, these objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` in C\#\. + +**Tip** +You might define short aliases to make it easier to work with these sepecific dictionary types\. + +``` +using StringDict = System.Collections.Dictionary; +using ObjectDict = System.Collections.Dictionary; +``` ### Missing values diff --git a/v1/work-with-cdk-java.md b/v1/work-with-cdk-java.md index 25db10e7..32d5f39a 100644 --- a/v1/work-with-cdk-java.md +++ b/v1/work-with-cdk-java.md @@ -2,9 +2,14 @@ Java is a fully\-supported client platform for the AWS CDK and is considered stable\. You can develop AWS CDK applications in Java using familiar tools, including the JDK \(Oracle's, or an OpenJDK distribution such as Amazon Corretto\) and Apache Maven\. The modules comprising the AWS Construct Library are distributed via the [Maven Central Repository](https://search.maven.org/search?q=g:software.amazon.awscdk)\. -You can use any text editor, or a Java IDE that can read Maven projects, to work on your AWS CDK apps\. We provide [Eclipse](https://www.eclipse.org/downloads/) hints in this Guide, but IntelliJ IDEA, NetBeans, and other IDEs can import Maven projects and will work fine for developing AWS CDK applications in Java\. +The AWS CDK supports Java 8 and later\. We recommend using the latest version you can, however, because later versions of the language include improvements that are particularly convenient for developing AWS CDK applications\. For example, Java 9 introduces the `Map.of()` method \(a convenient way to declare hashmaps that would be written as object literals in TypeScript\)\. Java 10 introduces local type inference using the `var` keyword\. -It is possible to write AWS CDK applications in JVM\-hosted languages other than Java \(for example, Kotlin, Groovy, Clojure, or Scala\), but we are unable to provide support for these languages\. +**Note** +Most code examples in this Developer Guide work with Java 8\. A few examples use `Map.of()`; these examples include comments noting that they require Java 9\. + +You can use any text editor, or a Java IDE that can read Maven projects, to work on your AWS CDK apps\. We provide [Eclipse](https://www.eclipse.org/downloads/) hints in this Guide, but IntelliJ IDEA, NetBeans, and other IDEs can import Maven projects and can be used for developing AWS CDK applications in Java\. + +It is possible to write AWS CDK applications in JVM\-hosted languages other than Java \(for example, Kotlin, Groovy, Clojure, or Scala\), but the experience may not be particularly idiomatic, and we are unable to provide any support for these languages\. ## Prerequisites @@ -95,17 +100,20 @@ When deriving your own construct from an existing construct, you may want to acc ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Java, these objects are represented as `java.util.Map`\. In cases where the values are all strings, you can use `Map`\. It is convenient to use double braces to define `HashMap`s\. +In some APIs, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In Java, these objects are represented as `java.util.Map`\. In cases where the values are all strings, you can use `Map`\. + +Java does not provide a way to write literals for such containers like some other languages do\. In Java 9 and later, you can use [https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#ofEntries-java.util.Map.Entry...-](https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#ofEntries-java.util.Map.Entry...-) to conveniently define maps of up to ten entries inline with one of these calls\. ``` -new HashMap() {{ - put("base-directory", "dist"); - put("files", "LambdaStack.template.json"); -}}; +java.util.Map.of( + "base-directory", "dist", + "files", "LambdaStack.template.json" + ) ``` -**Note** -The double\-brace notation \(which technically declares an anonymous inner class\) is sometimes considered an anti\-pattern\. However, its disadvantages are not very relevant to using it in CDK apps\. It is a reasonable substitute for what would be object or dictionary literals in other languages\. +To create maps with more than ten entries, use [https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#ofEntries-java.util.Map.Entry...-](https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#ofEntries-java.util.Map.Entry...-)\. + +If you are using Java 8, you could provide your own methods similar to to these\. JavaScript arrays are represented as `List` or `List` in Java\. The method `java.util.Arrays.asList` is convenient for defining short `ArrayList`s\. diff --git a/v2/aspects.md b/v2/aspects.md index 72054db9..407e76b7 100644 --- a/v2/aspects.md +++ b/v2/aspects.md @@ -92,6 +92,8 @@ During the [prepare phase](apps.md#lifecycle), the AWS CDK calls the `visit` met The `visit` method is free to change anything in the construct\. In strongly\-typed languages, cast the received construct to a more specific type before accessing construct\-specific properties or methods\. +Aspects don't propagate across `Stage` construct boundaries, because `Stages` are self\-contained and immutable after definition\. Apply aspects on the `Stage` construct itself \(or lower\) if you want them to visit constructs inside the `Stage`\. + ## Example The following example validates that all buckets created in the stack have versioning enabled\. The aspect adds an error annotation to the constructs that fail the validation, which results in the synth operation failing and prevents deploying the resulting cloud assembly\. @@ -107,7 +109,7 @@ class BucketVersioningChecker implements IAspect { // Check for versioning property, exclude the case where the property // can be a token (IResolvable). - if (!node.versioningConfiguration + if (!node.versioningConfiguration || (!Tokenization.isResolvable(node.versioningConfiguration) && node.versioningConfiguration.status !== 'Enabled')) { Annotations.of(node).addError('Bucket versioning is not enabled'); @@ -131,7 +133,7 @@ class BucketVersioningChecker { // Check for versioning property, exclude the case where the property // can be a token (IResolvable). - if (!node.versioningConfiguration + if (!node.versioningConfiguration || !Tokenization.isResolvable(node.versioningConfiguration) && node.versioningConfiguration.status !== 'Enabled') { Annotations.of(node).addError('Bucket versioning is not enabled'); @@ -150,7 +152,7 @@ Aspects.of(stack).add(new BucketVersioningChecker()); ``` @jsii.implements(cdk.IAspect) class BucketVersioningChecker: - + def visit(self, node): # See that we're dealing with a CfnBucket if isinstance(node, s3.CfnBucket): @@ -159,7 +161,7 @@ class BucketVersioningChecker: # can be a token (IResolvable). if (not node.versioning_configuration or not Tokenization.is_resolvable(node.versioning_configuration) - and node.versioning_configuration.status != "Enabled"): + and node.versioning_configuration.status != "Enabled"): Annotations.of(node).add_error('Bucket versioning is not enabled') # Later, apply to the stack diff --git a/v2/constructs.md b/v2/constructs.md index ea97c474..7068d23e 100644 --- a/v2/constructs.md +++ b/v2/constructs.md @@ -753,7 +753,7 @@ public class NotifyingBucket : Construct **Note** Our `NotifyingBucket` construct inherits not from `Bucket` but rather from `Construct`\. We are using composition, not inheritance, to bundle an Amazon S3 bucket and an Amazon SNS topic together\. In general, composition is preferred over inheritance when developing AWS CDK constructs\. -The `NotifyingBucket` constructor has a typical construct signature: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. \(The base `Construct` class does not take a `props`argument\.\) You could define an instance of this construct in your app without `props`, for example: +The `NotifyingBucket` constructor has a typical construct signature: `scope`, `id`, and `props`\. The last argument, `props`, is optional \(gets the default value `{}`\) because all props are optional\. \(The base `Construct` class does not take a `props` argument\.\) You could define an instance of this construct in your app without `props`, for example: ------ #### [ TypeScript ] diff --git a/v2/tagging.md b/v2/tagging.md index 5c262efe..a353b5dd 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -90,7 +90,9 @@ Tags.Of(myConstruct).Remove("key"); ------ -## Tag priorities +If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. + +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. @@ -325,7 +327,7 @@ the_best_stack = Stack(app, 'MarketingSystem') Tags.of(the_best_stack).add("StackType", "TheBest") # Remove the tag from all resources except subnet resources -Tags.of(the_best_stack).remove("StackType", +Tags.of(the_best_stack).remove("StackType", exclude_resource_types=["AWS::EC2::Subnet"]) ``` @@ -358,7 +360,7 @@ var theBestStack = new Stack(app, 'MarketingSystem'); Tags.Of(theBestStack).Add("StackType", "TheBest"); // Remove the tag from all resources except subnet resources -Tags.Of(theBestStack).Remove("StackType", new TagProps +Tags.Of(theBestStack).Remove("StackType", new TagProps { ExcludeResourceTypes = ["AWS::EC2::Subnet"] }); @@ -372,7 +374,7 @@ The following code achieves the same result\. Consider which approach \(inclusio #### [ TypeScript ] ``` -Tags.of(theBestStack).add('StackType', 'TheBest', +Tags.of(theBestStack).add('StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet']}); ``` @@ -380,7 +382,7 @@ Tags.of(theBestStack).add('StackType', 'TheBest', #### [ JavaScript ] ``` -Tags.of(theBestStack).add('StackType', 'TheBest', +Tags.of(theBestStack).add('StackType', 'TheBest', { includeResourceTypes: ['AWS::EC2::Subnet']}); ``` @@ -388,7 +390,7 @@ Tags.of(theBestStack).add('StackType', 'TheBest', #### [ Python ] ``` -Tags.of(the_best_stack).add("StackType", "TheBest", +Tags.of(the_best_stack).add("StackType", "TheBest", include_resource_types=["AWS::EC2::Subnet"]) ``` diff --git a/v2/work-with-cdk-csharp.md b/v2/work-with-cdk-csharp.md index dd5dbc0f..c0d6422f 100644 --- a/v2/work-with-cdk-csharp.md +++ b/v2/work-with-cdk-csharp.md @@ -131,7 +131,15 @@ A future release of the AWS CDK could coincidentally add a new property with a n ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html) method\.\) In C\#, these objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` array types in C\#\. +In some APIs, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html) method\.\) In C\#, these objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` array types in C\#\. + +**Tip** +You might define short aliases to make it easier to work with these sepecific dictionary types\. + +``` +using StringDict = System.Collections.Dictionary; +using ObjectDict = System.Collections.Dictionary; +``` ### Missing values diff --git a/v2/work-with-cdk-java.md b/v2/work-with-cdk-java.md index a1155a8e..a915dcf2 100644 --- a/v2/work-with-cdk-java.md +++ b/v2/work-with-cdk-java.md @@ -2,9 +2,14 @@ Java is a fully\-supported client platform for the AWS CDK and is considered stable\. You can develop AWS CDK applications in Java using familiar tools, including the JDK \(Oracle's, or an OpenJDK distribution such as Amazon Corretto\) and Apache Maven\. The modules comprising the AWS Construct Library are distributed via the [Maven Central Repository](https://search.maven.org/search?q=g:software.amazon.awscdk)\. -You can use any text editor, or a Java IDE that can read Maven projects, to work on your AWS CDK apps\. We provide [Eclipse](https://www.eclipse.org/downloads/) hints in this Guide, but IntelliJ IDEA, NetBeans, and other IDEs can import Maven projects and will work fine for developing AWS CDK applications in Java\. +The AWS CDK supports Java 8 and later\. We recommend using the latest version you can, however, because later versions of the language include improvements that are particularly convenient for developing AWS CDK applications\. For example, Java 9 introduces the `Map.of()` method \(a convenient way to declare hashmaps that would be written as object literals in TypeScript\)\. Java 10 introduces local type inference using the `var` keyword\. -It is possible to write AWS CDK applications in JVM\-hosted languages other than Java \(for example, Kotlin, Groovy, Clojure, or Scala\), but we are unable to provide support for these languages\. +**Note** +Most code examples in this Developer Guide work with Java 8\. A few examples use `Map.of()`; these examples include comments noting that they require Java 9\. + +You can use any text editor, or a Java IDE that can read Maven projects, to work on your AWS CDK apps\. We provide [Eclipse](https://www.eclipse.org/downloads/) hints in this Guide, but IntelliJ IDEA, NetBeans, and other IDEs can import Maven projects and can be used for developing AWS CDK applications in Java\. + +It is possible to write AWS CDK applications in JVM\-hosted languages other than Java \(for example, Kotlin, Groovy, Clojure, or Scala\), but the experience may not be particularly idiomatic, and we are unable to provide any support for these languages\. ## Prerequisites @@ -84,17 +89,20 @@ When deriving your own construct from an existing construct, you may want to acc ### Generic structures -In some places, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html#static-fromwbrobjectvalue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html#static-fromwbrobjectvalue) method\.\) In Java, these objects are represented as `java.util.Map`\. In cases where the values are all strings, you can use `Map`\. It is convenient to use double braces to define `HashMap`s\. +In some APIs, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html#static-fromwbrobjectvalue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html#static-fromwbrobjectvalue) method\.\) In Java, these objects are represented as `java.util.Map`\. In cases where the values are all strings, you can use `Map`\. + +Java does not provide a way to write literals for such containers like some other languages do\. In Java 9 and later, you can use [https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#ofEntries-java.util.Map.Entry...-](https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#ofEntries-java.util.Map.Entry...-) to conveniently define maps of up to ten entries inline with one of these calls\. ``` -new HashMap() {{ - put("base-directory", "dist"); - put("files", "LambdaStack.template.json"); -}}; +java.util.Map.of( + "base-directory", "dist", + "files", "LambdaStack.template.json" + ) ``` -**Note** -The double\-brace notation \(which technically declares an anonymous inner class\) is sometimes considered an anti\-pattern\. However, its disadvantages are not very relevant to using it in CDK apps\. It is a reasonable substitute for what would be object or dictionary literals in other languages\. +To create maps with more than ten entries, use [https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#ofEntries-java.util.Map.Entry...-](https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#ofEntries-java.util.Map.Entry...-)\. + +If you are using Java 8, you could provide your own methods similar to to these\. JavaScript arrays are represented as `List` or `List` in Java\. The method `java.util.Arrays.asList` is convenient for defining short `ArrayList`s\. From b56694c979b648b0fd771b57401a6e89e598a7f5 Mon Sep 17 00:00:00 2001 From: Arun Donti Date: Tue, 15 Feb 2022 17:42:28 -0500 Subject: [PATCH 488/655] Drop 'rc1' from python and javascript instructions (#375) --- v2/migrating-v2.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 933f1af0..3014660c 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -195,7 +195,7 @@ Experimental constructs are provided in separate, independently\-versioned packa ``` { "dependencies": { - "aws-cdk-lib": "^2.0.0-rc.1", + "aws-cdk-lib": "^2.0.0", "@aws-cdk/aws-codestar-alpha": "2.0.0-alpha.1", "constructs": "^10.0.0" } @@ -222,7 +222,7 @@ Experimental constructs are provided in separate, independently\-versioned packa ``` install_requires=[ - "aws-cdk-lib>=2.0.0rc1", + "aws-cdk-lib>=2.0.0", "constructs>=10.0.0", "aws-cdk.aws-codestar-alpha>=2.0.0alpha1", # ... @@ -342,4 +342,4 @@ Expected changes include but are not limited to: Unexpected changes are typically not caused by upgrading to AWS CDK v2 in itself, but are usually the result of deprecated behavior that was previously changed by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, removing feature flags, revising your code as necessary, deploying, and then upgrading to v2\. -If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. \ No newline at end of file +If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. From 1d61e0a8c319d850688595d957ef7cf27ce9bf83 Mon Sep 17 00:00:00 2001 From: Rui Valim Junior Date: Tue, 15 Feb 2022 19:43:43 -0300 Subject: [PATCH 489/655] fix: windows doskey for cdk 1.x (#376) --- v2/migrating-v2.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 3014660c..a044b4da 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -124,7 +124,7 @@ alias cdk="npx aws-cdk@2.x" ``` ``` -doskey cdk=npx1 aws-cdk@1.x $* +doskey cdk1=npx aws-cdk@1.x $* doskey cdk=npx aws-cdk@2.x $* ``` From c118728c3b3e010833dd9f745d7764d073c2fe7b Mon Sep 17 00:00:00 2001 From: Felix Coutinho Date: Tue, 15 Feb 2022 17:48:35 -0500 Subject: [PATCH 490/655] Fixed navigation link-anchor to differentiate between 'at deployment' and 'at synthesis' SSM read when using CDK documentation (#378) --- v1/get_ssm_value.md | 44 +++++++++++++++++++++++++++----------------- v2/get_ssm_value.md | 44 +++++++++++++++++++++++++++----------------- 2 files changed, 54 insertions(+), 34 deletions(-) diff --git a/v1/get_ssm_value.md b/v1/get_ssm_value.md index 6f70386e..e0886064 100644 --- a/v1/get_ssm_value.md +++ b/v1/get_ssm_value.md @@ -7,13 +7,14 @@ The AWS CDK supports retrieving both plain and secure values\. You may request a **Note** This topic shows how to read attributes from the AWS Systems Manager Parameter Store\. You can also read secrets from the AWS Secrets Manager \(see [Get a value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. -## Reading Systems Manager values at deployment time +## Reading Systems Manager values at deployment time To read values from the Systems Manager Parameter Store, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-string-parameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-for-secure-string-parameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md), not the actual value\. The value is resolved by AWS CloudFormation during deployment\. A [limited number of AWS services](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#template-parameters-dynamic-patterns-resources) currently support this feature\. ------- +--- + #### [ TypeScript ] ``` @@ -30,7 +31,8 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ------- +--- + #### [ JavaScript ] ``` @@ -47,12 +49,13 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ------- +--- + #### [ Python ] ``` import aws_cdk.aws_ssm as ssm - + # Get latest version or specified version of plain string attribute latest_string_token = ssm.StringParameter.value_for_string_parameter( self, "my-plain-parameter-name") @@ -64,7 +67,8 @@ secure_string_token = ssm.StringParameter.value_for_secure_string_parameter( self, "my-secure-parameter-name", 1) # must specify version ``` ------- +--- + #### [ Java ] ``` @@ -81,7 +85,8 @@ String secureStringToken = StringParameter.valueForSecureStringParameter( this, "my-secure-parameter-name", 1); // must specify version ``` ------- +--- + #### [ C\# ] ``` @@ -98,20 +103,21 @@ var secureStringToken = StringParameter.ValueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ------- +--- -## Reading Systems Manager values at synthesis time +## Reading Systems Manager values at synthesis time It is sometimes useful to "bake in" a parameter at synthesis time, so that the resulting AWS CloudFormation template always uses the same value, rather than resolving the value during deployment\. -To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. +To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack _must_ be synthesized with explicit account and region information\. Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. **Important** The retrieved value will end up in your synthesized AWS CloudFormation template, which may be a security risk depending on who has access to your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. ------- +--- + #### [ TypeScript ] ``` @@ -120,7 +126,8 @@ import * as ssm from '@aws-cdk/aws-ssm'; const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` ------- +--- + #### [ JavaScript ] ``` @@ -129,7 +136,8 @@ const ssm = require('@aws-cdk/aws-ssm'); const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` ------- +--- + #### [ Python ] ``` @@ -138,7 +146,8 @@ import aws_cdk.aws_ssm as ssm string_value = ssm.StringParameter.value_from_lookup(self, "my-plain-parameter-name") ``` ------- +--- + #### [ Java ] ``` @@ -147,7 +156,8 @@ import software.amazon.awscdk.services.ssm.StringParameter; String stringValue = StringParameter.valueFromLookup(this, "my-plain-parameter-name"); ``` ------- +--- + #### [ C\# ] ``` @@ -156,7 +166,7 @@ using Amazon.CDK.AWS.SSM; var stringValue = StringParameter.ValueFromLookup(this, "my-plain-parameter-name"); ``` ------- +--- ## Writing values to Systems Manager @@ -172,4 +182,4 @@ When updating an SSM value that already exists, also include the `--overwrite` o ``` aws ssm put-parameter --overwrite --name "parameter-name" --type "String" --value "parameter-value" aws ssm put-parameter --overwrite --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" -``` \ No newline at end of file +``` diff --git a/v2/get_ssm_value.md b/v2/get_ssm_value.md index 82e05cda..45c3b040 100644 --- a/v2/get_ssm_value.md +++ b/v2/get_ssm_value.md @@ -7,13 +7,14 @@ The AWS CDK supports retrieving both plain and secure values\. You may request a **Note** This topic shows how to read attributes from the AWS Systems Manager Parameter Store\. You can also read secrets from the AWS Secrets Manager \(see [Get a value from AWS Secrets Manager](get_secrets_manager_value.md)\)\. -## Reading Systems Manager values at deployment time +## Reading Systems Manager values at deployment time To read values from the Systems Manager Parameter Store, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrforwbrstringwbrparameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrforwbrsecurewbrstringwbrparameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md), not the actual value\. The value is resolved by AWS CloudFormation during deployment\. A [limited number of AWS services](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#template-parameters-dynamic-patterns-resources) currently support this feature\. ------- +--- + #### [ TypeScript ] ``` @@ -30,7 +31,8 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ------- +--- + #### [ JavaScript ] ``` @@ -47,12 +49,13 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ------- +--- + #### [ Python ] ``` import aws_cdk.aws_ssm as ssm - + # Get latest version or specified version of plain string attribute latest_string_token = ssm.StringParameter.value_for_string_parameter( self, "my-plain-parameter-name") @@ -64,7 +67,8 @@ secure_string_token = ssm.StringParameter.value_for_secure_string_parameter( self, "my-secure-parameter-name", 1) # must specify version ``` ------- +--- + #### [ Java ] ``` @@ -81,7 +85,8 @@ String secureStringToken = StringParameter.valueForSecureStringParameter( this, "my-secure-parameter-name", 1); // must specify version ``` ------- +--- + #### [ C\# ] ``` @@ -98,20 +103,21 @@ var secureStringToken = StringParameter.ValueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ------- +--- -## Reading Systems Manager values at synthesis time +## Reading Systems Manager values at synthesis time It is sometimes useful to "bake in" a parameter at synthesis time, so that the resulting AWS CloudFormation template always uses the same value, rather than resolving the value during deployment\. -To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrfromwbrlookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. +To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrfromwbrlookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack _must_ be synthesized with explicit account and region information\. Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. **Important** The retrieved value will end up in your synthesized AWS CloudFormation template, which may be a security risk depending on who has access to your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. ------- +--- + #### [ TypeScript ] ``` @@ -120,7 +126,8 @@ import * as ssm from 'aws-cdk-lib/aws-ssm'; const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` ------- +--- + #### [ JavaScript ] ``` @@ -129,7 +136,8 @@ const ssm = require('aws-cdk-lib/aws-ssm'); const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` ------- +--- + #### [ Python ] ``` @@ -138,7 +146,8 @@ import aws_cdk.aws_ssm as ssm string_value = ssm.StringParameter.value_from_lookup(self, "my-plain-parameter-name") ``` ------- +--- + #### [ Java ] ``` @@ -147,7 +156,8 @@ import software.amazon.awscdk.services.ssm.StringParameter; String stringValue = StringParameter.valueFromLookup(this, "my-plain-parameter-name"); ``` ------- +--- + #### [ C\# ] ``` @@ -156,7 +166,7 @@ using Amazon.CDK.AWS.SSM; var stringValue = StringParameter.ValueFromLookup(this, "my-plain-parameter-name"); ``` ------- +--- ## Writing values to Systems Manager @@ -172,4 +182,4 @@ When updating an SSM value that already exists, also include the `--overwrite` o ``` aws ssm put-parameter --overwrite --name "parameter-name" --type "String" --value "parameter-value" aws ssm put-parameter --overwrite --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" -``` \ No newline at end of file +``` From c0dc1167dc3402b07e6a5695121ad8affd0e73e9 Mon Sep 17 00:00:00 2001 From: Tatsuya Yamamoto Date: Wed, 16 Feb 2022 07:55:27 +0900 Subject: [PATCH 491/655] Remove unnecessary parentheses (#379) --- v2/resources.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v2/resources.md b/v2/resources.md index 519a86a2..91770543 100644 --- a/v2/resources.md +++ b/v2/resources.md @@ -579,7 +579,7 @@ Vpc.FromVpcAttributes(this, "MyVpc", new VpcAttributes ------ -Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables\), it can be difficult to import those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. +Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables, it can be difficult to import those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. You must provide attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want to import the VPC marked as the default is sufficient\. @@ -1278,4 +1278,4 @@ resource.ApplyRemovalPolicy(cdk.RemovalPolicy.DESTROY); ------ **Note** -The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. \ No newline at end of file +The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. From d61fbaa9856628c582d922f0c5a2e2aa675e638a Mon Sep 17 00:00:00 2001 From: Tatsuya Yamamoto Date: Wed, 16 Feb 2022 07:57:07 +0900 Subject: [PATCH 492/655] Remove unnecessary period (#380) --- v2/resources.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/resources.md b/v2/resources.md index 91770543..08dc00da 100644 --- a/v2/resources.md +++ b/v2/resources.md @@ -1133,7 +1133,7 @@ Resources besides those that store data persistently may also have a `removalPol AWS CloudFormation does not remove Amazon S3 buckets that contain files even if their removal policy is set to `DESTROY`\. Attempting to do so is a AWS CloudFormation error\. To have the AWS CDK delete all files from the bucket before destroying it, set the bucket's `autoDeleteObjects` property to `true`\. -Following is an example of creating an Amazon S3 bucket with `RemovalPolicy` of `DESTROY` and `autoDeleteOjbects` set to `true`\. \. +Following is an example of creating an Amazon S3 bucket with `RemovalPolicy` of `DESTROY` and `autoDeleteOjbects` set to `true`\. ------ #### [ TypeScript ] From 06730c8b29d970595aca22754f77d2922cb3e822 Mon Sep 17 00:00:00 2001 From: Chris Lloyd Date: Wed, 16 Feb 2022 12:02:41 +1300 Subject: [PATCH 493/655] Update Aspects C# code (#384) Corrected namespace of DeputyBase and fixed the If statement --- v2/aspects.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/v2/aspects.md b/v2/aspects.md index 407e76b7..55063c57 100644 --- a/v2/aspects.md +++ b/v2/aspects.md @@ -199,7 +199,7 @@ Aspects.of(stack).add(new BucketVersioningChecker()); #### [ C\# ] ``` -class BucketVersioningChecker : Amazon.Jsii.Runtime.DeputyBase, IAspect +class BucketVersioningChecker : Amazon.Jsii.Runtime.Deputy.DeputyBase, IAspect { public void Visit(IConstruct node) { @@ -209,7 +209,7 @@ class BucketVersioningChecker : Amazon.Jsii.Runtime.DeputyBase, IAspect var bucket = (CfnBucket)node; if (bucket.VersioningConfiguration is null || !Tokenization.IsResolvable(bucket.VersioningConfiguration) && - !bucket.VersioningConfiguration.ToString().Contains("Enabled") + !bucket.VersioningConfiguration.ToString().Contains("Enabled")) Annotations.Of(bucket.Node).AddError("Bucket versioning is not enabled"); } } @@ -219,4 +219,4 @@ class BucketVersioningChecker : Amazon.Jsii.Runtime.DeputyBase, IAspect Aspects.Of(stack).add(new BucketVersioningChecker()); ``` ------- \ No newline at end of file +------ From b7adfe3e84d9a83e351427182fbd088999540750 Mon Sep 17 00:00:00 2001 From: Hasib Hassan <67892792+hasibhassan@users.noreply.github.com> Date: Tue, 15 Feb 2022 17:04:55 -0600 Subject: [PATCH 494/655] Update hello_world.md (#382) --- v2/hello_world.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v2/hello_world.md b/v2/hello_world.md index 6fab48db..bc374011 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -462,7 +462,7 @@ Resources This diff has four sections\. + **IAM Statement Changes** and **IAM Policy Changes** \- These permission changes are there because we set the `AutoDeleteObjects` property on our Amazon S3 bucket\. The auto\-delete feature uses a custom resource to delete the objects in the bucket before the bucket itself is deleted\. The IAM objects grant the custom resource's code access to the bucket\. + **Parameters** \- The AWS CDK uses these entries to locate the Lambda function asset for the custom resource\. -+ **Resources** \- The new and changed resources in this stack\. We can see the aforementioned IAM objects, the custom resource ,and its associated Lambda function being added\. We can also see that the bucket's `DeletionPolicy` and `UpdateReplacePolicy` attributes are being updated\. These allow the bucket to be deleted along with the stack, and to be replaced with a new one\. ++ **Resources** \- The new and changed resources in this stack\. We can see the aforementioned IAM objects, the custom resource, and its associated Lambda function being added\. We can also see that the bucket's `DeletionPolicy` and `UpdateReplacePolicy` attributes are being updated\. These allow the bucket to be deleted along with the stack, and to be replaced with a new one\. You may be curious about why we specified `RemovalPolicy` in our AWS CDK app but got a `DeletionPolicy` property in the resulting AWS CloudFormation template\. The AWS CDK uses a different name for the property because the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it\. See [Removal policies](resources.md#resources_removal) for further details\. @@ -533,4 +533,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) to discover constructs created by AWS and others\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? From d2f239b4d275f23bb62b4e9a2e62c5bb900303d0 Mon Sep 17 00:00:00 2001 From: Suhas Gaddam Date: Tue, 15 Feb 2022 15:08:18 -0800 Subject: [PATCH 495/655] fix: Update interface for CDKv2 (#385) https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Code.html#static-fromwbrassetpath-options --- v2/sam.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v2/sam.md b/v2/sam.md index f6910462..f020fd2f 100644 --- a/v2/sam.md +++ b/v2/sam.md @@ -26,7 +26,7 @@ The instructions here apply to the current \(non\-preview\) version of the AWS S new lambda.Function(this, 'MyFunction', { runtime: lambda.Runtime.PYTHON_3_7, handler: 'app.lambda_handler', - code: lambda.Code.asset('./my_function'), + code: lambda.Code.fromAsset('./my_function'), }); ``` @@ -74,4 +74,4 @@ The instructions here apply to the current \(non\-preview\) version of the AWS S REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB "This is a Lambda Function defined through CDK" - ``` \ No newline at end of file + ``` From 6a2471a7ebc437f06b845a654a078ebc95b3f642 Mon Sep 17 00:00:00 2001 From: Michael Kaiser Date: Tue, 15 Feb 2022 17:17:32 -0600 Subject: [PATCH 496/655] Update bootstrapping.md (#386) --- v2/bootstrapping.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index 094f2d38..b3a2f2e9 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -554,4 +554,5 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 6 | 1\.108\.0 | Add lookup role separate from deployment role\. | | 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | -| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | \ No newline at end of file +| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | +| 9 | 1\.135\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | From 4c83259af44b702414e9320725bbc47d414159f5 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 15 Feb 2022 23:57:28 +0000 Subject: [PATCH 497/655] fix some typos and other minor errors --- v1/aspects.md | 8 +++---- v1/bootstrapping.md | 3 ++- v1/ecs_example.md | 2 +- v1/get_ssm_value.md | 40 +++++++++++++--------------------- v1/hello_world.md | 2 +- v1/resources.md | 4 ++-- v1/sam.md | 2 +- v1/work-with-cdk-csharp.md | 2 +- v2/aspects.md | 6 ++--- v2/bootstrapping.md | 2 +- v2/ecs_example.md | 2 +- v2/get_ssm_value.md | 40 +++++++++++++--------------------- v2/hello_world.md | 2 +- v2/migrating-v2.md | 2 +- v2/resources.md | 2 +- v2/sam.md | 2 +- v2/work-with-cdk-csharp.md | 2 +- v2/work-with-cdk-javascript.md | 2 +- 18 files changed, 53 insertions(+), 72 deletions(-) diff --git a/v1/aspects.md b/v1/aspects.md index 9e13f8de..bce46526 100644 --- a/v1/aspects.md +++ b/v1/aspects.md @@ -111,7 +111,7 @@ class BucketVersioningChecker implements IAspect { // can be a token (IResolvable). if (!node.versioningConfiguration || (!Tokenization.isResolvable(node.versioningConfiguration) - && node.versioningConfiguration.status !== 'Enabled')) { + && node.versioningConfiguration.status !== 'Enabled') { Annotations.of(node).addError('Bucket versioning is not enabled'); } } @@ -184,7 +184,7 @@ public class BucketVersioningChecker implements IAspect Object versioningConfiguration = bucket.getVersioningConfiguration(); if (versioningConfiguration == null || !Tokenization.isResolvable(versioningConfiguration.toString()) && - !versioningConfiguration.toString().contains("Enabled") + !versioningConfiguration.toString().contains("Enabled")) Annotations.of(bucket.getNode()).addError("Bucket versioning is not enabled"); } } @@ -199,7 +199,7 @@ Aspects.of(stack).add(new BucketVersioningChecker()); #### [ C\# ] ``` -class BucketVersioningChecker : Amazon.Jsii.Runtime.DeputyBase, IAspect +class BucketVersioningChecker : Amazon.Jsii.Runtime.Deputy.DeputyBase, IAspect { public void Visit(IConstruct node) { @@ -209,7 +209,7 @@ class BucketVersioningChecker : Amazon.Jsii.Runtime.DeputyBase, IAspect var bucket = (CfnBucket)node; if (bucket.VersioningConfiguration is null || !Tokenization.IsResolvable(bucket.VersioningConfiguration) && - !bucket.VersioningConfiguration.ToString().Contains("Enabled") + !bucket.VersioningConfiguration.ToString().Contains("Enabled")) Annotations.Of(bucket.Node).AddError("Bucket versioning is not enabled"); } } diff --git a/v1/bootstrapping.md b/v1/bootstrapping.md index cc423830..cf9089a1 100644 --- a/v1/bootstrapping.md +++ b/v1/bootstrapping.md @@ -626,4 +626,5 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 6 | 1\.108\.0 | Add lookup role separate from deployment role\. | | 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | -| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | \ No newline at end of file +| 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | +| 9 | 1\.135\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | \ No newline at end of file diff --git a/v1/ecs_example.md b/v1/ecs_example.md index 5471f6bd..7cfb79ee 100644 --- a/v1/ecs_example.md +++ b/v1/ecs_example.md @@ -358,7 +358,7 @@ cdk deploy AWS CloudFormation displays information about the dozens of steps that it takes as it deploys your app\. -That's how easy it is to create a Fargate service to run a Docker image\. +That's how easy it is to create a Fargate\-powered Amazon ECS service to run a Docker image\. ## Clean up diff --git a/v1/get_ssm_value.md b/v1/get_ssm_value.md index e0886064..359ea52d 100644 --- a/v1/get_ssm_value.md +++ b/v1/get_ssm_value.md @@ -13,8 +13,7 @@ To read values from the Systems Manager Parameter Store, use the [valueForString A [limited number of AWS services](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#template-parameters-dynamic-patterns-resources) currently support this feature\. ---- - +------ #### [ TypeScript ] ``` @@ -31,8 +30,7 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ---- - +------ #### [ JavaScript ] ``` @@ -49,13 +47,12 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ---- - +------ #### [ Python ] ``` import aws_cdk.aws_ssm as ssm - + # Get latest version or specified version of plain string attribute latest_string_token = ssm.StringParameter.value_for_string_parameter( self, "my-plain-parameter-name") @@ -67,8 +64,7 @@ secure_string_token = ssm.StringParameter.value_for_secure_string_parameter( self, "my-secure-parameter-name", 1) # must specify version ``` ---- - +------ #### [ Java ] ``` @@ -85,8 +81,7 @@ String secureStringToken = StringParameter.valueForSecureStringParameter( this, "my-secure-parameter-name", 1); // must specify version ``` ---- - +------ #### [ C\# ] ``` @@ -103,21 +98,20 @@ var secureStringToken = StringParameter.ValueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ---- +------ ## Reading Systems Manager values at synthesis time It is sometimes useful to "bake in" a parameter at synthesis time, so that the resulting AWS CloudFormation template always uses the same value, rather than resolving the value during deployment\. -To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack _must_ be synthesized with explicit account and region information\. +To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ssm.StringParameter.html#static-value-wbr-from-wbr-lookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. **Important** The retrieved value will end up in your synthesized AWS CloudFormation template, which may be a security risk depending on who has access to your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. ---- - +------ #### [ TypeScript ] ``` @@ -126,8 +120,7 @@ import * as ssm from '@aws-cdk/aws-ssm'; const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` ---- - +------ #### [ JavaScript ] ``` @@ -136,8 +129,7 @@ const ssm = require('@aws-cdk/aws-ssm'); const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` ---- - +------ #### [ Python ] ``` @@ -146,8 +138,7 @@ import aws_cdk.aws_ssm as ssm string_value = ssm.StringParameter.value_from_lookup(self, "my-plain-parameter-name") ``` ---- - +------ #### [ Java ] ``` @@ -156,8 +147,7 @@ import software.amazon.awscdk.services.ssm.StringParameter; String stringValue = StringParameter.valueFromLookup(this, "my-plain-parameter-name"); ``` ---- - +------ #### [ C\# ] ``` @@ -166,7 +156,7 @@ using Amazon.CDK.AWS.SSM; var stringValue = StringParameter.ValueFromLookup(this, "my-plain-parameter-name"); ``` ---- +------ ## Writing values to Systems Manager @@ -182,4 +172,4 @@ When updating an SSM value that already exists, also include the `--overwrite` o ``` aws ssm put-parameter --overwrite --name "parameter-name" --type "String" --value "parameter-value" aws ssm put-parameter --overwrite --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" -``` +``` \ No newline at end of file diff --git a/v1/hello_world.md b/v1/hello_world.md index 42055e94..78842295 100644 --- a/v1/hello_world.md +++ b/v1/hello_world.md @@ -518,7 +518,7 @@ Resources This diff has four sections\. + **IAM Statement Changes** and **IAM Policy Changes** \- These permission changes are there because we set the `AutoDeleteObjects` property on our Amazon S3 bucket\. The auto\-delete feature uses a custom resource to delete the objects in the bucket before the bucket itself is deleted\. The IAM objects grant the custom resource's code access to the bucket\. + **Parameters** \- The AWS CDK uses these entries to locate the Lambda function asset for the custom resource\. -+ **Resources** \- The new and changed resources in this stack\. We can see the aforementioned IAM objects, the custom resource ,and its associated Lambda function being added\. We can also see that the bucket's `DeletionPolicy` and `UpdateReplacePolicy` attributes are being updated\. These allow the bucket to be deleted along with the stack, and to be replaced with a new one\. ++ **Resources** \- The new and changed resources in this stack\. We can see the aforementioned IAM objects, the custom resource, and its associated Lambda function being added\. We can also see that the bucket's `DeletionPolicy` and `UpdateReplacePolicy` attributes are being updated\. These allow the bucket to be deleted along with the stack, and to be replaced with a new one\. You may be curious about why we specified `RemovalPolicy` in our AWS CDK app but got a `DeletionPolicy` property in the resulting AWS CloudFormation template\. The AWS CDK uses a different name for the property because the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it\. See [Removal policies](resources.md#resources_removal) for further details\. diff --git a/v1/resources.md b/v1/resources.md index 1db83d28..7f053333 100644 --- a/v1/resources.md +++ b/v1/resources.md @@ -575,7 +575,7 @@ Vpc.FromVpcAttributes(this, "MyVpc", new VpcAttributes ------ -Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables\), it can be difficult to import those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. +Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables, it can be difficult to import those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. You must provide attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want to import the VPC marked as the default is sufficient\. @@ -1129,7 +1129,7 @@ Resources besides those that store data persistently may also have a `removalPol AWS CloudFormation does not remove Amazon S3 buckets that contain files even if their removal policy is set to `DESTROY`\. Attempting to do so is a AWS CloudFormation error\. To have the AWS CDK delete all files from the bucket before destroying it, set the bucket's `autoDeleteObjects` property to `true`\. -Following is an example of creating an Amazon S3 bucket with `RemovalPolicy` of `DESTROY` and `autoDeleteOjbects` set to `true`\. \. +Following is an example of creating an Amazon S3 bucket with `RemovalPolicy` of `DESTROY` and `autoDeleteOjbects` set to `true`\. ------ #### [ TypeScript ] diff --git a/v1/sam.md b/v1/sam.md index ac93efb2..522674a9 100644 --- a/v1/sam.md +++ b/v1/sam.md @@ -27,7 +27,7 @@ The instructions here apply to the current \(non\-preview\) version of the AWS S new lambda.Function(this, 'MyFunction', { runtime: lambda.Runtime.PYTHON_3_7, handler: 'app.lambda_handler', - code: lambda.Code.asset('./my_function'), + code: lambda.Code.fromAsset('./my_function'), }); ``` diff --git a/v1/work-with-cdk-csharp.md b/v1/work-with-cdk-csharp.md index 55b93d8c..646b31cf 100644 --- a/v1/work-with-cdk-csharp.md +++ b/v1/work-with-cdk-csharp.md @@ -44,7 +44,7 @@ We recommend writing a single C\# `using` directive for each AWS Construct Libra **Important** All AWS Construct Library modules used in your project must be the same version\. -NuGet has four standard, mostly\-equivalent interfaces; you can use the one that suits your needs and working style\. You can also use compatible tools, such as [Paket](https://fsprojects.github.io/Paket/) or [MyGet](https://fsprojects.github.io/Paket/)\. +NuGet has four standard, mostly\-equivalent interfaces; you can use the one that suits your needs and working style\. You can also use compatible tools, such as [Paket](https://fsprojects.github.io/Paket/) or [MyGet](https://www.myget.org/)\. ### The Visual Studio NuGet GUI diff --git a/v2/aspects.md b/v2/aspects.md index 55063c57..b3b28d1c 100644 --- a/v2/aspects.md +++ b/v2/aspects.md @@ -111,7 +111,7 @@ class BucketVersioningChecker implements IAspect { // can be a token (IResolvable). if (!node.versioningConfiguration || (!Tokenization.isResolvable(node.versioningConfiguration) - && node.versioningConfiguration.status !== 'Enabled')) { + && node.versioningConfiguration.status !== 'Enabled') { Annotations.of(node).addError('Bucket versioning is not enabled'); } } @@ -184,7 +184,7 @@ public class BucketVersioningChecker implements IAspect Object versioningConfiguration = bucket.getVersioningConfiguration(); if (versioningConfiguration == null || !Tokenization.isResolvable(versioningConfiguration.toString()) && - !versioningConfiguration.toString().contains("Enabled") + !versioningConfiguration.toString().contains("Enabled")) Annotations.of(bucket.getNode()).addError("Bucket versioning is not enabled"); } } @@ -219,4 +219,4 @@ class BucketVersioningChecker : Amazon.Jsii.Runtime.Deputy.DeputyBase, IAspect Aspects.Of(stack).add(new BucketVersioningChecker()); ``` ------- +------ \ No newline at end of file diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index b3a2f2e9..6164659b 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -555,4 +555,4 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | | 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | -| 9 | 1\.135\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | +| 9 | 2\.1\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | \ No newline at end of file diff --git a/v2/ecs_example.md b/v2/ecs_example.md index 12a9ab33..89c900e9 100644 --- a/v2/ecs_example.md +++ b/v2/ecs_example.md @@ -295,7 +295,7 @@ cdk deploy AWS CloudFormation displays information about the dozens of steps that it takes as it deploys your app\. -That's how easy it is to create a Fargate\-powered EC2 service to run a Docker image\. +That's how easy it is to create a Fargate\-powered Amazon ECS service to run a Docker image\. ## Clean up diff --git a/v2/get_ssm_value.md b/v2/get_ssm_value.md index 45c3b040..e0a3a275 100644 --- a/v2/get_ssm_value.md +++ b/v2/get_ssm_value.md @@ -13,8 +13,7 @@ To read values from the Systems Manager Parameter Store, use the [valueForString A [limited number of AWS services](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#template-parameters-dynamic-patterns-resources) currently support this feature\. ---- - +------ #### [ TypeScript ] ``` @@ -31,8 +30,7 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ---- - +------ #### [ JavaScript ] ``` @@ -49,13 +47,12 @@ const secureStringToken = ssm.StringParameter.valueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ---- - +------ #### [ Python ] ``` import aws_cdk.aws_ssm as ssm - + # Get latest version or specified version of plain string attribute latest_string_token = ssm.StringParameter.value_for_string_parameter( self, "my-plain-parameter-name") @@ -67,8 +64,7 @@ secure_string_token = ssm.StringParameter.value_for_secure_string_parameter( self, "my-secure-parameter-name", 1) # must specify version ``` ---- - +------ #### [ Java ] ``` @@ -85,8 +81,7 @@ String secureStringToken = StringParameter.valueForSecureStringParameter( this, "my-secure-parameter-name", 1); // must specify version ``` ---- - +------ #### [ C\# ] ``` @@ -103,21 +98,20 @@ var secureStringToken = StringParameter.ValueForSecureStringParameter( this, 'my-secure-parameter-name', 1); // must specify version ``` ---- +------ ## Reading Systems Manager values at synthesis time It is sometimes useful to "bake in" a parameter at synthesis time, so that the resulting AWS CloudFormation template always uses the same value, rather than resolving the value during deployment\. -To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrfromwbrlookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack _must_ be synthesized with explicit account and region information\. +To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrfromwbrlookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. **Important** The retrieved value will end up in your synthesized AWS CloudFormation template, which may be a security risk depending on who has access to your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. ---- - +------ #### [ TypeScript ] ``` @@ -126,8 +120,7 @@ import * as ssm from 'aws-cdk-lib/aws-ssm'; const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` ---- - +------ #### [ JavaScript ] ``` @@ -136,8 +129,7 @@ const ssm = require('aws-cdk-lib/aws-ssm'); const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); ``` ---- - +------ #### [ Python ] ``` @@ -146,8 +138,7 @@ import aws_cdk.aws_ssm as ssm string_value = ssm.StringParameter.value_from_lookup(self, "my-plain-parameter-name") ``` ---- - +------ #### [ Java ] ``` @@ -156,8 +147,7 @@ import software.amazon.awscdk.services.ssm.StringParameter; String stringValue = StringParameter.valueFromLookup(this, "my-plain-parameter-name"); ``` ---- - +------ #### [ C\# ] ``` @@ -166,7 +156,7 @@ using Amazon.CDK.AWS.SSM; var stringValue = StringParameter.ValueFromLookup(this, "my-plain-parameter-name"); ``` ---- +------ ## Writing values to Systems Manager @@ -182,4 +172,4 @@ When updating an SSM value that already exists, also include the `--overwrite` o ``` aws ssm put-parameter --overwrite --name "parameter-name" --type "String" --value "parameter-value" aws ssm put-parameter --overwrite --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" -``` +``` \ No newline at end of file diff --git a/v2/hello_world.md b/v2/hello_world.md index bc374011..3a32efa7 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -533,4 +533,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) to discover constructs created by AWS and others\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index a044b4da..3ad88092 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -342,4 +342,4 @@ Expected changes include but are not limited to: Unexpected changes are typically not caused by upgrading to AWS CDK v2 in itself, but are usually the result of deprecated behavior that was previously changed by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, removing feature flags, revising your code as necessary, deploying, and then upgrading to v2\. -If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. +If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. \ No newline at end of file diff --git a/v2/resources.md b/v2/resources.md index 08dc00da..0464f2a8 100644 --- a/v2/resources.md +++ b/v2/resources.md @@ -1278,4 +1278,4 @@ resource.ApplyRemovalPolicy(cdk.RemovalPolicy.DESTROY); ------ **Note** -The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. +The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. \ No newline at end of file diff --git a/v2/sam.md b/v2/sam.md index f020fd2f..676576a2 100644 --- a/v2/sam.md +++ b/v2/sam.md @@ -74,4 +74,4 @@ The instructions here apply to the current \(non\-preview\) version of the AWS S REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB "This is a Lambda Function defined through CDK" - ``` + ``` \ No newline at end of file diff --git a/v2/work-with-cdk-csharp.md b/v2/work-with-cdk-csharp.md index c0d6422f..fa3aedbd 100644 --- a/v2/work-with-cdk-csharp.md +++ b/v2/work-with-cdk-csharp.md @@ -41,7 +41,7 @@ The AWS CDK's main module, which you'll need in most AWS CDK apps, is imported i We recommend writing C\# `using` directives for the CDK core constructs and for each AWS service you use in each of your C\# source files\. You may find it convenient to use an alias for a namespace or type to help resolve name conflicts\. You can always use a type's fully\-qualfiied name \(including its namespace\) without a `using` statement\. -NuGet has four standard, mostly\-equivalent interfaces; you can use the one that suits your needs and working style\. You can also use compatible tools, such as [Paket](https://fsprojects.github.io/Paket/) or [MyGet](https://fsprojects.github.io/Paket/)\. +NuGet has four standard, mostly\-equivalent interfaces; you can use the one that suits your needs and working style\. You can also use compatible tools, such as [Paket](https://fsprojects.github.io/Paket/) or [MyGet](https://www.myget.org/)\. ### The Visual Studio NuGet GUI diff --git a/v2/work-with-cdk-javascript.md b/v2/work-with-cdk-javascript.md index 90bf9658..4dda0702 100644 --- a/v2/work-with-cdk-javascript.md +++ b/v2/work-with-cdk-javascript.md @@ -20,7 +20,7 @@ cd my-project cdk init app --language javascript ``` -Creating a project also installs the [ `aws-cdk-lib`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html) module and its dependencies\. +Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html) module and its dependencies\. `cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. From 37c3ab194eb591e5d2c736e047002361d8fd8a8e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 8 Mar 2022 02:35:15 +0000 Subject: [PATCH 498/655] minor but important tweaks --- v1/getting_started.md | 3 ++- v1/identifiers.md | 4 +--- v1/parameters.md | 4 ++-- v1/work-with-cdk-csharp.md | 2 +- v1/work-with-cdk-java.md | 2 +- v1/work-with-cdk-python.md | 2 +- v2/getting_started.md | 3 ++- v2/identifiers.md | 4 +--- v2/parameters.md | 4 ++-- v2/work-with-cdk-csharp.md | 2 +- v2/work-with-cdk-java.md | 4 ++-- v2/work-with-cdk-python.md | 2 +- 12 files changed, 17 insertions(+), 19 deletions(-) diff --git a/v1/getting_started.md b/v1/getting_started.md index 277542be..ca4da450 100644 --- a/v1/getting_started.md +++ b/v1/getting_started.md @@ -149,7 +149,8 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials ``` **Note** -Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. +Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. +AWS CDK does not natively support Single Sign\-On \(SSO\)\. To use SSO with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. diff --git a/v1/identifiers.md b/v1/identifiers.md index 928cca43..3220ae14 100644 --- a/v1/identifiers.md +++ b/v1/identifiers.md @@ -272,8 +272,6 @@ Unique IDs serve as the *logical identifiers*, which are sometimes called *logic For example, the Amazon S3 bucket in the previous example that is created within `Stack2` results in an `AWS::S3::Bucket` resource with the logical ID `Stack2MyBucket4DD88B4F` in the resulting AWS CloudFormation template\. -Think of construct IDs as part of your construct's public contract\. If you change the ID of a construct in your construct tree, AWS CloudFormation will replace the deployed resource instances of that construct, potentially causing service interruption or data loss\. - ### Logical ID stability -Avoid changing the logical ID of a resource between deployments\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID\. \ No newline at end of file +Avoid changing the logical ID of a resource after it has been created\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID, which may cause service interruption or data loss\. \ No newline at end of file diff --git a/v1/parameters.md b/v1/parameters.md index 45b5675e..37bfd443 100644 --- a/v1/parameters.md +++ b/v1/parameters.md @@ -6,14 +6,14 @@ Using the AWS CDK, you can both define parameters, which can then be used in the When deploying the AWS CloudFormation template using the AWS CDK Toolkit, you provide the parameter values on the command line\. If you deploy the template through the AWS CloudFormation console, you are prompted for the parameter values\. -In general, we recommend against using AWS CloudFormation parameters with the AWS CDK\. Unlike [context values](context.md) or environment variables, the usual way to pass values into your AWS CDK apps without hard\-coding them, parameter values are not available at synthesis time, and thus cannot be easily used in other parts of your AWS CDK app, particularly for control flow\. +In general, we recommend against using AWS CloudFormation parameters with the AWS CDK\. The usual ways to pass values into AWS CDK apps are [context values](context.md) and environment variables\. Because they are not available at synthesis time, parameter values cannot be easily used for flow control and other purposes in your CDK app\. **Note** To do control flow with parameters, you can use [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnCondition.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.CfnCondition.html) constructs, although this is awkward compared to native `if` statements\. Using parameters requires you to be mindful of how the code you're writing behaves at deployment time, as well as at synthesis time\. This makes it harder to understand and reason about your AWS CDK application, in many cases for little benefit\. -It is better, again in general, to have your CDK app accept any necessary information from the user and use it directly to declare constructs in your CDK app\. An ideal AWS CDK\-generated AWS CloudFormation template is concrete, with no values remaining to be specified at deployment time\. +It is better, again in general, to have your CDK app accept any necessary information in some well\-defined way and use it directly to declare constructs in your CDK app\. An ideal AWS CDK\-generated AWS CloudFormation template is concrete, with no values remaining to be specified at deployment time\. There are, however, use cases to which AWS CloudFormation parameters are uniquely suited\. If you have separate teams defining and deploying infrastructure, for example, you can use parameters to make the generated templates more widely useful\. Additionally, the AWS CDK's support for AWS CloudFormation parameters lets you use the AWS CDK with AWS services that use AWS CloudFormation templates \(such as AWS Service Catalog\), which use parameters to configure the template being deployed\. diff --git a/v1/work-with-cdk-csharp.md b/v1/work-with-cdk-csharp.md index 646b31cf..3aa81daf 100644 --- a/v1/work-with-cdk-csharp.md +++ b/v1/work-with-cdk-csharp.md @@ -1,6 +1,6 @@ # Working with the AWS CDK in C\# -\.NET is a fully\-supported client platform for the AWS CDK and is considered stable\. C\# is the main \.NET language for which we provide examples and support\. You can choose to write AWS CDK applications in other \.NET languages, such as Visual Basic or F\#, but AWS offers limited support for using these languages with the CDK\. +\.NET is a fully\-supported client language for the AWS CDK and is considered stable\. C\# is the main \.NET language for which we provide examples and support\. You can choose to write AWS CDK applications in other \.NET languages, such as Visual Basic or F\#, but AWS offers limited support for using these languages with the CDK\. You can develop AWS CDK applications in C\# using familiar tools including Visual Studio, Visual Studio Code, the `dotnet` command, and the NuGet package manager\. The modules comprising the AWS Construct Library are distributed via [nuget\.org](https://www.nuget.org/packages?q=amazon.cdk.aws)\. diff --git a/v1/work-with-cdk-java.md b/v1/work-with-cdk-java.md index 32d5f39a..8b1aa2d2 100644 --- a/v1/work-with-cdk-java.md +++ b/v1/work-with-cdk-java.md @@ -1,6 +1,6 @@ # Working with the AWS CDK in Java -Java is a fully\-supported client platform for the AWS CDK and is considered stable\. You can develop AWS CDK applications in Java using familiar tools, including the JDK \(Oracle's, or an OpenJDK distribution such as Amazon Corretto\) and Apache Maven\. The modules comprising the AWS Construct Library are distributed via the [Maven Central Repository](https://search.maven.org/search?q=g:software.amazon.awscdk)\. +Java is a fully\-supported client language for the AWS CDK and is considered stable\. You can develop AWS CDK applications in Java using familiar tools, including the JDK \(Oracle's, or an OpenJDK distribution such as Amazon Corretto\) and Apache Maven\. The modules comprising the AWS Construct Library are distributed via the [Maven Central Repository](https://search.maven.org/search?q=g:software.amazon.awscdk)\. The AWS CDK supports Java 8 and later\. We recommend using the latest version you can, however, because later versions of the language include improvements that are particularly convenient for developing AWS CDK applications\. For example, Java 9 introduces the `Map.of()` method \(a convenient way to declare hashmaps that would be written as object literals in TypeScript\)\. Java 10 introduces local type inference using the `var` keyword\. diff --git a/v1/work-with-cdk-python.md b/v1/work-with-cdk-python.md index dfce4439..529ca48e 100644 --- a/v1/work-with-cdk-python.md +++ b/v1/work-with-cdk-python.md @@ -8,7 +8,7 @@ You can use any editor or IDE\. Many AWS CDK developers use [Visual Studio Code] To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. -Python AWS CDK applications require Python 3\.6 or later\. If you don't already have it installed, [download a compatible version](https://www.python.org/downloads/) for your platform at [python\.org](https://www.python.org/)\. If you run Linux, your system may have come with a compatible version, or you may install it using your distro's package manager \(`yum`, `apt`, etc\.\)\. Mac users may be interested in [Homebrew](https://brew.sh/), a Linux\-style package manager for macOS\. +Python AWS CDK applications require Python 3\.6 or later\. If you don't already have it installed, [download a compatible version](https://www.python.org/downloads/) for your operating system at [python\.org](https://www.python.org/)\. If you run Linux, your system may have come with a compatible version, or you may install it using your distro's package manager \(`yum`, `apt`, etc\.\)\. Mac users may be interested in [Homebrew](https://brew.sh/), a Linux\-style package manager for macOS\. The Python package installer, `pip`, and virtual environment manager, `virtualenv`, are also required\. Windows installations of compatible Python versions include these tools\. On Linux, `pip` and `virtualenv` may be provided as separate packages in your package manager\. Alternatively, you may install them with the following commands: diff --git a/v2/getting_started.md b/v2/getting_started.md index afc4f42c..49786bdb 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -199,7 +199,8 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials ``` **Note** -Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. +Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. +AWS CDK does not natively support Single Sign\-On \(SSO\)\. To use SSO with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. diff --git a/v2/identifiers.md b/v2/identifiers.md index be2ac4e6..985d5ad7 100644 --- a/v2/identifiers.md +++ b/v2/identifiers.md @@ -276,8 +276,6 @@ Unique IDs serve as the *logical identifiers*, which are sometimes called *logic For example, the Amazon S3 bucket in the previous example that is created within `Stack2` results in an `AWS::S3::Bucket` resource with the logical ID `Stack2MyBucket4DD88B4F` in the resulting AWS CloudFormation template\. -Think of construct IDs as part of your construct's public contract\. If you change the ID of a construct in your construct tree, AWS CloudFormation will replace the deployed resource instances of that construct, potentially causing service interruption or data loss\. - ### Logical ID stability -Avoid changing the logical ID of a resource between deployments\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID\. \ No newline at end of file +Avoid changing the logical ID of a resource after it has been created\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID, which may cause service interruption or data loss\. \ No newline at end of file diff --git a/v2/parameters.md b/v2/parameters.md index f4aae69c..098145cf 100644 --- a/v2/parameters.md +++ b/v2/parameters.md @@ -6,14 +6,14 @@ Using the AWS CDK, you can both define parameters, which can then be used in the When deploying the AWS CloudFormation template using the AWS CDK Toolkit, you provide the parameter values on the command line\. If you deploy the template through the AWS CloudFormation console, you are prompted for the parameter values\. -In general, we recommend against using AWS CloudFormation parameters with the AWS CDK\. Unlike [context values](context.md) or environment variables, the usual way to pass values into your AWS CDK apps without hard\-coding them, parameter values are not available at synthesis time, and thus cannot be easily used in other parts of your AWS CDK app, particularly for control flow\. +In general, we recommend against using AWS CloudFormation parameters with the AWS CDK\. The usual ways to pass values into AWS CDK apps are [context values](context.md) and environment variables\. Because they are not available at synthesis time, parameter values cannot be easily used for flow control and other purposes in your CDK app\. **Note** To do control flow with parameters, you can use [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnCondition.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnCondition.html) constructs, although this is awkward compared to native `if` statements\. Using parameters requires you to be mindful of how the code you're writing behaves at deployment time, as well as at synthesis time\. This makes it harder to understand and reason about your AWS CDK application, in many cases for little benefit\. -It is better, again in general, to have your CDK app accept any necessary information from the user and use it directly to declare constructs in your CDK app\. An ideal AWS CDK\-generated AWS CloudFormation template is concrete, with no values remaining to be specified at deployment time\. +It is better, again in general, to have your CDK app accept any necessary information in some well\-defined way and use it directly to declare constructs in your CDK app\. An ideal AWS CDK\-generated AWS CloudFormation template is concrete, with no values remaining to be specified at deployment time\. There are, however, use cases to which AWS CloudFormation parameters are uniquely suited\. If you have separate teams defining and deploying infrastructure, for example, you can use parameters to make the generated templates more widely useful\. Additionally, the AWS CDK's support for AWS CloudFormation parameters lets you use the AWS CDK with AWS services that use AWS CloudFormation templates \(such as AWS Service Catalog\), which use parameters to configure the template being deployed\. diff --git a/v2/work-with-cdk-csharp.md b/v2/work-with-cdk-csharp.md index fa3aedbd..a02ced8f 100644 --- a/v2/work-with-cdk-csharp.md +++ b/v2/work-with-cdk-csharp.md @@ -1,6 +1,6 @@ # Working with the AWS CDK in C\# -\.NET is a fully\-supported client platform for the AWS CDK and is considered stable\. C\# is the main \.NET language for which we provide examples and support\. You can choose to write AWS CDK applications in other \.NET languages, such as Visual Basic or F\#, but AWS offers limited support for using these languages with the CDK\. +\.NET is a fully\-supported client language for the AWS CDK and is considered stable\. C\# is the main \.NET language for which we provide examples and support\. You can choose to write AWS CDK applications in other \.NET languages, such as Visual Basic or F\#, but AWS offers limited support for using these languages with the CDK\. You can develop AWS CDK applications in C\# using familiar tools including Visual Studio, Visual Studio Code, the `dotnet` command, and the NuGet package manager\. The modules comprising the AWS Construct Library are distributed via [nuget\.org](https://www.nuget.org/packages?q=amazon.cdk.aws)\. diff --git a/v2/work-with-cdk-java.md b/v2/work-with-cdk-java.md index a915dcf2..0a9eba42 100644 --- a/v2/work-with-cdk-java.md +++ b/v2/work-with-cdk-java.md @@ -1,6 +1,6 @@ # Working with the AWS CDK in Java -Java is a fully\-supported client platform for the AWS CDK and is considered stable\. You can develop AWS CDK applications in Java using familiar tools, including the JDK \(Oracle's, or an OpenJDK distribution such as Amazon Corretto\) and Apache Maven\. The modules comprising the AWS Construct Library are distributed via the [Maven Central Repository](https://search.maven.org/search?q=g:software.amazon.awscdk)\. +Java is a fully\-supported client language for the AWS CDK and is considered stable\. You can develop AWS CDK applications in Java using familiar tools, including the JDK \(Oracle's, or an OpenJDK distribution such as Amazon Corretto\) and Apache Maven\. The AWS CDK supports Java 8 and later\. We recommend using the latest version you can, however, because later versions of the language include improvements that are particularly convenient for developing AWS CDK applications\. For example, Java 9 introduces the `Map.of()` method \(a convenient way to declare hashmaps that would be written as object literals in TypeScript\)\. Java 10 introduces local type inference using the `var` keyword\. @@ -35,7 +35,7 @@ If you are using an IDE, you can now open or import the project\. In Eclipse, fo ## Managing AWS Construct Library modules -Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk`\. Most constructs are in the artifact `aws-cdk-lib`\. Modules for services whose higher\-level CDK support is still being developed are in separate "experimental" packages, named with a short version \(no AWS or Amazon prefix\) of their service's name\. [Search the Maven Central Repository](https://search.maven.org/search?q=software.amazon.awscdk) to find the names of all AWS CDK and AWS Construct Module libraries\. +Use Maven to install AWS Construct Library packages, which are in the group `software.amazon.awscdk`\. Most constructs are in the artifact `aws-cdk-lib`, which is added to new Java projects by default\. Modules for services whose higher\-level CDK support is still being developed are in separate "experimental" packages, named with a short version \(no AWS or Amazon prefix\) of their service's name\. [Search the Maven Central Repository](https://search.maven.org/search?q=software.amazon.awscdk) to find the names of all AWS CDK and AWS Construct Module libraries\. **Note** The [Java edition of the CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/java/index.html) also shows the package names\. diff --git a/v2/work-with-cdk-python.md b/v2/work-with-cdk-python.md index 4e8798d0..dbf4cc48 100644 --- a/v2/work-with-cdk-python.md +++ b/v2/work-with-cdk-python.md @@ -8,7 +8,7 @@ You can use any editor or IDE\. Many AWS CDK developers use [Visual Studio Code] To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. -Python AWS CDK applications require Python 3\.6 or later\. If you don't already have it installed, [download a compatible version](https://www.python.org/downloads/) for your platform at [python\.org](https://www.python.org/)\. If you run Linux, your system may have come with a compatible version, or you may install it using your distro's package manager \(`yum`, `apt`, etc\.\)\. Mac users may be interested in [Homebrew](https://brew.sh/), a Linux\-style package manager for macOS\. +Python AWS CDK applications require Python 3\.6 or later\. If you don't already have it installed, [download a compatible version](https://www.python.org/downloads/) for your operating system at [python\.org](https://www.python.org/)\. If you run Linux, your system may have come with a compatible version, or you may install it using your distro's package manager \(`yum`, `apt`, etc\.\)\. Mac users may be interested in [Homebrew](https://brew.sh/), a Linux\-style package manager for macOS\. The Python package installer, `pip`, and virtual environment manager, `virtualenv`, are also required\. Windows installations of compatible Python versions include these tools\. On Linux, `pip` and `virtualenv` may be provided as separate packages in your package manager\. Alternatively, you may install them with the following commands: From 17b683be3a6c5b40934035e11a26b3ca028c7ceb Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 9 Mar 2022 17:12:44 +0000 Subject: [PATCH 499/655] use Map.of for ad hoc hashmap --- v1/resources.md | 8 ++++---- v2/resources.md | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/v1/resources.md b/v1/resources.md index 7f053333..e6f9140a 100644 --- a/v1/resources.md +++ b/v1/resources.md @@ -466,9 +466,9 @@ lambda.Function(self, "MyLambda", environment=dict(BUCKET_NAME=bucket.bucket_nam final Bucket bucket = new Bucket(this, "Bucket"); Function.Builder.create(this, "MyLambda") - .environment(new HashMap() {{ - put("BUCKET_NAME", bucket.getBucketName()); - }}).build(); + .environment(java.util.Map.of( // Java 9 or later + "BUCKET_NAME", bucket.getBucketName())) + .build(); ``` ------ @@ -655,7 +655,7 @@ ec2.Vpc.from_lookup(self, "PublicVpc", ``` Vpc.fromLookup(this, "PublicVpc", VpcLookupOptions.builder() - .tags(new HashMap {{ put("aws-cdk:subnet-type", "Public"); }}) + .tags(java.util.Map.of("aws-cdk:subnet-type", "Public")) // Java 9 or later .build()); ``` diff --git a/v2/resources.md b/v2/resources.md index 0464f2a8..a8ddf966 100644 --- a/v2/resources.md +++ b/v2/resources.md @@ -470,9 +470,9 @@ lambda.Function(self, "MyLambda", environment=dict(BUCKET_NAME=bucket.bucket_nam final Bucket bucket = new Bucket(this, "Bucket"); Function.Builder.create(this, "MyLambda") - .environment(new HashMap() {{ - put("BUCKET_NAME", bucket.getBucketName()); - }}).build(); + .environment(java.util.Map.of( // Java 9 or later + "BUCKET_NAME", bucket.getBucketName())) + .build(); ``` ------ @@ -659,7 +659,7 @@ ec2.Vpc.from_lookup(self, "PublicVpc", ``` Vpc.fromLookup(this, "PublicVpc", VpcLookupOptions.builder() - .tags(new HashMap {{ put("aws-cdk:subnet-type", "Public"); }}) + .tags(java.util.Map.of("aws-cdk:subnet-type", "Public")) // Java 9 or later .build()); ``` From d9e5d4faddecf1377e31b343d5ab4e1d3db0d503 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 10 Mar 2022 00:26:21 +0000 Subject: [PATCH 500/655] use Map.of instead of {{ ... }} in Java examples --- v1/assets.md | 16 ++++++++-------- v1/cdk_pipeline.md | 4 ++-- v1/cfn_layer.md | 31 +++++++++++++------------------ v1/constructs.md | 6 +++--- v1/how_to_set_cw_alarm.md | 6 +++--- v1/permissions.md | 9 ++++----- v1/serverless_example.md | 12 ++++++------ v1/tokens.md | 11 +++++------ v1/use_cfn_public_registry.md | 6 +++--- v1/use_cfn_template.md | 12 +++++------- v2/assets.md | 16 ++++++++-------- v2/cdk_pipeline.md | 4 ++-- v2/cfn_layer.md | 31 +++++++++++++------------------ v2/constructs.md | 6 +++--- v2/how_to_set_cw_alarm.md | 6 +++--- v2/permissions.md | 9 ++++----- v2/serverless_example.md | 12 ++++++------ v2/tokens.md | 11 +++++------ v2/use_cfn_public_registry.md | 6 +++--- v2/use_cfn_template.md | 12 +++++------- 20 files changed, 104 insertions(+), 122 deletions(-) diff --git a/v1/assets.md b/v1/assets.md index d9cc2728..bec9c384 100644 --- a/v1/assets.md +++ b/v1/assets.md @@ -371,11 +371,11 @@ public class FunctionStack extends Stack { .code(Code.fromAsset(new File(startDir, "handler").toString())) .runtime(Runtime.PYTHON_3_6) .handler("index.lambda_handler") - .environment(new HashMap() {{ - put("S3_BUCKET_NAME", imageAsset.getS3BucketName()); - put("S3_OBJECT_KEY", imageAsset.getS3ObjectKey()); - put("S3_URL", imageAsset.getS3Url()); - }}).build(); + .environment(java.util.Map.of( // Java 9 or later + "S3_BUCKET_NAME", imageAsset.getS3BucketName(), + "S3_OBJECT_KEY", imageAsset.getS3ObjectKey(), + "S3_URL", imageAsset.getS3Url())) + .build(); } } ``` @@ -843,9 +843,9 @@ asset = DockerImageAsset(self, "MyBulidImage", ``` DockerImageAsset asset = DockerImageAsset.Builder.create(this, "my-image"), .directory(new File(startDir, "my-image").toString()) - .buildArgs(new HashMap() {{ - put("HTTP_PROXY", "http://10.20.30.2:1234"); - }}).build(); + .buildArgs(java.util.Map.of( // Java 9 or later + "HTTP_PROXY", "http://10.20.30.2:1234")) + .build(); ``` ------ diff --git a/v1/cdk_pipeline.md b/v1/cdk_pipeline.md index a10b25c1..005cb699 100644 --- a/v1/cdk_pipeline.md +++ b/v1/cdk_pipeline.md @@ -1158,8 +1158,8 @@ loadBalancerAddress = CfnOutput.Builder.create(lbStack, "LbAddress") .build(); stage.addPost(ShellStep.Builder.create("lbaddr") - .envFromCfnOutputs(new HashMap() {{ - put("lbAddr", loadBalancerAddress); }}) + .envFromCfnOutputs( // Map.of requires Java 9 or later + java.util.Map.of("lbAddr", loadBalancerAddress)) .commands(Arrays.asList("echo $lbAddr")) .build()); ``` diff --git a/v1/cfn_layer.md b/v1/cfn_layer.md index e6da8c9e..a57b63fe 100644 --- a/v1/cfn_layer.md +++ b/v1/cfn_layer.md @@ -59,10 +59,9 @@ s3.CfnBucket(self, "MyBucket", ``` CfnBucket.Builder.create(this, "MyBucket") - .analyticsConfigurations(Arrays.asList(new HashMap() {{ - put("id", "Config"); - // ... - }})).build(); + .analyticsConfigurations(Arrays.asList(java.util.Map.of( // Java 9 or later + "id", "Config", // ... + ))).build(); ``` ------ @@ -142,14 +141,12 @@ cdk.CfnResource(self, 'MyBucket', ``` CfnResource.Builder.create(this, "MyBucket") .type("AWS::S3::Bucket") - .properties(new HashMap() {{ + .properties(java.util.Map.of( // Map.of requires Java 9 or later // Note the PascalCase here! These are CloudFormation identifiers - put("AnalyticsConfigurations", Arrays.asList( - new HashMap() {{ - put("Id", "Config"); - // ... - }})); - }}).build(); + "AnalyticsConfigurations", Arrays.asList( + java.util.Map.of("Id", "Config", // ... + )))) + .build(); ``` ------ @@ -239,10 +236,9 @@ cfn_bucket.analytics_configuration = [ CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); cfnBucket.setAnalyticsConfigurations( - Arrays.asList(new HashMap() {{ - put("Id", "Config"); - // ... - }})); + Arrays.asList(java.util.Map.of( // Java 9 or later + "Id", "Config", // ... + )); ``` ------ @@ -296,9 +292,8 @@ cfn_bucket.cfn_options.metadata = { #### [ Java ] ``` -cfnBucket.getCfnOptions().setMetadata(new HashMap() {{ - put("MetadataKey", "Metadatavalue"); -}}); +cfnBucket.getCfnOptions().setMetadata(java.util.Map.of( // Java 9+ + "MetadataKey", "Metadatavalue")); ``` ------ diff --git a/v1/constructs.md b/v1/constructs.md index a4bb9ba2..73ba8ef7 100644 --- a/v1/constructs.md +++ b/v1/constructs.md @@ -607,9 +607,9 @@ final Queue jobsQueue = new Queue(this, "jobs"); Function createJobLambda = Function.Builder.create(this, "create-job") .handler("index.handler") .code(Code.fromAsset("./create-job-lambda-code")) - .environment(new HashMap() {{ - put("QUEUE_URL", jobsQueue.getQueueUrl()); - }}).build(); + .environment(java.util.Map.of( // Map.of is Java 9 or later + "QUEUE_URL", jobsQueue.getQueueUrl()) + .build(); ``` ------ diff --git a/v1/how_to_set_cw_alarm.md b/v1/how_to_set_cw_alarm.md index c3be2bd1..e04f3951 100644 --- a/v1/how_to_set_cw_alarm.md +++ b/v1/how_to_set_cw_alarm.md @@ -87,9 +87,9 @@ metric = cloudwatch.Metric( Metric metric = Metric.Builder.create() .namespace("MyNamespace") .metricName("MyMetric") - .dimensions(new HashMap() {{ - put("MyDimension", "MyDimensionValue"); - }}).build(); + .dimensions(java.util.Map.of( // Java 9 or later + "MyDimension", "MyDimensionValue")) + .build(); ``` ------ diff --git a/v1/permissions.md b/v1/permissions.md index 6c8e0755..1f0a5822 100644 --- a/v1/permissions.md +++ b/v1/permissions.md @@ -232,11 +232,10 @@ role.addToPolicy(PolicyStatement.Builder.create() .effect(Effect.DENY) .resources(Arrays.asList(bucket.getBucketArn(), otherRole.getRoleArn())) .actions(Arrays.asList("ec2:SomeAction", "s3:AnotherAction")) - .conditions(new HashMap() {{ - put("StringEquals", new HashMap() {{ - put("ec2:AuthorizedService", "codebuild.amazonaws.com"); - }}); - }}).build()); + .conditions(java.util.Map.of( // Map.of requires Java 9 or later + "StringEquals", java.util.Map.of( + "ec2:AuthorizedService", "codebuild.amazonaws.com"))) + .build()); ``` ------ diff --git a/v1/serverless_example.md b/v1/serverless_example.md index 61837e04..5b8ffcdd 100644 --- a/v1/serverless_example.md +++ b/v1/serverless_example.md @@ -421,9 +421,9 @@ public class WidgetService extends Construct { .runtime(Runtime.NODEJS_14_X) .code(Code.fromAsset("resources")) .handler("widgets.main") - .environment(new HashMap() {{ - put("BUCKET", bucket.getBucketName()); - }}).build(); + .environment(java.util.Map.of // Java 9 or later + "BUCKET", bucket.getBucketName()) + .build(); bucket.grantReadWrite(handler); @@ -432,9 +432,9 @@ public class WidgetService extends Construct { .build(); LambdaIntegration getWidgetsIntegration = LambdaIntegration.Builder.create(handler) - .requestTemplates(new HashMap() {{ - put("application/json", "{ \"statusCode\": \"200\" }"); - }}).build(); + .requestTemplates(java.util.Map.of( // Map.of is Java 9 or later + "application/json", "{ \"statusCode\": \"200\" }")) + .build(); api.getRoot().addMethod("GET", getWidgetsIntegration); } diff --git a/v1/tokens.md b/v1/tokens.md index 0403e6b6..419c2205 100644 --- a/v1/tokens.md +++ b/v1/tokens.md @@ -55,9 +55,9 @@ fn = lambda_.Function(stack, "MyLambda", final Bucket bucket = new Bucket(this, "MyBucket"); Function fn = Function.Builder.create(this, "MyLambda") - .environment(new HashMap() {{ - put("BUCKET_NAME", bucket.getBucketName()); - }}).build(); + .environment(java.util.Map.of( // Map.of requires Java 9+ + "BUCKET_NAME", bucket.getBucketName())) + .build(); ``` ------ @@ -408,9 +408,8 @@ string = stack.to_json_string(dict(value=bucket.bucket_name)) ``` Stack stack = Stack.of(this); -String stringVal = stack.toJsonString(new HashMap() {{ - put("value", bucket.getBucketName()); -}}); +String stringVal = stack.toJsonString(java.util.Map.of( // Map.of requires Java 9+ + "value", bucket.getBucketName())); ``` ------ diff --git a/v1/use_cfn_public_registry.md b/v1/use_cfn_public_registry.md index 2f4c8458..ce3a2de0 100644 --- a/v1/use_cfn_public_registry.md +++ b/v1/use_cfn_public_registry.md @@ -90,9 +90,9 @@ ubucket = CfnResource(self, "MyUltimateBucket", ``` CfnResource.Builder.create(this, "MyUltimateBucket") .type("MY::S5::UltimateBucket::MODULE") - .properties(new HashMap() {{ - put("BucketName", "UltimateBucket"); - }}); + .properties(java.util.Map.of( // Map.of requires Java 9+ + "BucketName", "UltimateBucket")) + .build();; ``` ------ diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index eb79b7d7..5e1fae6a 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -482,9 +482,8 @@ template = cfn_inc.CfnInclude(self, "Template", ``` CfnInclude template = CfnInclude.Builder.create(this, "Template") .templateFile("my-template.json") - .parameters(new HashMap() {{ - put("UploadBucket", bucket.getBucketArn()); - }}) + .parameters(java.util.Map.of( // Map.of requires Java 9+ + "UploadBucket", bucket.getBucketArn())) .build(); ``` @@ -634,10 +633,9 @@ nested_template = main_template.load_nested_stack("NestedStack", ``` CfnInclude mainTemplate = CfnInclude.Builder.create(this, "MainStack") .templateFile("main-template.json") - .loadNestedStacks(new HashMap() {{ - put("NestedStack", CfnIncludeProps.builder() - .templateFile("nested-template.json").build()); - }}) + .loadNestedStacks(java.util.Map.of( // Map.of requires Java 9+ + "NestedStack", CfnIncludeProps.builder() + .templateFile("nested-template.json").build())) .build(); // or add it some time after importing the main stack diff --git a/v2/assets.md b/v2/assets.md index a629a5e9..91be33bc 100644 --- a/v2/assets.md +++ b/v2/assets.md @@ -373,11 +373,11 @@ public class FunctionStack extends Stack { .code(Code.fromAsset(new File(startDir, "handler").toString())) .runtime(Runtime.PYTHON_3_6) .handler("index.lambda_handler") - .environment(new HashMap() {{ - put("S3_BUCKET_NAME", imageAsset.getS3BucketName()); - put("S3_OBJECT_KEY", imageAsset.getS3ObjectKey()); - put("S3_URL", imageAsset.getS3Url()); - }}).build(); + .environment(java.util.Map.of( // Java 9 or later + "S3_BUCKET_NAME", imageAsset.getS3BucketName(), + "S3_OBJECT_KEY", imageAsset.getS3ObjectKey(), + "S3_URL", imageAsset.getS3Url())) + .build(); } } ``` @@ -845,9 +845,9 @@ asset = DockerImageAsset(self, "MyBulidImage", ``` DockerImageAsset asset = DockerImageAsset.Builder.create(this, "my-image"), .directory(new File(startDir, "my-image").toString()) - .buildArgs(new HashMap() {{ - put("HTTP_PROXY", "http://10.20.30.2:1234"); - }}).build(); + .buildArgs(java.util.Map.of( // Java 9 or later + "HTTP_PROXY", "http://10.20.30.2:1234")) + .build(); ``` ------ diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index 1aeb3a69..a21e658d 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -1084,8 +1084,8 @@ loadBalancerAddress = CfnOutput.Builder.create(lbStack, "LbAddress") .build(); stage.addPost(ShellStep.Builder.create("lbaddr") - .envFromCfnOutputs(new HashMap() {{ - put("lbAddr", loadBalancerAddress); }}) + .envFromCfnOutputs( // Map.of requires Java 9 or later + java.util.Map.of("lbAddr", loadBalancerAddress)) .commands(Arrays.asList("echo $lbAddr")) .build()); ``` diff --git a/v2/cfn_layer.md b/v2/cfn_layer.md index 3badc196..34b897b9 100644 --- a/v2/cfn_layer.md +++ b/v2/cfn_layer.md @@ -59,10 +59,9 @@ s3.CfnBucket(self, "MyBucket", ``` CfnBucket.Builder.create(this, "MyBucket") - .analyticsConfigurations(Arrays.asList(new HashMap() {{ - put("id", "Config"); - // ... - }})).build(); + .analyticsConfigurations(Arrays.asList(java.util.Map.of( // Java 9 or later + "id", "Config", // ... + ))).build(); ``` ------ @@ -142,14 +141,12 @@ cdk.CfnResource(self, 'MyBucket', ``` CfnResource.Builder.create(this, "MyBucket") .type("AWS::S3::Bucket") - .properties(new HashMap() {{ + .properties(java.util.Map.of( // Map.of requires Java 9 or later // Note the PascalCase here! These are CloudFormation identifiers - put("AnalyticsConfigurations", Arrays.asList( - new HashMap() {{ - put("Id", "Config"); - // ... - }})); - }}).build(); + "AnalyticsConfigurations", Arrays.asList( + java.util.Map.of("Id", "Config", // ... + )))) + .build(); ``` ------ @@ -239,10 +236,9 @@ cfn_bucket.analytics_configuration = [ CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); cfnBucket.setAnalyticsConfigurations( - Arrays.asList(new HashMap() {{ - put("Id", "Config"); - // ... - }})); + Arrays.asList(java.util.Map.of( // Java 9 or later + "Id", "Config", // ... + )); ``` ------ @@ -296,9 +292,8 @@ cfn_bucket.cfn_options.metadata = { #### [ Java ] ``` -cfnBucket.getCfnOptions().setMetadata(new HashMap() {{ - put("MetadataKey", "Metadatavalue"); -}}); +cfnBucket.getCfnOptions().setMetadata(java.util.Map.of( // Java 9+ + "MetadataKey", "Metadatavalue")); ``` ------ diff --git a/v2/constructs.md b/v2/constructs.md index 7068d23e..f05b3c7c 100644 --- a/v2/constructs.md +++ b/v2/constructs.md @@ -611,9 +611,9 @@ final Queue jobsQueue = new Queue(this, "jobs"); Function createJobLambda = Function.Builder.create(this, "create-job") .handler("index.handler") .code(Code.fromAsset("./create-job-lambda-code")) - .environment(new HashMap() {{ - put("QUEUE_URL", jobsQueue.getQueueUrl()); - }}).build(); + .environment(java.util.Map.of( // Map.of is Java 9 or later + "QUEUE_URL", jobsQueue.getQueueUrl()) + .build(); ``` ------ diff --git a/v2/how_to_set_cw_alarm.md b/v2/how_to_set_cw_alarm.md index 42fb63d3..ed562f65 100644 --- a/v2/how_to_set_cw_alarm.md +++ b/v2/how_to_set_cw_alarm.md @@ -87,9 +87,9 @@ metric = cloudwatch.Metric( Metric metric = Metric.Builder.create() .namespace("MyNamespace") .metricName("MyMetric") - .dimensions(new HashMap() {{ - put("MyDimension", "MyDimensionValue"); - }}).build(); + .dimensions(java.util.Map.of( // Java 9 or later + "MyDimension", "MyDimensionValue")) + .build(); ``` ------ diff --git a/v2/permissions.md b/v2/permissions.md index e51ec1bf..2f051297 100644 --- a/v2/permissions.md +++ b/v2/permissions.md @@ -232,11 +232,10 @@ role.addToPolicy(PolicyStatement.Builder.create() .effect(Effect.DENY) .resources(Arrays.asList(bucket.getBucketArn(), otherRole.getRoleArn())) .actions(Arrays.asList("ec2:SomeAction", "s3:AnotherAction")) - .conditions(new HashMap() {{ - put("StringEquals", new HashMap() {{ - put("ec2:AuthorizedService", "codebuild.amazonaws.com"); - }}); - }}).build()); + .conditions(java.util.Map.of( // Map.of requires Java 9 or later + "StringEquals", java.util.Map.of( + "ec2:AuthorizedService", "codebuild.amazonaws.com"))) + .build()); ``` ------ diff --git a/v2/serverless_example.md b/v2/serverless_example.md index 18d957d1..101c4063 100644 --- a/v2/serverless_example.md +++ b/v2/serverless_example.md @@ -359,9 +359,9 @@ public class WidgetService extends Construct { .runtime(Runtime.NODEJS_14_X) .code(Code.fromAsset("resources")) .handler("widgets.main") - .environment(new HashMap() {{ - put("BUCKET", bucket.getBucketName()); - }}).build(); + .environment(java.util.Map.of // Java 9 or later + "BUCKET", bucket.getBucketName()) + .build(); bucket.grantReadWrite(handler); @@ -370,9 +370,9 @@ public class WidgetService extends Construct { .build(); LambdaIntegration getWidgetsIntegration = LambdaIntegration.Builder.create(handler) - .requestTemplates(new HashMap() {{ - put("application/json", "{ \"statusCode\": \"200\" }"); - }}).build(); + .requestTemplates(java.util.Map.of( // Map.of is Java 9 or later + "application/json", "{ \"statusCode\": \"200\" }")) + .build(); api.getRoot().addMethod("GET", getWidgetsIntegration); } diff --git a/v2/tokens.md b/v2/tokens.md index 402da9c8..b0f56739 100644 --- a/v2/tokens.md +++ b/v2/tokens.md @@ -55,9 +55,9 @@ fn = lambda_.Function(stack, "MyLambda", final Bucket bucket = new Bucket(this, "MyBucket"); Function fn = Function.Builder.create(this, "MyLambda") - .environment(new HashMap() {{ - put("BUCKET_NAME", bucket.getBucketName()); - }}).build(); + .environment(java.util.Map.of( // Map.of requires Java 9+ + "BUCKET_NAME", bucket.getBucketName())) + .build(); ``` ------ @@ -408,9 +408,8 @@ string = stack.to_json_string(dict(value=bucket.bucket_name)) ``` Stack stack = Stack.of(this); -String stringVal = stack.toJsonString(new HashMap() {{ - put("value", bucket.getBucketName()); -}}); +String stringVal = stack.toJsonString(java.util.Map.of( // Map.of requires Java 9+ + put("value", bucket.getBucketName()))); ``` ------ diff --git a/v2/use_cfn_public_registry.md b/v2/use_cfn_public_registry.md index 363aba4b..819a3ae5 100644 --- a/v2/use_cfn_public_registry.md +++ b/v2/use_cfn_public_registry.md @@ -90,9 +90,9 @@ ubucket = CfnResource(self, "MyUltimateBucket", ``` CfnResource.Builder.create(this, "MyUltimateBucket") .type("MY::S5::UltimateBucket::MODULE") - .properties(new HashMap() {{ - put("BucketName", "UltimateBucket"); - }}); + .properties(java.util.Map.of( // Map.of requires Java 9+ + "BucketName", "UltimateBucket")) + .build();; ``` ------ diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 0241a652..4a1f7ee2 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -436,9 +436,8 @@ template = cfn_inc.CfnInclude(self, "Template", ``` CfnInclude template = CfnInclude.Builder.create(this, "Template") .templateFile("my-template.json") - .parameters(new HashMap() {{ - put("UploadBucket", bucket.getBucketArn()); - }}) + .parameters(java.util.Map.of( // Map.of requires Java 9+ + "UploadBucket", bucket.getBucketArn())) .build(); ``` @@ -588,10 +587,9 @@ nested_template = main_template.load_nested_stack("NestedStack", ``` CfnInclude mainTemplate = CfnInclude.Builder.create(this, "MainStack") .templateFile("main-template.json") - .loadNestedStacks(new HashMap() {{ - put("NestedStack", CfnIncludeProps.builder() - .templateFile("nested-template.json").build()); - }}) + .loadNestedStacks(java.util.Map.of( // Map.of requires Java 9+ + "NestedStack", CfnIncludeProps.builder() + .templateFile("nested-template.json").build())) .build(); // or add it some time after importing the main stack From 3d3acd4b62a433861565fb2316b0781a4236106b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 10 Mar 2022 01:19:02 +0000 Subject: [PATCH 501/655] use builder in place of new for Java import example and include one using var --- v1/multiple_languages.md | 10 ++++++++-- v2/multiple_languages.md | 10 ++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/v1/multiple_languages.md b/v1/multiple_languages.md index 992520c6..cc1f89b4 100644 --- a/v1/multiple_languages.md +++ b/v1/multiple_languages.md @@ -80,12 +80,18 @@ import software.amazon.awscdk.services.s3.EventType; // An imported class may now be accessed using the simple class name (assuming that name // does not conflict with another class) -Bucket bucket = new Bucket(...); +Bucket bucket = Bucket.Builder.create(...).build(); // We can always use the qualified name of a class (including its package) even without an // import directive software.amazon.awscdk.services.s3.Bucket bucket = - new software.amazon.awscdk.services.s3.Bucket(...); + software.amazon.awscdk.services.s3.Bucket.Builder.create(...) + .build(); + +// Java 10 or later can use var keyword to avoid typing the type twice +var bucket = + software.amazon.awscdk.services.s3.Bucket.Builder.create(...) + .build(); ``` ------ diff --git a/v2/multiple_languages.md b/v2/multiple_languages.md index df1e2f49..3da9f293 100644 --- a/v2/multiple_languages.md +++ b/v2/multiple_languages.md @@ -91,12 +91,18 @@ import software.amazon.awscdk.services.s3.EventType; // An imported class may now be accessed using the simple class name (assuming that name // does not conflict with another class) -Bucket bucket = new Bucket(...); +Bucket bucket = Bucket.Builder.create(...).build(); // We can always use the qualified name of a class (including its package) even without an // import directive software.amazon.awscdk.services.s3.Bucket bucket = - new software.amazon.awscdk.services.s3.Bucket(...); + software.amazon.awscdk.services.s3.Bucket.Builder.create(...) + .build(); + +// Java 10 or later can use var keyword to avoid typing the type twice +var bucket = + software.amazon.awscdk.services.s3.Bucket.Builder.create(...) + .build(); ``` ------ From 8cc10985b49fe10cd94c0d3deef3f64ffe0895f9 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 15 Mar 2022 23:37:36 +0000 Subject: [PATCH 502/655] fix property name in Java --- v1/how_to_set_cw_alarm.md | 2 +- v2/how_to_set_cw_alarm.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/how_to_set_cw_alarm.md b/v1/how_to_set_cw_alarm.md index e04f3951..247bcdcc 100644 --- a/v1/how_to_set_cw_alarm.md +++ b/v1/how_to_set_cw_alarm.md @@ -87,7 +87,7 @@ metric = cloudwatch.Metric( Metric metric = Metric.Builder.create() .namespace("MyNamespace") .metricName("MyMetric") - .dimensions(java.util.Map.of( // Java 9 or later + .dimensionsMap(java.util.Map.of( // Java 9 or later "MyDimension", "MyDimensionValue")) .build(); ``` diff --git a/v2/how_to_set_cw_alarm.md b/v2/how_to_set_cw_alarm.md index ed562f65..8a1ea880 100644 --- a/v2/how_to_set_cw_alarm.md +++ b/v2/how_to_set_cw_alarm.md @@ -87,7 +87,7 @@ metric = cloudwatch.Metric( Metric metric = Metric.Builder.create() .namespace("MyNamespace") .metricName("MyMetric") - .dimensions(java.util.Map.of( // Java 9 or later + .dimensionsMap(java.util.Map.of( // Java 9 or later "MyDimension", "MyDimensionValue")) .build(); ``` From 3298a688504ad830ab1049f1115846d48a43f14d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 15 Mar 2022 23:38:22 +0000 Subject: [PATCH 503/655] fix JSON template and remove unnecessary cast --- v1/use_cfn_template.md | 12 +++++++----- v2/use_cfn_template.md | 12 +++++++----- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index 5e1fae6a..18c04f12 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -65,10 +65,12 @@ You can use either a JSON or YAML template\. We recommend JSON if available, sin ``` { - "MyBucket": { - "Type": "AWS::S3::Bucket", - "Properties": { - "BucketName": "MyBucket", + "Resources": { + "MyBucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": "MyBucket", + } } } } @@ -328,7 +330,7 @@ const cfnBucket = template.getResource('MyBucket') as s3.CfnBucket; #### [ JavaScript ] ``` -const cfnBucket = template.getResource('MyBucket') as s3.CfnBucket; +const cfnBucket = template.getResource('MyBucket'); ``` ------ diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 4a1f7ee2..e78ef1ac 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -16,10 +16,12 @@ You can use either a JSON or YAML template\. We recommend JSON if available, sin ``` { - "MyBucket": { - "Type": "AWS::S3::Bucket", - "Properties": { - "BucketName": "MyBucket", + "Resources": { + "MyBucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": "MyBucket", + } } } } @@ -282,7 +284,7 @@ const cfnBucket = template.getResource('MyBucket') as s3.CfnBucket; #### [ JavaScript ] ``` -const cfnBucket = template.getResource('MyBucket') as s3.CfnBucket; +const cfnBucket = template.getResource('MyBucket'); ``` ------ From f5b270b7f7c354e26cafa56011031eb75b9c39ff Mon Sep 17 00:00:00 2001 From: "Martin S. Kyukov" Date: Fri, 18 Mar 2022 02:01:59 +0100 Subject: [PATCH 504/655] Double quotes instead of single quotes (#388) Double quotes are valid syntax for the example in the C# section --- v2/get_ssm_value.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/v2/get_ssm_value.md b/v2/get_ssm_value.md index e0a3a275..e0ddc47c 100644 --- a/v2/get_ssm_value.md +++ b/v2/get_ssm_value.md @@ -89,13 +89,13 @@ using Amazon.CDK.AWS.SSM; // Get latest version or specified version of plain string attribute var latestStringToken = StringParameter.ValueForStringParameter( - this, 'my-plain-parameter-name'); // latest version + this, "my-plain-parameter-name"); // latest version var versionOfStringToken = StringParameter.ValueForStringParameter( - this, 'my-plain-parameter-name', 1); // version 1 + this, "my-plain-parameter-name", 1); // version 1 // Get specified version of secure string attribute var secureStringToken = StringParameter.ValueForSecureStringParameter( - this, 'my-secure-parameter-name', 1); // must specify version + this, "my-secure-parameter-name", 1); // must specify version ``` ------ @@ -172,4 +172,4 @@ When updating an SSM value that already exists, also include the `--overwrite` o ``` aws ssm put-parameter --overwrite --name "parameter-name" --type "String" --value "parameter-value" aws ssm put-parameter --overwrite --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" -``` \ No newline at end of file +``` From e4133f64c99dc0eed736155a10847a576d723b43 Mon Sep 17 00:00:00 2001 From: Michael Kaiser Date: Thu, 17 Mar 2022 20:06:28 -0500 Subject: [PATCH 505/655] Chore(Bootstrap): Add latest version 10 to table. (#389) * Update bootstrapping.md * Update bootstrapping.md * Update bootstrapping.md --- v1/bootstrapping.md | 3 ++- v2/bootstrapping.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/v1/bootstrapping.md b/v1/bootstrapping.md index cf9089a1..69ca4896 100644 --- a/v1/bootstrapping.md +++ b/v1/bootstrapping.md @@ -627,4 +627,5 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | | 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | -| 9 | 1\.135\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | \ No newline at end of file +| 9 | 1\.135\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | +| 10 | 1\.139\.0 | ECR ScanOnPush is now enabled by default. | diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index 6164659b..6b9732ef 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -555,4 +555,5 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | | 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | -| 9 | 2\.1\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | \ No newline at end of file +| 9 | 2\.1\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | +| 10 | 2\.4\.0 | ECR ScanOnPush is now enabled by default. | From fa8ad2ca6077b9f6b431f289065f614680918495 Mon Sep 17 00:00:00 2001 From: "Sergio F. Gonzalez" Date: Fri, 18 Mar 2022 02:09:30 +0100 Subject: [PATCH 506/655] Fix orphan asterisk in docs (#390) --- v2/work-with.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v2/work-with.md b/v2/work-with.md index 3adf6468..79013a3a 100644 --- a/v2/work-with.md +++ b/v2/work-with.md @@ -100,7 +100,7 @@ Each module's reference material is broken into the following sections\. + *Classes*: Non\-construct classes that provide functionality used by constructs in the module\. + *Structs*: Data structures \(attribute bundles\) that define the structure of composite values such as properties \(the `props` argument of constructs\) and options\. + *Interfaces*: Interfaces, whose names all begin with "I", define the absolute minimum functionality for the corresponding construct or other class\. The CDK uses construct interfaces to represent AWS resources that are defined outside your AWS CDK app and imported by methods such as `Bucket.fromBucketArn()`\. -+ *Enums*: Collections of named values for use in specifying \*certain construct parameters\. Using an enumerated value allows the CDK to check these values for validity during synthesis\. ++ *Enums*: Collections of named values for use in specifying *certain construct parameters*. Using an enumerated value allows the CDK to check these values for validity during synthesis\. + *CloudFormation Resources*: These L1 constructs, whose names begin with "Cfn", represent exactly the resources defined in the CloudFormation specification\. They are automatically generated from that specification with each CDK release\. Each L2 or L3 construct encapsulates one or more CloudFormation resources\. + *CloudFormation Property Types*: The collection of named values that define the properties for each CloudFormation Resource\. @@ -115,4 +115,4 @@ When instantiating resources in your CDK app, then, you should always use concre Some interfaces are minimum versions of properties or options bundles \(shown in the AWS CDK API Reference as Structs\) that are associated with specific constructs\. For example, `IBucketProps` is the smallest set of properties required to instantiate a bucket\. Such interfaces can be useful when subclassing constructs to accept arguments that you'll pass on to your parent class\. If you require one or more additional properties, you'll want to implement or derive from this interface, or from a more specific type such as `BucketProps`\. **Note** -Some programming languages supported by the AWS CDK don't have an interface feature\. In these languages, interfaces are just ordinary classes\. You can identify them by their names, which follow the pattern of an initial "I" followed by the name of some other construct \(e\.g\. `IBucket`\)\. The same rules apply\. \ No newline at end of file +Some programming languages supported by the AWS CDK don't have an interface feature\. In these languages, interfaces are just ordinary classes\. You can identify them by their names, which follow the pattern of an initial "I" followed by the name of some other construct \(e\.g\. `IBucket`\)\. The same rules apply\. From 8c711ff77ce2706078b073bc30c065ddb100725e Mon Sep 17 00:00:00 2001 From: Mostafa Hussein Date: Fri, 18 Mar 2022 02:11:41 +0100 Subject: [PATCH 507/655] fix typo in C# csproj library Include (#393) --- v2/migrating-v2.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 3ad88092..14a5a4f8 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -297,7 +297,7 @@ Experimental constructs are provided in separate, independently\-versioned packa ``` - + ``` @@ -342,4 +342,4 @@ Expected changes include but are not limited to: Unexpected changes are typically not caused by upgrading to AWS CDK v2 in itself, but are usually the result of deprecated behavior that was previously changed by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, removing feature flags, revising your code as necessary, deploying, and then upgrading to v2\. -If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. \ No newline at end of file +If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. From f68eb7d94b560fa180d09ba28a8f010d2c653666 Mon Sep 17 00:00:00 2001 From: Gary Donovan Date: Fri, 18 Mar 2022 12:20:10 +1100 Subject: [PATCH 508/655] Update description of CDK bootstrap behaviour (#394) * Update behaviour of `cdk bootstrap` when app is present * Highlight default behaviour uses FullAdmin * Update warning about admin permissions to be more specific * quote the cdk command * Fix list formating * Tweak text Co-authored-by: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> --- v2/bootstrapping.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index 6b9732ef..0986ad7e 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -55,7 +55,7 @@ cdk bootstrap aws://123456789012/us-east-1 cdk bootstrap 123456789012/us-east-1 123456789012/us-west-1 ``` -If you do not specify at least one environment in the `cdk bootstrap` command, the AWS CDK Toolkit synthesizes the AWS CDK app in the current directory and bootstraps all the environments referenced in the app\. If a stack is environment\-agnostic \(that is, it does not have an `env` property\), the CDK's environment \(for example, the one specified using \-\-profile, or the default AWS environment otherwise\) is applied to make the stack environment\-specific, and that environment is then bootstrapped\. +The AWS CDK Toolkit always synthesizes the AWS CDK app in the current directory, and if you do not specify at least one environment in the `cdk bootstrap` command it will bootstrap all the environments referenced in the app\. If a stack is environment\-agnostic \(that is, it does not have an `env` property\), the CDK's environment \(for example, the one specified using \-\-profile, or the default AWS environment otherwise\) is applied to make the stack environment\-specific, and that environment is then bootstrapped\. For example, the following command synthesizes the current AWS CDK app using the `prod` AWS profile, then bootstraps its environments\. @@ -128,13 +128,15 @@ There are two ways to customize the bootstrapping resources\. The following command\-line options, when used with CDK Toolkit's cdk bootstrap, provide commonly\-needed adjustments to the bootstrapping template\. + \-\-bootstrap\-bucket\-name overrides the name of the Amazon S3 bucket\. May require changes to your CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + \-\-bootstrap\-kms\-key\-id overrides the AWS KMS key used to encrypt the S3 bucket\. -+ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. -**Tip** -The policies must be passed as a single string argument, with the policy ARNs separated by commas, like this: - - ``` - --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess". - ``` ++ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. + **Tip** + The policies must be passed as a single string argument, with the policy ARNs separated by commas, like this: + + ``` + --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess". + ``` + **Important** + At least one policy should be specified; otherwise, AWS CloudFormation will deploy using full administrator permissions from the `AdministratorAccess` policy\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. From ac91521f48a3a49c625727b9a5d9972b7b5a4418 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 18 Mar 2022 01:26:11 +0000 Subject: [PATCH 509/655] propagate recent PRs back to Github in both guide versions --- v1/bootstrapping.md | 8 +++++--- v1/get_ssm_value.md | 6 +++--- v1/work-with.md | 2 +- v2/bootstrapping.md | 22 +++++++++++----------- v2/get_ssm_value.md | 2 +- v2/migrating-v2.md | 4 ++-- v2/work-with.md | 4 ++-- 7 files changed, 25 insertions(+), 23 deletions(-) diff --git a/v1/bootstrapping.md b/v1/bootstrapping.md index 69ca4896..6f87739d 100644 --- a/v1/bootstrapping.md +++ b/v1/bootstrapping.md @@ -55,7 +55,7 @@ cdk bootstrap aws://123456789012/us-east-1 cdk bootstrap 123456789012/us-east-1 123456789012/us-west-1 ``` -If you do not specify at least one environment in the `cdk bootstrap` command, the AWS CDK Toolkit synthesizes the AWS CDK app in the current directory and bootstraps all the environments referenced in the app\. If a stack is environment\-agnostic \(that is, it does not have an `env` property\), the CDK's environment \(for example, the one specified using \-\-profile, or the default AWS environment otherwise\) is applied to make the stack environment\-specific, and that environment is then bootstrapped\. +The CDK Toolkit always synthesizes the AWS CDK app in the current directory\. If you do not specify at least one environment in the `cdk bootstrap` command, it bootstraps all the environments referenced in the app\. If a stack is environment\-agnostic \(that is, it does not have an `env` property\), the CDK's environment \(for example, the one specified using \-\-profile, or the default AWS environment otherwise\) is applied to make the stack environment\-specific, and that environment is then bootstrapped\. For example, the following command synthesizes the current AWS CDK app using the `prod` AWS profile, then bootstraps its environments\. @@ -174,11 +174,13 @@ The following command\-line options, when used with CDK Toolkit's cdk bootstrap, The following additional switches are available only with the modern bootstrapping template\. + \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. **Tip** - The policies must be passed as a single string argument, with the policy ARNs separated by commas, like this: +The policies must be passed as a single string argument, with the policy ARNs separated by commas, like this: ``` --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess". ``` +**Important** +At least one policy should be specified; otherwise, AWS CloudFormation will deploy using full administrator permissions from the `AdministratorAccess` policy\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. + \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. @@ -628,4 +630,4 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | | 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | | 9 | 1\.135\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | -| 10 | 1\.139\.0 | ECR ScanOnPush is now enabled by default. | +| 10 | 1\.139\.0 | ECR ScanOnPush is now enabled by default\. | \ No newline at end of file diff --git a/v1/get_ssm_value.md b/v1/get_ssm_value.md index 359ea52d..33903694 100644 --- a/v1/get_ssm_value.md +++ b/v1/get_ssm_value.md @@ -89,13 +89,13 @@ using Amazon.CDK.AWS.SSM; // Get latest version or specified version of plain string attribute var latestStringToken = StringParameter.ValueForStringParameter( - this, 'my-plain-parameter-name'); // latest version + this, "my-plain-parameter-name"); // latest version var versionOfStringToken = StringParameter.ValueForStringParameter( - this, 'my-plain-parameter-name', 1); // version 1 + this, "my-plain-parameter-name", 1); // version 1 // Get specified version of secure string attribute var secureStringToken = StringParameter.ValueForSecureStringParameter( - this, 'my-secure-parameter-name', 1); // must specify version + this, "my-secure-parameter-name", 1); // must specify version ``` ------ diff --git a/v1/work-with.md b/v1/work-with.md index 477c555b..c2b371c8 100644 --- a/v1/work-with.md +++ b/v1/work-with.md @@ -53,7 +53,7 @@ Each module's reference material is broken into the following sections\. + *Classes*: Non\-construct classes that provide functionality used by constructs in the module\. + *Structs*: Data structures \(attribute bundles\) that define the structure of composite values such as properties \(the `props` argument of constructs\) and options\. + *Interfaces*: Interfaces, whose names all begin with "I", define the absolute minimum functionality for the corresponding construct or other class\. The CDK uses construct interfaces to represent AWS resources that are defined outside your AWS CDK app and imported by methods such as `Bucket.fromBucketArn()`\. -+ *Enums*: Collections of named values for use in specifying \*certain construct parameters\. Using an enumerated value allows the CDK to check these values for validity during synthesis\. ++ *Enums*: Collections of named values for use in specifying certain construct parameters\. Using an enumerated value allows the CDK to check these values for validity during synthesis\. + *CloudFormation Resources*: These L1 constructs, whose names begin with "Cfn", represent exactly the resources defined in the CloudFormation specification\. They are automatically generated from that specification with each CDK release\. Each L2 or L3 construct encapsulates one or more CloudFormation resources\. + *CloudFormation Property Types*: The collection of named values that define the properties for each CloudFormation Resource\. diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index 0986ad7e..01ff48b7 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -55,7 +55,7 @@ cdk bootstrap aws://123456789012/us-east-1 cdk bootstrap 123456789012/us-east-1 123456789012/us-west-1 ``` -The AWS CDK Toolkit always synthesizes the AWS CDK app in the current directory, and if you do not specify at least one environment in the `cdk bootstrap` command it will bootstrap all the environments referenced in the app\. If a stack is environment\-agnostic \(that is, it does not have an `env` property\), the CDK's environment \(for example, the one specified using \-\-profile, or the default AWS environment otherwise\) is applied to make the stack environment\-specific, and that environment is then bootstrapped\. +The CDK Toolkit always synthesizes the AWS CDK app in the current directory\. If you do not specify at least one environment in the `cdk bootstrap` command, it bootstraps all the environments referenced in the app\. If a stack is environment\-agnostic \(that is, it does not have an `env` property\), the CDK's environment \(for example, the one specified using \-\-profile, or the default AWS environment otherwise\) is applied to make the stack environment\-specific, and that environment is then bootstrapped\. For example, the following command synthesizes the current AWS CDK app using the `prod` AWS profile, then bootstraps its environments\. @@ -128,15 +128,15 @@ There are two ways to customize the bootstrapping resources\. The following command\-line options, when used with CDK Toolkit's cdk bootstrap, provide commonly\-needed adjustments to the bootstrapping template\. + \-\-bootstrap\-bucket\-name overrides the name of the Amazon S3 bucket\. May require changes to your CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + \-\-bootstrap\-kms\-key\-id overrides the AWS KMS key used to encrypt the S3 bucket\. -+ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. - **Tip** - The policies must be passed as a single string argument, with the policy ARNs separated by commas, like this: - - ``` - --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess". - ``` - **Important** - At least one policy should be specified; otherwise, AWS CloudFormation will deploy using full administrator permissions from the `AdministratorAccess` policy\. ++ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. +**Tip** +The policies must be passed as a single string argument, with the policy ARNs separated by commas, like this: + + ``` + --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess". + ``` +**Important** +At least one policy should be specified; otherwise, AWS CloudFormation will deploy using full administrator permissions from the `AdministratorAccess` policy\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. @@ -558,4 +558,4 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | | 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | | 9 | 2\.1\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | -| 10 | 2\.4\.0 | ECR ScanOnPush is now enabled by default. | +| 10 | 2\.4\.0 | ECR ScanOnPush is now enabled by default\. | \ No newline at end of file diff --git a/v2/get_ssm_value.md b/v2/get_ssm_value.md index e0ddc47c..62ae2999 100644 --- a/v2/get_ssm_value.md +++ b/v2/get_ssm_value.md @@ -172,4 +172,4 @@ When updating an SSM value that already exists, also include the `--overwrite` o ``` aws ssm put-parameter --overwrite --name "parameter-name" --type "String" --value "parameter-value" aws ssm put-parameter --overwrite --name "secure-parameter-name" --type "SecureString" --value "secure-parameter-value" -``` +``` \ No newline at end of file diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 14a5a4f8..2cd0a6a1 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -293,7 +293,7 @@ import software.amazon.awscdk.services.codestar.alpha.GitHubRepository; The most straightforward way to upgrade the dependencies of a C\# CDK application is to edit the `.csproj` file manually\. Remove all stable `Amazon.CDK.*` package references and replace them with references to the `Amazon.CDK.Lib` and `Constructs` packages\. -Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. +Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` with which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. ``` @@ -342,4 +342,4 @@ Expected changes include but are not limited to: Unexpected changes are typically not caused by upgrading to AWS CDK v2 in itself, but are usually the result of deprecated behavior that was previously changed by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, removing feature flags, revising your code as necessary, deploying, and then upgrading to v2\. -If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. +If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. \ No newline at end of file diff --git a/v2/work-with.md b/v2/work-with.md index 79013a3a..b1e64809 100644 --- a/v2/work-with.md +++ b/v2/work-with.md @@ -100,7 +100,7 @@ Each module's reference material is broken into the following sections\. + *Classes*: Non\-construct classes that provide functionality used by constructs in the module\. + *Structs*: Data structures \(attribute bundles\) that define the structure of composite values such as properties \(the `props` argument of constructs\) and options\. + *Interfaces*: Interfaces, whose names all begin with "I", define the absolute minimum functionality for the corresponding construct or other class\. The CDK uses construct interfaces to represent AWS resources that are defined outside your AWS CDK app and imported by methods such as `Bucket.fromBucketArn()`\. -+ *Enums*: Collections of named values for use in specifying *certain construct parameters*. Using an enumerated value allows the CDK to check these values for validity during synthesis\. ++ *Enums*: Collections of named values for use in specifying certain construct parameters\. Using an enumerated value allows the CDK to check these values for validity during synthesis\. + *CloudFormation Resources*: These L1 constructs, whose names begin with "Cfn", represent exactly the resources defined in the CloudFormation specification\. They are automatically generated from that specification with each CDK release\. Each L2 or L3 construct encapsulates one or more CloudFormation resources\. + *CloudFormation Property Types*: The collection of named values that define the properties for each CloudFormation Resource\. @@ -115,4 +115,4 @@ When instantiating resources in your CDK app, then, you should always use concre Some interfaces are minimum versions of properties or options bundles \(shown in the AWS CDK API Reference as Structs\) that are associated with specific constructs\. For example, `IBucketProps` is the smallest set of properties required to instantiate a bucket\. Such interfaces can be useful when subclassing constructs to accept arguments that you'll pass on to your parent class\. If you require one or more additional properties, you'll want to implement or derive from this interface, or from a more specific type such as `BucketProps`\. **Note** -Some programming languages supported by the AWS CDK don't have an interface feature\. In these languages, interfaces are just ordinary classes\. You can identify them by their names, which follow the pattern of an initial "I" followed by the name of some other construct \(e\.g\. `IBucket`\)\. The same rules apply\. +Some programming languages supported by the AWS CDK don't have an interface feature\. In these languages, interfaces are just ordinary classes\. You can identify them by their names, which follow the pattern of an initial "I" followed by the name of some other construct \(e\.g\. `IBucket`\)\. The same rules apply\. \ No newline at end of file From 6d518fc9b477778fe2d24659418d9c2d091f27be Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 7 Apr 2022 16:26:03 +0000 Subject: [PATCH 510/655] add separate article on dependency management --- v1/manage-dependencies.md | 321 ++++++++++++++++++++++++++++++++++++++ v2/manage-dependencies.md | 305 ++++++++++++++++++++++++++++++++++++ 2 files changed, 626 insertions(+) create mode 100644 v1/manage-dependencies.md create mode 100644 v2/manage-dependencies.md diff --git a/v1/manage-dependencies.md b/v1/manage-dependencies.md new file mode 100644 index 00000000..aaf940ee --- /dev/null +++ b/v1/manage-dependencies.md @@ -0,0 +1,321 @@ +# Managing dependencies + +Dependencies for your AWS CDK app or library are managed using package management tools commonly used with the programming language in which you develop your app\. Typically, the CDK supports the language's standard or official package management tool, if there is one, or its most popular or widely\-supported one if not\. You may also be able to use other tools, especially if they interoperate with the supported tools, although our ability to support alternatives is limited\. + +The CDK supports the following package managers\. + + +| Language | Supported package management tool | +| --- | --- | +| TypeScript/JavaScript | NPM \(Node Package Manager\) or Yarn | +| Python | PIP \(Package Installer for Python\) | +| Java | Maven | +| C\# | NuGet | +| Go | Go modules | + +**Note** +The projects generated by cdk init specify dependencies for the CDK core libraries and stable constructs\. + +The remainder of this topic provides details on using AWS CDK dependencies in each language\. + +## TypeScript and JavaScript + +In TypeScript and JavaScript CDK projects, dependencies are specified in `package.json` in the project's main directory\. Every AWS Construct Library module is a separate NPM package\. All versions of AWS CDK packages match and specify a single version, and the same version\. If the versions are different, NPM is likely to install multiple copies of CDK libraries, and you will see unpredictable compilation or runtime errors\. + +**Tip** +When you install a package using npm install, NPM records it in `package.json` for you\. + +If you prefer, you may use Yarn in place of NPM\. However, the CDK does not support Yarn's plug\-and\-play mode, which is default mode in Yarn 2\. Add the following to your project's `.yarnrc.yml` file to disable this feature\. + +``` +nodeLinker: node-modules +``` + +### Applications + +The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. + +``` +{ + "name": "my-package", + "version": "0.1.0", + "bin": { + "my-package": "bin/my-package.js" + }, + "scripts": { + "build": "tsc", + "watch": "tsc -w", + "test": "jest", + "cdk": "cdk" + }, + "devDependencies": { + "@aws-cdk/assert": "1.121.0", + "@types/jest": "^26.0.10", + "@types/node": "10.17.27", + "jest": "^26.4.2", + "ts-jest": "^26.2.0", + "aws-cdk": "1.121.0", + "ts-node": "^9.0.0", + "typescript": "~3.9.7" + }, + "dependencies": { + "@aws-cdk/core": "1.121.0", + "source-map-support": "^0.5.16" + } +} +``` + +All CDK apps use `@aws-cdk/core`, which must be specified in the `dependencies` section of `package.json` along with all other AWS Construct Library module your app uses\. + +**Note** +All AWS CDK dependencies must have the same version\. + +Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. + +### Construct libraries + +If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. + +``` +{ + "name": "my-package", + "version": "0.0.1", + "peerDependencies": { + "@aws-cdk/core": "1.140.0", + "@aws-cdk/aws-s3": "1.140.0", + "@aws-cdk/aws-iam": "1.140.0" + }, + "devDependencies": { + "jsii": "^1.50.0", + "aws-cdk": "^1.140.0" + } +} +``` + +In `peerDependencies`, use a caret \(^\) to specify the lowest version of the AWS CDK packages that your library works with, to maximize the compatibility of your library with a range of CDK versions\. Using `peerDependencies` makes sure there is only one copy of all CDK libraries in the `node_modules` tree\. + +In `devDependencies`, specify the tools and libraries you need for testing, optionally with ^ to indicate that later compatible versions are acceptable\. Specify exactly \(without ^ or \~\) the lowest version of the CDK packages that you advertise your library be compatible with\. This practice ensures that your tests run against those versions, so that if you inadvertently use a feature found only in newer versions, your tests can catch it\. + +**Warning** +`peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies + +### Installing and updating dependencies + +Run the following command to install your project's dependencies\. + +------ +#### [ NPM ] + +``` +# Install the latest version of everything that matches the ranges in 'package.json' +npm install + +# Install the same exact dependency versions as recorded in 'package-lock.json' +npm ci +``` + +------ +#### [ Yarn ] + +``` +# Install the latest version of everything that matches the ranges in 'package.json' +yarn upgrade + +# Install the same exact dependency versions as recorded in 'yarn.lock' +yarn install --frozen-lockfile +``` + +------ + +To update the installed modules, the npm install and yarn upgrade commands given above can be used\. Either command updates the packages in `node_modules` to the latest versions that satisfy the rules in `package.json`, but they do not update `package.json` itself, which you might want to do to set a new minimum version\. If you host your package on GitHub, you can configure [Dependabot version updates](https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuring-dependabot-version-updates) to automatically update `package.json`\. Alternatively, use [npm\-check\-updates](https://www.npmjs.com/package/npm-check-updates)\. + +**Important** +By design, when you install or update dependencies, NPM and Yarn choose the latest version of every package that satisfies the requirements specified in `package.json`\. There is always a risk that these versions may be broken \(either accidentally or intentionally\)\. Test thoroughly after updating your project's dependencies\. + +## Python + +In Python, you specify dependencies by putting them in `requirements.txt` \(for applications\) or `setup.py` \(for construct libraries\)\. Dependencies are then managed with the PIP tool\. PIP is invoked in one of the following ways: + +``` +pip command options +python -m pip command options +``` + +The python \-m pip invocation works on most systems; pip requires that PIP's executable be on the system path\. If pip doesn't work, try replacing it with python \-m pip\. + +cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. + +### Applications + +An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. + +``` +aws-cdk.core==1.140.0 +aws-cdk.aws-s3==1.140.0 +aws-cdk.aws-iam==1.140.0 +``` + +**Note** +All AWS CDK dependencies must have the same version\. + +Installing a module with pip install does not add it to `requirements.txt`; you should do that yourself\. If you want to upgrade to a later version of a dependency, edit its version number in `requirements.txt`\. + +To install or update your project's dependencies after creating or editing `requirements.txt`, issue: + +``` +python -m pip install -r requirements.txt +``` + +**Tip** +The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. + +### Construct libraries + +In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. + +``` +from setuptools import setup + +setup( + name='my-package', + version='0.0.1', + install_requires=[ + 'aws-cdk.core==1.140.0', + 'aws-cdk.aws-s3==1.140.0', + 'aws-cdk.aws-iam==1.140.0', + ], + ... +) +``` + +**Note** +All AWS CDK dependencies must have the same version\. + +To work on the package for development, create or activate a virtual environment, then run the following command\. + +``` +python -m pip install -e . +``` + +Although PIP automatically installs transitive dependencies, there can only be one installed copy of any one package\. The version that is specified highest in the dependency tree is selected; applications always have the last word in what version of packages get installed\. + +## Java + +In Java, dependencies are specified in `pom.xml` and installed using Maven\. The `` container includes a `` element for each package\. Following is a section of `pom.xml` for a typical CDK Java app\. + +**Tip** +Many Java IDEs have integrated Maven support and visual `pom.xml` editors, which you may find convenient for managing dependencies\. + +``` + + 1.140.0 + + + + + software.amazon.awscdk + core + ${cdk.version} + + + software.amazon.awscdk + s3 + ${cdk.version} + + + software.amazon.awscdk + iam + ${cdk.version} + + +``` + +**Note** +All AWS CDK dependencies must have the same version\. To make it easier to update the versions of these packages while keeping them in sync, we define a propertywith the desired CDK version\. + +Maven does not support dependency locking, so while it is possible to specify version ranges in `pom.xml`, we recommend you always use exact versions to keep your builds repeatable\. + +Maven automatically installs transitive dependencies, but there can only be one installed copy of each package\. The version that is specified highest in the POM tree is selected; applications always have the last word in what version of packages get installed\. + +Maven automatically installs or updates your dependencies whenever you build \(mvn compile\) or package \(mvn package\) your project\. The CDK Toolkit does this automatically every time you run it, so generally there is no need to manually invoke Maven\. + +## C\# + +In C\# AWS CDK apps, you manage dependencies using NuGet\. NuGet has four standard, mostly\-equivalent interfaces; you can use the one that suits your needs and working style\. You can also use compatible tools, such as [Paket](https://fsprojects.github.io/Paket/) or [MyGet](https://www.myget.org/) or even edit the `.csproj` file directly\. + +NuGet does not allow you to specify version ranges for dependencies\. Every dependency is pinned to a specific version\. + +**Note** +All AWS CDK dependencies must have the same version\. + +After updating your dependencies, Visual Studio will use NuGet to retrieve the specified versions of each package the next time you build\. If you are not using Visual Studio, use the dotnet restore command to update your dependencies\. + +### Editing the project file directly + +Your project's `.csproj` file contains an `` container that lists your dependencies as ` + + + + +``` + +### The Visual Studio NuGet GUI + +Visual Studio's NuGet tools are accessible from **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution**\. Use the **Browse** tab to find the AWS Construct Library packages you want to install\. You can choose the desired version, including pre\-release versions of your modules and add them to any of the open projects\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v1/guide/images/visual-studio-nuget.png) + +Look on the **Updates** page to install new versions of your packages\. + +### The NuGet console + +The NuGet console is a PowerShell\-based interface to NuGet that works in the context of a Visual Studio project\. You can open it in Visual Studio by choosing **Tools** > **NuGet Package Manager** > **Package Manager Console**\. For more information about using this tool, see [Install and Manage Packages with the Package Manager Console in Visual Studio](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-powershell)\. + +### The `dotnet` command + +The `dotnet` command is the primary command\-line tool for working with Visual Studio C\# projects\. You can invoke it from any Windows command prompt\. Among its many capabilities, `dotnet` can add NuGet dependencies to a Visual Studio project\. + +Assuming you're in the same directory as the Visual Studio project \(`.csproj`\) file, issue a command like the following to install a package\. Note that since the main CDK library is included when you create a project, you should ever only need to explictly install experimental modules\. Experimental modules require you to specify an explicit version number\. + +``` +dotnet add package Amazon.CDK.AWS.IoT -v VERSION-NUMBER +``` + +You may issue the command from another directory by including the path to the project file, or to the directory that contains it, after the `add` keyword\. The following example assumes that you are in your AWS CDK project's main directory\. + +To install a specific version of a package, include the `-v` flag and the desired version\. + +To update a package, issue the same `dotnet add` command you used to install it\. For experimental modules, again, you must specify an explicit version number\. + +For more information about managing packages using the `dotnet` command, see [Install and Manage Packages Using the dotnet CLI](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli)\. + +### The `nuget` command + +The `nuget` command line tool can install and update NuGet packages\. However, it requires your Visual Studio project to be set up differently from the way `cdk init` sets up projects\. \(Technical details: `nuget` works with `Packages.config` projects, while `cdk init` creates a newer\-style `PackageReference` project\.\) + +We do not recommend the use of the `nuget` tool with AWS CDK projects created by `cdk init`\. If you are using another type of project, and want to use `nuget`, see the [NuGet CLI Reference](https://docs.microsoft.com/en-us/nuget/reference/nuget-exe-cli-reference)\. + +## Go + +In Go, dependencies versions are defined in `go.mod`\. The default `go.mod` is similar to the one shown here\. + +``` +module my-package + +go 1.16 + +require ( + github.com/aws/aws-cdk-go/awscdk/v2 v2.16.0 + github.com/aws/constructs-go/constructs/v10 v10.0.5 + github.com/aws/jsii-runtime-go v1.29.0 +) +``` + +Package names \(modules, in Go parlance\) are specified by URL with the version number appended\. Go's module system does not support version ranges, so all dependencies must be pinned to a specfic version\. + +Go automatically downloads dependencies whenever you build\. The CDK does this for you automatically whenever you run your app, so there is no need to do it manually\. + +You may use the go get command to install a module and update `go.mod`\. To see a list of available updates for your dependencies, issue go list \-m \-u all\. \ No newline at end of file diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md new file mode 100644 index 00000000..3bfdf888 --- /dev/null +++ b/v2/manage-dependencies.md @@ -0,0 +1,305 @@ +# Managing dependencies + +Dependencies for your AWS CDK app or library are managed using package management tools commonly used with the programming language in which you develop your app\. Typically, the CDK supports the language's standard or official package management tool, if there is one, or its most popular or widely\-supported one if not\. You may also be able to use other tools, especially if they interoperate with the supported tools, although our ability to support alternatives is limited\. + +The CDK supports the following package managers\. + + +| Language | Supported package management tool | +| --- | --- | +| TypeScript/JavaScript | NPM \(Node Package Manager\) or Yarn | +| Python | PIP \(Package Installer for Python\) | +| Java | Maven | +| C\# | NuGet | +| Go | Go modules | + +**Note** +The projects generated by cdk init specify dependencies for the CDK core libraries and stable constructs\. + +The remainder of this topic provides details on using AWS CDK dependencies in each language\. + +## TypeScript and JavaScript + +In TypeScript and JavaScript CDK projects, dependencies are specified in `package.json` in the project's main directory\. The core AWS CDK modules \(including all stable constructs\) are in a single NPM package, `aws-cdk-lib`\. Unstable modules, where the API is still undergoing refinement, are distributed in their own modules\. Additionally, the `construct` base class and supporting code is in the `constructs` module\. + +**Tip** +When you install a package using npm install, NPM records it in `package.json` for you\. + +If you prefer, you may use Yarn in place of NPM\. However, the CDK does not support Yarn's plug\-and\-play mode, which is default mode in Yarn 2\. Add the following to your project's `.yarnrc.yml` file to disable this feature\. + +``` +nodeLinker: node-modules +``` + +### Applications + +The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. + +``` +{ + "name": "my-package", + "version": "0.1.0", + "bin": { + "my-package": "bin/my-package.js" + }, + "scripts": { + "build": "tsc", + "watch": "tsc -w", + "test": "jest", + "cdk": "cdk" + }, + "devDependencies": { + "@types/jest": "^26.0.10", + "@types/node": "10.17.27", + "jest": "^26.4.2", + "ts-jest": "^26.2.0", + "aws-cdk": "2.16.0", + "ts-node": "^9.0.0", + "typescript": "~3.9.7" + }, + "dependencies": { + "aws-cdk-lib": "2.16.0", + "constructs": "^10.0.0", + "source-map-support": "^0.5.16" + } +} +``` + +For deployable CDK apps, `aws-cdk-lib` must be specified in the `dependencies` section of `package.json`\. You may use a caret \(^\) version number specifier to indicate that you will accept later versions than the one specified as long as they are within the same major version\. + +Specify exact versions for alpha construct library modules, which have APIs that may change\. Do not use ^ or \~ since later versions of these modules may bring API changes that can break your app\. + +Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. + +### Construct libraries + +If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. + +``` +{ + "name": "my-package", + "version": "0.0.1", + "peerDependencies": { + "aws-cdk-lib": "^2.14.0", + "@aws-cdk/aws-appsync-alpha": "2.10.0-alpha", + "constructs": "^10.0.0" + }, + "devDependencies": { + "aws-cdk-lib": "2.14.0", + "@aws-cdk/aws-appsync-alpha": "2.10.0-alpha", + "constructs": "10.0.0", + "jsii": "^1.50.0", + "aws-cdk": "^2.14.0" + } +} +``` + +In `peerDependencies`, use a caret \(^\) to specify the lowest version of `aws-cdk-lib` that your library works with, to maximize the compatibility of your library with a range of CDK versions\. Specify exact versions for alpha construct library modules, which have APIs that may change\. Using `peerDependencies` makes sure there is only one copy of all CDK libraries in the `node_modules` tree\. + +In `devDependencies`, specify the tools and libraries you need for testing, optionally with ^ to indicate that later compatible versions are acceptable\. Specify exactly \(without ^ or \~\) the lowest versions of `aws-cdk-lib` and other CDK packages that you advertise your library be compatible with\. This practice ensures that your tests run against those versions, so that if you inadvertently use a feature found only in newer versions, your tests can catch it\. + +**Warning** +`peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies + +### Installing and updating dependencies + +Run the following command to install your project's dependencies\. + +------ +#### [ NPM ] + +``` +# Install the latest version of everything that matches the ranges in 'package.json' +npm install + +# Install the same exact dependency versions as recorded in 'package-lock.json' +npm ci +``` + +------ +#### [ Yarn ] + +``` +# Install the latest version of everything that matches the ranges in 'package.json' +yarn upgrade + +# Install the same exact dependency versions as recorded in 'yarn.lock' +yarn install --frozen-lockfile +``` + +------ + +To update the installed modules, the npm install and yarn upgrade commands given above can be used\. Either command updates the packages in `node_modules` to the latest versions that satisfy the rules in `package.json`, but they do not update `package.json` itself, which you might want to do to set a new minimum version\. If you host your package on GitHub, you can configure [Dependabot version updates](https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuring-dependabot-version-updates) to automatically update `package.json`\. Alternatively, use [npm\-check\-updates](https://www.npmjs.com/package/npm-check-updates)\. + +**Important** +By design, when you install or update dependencies, NPM and Yarn choose the latest version of every package that satisfies the requirements specified in `package.json`\. There is always a risk that these versions may be broken \(either accidentally or intentionally\)\. Test thoroughly after updating your project's dependencies\. + +## Python + +In Python, you specify dependencies by putting them in `requirements.txt` \(for applications\) or `setup.py` \(for construct libraries\)\. Dependencies are then managed with the PIP tool\. PIP is invoked in one of the following ways: + +``` +pip command options +python -m pip command options +``` + +The python \-m pip invocation works on most systems; pip requires that PIP's executable be on the system path\. If pip doesn't work, try replacing it with python \-m pip\. + +cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. + +### Applications + +An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. + +``` +aws-cdk-lib==2.14.0 +aws-cdk.aws-appsync-alpha==2.10.0a0 +``` + +Installing a module with pip install does not add it to `requirements.txt`; you should do that yourself\. If you want to upgrade to a later version of a dependency, edit its version number in `requirements.txt`\. + +To install or update your project's dependencies after creating or editing `requirements.txt`, issue: + +``` +python -m pip install -r requirements.txt +``` + +**Tip** +The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. + +### Construct libraries + +In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. + +``` +from setuptools import setup + +setup( + name='my-package', + version='0.0.1', + install_requires=[ + 'aws-cdk-lib==2.14.0', + ], + ... +) +``` + +To work on the package for development, create or activate a virtual environment, then run the following command\. + +``` +python -m pip install -e . +``` + +Although PIP automatically installs transitive dependencies, there can only be one installed copy of any one package\. The version that is specified highest in the dependency tree is selected; applications always have the last word in what version of packages get installed\. + +## Java + +In Java, dependencies are specified in `pom.xml` and installed using Maven\. The `` container includes a `` element for each package\. Following is a section of `pom.xml` for a typical CDK Java app\. + +**Tip** +Many Java IDEs have integrated Maven support and visual `pom.xml` editors, which you may find convenient for managing dependencies\. + +``` + + + software.amazon.awscdk + aws-cdk-lib + 2.14.0 + + + software.amazon.awscdk + appsync-alpha + 2.10.0-alpha.0 + + +``` + +Maven does not support dependency locking, so while it is possible to specify version ranges in `pom.xml`, we recommend you always use exact versions to keep your builds repeatable\. + +Maven automatically installs transitive dependencies, but there can only be one installed copy of each package\. The version that is specified highest in the POM tree is selected; applications always have the last word in what version of packages get installed\. + +Maven automatically installs or updates your dependencies whenever you build \(mvn compile\) or package \(mvn package\) your project\. The CDK Toolkit does this automatically every time you run it, so generally there is no need to manually invoke Maven\. + +## C\# + +In C\# AWS CDK apps, you manage dependencies using NuGet\. NuGet has four standard, mostly\-equivalent interfaces; you can use the one that suits your needs and working style\. You can also use compatible tools, such as [Paket](https://fsprojects.github.io/Paket/) or [MyGet](https://www.myget.org/) or even edit the `.csproj` file directly\. + +NuGet does not allow you to specify version ranges for dependencies\. Every dependency is pinned to a specific version\. + +After updating your dependencies, Visual Studio will use NuGet to retrieve the specified versions of each package the next time you build\. If you are not using Visual Studio, use the dotnet restore command to update your dependencies\. + +### Editing the project file directly + +Your project's `.csproj` file contains an `` container that lists your dependencies as ` + + + +``` + +### The Visual Studio NuGet GUI + +Visual Studio's NuGet tools are accessible from **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution**\. Use the **Browse** tab to find the AWS Construct Library packages you want to install\. You can choose the desired version, including pre\-release versions of your modules and add them to any of the open projects\. + +**Note** +All AWS Construct Library modules deemed "experimental" \(see [Versioning](reference.md#versioning)\) are flagged as pre\-release in NuGet and have an `alpha` name suffix\. + +![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/visual-studio-nuget.png) + +Look on the **Updates** page to install new versions of your packages\. + +### The NuGet console + +The NuGet console is a PowerShell\-based interface to NuGet that works in the context of a Visual Studio project\. You can open it in Visual Studio by choosing **Tools** > **NuGet Package Manager** > **Package Manager Console**\. For more information about using this tool, see [Install and Manage Packages with the Package Manager Console in Visual Studio](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-powershell)\. + +### The `dotnet` command + +The `dotnet` command is the primary command\-line tool for working with Visual Studio C\# projects\. You can invoke it from any Windows command prompt\. Among its many capabilities, `dotnet` can add NuGet dependencies to a Visual Studio project\. + +Assuming you're in the same directory as the Visual Studio project \(`.csproj`\) file, issue a command like the following to install a package\. Note that since the main CDK library is included when you create a project, you should ever only need to explictly install experimental modules\. Experimental modules require you to specify an explicit version number\. + +``` +dotnet add package Amazon.CDK.AWS.IoT.Alpha -v VERSION-NUMBER +``` + +You may issue the command from another directory by including the path to the project file, or to the directory that contains it, after the `add` keyword\. The following example assumes that you are in your AWS CDK project's main directory\. + +``` +dotnet add src/PROJECT-DIR package Amazon.CDK.AWS.IoT.Alpha -v VERSION-NUMBER +``` + +To install a specific version of a package, include the `-v` flag and the desired version\. + +To update a package, issue the same `dotnet add` command you used to install it\. For experimental modules, again, you must specify an explicit version number\. + +For more information about managing packages using the `dotnet` command, see [Install and Manage Packages Using the dotnet CLI](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-dotnet-cli)\. + +### The `nuget` command + +The `nuget` command line tool can install and update NuGet packages\. However, it requires your Visual Studio project to be set up differently from the way `cdk init` sets up projects\. \(Technical details: `nuget` works with `Packages.config` projects, while `cdk init` creates a newer\-style `PackageReference` project\.\) + +We do not recommend the use of the `nuget` tool with AWS CDK projects created by `cdk init`\. If you are using another type of project, and want to use `nuget`, see the [NuGet CLI Reference](https://docs.microsoft.com/en-us/nuget/reference/nuget-exe-cli-reference)\. + +## Go + +In Go, dependencies versions are defined in `go.mod`\. The default `go.mod` is similar to the one shown here\. + +``` +module my-package + +go 1.16 + +require ( + github.com/aws/aws-cdk-go/awscdk/v2 v2.16.0 + github.com/aws/constructs-go/constructs/v10 v10.0.5 + github.com/aws/jsii-runtime-go v1.29.0 +) +``` + +Package names \(modules, in Go parlance\) are specified by URL with the version number appended\. Go's module system does not support version ranges, so all dependencies must be pinned to a specfic version\. + +Go automatically downloads dependencies whenever you build\. The CDK does this for you automatically whenever you run your app, so there is no need to do it manually\. + +You may use the go get command to install a module and update `go.mod`\. To see a list of available updates for your dependencies, issue go list \-m \-u all\. \ No newline at end of file From fa3fa7a6faf216e391a7cf50bede3bc02753ded5 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 7 Apr 2022 16:26:39 +0000 Subject: [PATCH 511/655] ID churn based on addition of new topic --- v1/cli.md | 26 +++++++++++++------------- v1/index.md | 1 + v1/tagging.md | 2 +- v1/use_cfn_template.md | 2 +- v2/cli.md | 26 +++++++++++++------------- v2/index.md | 1 + v2/migrating-v2.md | 2 +- v2/tagging.md | 2 +- v2/use_cfn_template.md | 2 +- 9 files changed, 33 insertions(+), 31 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index 5d52e798..5b47cf8b 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -349,7 +349,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -368,7 +368,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -376,7 +376,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -434,7 +434,7 @@ Wildcards, both `*` and `**`, can be used in the `"watch"` and `"build"` keys\. **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -456,7 +456,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -672,7 +672,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -685,7 +685,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -706,7 +706,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -783,7 +783,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -852,7 +852,7 @@ Options: detected. Implies --hotswap by default [boolean] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -871,7 +871,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -897,7 +897,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -919,7 +919,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/index.md b/v1/index.md index ee4a81d1..e546b765 100644 --- a/v1/index.md +++ b/v1/index.md @@ -24,6 +24,7 @@ Amazon's trademarks and trade dress may not be used in + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Working with the AWS CDK in C#](work-with-cdk-csharp.md) + [Working with the AWS CDK in Go](work-with-cdk-go.md) ++ [Managing dependencies](manage-dependencies.md) + [Migrating to AWS CDK v2](work-with-cdk-v2.md) + [Translating TypeScript AWS CDK code to other languages](multiple_languages.md) + [Concepts](core_concepts.md) diff --git a/v1/tagging.md b/v1/tagging.md index af22785c..9011b96a 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index 18c04f12..a19b7dba 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/cli.md b/v2/cli.md index 53f28544..b363ce04 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -341,7 +341,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -360,7 +360,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -368,7 +368,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -426,7 +426,7 @@ Wildcards, both `*` and `**`, can be used in the `"watch"` and `"build"` keys\. **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -448,7 +448,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -664,7 +664,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -677,7 +677,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -698,7 +698,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -775,7 +775,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -844,7 +844,7 @@ Options: detected. Implies --hotswap by default [boolean] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -863,7 +863,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -889,7 +889,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -911,7 +911,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/index.md b/v2/index.md index cd077823..6436d89b 100644 --- a/v2/index.md +++ b/v2/index.md @@ -24,6 +24,7 @@ Amazon's trademarks and trade dress may not be used in + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Working with the AWS CDK in C#](work-with-cdk-csharp.md) + [Working with the AWS CDK in Go](work-with-cdk-go.md) ++ [Managing dependencies](manage-dependencies.md) + [Migrating to AWS CDK v2](migrating-v2.md) + [Translating TypeScript AWS CDK code to other languages](multiple_languages.md) + [Concepts](core_concepts.md) diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 2cd0a6a1..bf7bab59 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -30,7 +30,7 @@ The modern bootstrap template effectively grants the permissions implied by the Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. Additional requirements are listed here\. + For TypeScript developers, TypeScript 3\.8 or later is required\. -+ A new version of the CDK Toolkit is required for use with CDK v2\. Now that CDK is Generally Available, it is the default version when installing\. It is backward\-compatible with CDK v1 projects, so you do not need to keep the old version installed unless you want to create CDK v1 projects\. To upgrade, issue `npm install -g aws-cdk`\. ++ A new version of the CDK Toolkit is required for use with CDK v2\. Now that CDK v2 is Generally Available, v2 is the default version when installing the CDK Toolkit\. It is backward\-compatible with CDK v1 projects, so you do not need to keep the old version installed unless you want to create CDK v1 projects\. To upgrade, issue `npm install -g aws-cdk`\. ## Upgrading from AWS CDK v2 Developer Preview diff --git a/v2/tagging.md b/v2/tagging.md index a353b5dd..1a4708cf 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index e78ef1ac..5020808f 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 1e8937d072b3e0ab5acfcee47ffd0f52c1e8dd7b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 20 Apr 2022 00:04:46 +0000 Subject: [PATCH 512/655] use ACCOUNT-NUMBER placeholder throughout so as not to imply ACCOUNT-ID is different from ACCOUNT-NUMBER --- v1/cdk_pipeline.md | 12 ++++++------ v2/cdk_pipeline.md | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/v1/cdk_pipeline.md b/v1/cdk_pipeline.md index 005cb699..f5f426cf 100644 --- a/v1/cdk_pipeline.md +++ b/v1/cdk_pipeline.md @@ -31,7 +31,7 @@ You may omit the \-\-profile option if your default AWS profile contains the nec export CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ - aws://ACCOUNT-ID/REGION + aws://ACCOUNT-NUMBER/REGION ``` ------ @@ -41,7 +41,7 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ set CDK_NEW_BOOTSTRAP=1 cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ - aws://ACCOUNT-ID/REGION + aws://ACCOUNT-NUMBER/REGION ``` ------ @@ -57,8 +57,8 @@ Again, you may omit the \-\-profile option if your default AWS profile contains export CDK_NEW_BOOTSTRAP=1 cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ - --trust PIPELINE-ACCOUNT-ID \ - aws://ACCOUNT-ID/REGION + --trust PIPELINE-ACCOUNT-NUMBER \ + aws://ACCOUNT-NUMBER/REGION ``` ------ @@ -68,8 +68,8 @@ cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ set CDK_NEW_BOOTSTRAP=1 cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ - --trust PIPELINE-ACCOUNT-ID ^ - aws://ACCOUNT-ID/REGION + --trust PIPELINE-ACCOUNT-NUMBER ^ + aws://ACCOUNT-NUMBER/REGION ``` ------ diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index a21e658d..5493f8a5 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -31,7 +31,7 @@ You may omit the \-\-profile option if your default AWS profile contains the nec export CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ - aws://ACCOUNT-ID/REGION + aws://ACCOUNT-NUMBER/REGION ``` ------ @@ -41,7 +41,7 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ set CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ - aws://ACCOUNT-ID/REGION + aws://ACCOUNT-NUMBER/REGION ``` ------ @@ -57,8 +57,8 @@ Again, you may omit the \-\-profile option if your default AWS profile contains export CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ - --trust PIPELINE-ACCOUNT-ID \ - aws://ACCOUNT-ID/REGION + --trust PIPELINE-ACCOUNT-NUMBER \ + aws://ACCOUNT-NUMBER/REGION ``` ------ @@ -68,8 +68,8 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ set CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ - --trust PIPELINE-ACCOUNT-ID ^ - aws://ACCOUNT-ID/REGION + --trust PIPELINE-ACCOUNT-NUMBER ^ + aws://ACCOUNT-NUMBER/REGION ``` ------ From 178f3e5b1a855777040a77fd4befd40e9c15b582 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 20 Apr 2022 23:05:48 +0000 Subject: [PATCH 513/655] document CDK Toolkit condfig (cdk.json) and improve Watch section --- v1/cli.md | 68 ++++++++++++++++++++++++++++++++++++++++++++----------- v2/cli.md | 64 ++++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 108 insertions(+), 24 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index 5b47cf8b..1f60d397 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -9,10 +9,10 @@ npm install -g aws-cdk@1.x # install latest 1.x version npm install -g aws-cdk@X.YY.Z # install specific version ``` -You may also use CDK Toolkit v2\.x with CDK v1\.x projects\. An exception is that CDK Toolkit v2 creates CDK v2 projects\. To create CDK v1 projects while CDK Toolkit v2\.x is installed globally, use npx to run the latest 1\.x release of the CDK Toolkit\. +You may also use CDK Toolkit v2\.x with CDK v1\.x projects\. An exception is that CDK Toolkit v2 creates CDK v2 projects\. You cannot create CDK v1 projects while CDK Toolkit v2\.x is installed globally; uninstall the global version and use npx to run the latest 1\.x release\. ``` -cdk init app --language typescript +npx aws-cdk@1.x init app --language typescript ``` **Tip** @@ -213,7 +213,7 @@ First, and most commonly, it can be specified using the `app` key inside the fil The CDK Toolkit looks for `cdk.json` in the current working directory when attempting to run your app, so you might keep a shell open in your project's main directory for issuing CDK Toolkit commands\. -The CDK Toolkit also looks for the app key in `~/.cdk.json` \(that is, in your home directory\) if it can't find it in `./cdk.json`\. Adding the app command here can be useful if you usually work with CDK code in the same language, as it does not require you to be in the app's main directory when you run a `cdk` command\. +The CDK Toolkit also looks for the app key in `~/.cdk.json` \(that is, in your home directory\) if it can't find it in `./cdk.json`\. Adding the app command here can be useful if you usually work with CDK code in the same language\. If you are in some other directory, or if you want to run your app via a command other than the one in `cdk.json`, you can use the `--app` \(or `-a`\) option to specify it\. @@ -425,11 +425,21 @@ By default, these deployments use the `--hotswap` flag, which fast\-tracks deplo Any changes made while `cdk watch` is already performing a deployment will be combined into a single deployment, which will begin as soon as the in\-progress deployment is complete\. -Watch mode uses the `"watch"` key in the project's `cdk.json` to determine which files to monitor\. By default, these files are your application files and assets, but this can be changed by modifying the `"include"` and `"exclude"` entries in the `"watch"` key\. +Watch mode uses the `"watch"` key in the project's `cdk.json` to determine which files to monitor\. By default, these files are your application files and assets, but this can be changed by modifying the `"include"` and `"exclude"` entries in the `"watch"` key\. The following `cdk.json` file shows an example of these entries\. + +``` +{ + "app": "mvn -e -q compile exec:java", + "watch": { + "include": "src/main/**", + "exclude": "target/*" + } +} +``` `cdk watch` executes the `"build"` command from `cdk.json` to build your app before synthesis\. If your deployment requires any commands to build or package your Lambda code \(or anything else that's not in your CDK app proper\), add it here\. -Wildcards, both `*` and `**`, can be used in the `"watch"` and `"build"` keys\. Each path is interpreted relative to the parent directory of `cdk.json`\. +Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"build"` keys\. Each path is interpreted relative to the parent directory of `cdk.json`\. The default value of `include` is `**/*`, meaning all files and directories in the project root directory\. `exclude` is optional\. **Important** Watch mode is not recommended for production deployments\. @@ -549,6 +559,38 @@ To compare your app's stack\(s\) with a saved CloudFormation template: cdk diff --template ~/stacks/MyStack.old MyStack ``` +## Configuration \(`cdk.json`\) + +Default values for many CDK Toolkit command\-line flags may be stored in a project's `cdk.json` file or in the `.cdk.json` file in your user directory\. Below is an alphabetical reference to the supported configuration settings\. + + +| Key | Notes | CDK Toolkit option | +| --- | --- | --- | +| app | The command that executes the CDK application\. | \-\-app | +| assetMetadata | Set to false to disable addition of CDK metadata to resources that use assets\. | \-\-no\-asset\-metadata | +| bootstrapKmsKeyId | Overrides the AWS KMS key used to encrypt the Amazon S3 deployment bucket\. | \-\-bootstrap\-kms\-key\-id | +| build | The command that compiles or builds the CDK application before synthesis\. Not permitted in \~/\.cdk\.json\. | \-\-build | +| browser | The command line for launching a Web browser for the cdk docs subcommand\. | \-\-browser | +| context | See [Runtime context](context.md)\. Context values in a configuration file will not be erased by cdk context \-\-clear\. \(The CDK Toolkit places cached context values in cdk\.context\.json\.\) | \-\-context | +| debug | If true, CDK Toolkit emits more detailed information useful for debugging\. | \-\-debug | +| language | Default language to be used for initializing new projects\. | \-\-language | +| lookups | Set to false to disallow context lookups\. Synthesis will fail if any context lookups need to be performed\. | \-\-no\-lookups | +| notices | If false, suppresses the display of messages about security vulnerabilities, regressions, and unsupported versions\. | \-\-no\-notices | +| output | Specifies the name of the directory into which the synthesized cloud assembly will be emitted \(default "cdk\.out"\)\. | \-\-outputs\-file | +| outputsFile | Specifies the file to which AWS CloudFormation outputs from deployed stacks will be written\. | \-\-outputs\-file | +| pathMetadata | Set to false to disable addition of CDK path metadata to synthesized templates\. | \-\-no\-path\-metadata | +| plugin | JSON array specifying the package names or local paths of packages that extends the CDK | \-\-plugin | +| profile | Name of the default AWS profile used for specifying region and account credentials\. | \-\-profile | +| progress | If set to "events", the CDK Toolkit displays all AWS CloudFormation events during deployment, rather than a progress bar\. | \-\-progress | +| requireApproval | Default value of approval level for security changes\. See [Security\-related changes](#cli-security) | \-\-require\-approval | +| rollback | Set to false to disable rollback of failed deployments\. | \-\-no\-rollback | +| staging | Set to false to avoid copying assets to the output directory for local debugging of the source files with AWS SAM\. | \-\-no\-staging | +| tags | JSON object containing key\-value pairs specifying tags for the stack\. | \-\-tags | +| toolkitBucketName | Sets the name of the Amazon S3 bucket used for deploying assets such as Lambda functions and container images \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-bucket\-name | +| toolkitStackName | Sets the name of the bootstrap stack \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-stack\-name | +| versionReporting | If false, opts out of version reporting\. | \-\-no\-version\-reporting | +| watch | JSON object containing "include" and "exclude" keys that indicate which files should \(or should not\) trigger a rebuild of the project when changed\. See [Watch mode](#cli-deploy-watch)\. See [Watch mode](#cli-deploy-watch) | \-\-watch | + ## Toolkit reference This section provides a reference for the AWS CDK Toolkit derived from its help, first a general reference with the options available with all commands, then \(in collapsible sections\) specific references with options available only with specific subcommands\. @@ -672,7 +714,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -685,7 +727,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -706,7 +748,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -783,7 +825,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -852,7 +894,7 @@ Options: detected. Implies --hotswap by default [boolean] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -871,7 +913,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -897,7 +939,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -919,7 +961,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/cli.md b/v2/cli.md index b363ce04..52c2bdf3 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -207,7 +207,7 @@ First, and most commonly, it can be specified using the `app` key inside the fil The CDK Toolkit looks for `cdk.json` in the current working directory when attempting to run your app, so you might keep a shell open in your project's main directory for issuing CDK Toolkit commands\. -The CDK Toolkit also looks for the app key in `~/.cdk.json` \(that is, in your home directory\) if it can't find it in `./cdk.json`\. Adding the app command here can be useful if you usually work with CDK code in the same language, as it does not require you to be in the app's main directory when you run a `cdk` command\. +The CDK Toolkit also looks for the app key in `~/.cdk.json` \(that is, in your home directory\) if it can't find it in `./cdk.json`\. Adding the app command here can be useful if you usually work with CDK code in the same language\. If you are in some other directory, or if you want to run your app via a command other than the one in `cdk.json`, you can use the `--app` \(or `-a`\) option to specify it\. @@ -417,11 +417,21 @@ By default, these deployments use the `--hotswap` flag, which fast\-tracks deplo Any changes made while `cdk watch` is already performing a deployment will be combined into a single deployment, which will begin as soon as the in\-progress deployment is complete\. -Watch mode uses the `"watch"` key in the project's `cdk.json` to determine which files to monitor\. By default, these files are your application files and assets, but this can be changed by modifying the `"include"` and `"exclude"` entries in the `"watch"` key\. +Watch mode uses the `"watch"` key in the project's `cdk.json` to determine which files to monitor\. By default, these files are your application files and assets, but this can be changed by modifying the `"include"` and `"exclude"` entries in the `"watch"` key\. The following `cdk.json` file shows an example of these entries\. + +``` +{ + "app": "mvn -e -q compile exec:java", + "watch": { + "include": "src/main/**", + "exclude": "target/*" + } +} +``` `cdk watch` executes the `"build"` command from `cdk.json` to build your app before synthesis\. If your deployment requires any commands to build or package your Lambda code \(or anything else that's not in your CDK app proper\), add it here\. -Wildcards, both `*` and `**`, can be used in the `"watch"` and `"build"` keys\. Each path is interpreted relative to the parent directory of `cdk.json`\. +Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"build"` keys\. Each path is interpreted relative to the parent directory of `cdk.json`\. The default value of `include` is `**/*`, meaning all files and directories in the project root directory\. `exclude` is optional\. **Important** Watch mode is not recommended for production deployments\. @@ -541,6 +551,38 @@ To compare your app's stack\(s\) with a saved CloudFormation template: cdk diff --template ~/stacks/MyStack.old MyStack ``` +## Configuration \(`cdk.json`\) + +Default values for many CDK Toolkit command\-line flags may be stored in a project's `cdk.json` file or in the `.cdk.json` file in your user directory\. Below is an alphabetical reference to the supported configuration settings\. + + +| Key | Notes | CDK Toolkit option | +| --- | --- | --- | +| app | The command that executes the CDK application\. | \-\-app | +| assetMetadata | Set to false to disable addition of CDK metadata to resources that use assets\. | \-\-no\-asset\-metadata | +| bootstrapKmsKeyId | Overrides the AWS KMS key used to encrypt the Amazon S3 deployment bucket\. | \-\-bootstrap\-kms\-key\-id | +| build | The command that compiles or builds the CDK application before synthesis\. Not permitted in \~/\.cdk\.json\. | \-\-build | +| browser | The command line for launching a Web browser for the cdk docs subcommand\. | \-\-browser | +| context | See [Runtime context](context.md)\. Context values in a configuration file will not be erased by cdk context \-\-clear\. \(The CDK Toolkit places cached context values in cdk\.context\.json\.\) | \-\-context | +| debug | If true, CDK Toolkit emits more detailed information useful for debugging\. | \-\-debug | +| language | Default language to be used for initializing new projects\. | \-\-language | +| lookups | Set to false to disallow context lookups\. Synthesis will fail if any context lookups need to be performed\. | \-\-no\-lookups | +| notices | If false, suppresses the display of messages about security vulnerabilities, regressions, and unsupported versions\. | \-\-no\-notices | +| output | Specifies the name of the directory into which the synthesized cloud assembly will be emitted \(default "cdk\.out"\)\. | \-\-outputs\-file | +| outputsFile | Specifies the file to which AWS CloudFormation outputs from deployed stacks will be written\. | \-\-outputs\-file | +| pathMetadata | Set to false to disable addition of CDK path metadata to synthesized templates\. | \-\-no\-path\-metadata | +| plugin | JSON array specifying the package names or local paths of packages that extends the CDK | \-\-plugin | +| profile | Name of the default AWS profile used for specifying region and account credentials\. | \-\-profile | +| progress | If set to "events", the CDK Toolkit displays all AWS CloudFormation events during deployment, rather than a progress bar\. | \-\-progress | +| requireApproval | Default value of approval level for security changes\. See [Security\-related changes](#cli-security) | \-\-require\-approval | +| rollback | Set to false to disable rollback of failed deployments\. | \-\-no\-rollback | +| staging | Set to false to avoid copying assets to the output directory for local debugging of the source files with AWS SAM\. | \-\-no\-staging | +| tags | JSON object containing key\-value pairs specifying tags for the stack\. | \-\-tags | +| toolkitBucketName | Sets the name of the Amazon S3 bucket used for deploying assets such as Lambda functions and container images \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-bucket\-name | +| toolkitStackName | Sets the name of the bootstrap stack \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-stack\-name | +| versionReporting | If false, opts out of version reporting\. | \-\-no\-version\-reporting | +| watch | JSON object containing "include" and "exclude" keys that indicate which files should \(or should not\) trigger a rebuild of the project when changed\. See [Watch mode](#cli-deploy-watch)\. See [Watch mode](#cli-deploy-watch) | \-\-watch | + ## Toolkit reference This section provides a reference for the AWS CDK Toolkit derived from its help, first a general reference with the options available with all commands, then \(in collapsible sections\) specific references with options available only with specific subcommands\. @@ -664,7 +706,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -677,7 +719,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -698,7 +740,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -775,7 +817,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -844,7 +886,7 @@ Options: detected. Implies --hotswap by default [boolean] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -863,7 +905,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -889,7 +931,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -911,7 +953,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context From 931907ae5c16bff3f32c3fb7eb019cd6d0013633 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 20 Apr 2022 23:18:54 +0000 Subject: [PATCH 514/655] update CDK help --- v1/cli.md | 167 ++++++++++++++++++++++++++++++------------------------ v2/cli.md | 167 ++++++++++++++++++++++++++++++------------------------ 2 files changed, 188 insertions(+), 146 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index 1f60d397..d081631a 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -611,6 +611,9 @@ Commands: cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your AWS account + cdk import [STACK] Import existing resource(s) into the given + STACK + cdk watch [STACKS..] Shortcut for 'deploy --watch' cdk destroy [STACKS..] Destroy the stack(s) named STACKS @@ -622,6 +625,11 @@ Commands: cdk metadata [STACK] Returns all metadata associated with this stack + cdk acknowledge [ID] Acknowledge a notice so that it does not show + up anymore [aliases: ack] + + cdk notices Returns a list of relevant notices + cdk init [TEMPLATE] Create a new, empty CDK project from a template. @@ -634,79 +642,80 @@ Commands: Options: - -a, --app REQUIRED: command-line for executing your app or a - cloud assembly directory (e.g. "node bin/my-app.js") + -a, --app REQUIRED: command-line for executing your app or a + cloud assembly directory (e.g. "node bin/my-app.js") [string] - -c, --context Add contextual string parameter (KEY=VALUE) [array] + --build Command-line for a pre-synth build [string] + + -c, --context Add contextual string parameter (KEY=VALUE) [array] - -p, --plugin Name or path of a node package that extend the CDK - features. Can be specified multiple times [array] + -p, --plugin Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] - --trace Print trace for stack warnings [boolean] + --trace Print trace for stack warnings [boolean] - --strict Do not construct stacks with warnings [boolean] + --strict Do not construct stacks with warnings [boolean] - --lookups Perform context lookups (synthesis fails if this is - disabled and context lookups need to be performed) + --lookups Perform context lookups (synthesis fails if this is + disabled and context lookups need to be performed) [boolean] [default: true] - --ignore-errors Ignores synthesis errors, which will likely produce - an invalid output [boolean] [default: false] + --ignore-errors Ignores synthesis errors, which will likely produce + an invalid output [boolean] [default: false] - -j, --json Use JSON output instead of YAML when templates are - printed to STDOUT [boolean] [default: false] + -j, --json Use JSON output instead of YAML when templates are + printed to STDOUT [boolean] [default: false] - -v, --verbose Show debug logs (specify multiple times to increase - verbosity) [count] [default: false] + -v, --verbose Show debug logs (specify multiple times to increase + verbosity) [count] [default: false] - --debug Enable emission of additional debugging information, - such as creation stack traces of tokens + --debug Enable emission of additional debugging information, + such as creation stack traces of tokens [boolean] [default: false] - --profile Use the indicated AWS profile as the default - environment [string] + --profile Use the indicated AWS profile as the default + environment [string] - --proxy Use the indicated proxy. Will read from HTTPS_PROXY - environment variable if not specified [string] + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified [string] - --ca-bundle-path Path to CA certificate to use when validating HTTPS - requests. Will read from AWS_CA_BUNDLE environment - variable if not specified [string] + --ca-bundle-path Path to CA certificate to use when validating HTTPS + requests. Will read from AWS_CA_BUNDLE environment + variable if not specified [string] - -i, --ec2creds Force trying to fetch EC2 instance credentials. - Default: guess EC2 instance status [boolean] + -i, --ec2creds Force trying to fetch EC2 instance credentials. + Default: guess EC2 instance status [boolean] - --version-reporting Include the "AWS::CDK::Metadata" resource in - synthesized templates (enabled by default) [boolean] + --version-reporting Include the "AWS::CDK::Metadata" resource in + synthesized templates (enabled by default) [boolean] - --path-metadata Include "aws:cdk:path" CloudFormation metadata for - each resource (enabled by default) + --path-metadata Include "aws:cdk:path" CloudFormation metadata for + each resource (enabled by default) [boolean] [default: true] - --asset-metadata Include "aws:asset:*" CloudFormation metadata for - resources that uses assets (enabled by default) + --asset-metadata Include "aws:asset:*" CloudFormation metadata for + resources that uses assets (enabled by default) [boolean] [default: true] - -r, --role-arn ARN of Role to use when invoking CloudFormation + -r, --role-arn ARN of Role to use when invoking CloudFormation [string] - --toolkit-stack-name The name of the CDK toolkit stack [string] + --staging Copy assets to the output directory (use --no-staging + to disable, needed for local debugging the source + files with SAM CLI) [boolean] [default: true] - --staging Copy assets to the output directory (use - --no-staging to disable, needed for local debugging - the source files with SAM CLI) - [boolean] [default: true] + -o, --output Emits the synthesized cloud assembly into a directory + (default: cdk.out) [string] - -o, --output Emits the synthesized cloud assembly into a - directory (default: cdk.out) [string] + --notices Show relevant notices [boolean] - --no-color Removes colors and other style from console output + --no-color Removes colors and other style from console output [boolean] [default: false] - --version Show version number [boolean] + --version Show version number [boolean] - -h, --help Show help [boolean] + -h, --help Show help [boolean] If your app has a single stack, there is no need to specify the stack name @@ -723,7 +732,7 @@ Lists all stacks in the app Options: - -l, --long Display environment information for each stack + -l, --long Display environment information for each stack [boolean] [default: false] ``` @@ -736,15 +745,15 @@ Synthesizes and prints the CloudFormation template for this stack Options: - -e, --exclusively Only synthesize requested stacks, don't include - dependencies [boolean] + -e, --exclusively Only synthesize requested stacks, don't include + dependencies [boolean] - --validation After synthesis, validate stacks with the - "validateOnSynth" attribute set (can also be - controlled with CDK_VALIDATION) + --validation After synthesis, validate stacks with the + "validateOnSynth" attribute set (can also be + controlled with CDK_VALIDATION) [boolean] [default: true] - -q, --quiet Do not output CloudFormation Template to stdout + -q, --quiet Do not output CloudFormation Template to stdout [boolean] [default: false] ``` @@ -819,6 +828,9 @@ Options: customization [boolean] [default: false] + --toolkit-stack-name The name of the CDK toolkit stack to + create [string] + --template Use the template from the given file instead of the built-in one (use --show-template to obtain an @@ -874,6 +886,9 @@ Options: must specify all parameters on every deployment if this is disabled) [boolean] [default: true] + --toolkit-stack-name The name of the existing CDK toolkit stack (only + used for app using legacy synthesis) [string] + --progress Display mode for stack activity events [string] [choices: "bar", "events"] @@ -891,7 +906,13 @@ Options: --watch Continuously observe the project files, and deploy the given stack(s) automatically when changes are - detected. Implies --hotswap by default [boolean] + detected. Implies --hotswap by default [boolean] + + --logs Show CloudWatch log events from all resources in + the selected Stacks in the terminal. 'true' by + default, use --no-logs to turn off. Only in effect + if specified alongside the '--watch' option + [boolean] [default: true] ``` ### `cdk destroy` @@ -903,14 +924,14 @@ Destroy the stack(s) named STACKS Options: - --all Destroy all available stacks + --all Destroy all available stacks [boolean] [default: false] - -e, --exclusively Only destroy requested stacks, don't include - dependees [boolean] + -e, --exclusively Only destroy requested stacks, don't include + dependees [boolean] - -f, --force Do not ask for confirmation before destroying the - stacks [boolean] + -f, --force Do not ask for confirmation before destroying the + stacks [boolean] ``` ### `cdk diff` @@ -923,19 +944,19 @@ and returns with status 1 if any difference is found Options: - -e, --exclusively Only diff requested stacks, don't include - dependencies [boolean] + -e, --exclusively Only diff requested stacks, don't include + dependencies [boolean] - --context-lines Number of context lines to include in arbitrary JSON - diff rendering [number] [default: 3] + --context-lines Number of context lines to include in arbitrary JSON + diff rendering [number] [default: 3] - --template The path to the CloudFormation template to compare - with [string] + --template The path to the CloudFormation template to compare + with [string] - --security-only Only diff for broadened security changes + --security-only Only diff for broadened security changes [boolean] [default: false] - --fail Fail with exit code 1 in case of diff + --fail Fail with exit code 1 in case of diff [boolean] [default: false] ``` @@ -948,17 +969,17 @@ Create a new, empty CDK project from a template. Options: - -l, --language The language to be used for the new project (default - can be configured in ~/.cdk.json) + -l, --language The language to be used for the new project (default + can be configured in ~/.cdk.json) [string] [choices: "csharp", "fsharp", "go", "java", "javascript", "python", "typescript"] - --list List the available templates [boolean] + --list List the available templates [boolean] - --generate-only If true, only generates project files, without - executing additional operations such as setting up a - git repo, installing dependencies or compiling the - project [boolean] [default: false] + --generate-only If true, only generates project files, without + executing additional operations such as setting up a + git repo, installing dependencies or compiling the + project [boolean] [default: false] ``` ### `cdk context` @@ -970,7 +991,7 @@ Manage cached context values Options: - -e, --reset The context key (or its index) to reset [string] + -e, --reset The context key (or its index) to reset [string] - --clear Clear all context [boolean] + --clear Clear all context [boolean] ``` \ No newline at end of file diff --git a/v2/cli.md b/v2/cli.md index 52c2bdf3..cfdb5e93 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -603,6 +603,9 @@ Commands: cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your AWS account + cdk import [STACK] Import existing resource(s) into the given + STACK + cdk watch [STACKS..] Shortcut for 'deploy --watch' cdk destroy [STACKS..] Destroy the stack(s) named STACKS @@ -614,6 +617,11 @@ Commands: cdk metadata [STACK] Returns all metadata associated with this stack + cdk acknowledge [ID] Acknowledge a notice so that it does not show + up anymore [aliases: ack] + + cdk notices Returns a list of relevant notices + cdk init [TEMPLATE] Create a new, empty CDK project from a template. @@ -626,79 +634,80 @@ Commands: Options: - -a, --app REQUIRED: command-line for executing your app or a - cloud assembly directory (e.g. "node bin/my-app.js") + -a, --app REQUIRED: command-line for executing your app or a + cloud assembly directory (e.g. "node bin/my-app.js") [string] - -c, --context Add contextual string parameter (KEY=VALUE) [array] + --build Command-line for a pre-synth build [string] + + -c, --context Add contextual string parameter (KEY=VALUE) [array] - -p, --plugin Name or path of a node package that extend the CDK - features. Can be specified multiple times [array] + -p, --plugin Name or path of a node package that extend the CDK + features. Can be specified multiple times [array] - --trace Print trace for stack warnings [boolean] + --trace Print trace for stack warnings [boolean] - --strict Do not construct stacks with warnings [boolean] + --strict Do not construct stacks with warnings [boolean] - --lookups Perform context lookups (synthesis fails if this is - disabled and context lookups need to be performed) + --lookups Perform context lookups (synthesis fails if this is + disabled and context lookups need to be performed) [boolean] [default: true] - --ignore-errors Ignores synthesis errors, which will likely produce - an invalid output [boolean] [default: false] + --ignore-errors Ignores synthesis errors, which will likely produce + an invalid output [boolean] [default: false] - -j, --json Use JSON output instead of YAML when templates are - printed to STDOUT [boolean] [default: false] + -j, --json Use JSON output instead of YAML when templates are + printed to STDOUT [boolean] [default: false] - -v, --verbose Show debug logs (specify multiple times to increase - verbosity) [count] [default: false] + -v, --verbose Show debug logs (specify multiple times to increase + verbosity) [count] [default: false] - --debug Enable emission of additional debugging information, - such as creation stack traces of tokens + --debug Enable emission of additional debugging information, + such as creation stack traces of tokens [boolean] [default: false] - --profile Use the indicated AWS profile as the default - environment [string] + --profile Use the indicated AWS profile as the default + environment [string] - --proxy Use the indicated proxy. Will read from HTTPS_PROXY - environment variable if not specified [string] + --proxy Use the indicated proxy. Will read from HTTPS_PROXY + environment variable if not specified [string] - --ca-bundle-path Path to CA certificate to use when validating HTTPS - requests. Will read from AWS_CA_BUNDLE environment - variable if not specified [string] + --ca-bundle-path Path to CA certificate to use when validating HTTPS + requests. Will read from AWS_CA_BUNDLE environment + variable if not specified [string] - -i, --ec2creds Force trying to fetch EC2 instance credentials. - Default: guess EC2 instance status [boolean] + -i, --ec2creds Force trying to fetch EC2 instance credentials. + Default: guess EC2 instance status [boolean] - --version-reporting Include the "AWS::CDK::Metadata" resource in - synthesized templates (enabled by default) [boolean] + --version-reporting Include the "AWS::CDK::Metadata" resource in + synthesized templates (enabled by default) [boolean] - --path-metadata Include "aws:cdk:path" CloudFormation metadata for - each resource (enabled by default) + --path-metadata Include "aws:cdk:path" CloudFormation metadata for + each resource (enabled by default) [boolean] [default: true] - --asset-metadata Include "aws:asset:*" CloudFormation metadata for - resources that uses assets (enabled by default) + --asset-metadata Include "aws:asset:*" CloudFormation metadata for + resources that uses assets (enabled by default) [boolean] [default: true] - -r, --role-arn ARN of Role to use when invoking CloudFormation + -r, --role-arn ARN of Role to use when invoking CloudFormation [string] - --toolkit-stack-name The name of the CDK toolkit stack [string] + --staging Copy assets to the output directory (use --no-staging + to disable, needed for local debugging the source + files with SAM CLI) [boolean] [default: true] - --staging Copy assets to the output directory (use - --no-staging to disable, needed for local debugging - the source files with SAM CLI) - [boolean] [default: true] + -o, --output Emits the synthesized cloud assembly into a directory + (default: cdk.out) [string] - -o, --output Emits the synthesized cloud assembly into a - directory (default: cdk.out) [string] + --notices Show relevant notices [boolean] - --no-color Removes colors and other style from console output + --no-color Removes colors and other style from console output [boolean] [default: false] - --version Show version number [boolean] + --version Show version number [boolean] - -h, --help Show help [boolean] + -h, --help Show help [boolean] If your app has a single stack, there is no need to specify the stack name @@ -715,7 +724,7 @@ Lists all stacks in the app Options: - -l, --long Display environment information for each stack + -l, --long Display environment information for each stack [boolean] [default: false] ``` @@ -728,15 +737,15 @@ Synthesizes and prints the CloudFormation template for this stack Options: - -e, --exclusively Only synthesize requested stacks, don't include - dependencies [boolean] + -e, --exclusively Only synthesize requested stacks, don't include + dependencies [boolean] - --validation After synthesis, validate stacks with the - "validateOnSynth" attribute set (can also be - controlled with CDK_VALIDATION) + --validation After synthesis, validate stacks with the + "validateOnSynth" attribute set (can also be + controlled with CDK_VALIDATION) [boolean] [default: true] - -q, --quiet Do not output CloudFormation Template to stdout + -q, --quiet Do not output CloudFormation Template to stdout [boolean] [default: false] ``` @@ -811,6 +820,9 @@ Options: customization [boolean] [default: false] + --toolkit-stack-name The name of the CDK toolkit stack to + create [string] + --template Use the template from the given file instead of the built-in one (use --show-template to obtain an @@ -866,6 +878,9 @@ Options: must specify all parameters on every deployment if this is disabled) [boolean] [default: true] + --toolkit-stack-name The name of the existing CDK toolkit stack (only + used for app using legacy synthesis) [string] + --progress Display mode for stack activity events [string] [choices: "bar", "events"] @@ -883,7 +898,13 @@ Options: --watch Continuously observe the project files, and deploy the given stack(s) automatically when changes are - detected. Implies --hotswap by default [boolean] + detected. Implies --hotswap by default [boolean] + + --logs Show CloudWatch log events from all resources in + the selected Stacks in the terminal. 'true' by + default, use --no-logs to turn off. Only in effect + if specified alongside the '--watch' option + [boolean] [default: true] ``` ### `cdk destroy` @@ -895,14 +916,14 @@ Destroy the stack(s) named STACKS Options: - --all Destroy all available stacks + --all Destroy all available stacks [boolean] [default: false] - -e, --exclusively Only destroy requested stacks, don't include - dependees [boolean] + -e, --exclusively Only destroy requested stacks, don't include + dependees [boolean] - -f, --force Do not ask for confirmation before destroying the - stacks [boolean] + -f, --force Do not ask for confirmation before destroying the + stacks [boolean] ``` ### `cdk diff` @@ -915,19 +936,19 @@ and returns with status 1 if any difference is found Options: - -e, --exclusively Only diff requested stacks, don't include - dependencies [boolean] + -e, --exclusively Only diff requested stacks, don't include + dependencies [boolean] - --context-lines Number of context lines to include in arbitrary JSON - diff rendering [number] [default: 3] + --context-lines Number of context lines to include in arbitrary JSON + diff rendering [number] [default: 3] - --template The path to the CloudFormation template to compare - with [string] + --template The path to the CloudFormation template to compare + with [string] - --security-only Only diff for broadened security changes + --security-only Only diff for broadened security changes [boolean] [default: false] - --fail Fail with exit code 1 in case of diff + --fail Fail with exit code 1 in case of diff [boolean] [default: false] ``` @@ -940,17 +961,17 @@ Create a new, empty CDK project from a template. Options: - -l, --language The language to be used for the new project (default - can be configured in ~/.cdk.json) + -l, --language The language to be used for the new project (default + can be configured in ~/.cdk.json) [string] [choices: "csharp", "fsharp", "go", "java", "javascript", "python", "typescript"] - --list List the available templates [boolean] + --list List the available templates [boolean] - --generate-only If true, only generates project files, without - executing additional operations such as setting up a - git repo, installing dependencies or compiling the - project [boolean] [default: false] + --generate-only If true, only generates project files, without + executing additional operations such as setting up a + git repo, installing dependencies or compiling the + project [boolean] [default: false] ``` ### `cdk context` @@ -962,7 +983,7 @@ Manage cached context values Options: - -e, --reset The context key (or its index) to reset [string] + -e, --reset The context key (or its index) to reset [string] - --clear Clear all context [boolean] + --clear Clear all context [boolean] ``` \ No newline at end of file From e271750240015253b8c8b8951fa547b0c56cab21 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 21 Apr 2022 18:31:27 +0000 Subject: [PATCH 515/655] improvements to recently-added configuration documentation --- v1/cli.md | 32 ++++++++++++++++---------------- v2/cli.md | 32 ++++++++++++++++---------------- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index d081631a..a97849a6 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -567,29 +567,29 @@ Default values for many CDK Toolkit command\-line flags may be stored in a proje | Key | Notes | CDK Toolkit option | | --- | --- | --- | | app | The command that executes the CDK application\. | \-\-app | -| assetMetadata | Set to false to disable addition of CDK metadata to resources that use assets\. | \-\-no\-asset\-metadata | -| bootstrapKmsKeyId | Overrides the AWS KMS key used to encrypt the Amazon S3 deployment bucket\. | \-\-bootstrap\-kms\-key\-id | +| assetMetadata | If false, CDK does not add metadata to resources that use assets\. | \-\-no\-asset\-metadata | +| bootstrapKmsKeyId | Overrides the ID of the AWS KMS key used to encrypt the Amazon S3 deployment bucket\. | \-\-bootstrap\-kms\-key\-id | | build | The command that compiles or builds the CDK application before synthesis\. Not permitted in \~/\.cdk\.json\. | \-\-build | -| browser | The command line for launching a Web browser for the cdk docs subcommand\. | \-\-browser | +| browser | The command for launching a Web browser for the cdk docs subcommand\. | \-\-browser | | context | See [Runtime context](context.md)\. Context values in a configuration file will not be erased by cdk context \-\-clear\. \(The CDK Toolkit places cached context values in cdk\.context\.json\.\) | \-\-context | | debug | If true, CDK Toolkit emits more detailed information useful for debugging\. | \-\-debug | -| language | Default language to be used for initializing new projects\. | \-\-language | -| lookups | Set to false to disallow context lookups\. Synthesis will fail if any context lookups need to be performed\. | \-\-no\-lookups | +| language | The language to be used for initializing new projects\. | \-\-language | +| lookups | If false, no context lookups are permitted\. Synthesis will fail if any context lookups need to be performed\. | \-\-no\-lookups | | notices | If false, suppresses the display of messages about security vulnerabilities, regressions, and unsupported versions\. | \-\-no\-notices | -| output | Specifies the name of the directory into which the synthesized cloud assembly will be emitted \(default "cdk\.out"\)\. | \-\-outputs\-file | -| outputsFile | Specifies the file to which AWS CloudFormation outputs from deployed stacks will be written\. | \-\-outputs\-file | -| pathMetadata | Set to false to disable addition of CDK path metadata to synthesized templates\. | \-\-no\-path\-metadata | -| plugin | JSON array specifying the package names or local paths of packages that extends the CDK | \-\-plugin | +| output | The name of the directory into which the synthesized cloud assembly will be emitted \(default "cdk\.out"\)\. | \-\-outputs\-file | +| outputsFile | The file to which AWS CloudFormation outputs from deployed stacks will be written \(in JSON format\)\. | \-\-outputs\-file | +| pathMetadata | If false, CDK path metadata is not added to synthesized templates\. | \-\-no\-path\-metadata | +| plugin | JSON array specifying the package names or local paths of packages that extend the CDK | \-\-plugin | | profile | Name of the default AWS profile used for specifying region and account credentials\. | \-\-profile | | progress | If set to "events", the CDK Toolkit displays all AWS CloudFormation events during deployment, rather than a progress bar\. | \-\-progress | -| requireApproval | Default value of approval level for security changes\. See [Security\-related changes](#cli-security) | \-\-require\-approval | -| rollback | Set to false to disable rollback of failed deployments\. | \-\-no\-rollback | -| staging | Set to false to avoid copying assets to the output directory for local debugging of the source files with AWS SAM\. | \-\-no\-staging | -| tags | JSON object containing key\-value pairs specifying tags for the stack\. | \-\-tags | -| toolkitBucketName | Sets the name of the Amazon S3 bucket used for deploying assets such as Lambda functions and container images \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-bucket\-name | -| toolkitStackName | Sets the name of the bootstrap stack \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-stack\-name | +| requireApproval | Default approval level for security changes\. See [Security\-related changes](#cli-security) | \-\-require\-approval | +| rollback | If false, failed deployments are not rolled back\. | \-\-no\-rollback | +| staging | If false, assets are not copied to the output directory \(use for local debugging of the source files with AWS SAM\)\. | \-\-no\-staging | +| tags | JSON object containing tags \(key\-value pairs\) for the stack\. | \-\-tags | +| toolkitBucketName | The name of the Amazon S3 bucket used for deploying assets such as Lambda functions and container images \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-bucket\-name | +| toolkitStackName | The name of the bootstrap stack \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-stack\-name | | versionReporting | If false, opts out of version reporting\. | \-\-no\-version\-reporting | -| watch | JSON object containing "include" and "exclude" keys that indicate which files should \(or should not\) trigger a rebuild of the project when changed\. See [Watch mode](#cli-deploy-watch)\. See [Watch mode](#cli-deploy-watch) | \-\-watch | +| watch | JSON object containing "include" and "exclude" keys that indicate which files should \(or should not\) trigger a rebuild of the project when changed\. See [Watch mode](#cli-deploy-watch)\. | \-\-watch | ## Toolkit reference diff --git a/v2/cli.md b/v2/cli.md index cfdb5e93..e3cc2dd1 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -559,29 +559,29 @@ Default values for many CDK Toolkit command\-line flags may be stored in a proje | Key | Notes | CDK Toolkit option | | --- | --- | --- | | app | The command that executes the CDK application\. | \-\-app | -| assetMetadata | Set to false to disable addition of CDK metadata to resources that use assets\. | \-\-no\-asset\-metadata | -| bootstrapKmsKeyId | Overrides the AWS KMS key used to encrypt the Amazon S3 deployment bucket\. | \-\-bootstrap\-kms\-key\-id | +| assetMetadata | If false, CDK does not add metadata to resources that use assets\. | \-\-no\-asset\-metadata | +| bootstrapKmsKeyId | Overrides the ID of the AWS KMS key used to encrypt the Amazon S3 deployment bucket\. | \-\-bootstrap\-kms\-key\-id | | build | The command that compiles or builds the CDK application before synthesis\. Not permitted in \~/\.cdk\.json\. | \-\-build | -| browser | The command line for launching a Web browser for the cdk docs subcommand\. | \-\-browser | +| browser | The command for launching a Web browser for the cdk docs subcommand\. | \-\-browser | | context | See [Runtime context](context.md)\. Context values in a configuration file will not be erased by cdk context \-\-clear\. \(The CDK Toolkit places cached context values in cdk\.context\.json\.\) | \-\-context | | debug | If true, CDK Toolkit emits more detailed information useful for debugging\. | \-\-debug | -| language | Default language to be used for initializing new projects\. | \-\-language | -| lookups | Set to false to disallow context lookups\. Synthesis will fail if any context lookups need to be performed\. | \-\-no\-lookups | +| language | The language to be used for initializing new projects\. | \-\-language | +| lookups | If false, no context lookups are permitted\. Synthesis will fail if any context lookups need to be performed\. | \-\-no\-lookups | | notices | If false, suppresses the display of messages about security vulnerabilities, regressions, and unsupported versions\. | \-\-no\-notices | -| output | Specifies the name of the directory into which the synthesized cloud assembly will be emitted \(default "cdk\.out"\)\. | \-\-outputs\-file | -| outputsFile | Specifies the file to which AWS CloudFormation outputs from deployed stacks will be written\. | \-\-outputs\-file | -| pathMetadata | Set to false to disable addition of CDK path metadata to synthesized templates\. | \-\-no\-path\-metadata | -| plugin | JSON array specifying the package names or local paths of packages that extends the CDK | \-\-plugin | +| output | The name of the directory into which the synthesized cloud assembly will be emitted \(default "cdk\.out"\)\. | \-\-outputs\-file | +| outputsFile | The file to which AWS CloudFormation outputs from deployed stacks will be written \(in JSON format\)\. | \-\-outputs\-file | +| pathMetadata | If false, CDK path metadata is not added to synthesized templates\. | \-\-no\-path\-metadata | +| plugin | JSON array specifying the package names or local paths of packages that extend the CDK | \-\-plugin | | profile | Name of the default AWS profile used for specifying region and account credentials\. | \-\-profile | | progress | If set to "events", the CDK Toolkit displays all AWS CloudFormation events during deployment, rather than a progress bar\. | \-\-progress | -| requireApproval | Default value of approval level for security changes\. See [Security\-related changes](#cli-security) | \-\-require\-approval | -| rollback | Set to false to disable rollback of failed deployments\. | \-\-no\-rollback | -| staging | Set to false to avoid copying assets to the output directory for local debugging of the source files with AWS SAM\. | \-\-no\-staging | -| tags | JSON object containing key\-value pairs specifying tags for the stack\. | \-\-tags | -| toolkitBucketName | Sets the name of the Amazon S3 bucket used for deploying assets such as Lambda functions and container images \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-bucket\-name | -| toolkitStackName | Sets the name of the bootstrap stack \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-stack\-name | +| requireApproval | Default approval level for security changes\. See [Security\-related changes](#cli-security) | \-\-require\-approval | +| rollback | If false, failed deployments are not rolled back\. | \-\-no\-rollback | +| staging | If false, assets are not copied to the output directory \(use for local debugging of the source files with AWS SAM\)\. | \-\-no\-staging | +| tags | JSON object containing tags \(key\-value pairs\) for the stack\. | \-\-tags | +| toolkitBucketName | The name of the Amazon S3 bucket used for deploying assets such as Lambda functions and container images \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-bucket\-name | +| toolkitStackName | The name of the bootstrap stack \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-stack\-name | | versionReporting | If false, opts out of version reporting\. | \-\-no\-version\-reporting | -| watch | JSON object containing "include" and "exclude" keys that indicate which files should \(or should not\) trigger a rebuild of the project when changed\. See [Watch mode](#cli-deploy-watch)\. See [Watch mode](#cli-deploy-watch) | \-\-watch | +| watch | JSON object containing "include" and "exclude" keys that indicate which files should \(or should not\) trigger a rebuild of the project when changed\. See [Watch mode](#cli-deploy-watch)\. | \-\-watch | ## Toolkit reference From 78347c08967bf458112def3f20718e95e9c8db40 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 21 Apr 2022 22:46:18 +0000 Subject: [PATCH 516/655] add info about using a Secrets Manager secret value (and some churn with anchor IDs) --- v1/cli.md | 26 +++++++++++++------------- v1/get_secrets_manager_value.md | 6 ++++-- v1/manage-dependencies.md | 10 +++++----- v1/tagging.md | 2 +- v1/use_cfn_template.md | 2 +- v2/cli.md | 26 +++++++++++++------------- v2/get_secrets_manager_value.md | 6 ++++-- v2/manage-dependencies.md | 10 +++++----- v2/tagging.md | 2 +- v2/use_cfn_template.md | 2 +- 10 files changed, 48 insertions(+), 44 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index a97849a6..d3553b0c 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -349,7 +349,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -368,7 +368,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -376,7 +376,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -444,7 +444,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -466,7 +466,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -723,7 +723,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -736,7 +736,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -757,7 +757,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -837,7 +837,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -915,7 +915,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -934,7 +934,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -960,7 +960,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -982,7 +982,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/get_secrets_manager_value.md b/v1/get_secrets_manager_value.md index a4b19c3b..a975e114 100644 --- a/v1/get_secrets_manager_value.md +++ b/v1/get_secrets_manager_value.md @@ -103,10 +103,12 @@ public class SecretsManagerStack : Stack ------ -Use the [create\-secret](https://docs.aws.amazon.com/cli/latest/reference/secretsmanager/create-secret.html) CLI command to create a secret from the command\-line, such as when testing: +**Tip** +Use the [create\-secret](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_secretsmanager.Secret.html) CLI command to create a secret from the command\-line, such as when testing: ``` aws secretsmanager create-secret --name ImportedSecret --secret-string mygroovybucket ``` +The command returns an ARN you can use with the above example\. -The command returns an ARN you can use for the example\. \ No newline at end of file +Once you have created a `Secret` instance, you can get the secret's value from the instance's `secretValue` attribute\. The value is represented by a `[SecretValue](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.SecretValue.html)` instance, a special type of [Tokens](tokens.md)\. As it is a token, it has meaning only after resolution; your CDK app does not need to access its actual value, but can instead pass the `SecretValue` instance \(or its string or numeric representation\) to whatever CDK method needs the value\. \ No newline at end of file diff --git a/v1/manage-dependencies.md b/v1/manage-dependencies.md index aaf940ee..427779a1 100644 --- a/v1/manage-dependencies.md +++ b/v1/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -72,7 +72,7 @@ All AWS CDK dependencies must have the same version\. Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -99,7 +99,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -145,7 +145,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -169,7 +169,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v1/tagging.md b/v1/tagging.md index 9011b96a..437394ca 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index a19b7dba..d4f79a47 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/cli.md b/v2/cli.md index e3cc2dd1..fa17a81e 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -341,7 +341,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -360,7 +360,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -368,7 +368,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -436,7 +436,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -458,7 +458,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -715,7 +715,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -728,7 +728,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -749,7 +749,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -829,7 +829,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -907,7 +907,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -926,7 +926,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -952,7 +952,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -974,7 +974,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/get_secrets_manager_value.md b/v2/get_secrets_manager_value.md index b09865bc..b7735f00 100644 --- a/v2/get_secrets_manager_value.md +++ b/v2/get_secrets_manager_value.md @@ -103,10 +103,12 @@ public class SecretsManagerStack : Stack ------ -Use the [create\-secret](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_secretsmanager.Secret.html) CLI command to create a secret from the command\-line, such as when testing: +**Tip** +Use the [create\-secret](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_secretsmanager.Secret.html) CLI command to create a secret from the command\-line, such as when testing: ``` aws secretsmanager create-secret --name ImportedSecret --secret-string mygroovybucket ``` +The command returns an ARN you can use with the above example\. -The command returns an ARN you can use for the example\. \ No newline at end of file +Once you have created a `Secret` instance, you can get the secret's value from the instance's `secretValue` attribute\. The value is represented by a `[SecretValue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.SecretValue.html)` instance, a special type of [Tokens](tokens.md)\. As it is a token, it has meaning only after resolution; your CDK app does not need to access its actual value, but can instead pass the `SecretValue` instance \(or its string or numeric representation\) to whatever CDK method needs the value\. \ No newline at end of file diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index 3bfdf888..2625fd5c 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -71,7 +71,7 @@ Specify exact versions for alpha construct library modules, which have APIs that Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -101,7 +101,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -147,7 +147,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -167,7 +167,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v2/tagging.md b/v2/tagging.md index 1a4708cf..b84d476d 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 5020808f..897de566 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 154b2c8ed923c12c878266a041c85fbf9707d5af Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 28 Apr 2022 18:12:07 +0000 Subject: [PATCH 517/655] add instructions for setting up lambda source directory --- v1/testing.md | 14 ++++++++++++++ v2/testing.md | 14 ++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/v1/testing.md b/v1/testing.md index 88557cfa..2becebfe 100644 --- a/v1/testing.md +++ b/v1/testing.md @@ -547,6 +547,20 @@ namespace AwsCdkAssertionSamples ------ +## The Lambda function + +Our example stack includes a Lambda function that starts our state machine\. We must provide the source code for this function so the CDK can bundle it up and deploy it as part of creating the Lambda function resource\. ++ Create the folder `start-state-machine` in the app's main directory\. ++ In this folder, create at least one file\. For example, you can save the code below in `start-state-machines/index.js`\. + + ``` + exports.handler = async function (event, context) { + return 'hello world'; + }; + ``` + + However, any file will work, since we won't actually be deploying the stack\. + ## Running tests For reference, here are the commands you use to run tests in your AWS CDK app\. These are the same commands you'd use to run the tests in any project using the same testing framework\. For languages that require a build step, include that to make sure your tests have been compiled\. diff --git a/v2/testing.md b/v2/testing.md index 32a8f523..690b74f8 100644 --- a/v2/testing.md +++ b/v2/testing.md @@ -473,6 +473,20 @@ namespace AwsCdkAssertionSamples ------ +## The Lambda function + +Our example stack includes a Lambda function that starts our state machine\. We must provide the source code for this function so the CDK can bundle it up and deploy it as part of creating the Lambda function resource\. ++ Create the folder `start-state-machine` in the app's main directory\. ++ In this folder, create at least one file\. For example, you can save the code below in `start-state-machines/index.js`\. + + ``` + exports.handler = async function (event, context) { + return 'hello world'; + }; + ``` + + However, any file will work, since we won't actually be deploying the stack\. + ## Running tests For reference, here are the commands you use to run tests in your AWS CDK app\. These are the same commands you'd use to run the tests in any project using the same testing framework\. For languages that require a build step, include that to make sure your tests have been compiled\. From 81ed6250e0f2b036daf2fcbf18c428f54668e9a4 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 28 Apr 2022 18:25:49 +0000 Subject: [PATCH 518/655] fix Parameters link in Get Cfn Value topic (also some ID churn) --- v1/cli.md | 26 +++++++++++++------------- v1/get_cfn_param.md | 6 +++--- v1/index.md | 2 +- v1/manage-dependencies.md | 10 +++++----- v1/tagging.md | 2 +- v1/use_cfn_template.md | 2 +- v2/cli.md | 26 +++++++++++++------------- v2/get_cfn_param.md | 6 +++--- v2/index.md | 2 +- v2/manage-dependencies.md | 10 +++++----- v2/tagging.md | 2 +- v2/use_cfn_template.md | 2 +- 12 files changed, 48 insertions(+), 48 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index d3553b0c..a97849a6 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -349,7 +349,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -368,7 +368,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -376,7 +376,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -444,7 +444,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -466,7 +466,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -723,7 +723,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -736,7 +736,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -757,7 +757,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -837,7 +837,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -915,7 +915,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -934,7 +934,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -960,7 +960,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -982,7 +982,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/get_cfn_param.md b/v1/get_cfn_param.md index 9607aa96..12e07b27 100644 --- a/v1/get_cfn_param.md +++ b/v1/get_cfn_param.md @@ -1,5 +1,5 @@ -# Use an AWS CloudFormation parameter +# Use an AWS CloudFormation value -See [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for information about using the optional *Parameters* section to customize your AWS CloudFormation templates\. +See [Parameters](parameters.md) for information about using AWS CloudFormation parameters with the AWS CDK\. -You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [Import or migrate an existing AWS CloudFormation template](use_cfn_template.md)\. \ No newline at end of file +To get a reference to a resource in an existing AWS CloudFormation template, see [Import or migrate an existing AWS CloudFormation template](use_cfn_template.md)\. \ No newline at end of file diff --git a/v1/index.md b/v1/index.md index e546b765..b2ab465b 100644 --- a/v1/index.md +++ b/v1/index.md @@ -52,7 +52,7 @@ Amazon's trademarks and trade dress may not be used in + [AWS CDK examples](about_examples.md) + [AWS CDK how-tos](how_tos.md) + [Get a value from an environment variable](get_env_var.md) - + [Use an AWS CloudFormation parameter](get_cfn_param.md) + + [Use an AWS CloudFormation value](get_cfn_param.md) + [Import or migrate an existing AWS CloudFormation template](use_cfn_template.md) + [Using resources from the AWS CloudFormation Public Registry](use_cfn_public_registry.md) + [Get a value from the Systems Manager Parameter Store](get_ssm_value.md) diff --git a/v1/manage-dependencies.md b/v1/manage-dependencies.md index 427779a1..aaf940ee 100644 --- a/v1/manage-dependencies.md +++ b/v1/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -72,7 +72,7 @@ All AWS CDK dependencies must have the same version\. Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -99,7 +99,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -145,7 +145,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -169,7 +169,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v1/tagging.md b/v1/tagging.md index 437394ca..9011b96a 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index d4f79a47..a19b7dba 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/cli.md b/v2/cli.md index fa17a81e..e3cc2dd1 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -341,7 +341,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -360,7 +360,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -368,7 +368,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -436,7 +436,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -458,7 +458,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -715,7 +715,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -728,7 +728,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -749,7 +749,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -829,7 +829,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -907,7 +907,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -926,7 +926,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -952,7 +952,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -974,7 +974,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/get_cfn_param.md b/v2/get_cfn_param.md index 9607aa96..12e07b27 100644 --- a/v2/get_cfn_param.md +++ b/v2/get_cfn_param.md @@ -1,5 +1,5 @@ -# Use an AWS CloudFormation parameter +# Use an AWS CloudFormation value -See [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for information about using the optional *Parameters* section to customize your AWS CloudFormation templates\. +See [Parameters](parameters.md) for information about using AWS CloudFormation parameters with the AWS CDK\. -You can also get a reference to a resource in an existing AWS CloudFormation template, as described in [Import or migrate an existing AWS CloudFormation template](use_cfn_template.md)\. \ No newline at end of file +To get a reference to a resource in an existing AWS CloudFormation template, see [Import or migrate an existing AWS CloudFormation template](use_cfn_template.md)\. \ No newline at end of file diff --git a/v2/index.md b/v2/index.md index 6436d89b..072e9328 100644 --- a/v2/index.md +++ b/v2/index.md @@ -52,7 +52,7 @@ Amazon's trademarks and trade dress may not be used in + [AWS CDK examples](about_examples.md) + [AWS CDK how-tos](how_tos.md) + [Get a value from an environment variable](get_env_var.md) - + [Use an AWS CloudFormation parameter](get_cfn_param.md) + + [Use an AWS CloudFormation value](get_cfn_param.md) + [Import or migrate an existing AWS CloudFormation template](use_cfn_template.md) + [Using resources from the AWS CloudFormation Public Registry](use_cfn_public_registry.md) + [Get a value from the Systems Manager Parameter Store](get_ssm_value.md) diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index 2625fd5c..3bfdf888 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -71,7 +71,7 @@ Specify exact versions for alpha construct library modules, which have APIs that Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -101,7 +101,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -147,7 +147,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -167,7 +167,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v2/tagging.md b/v2/tagging.md index b84d476d..1a4708cf 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 897de566..5020808f 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 58c8c9c3e9dae235db416237785d3ef50684591f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 28 Apr 2022 20:16:26 +0000 Subject: [PATCH 519/655] add information about importing IAM resources (plus some ID churn) --- v1/cli.md | 26 +++++++++++++------------- v1/manage-dependencies.md | 10 +++++----- v1/permissions.md | 19 ++++++++++++++++++- v1/tagging.md | 2 +- v1/use_cfn_template.md | 2 +- v2/cli.md | 26 +++++++++++++------------- v2/manage-dependencies.md | 10 +++++----- v2/permissions.md | 19 ++++++++++++++++++- v2/tagging.md | 2 +- v2/use_cfn_template.md | 2 +- 10 files changed, 76 insertions(+), 42 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index a97849a6..371f9341 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -349,7 +349,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -368,7 +368,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -376,7 +376,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -444,7 +444,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -466,7 +466,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -723,7 +723,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -736,7 +736,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -757,7 +757,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -837,7 +837,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -915,7 +915,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -934,7 +934,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -960,7 +960,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -982,7 +982,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/manage-dependencies.md b/v1/manage-dependencies.md index aaf940ee..757723d1 100644 --- a/v1/manage-dependencies.md +++ b/v1/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -72,7 +72,7 @@ All AWS CDK dependencies must have the same version\. Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -99,7 +99,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -145,7 +145,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -169,7 +169,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v1/permissions.md b/v1/permissions.md index 1f0a5822..b52fa972 100644 --- a/v1/permissions.md +++ b/v1/permissions.md @@ -486,4 +486,21 @@ bucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps })); ``` ------- \ No newline at end of file +------ + +## Using external IAM objects + +If you have defined an IAM user, principal, group, or role outside your AWS CDK app, you can use that IAM object in your AWS CDK app by creating a reference to it using its ARN or \(for users, groups, and roles\) its name\. The returned reference can then be used to grant permissions or to construct policy statements as explained above\. ++ For users, call `[User\.fromUserArn\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.User.html#static-fromwbruserwbrarnscope-id-userarn)` or `[User\.fromUserName\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.User.html#static-fromwbruserwbrnamescope-id-username)`\. `User.fromUserAttributes()` is also available, but currently provides the same functionality as `User.fromUserArn()`\. ++ For principals, instantiate an `[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ArnPrincipal.html)` object\. ++ For groups, call `[Group\.fromGroupArn\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Group.html#static-fromwbrgroupwbrarnscope-id-grouparn)` or `[Group\.fromGroupName\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Group.html#static-fromwbrgroupwbrnamescope-id-groupname)`\. ++ For roles, call `[Role\.fromRoleArn\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html#static-fromwbrrolewbrarnscope-id-rolearn-options)` or `[Role\.fromRoleName\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html#static-fromwbrrolewbrnamescope-id-rolename)`\. + +Policies \(including managed policies\) can be imported in similar fashion using the methods listed below\. You can use references to these objects anywhere an IAM policy is required\. ++ `[Policy\.fromPolicyName](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Policy.html#static-fromwbrpolicywbrnamescope-id-policyname)` ++ `[ManagedPolicy\.fromManagedPolicyArn](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ManagedPolicy.html#static-fromwbrmanagedwbrpolicywbrarnscope-id-managedpolicyarn)` ++ `[ManagedPolicy\.fromManagedPolicyName](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ManagedPolicy.html#static-fromwbrmanagedwbrpolicywbrnamescope-id-managedpolicyname)` ++ `[ManagedPolicy\.fromAwsManagedPolicyName](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ManagedPolicy.html#static-fromwbrawswbrmanagedwbrpolicywbrnamemanagedpolicyname)` + +**Note** +As with all references to external AWS resources, you cannot modify imported IAM objects in your CDK app\. \ No newline at end of file diff --git a/v1/tagging.md b/v1/tagging.md index 9011b96a..ab4b3f58 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index a19b7dba..4273e248 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/cli.md b/v2/cli.md index e3cc2dd1..c60a02af 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -341,7 +341,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -360,7 +360,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -368,7 +368,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -436,7 +436,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -458,7 +458,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -715,7 +715,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -728,7 +728,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -749,7 +749,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -829,7 +829,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -907,7 +907,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -926,7 +926,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -952,7 +952,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -974,7 +974,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index 3bfdf888..a35d9c53 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -71,7 +71,7 @@ Specify exact versions for alpha construct library modules, which have APIs that Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -101,7 +101,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -147,7 +147,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -167,7 +167,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v2/permissions.md b/v2/permissions.md index 2f051297..31aca148 100644 --- a/v2/permissions.md +++ b/v2/permissions.md @@ -486,4 +486,21 @@ bucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps })); ``` ------- \ No newline at end of file +------ + +## Using external IAM objects + +If you have defined an IAM user, principal, group, or role outside your AWS CDK app, you can use that IAM object in your AWS CDK app by creating a reference to it using its ARN or \(for users, groups, and roles\) its name\. The returned reference can then be used to grant permissions or to construct policy statements as explained above\. ++ For users, call `[User\.fromUserArn\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html#static-fromwbruserwbrarnscope-id-userarn)` or `[User\.fromUserName\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html#static-fromwbruserwbrnamescope-id-username)`\. `User.fromUserAttributes()` is also available, but currently provides the same functionality as `User.fromUserArn()`\. ++ For principals, instantiate an `[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ArnPrincipal.html)` object\. ++ For groups, call `[Group\.fromGroupArn\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Group.html#static-fromwbrgroupwbrarnscope-id-grouparn)` or `[Group\.fromGroupName\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Group.html#static-fromwbrgroupwbrnamescope-id-groupname)`\. ++ For roles, call `[Role\.fromRoleArn\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html#static-fromwbrrolewbrarnscope-id-rolearn-options)` or `[Role\.fromRoleName\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html#static-fromwbrrolewbrnamescope-id-rolename)`\. + +Policies \(including managed policies\) can be imported in similar fashion using the methods listed below\. You can use references to these objects anywhere an IAM policy is required\. ++ `[Policy\.fromPolicyName](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Policy.html#static-fromwbrpolicywbrnamescope-id-policyname)` ++ `[ManagedPolicy\.fromManagedPolicyArn](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ManagedPolicy.html#static-fromwbrmanagedwbrpolicywbrarnscope-id-managedpolicyarn)` ++ `[ManagedPolicy\.fromManagedPolicyName](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ManagedPolicy.html#static-fromwbrmanagedwbrpolicywbrnamescope-id-managedpolicyname)` ++ `[ManagedPolicy\.fromAwsManagedPolicyName](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ManagedPolicy.html#static-fromwbrawswbrmanagedwbrpolicywbrnamemanagedpolicyname)` + +**Note** +As with all references to external AWS resources, you cannot modify imported IAM objects in your CDK app\. \ No newline at end of file diff --git a/v2/tagging.md b/v2/tagging.md index 1a4708cf..fabd3c98 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 5020808f..1df7fdf8 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 696ec209e202a32f89275a4bd550bca0d64ee1ed Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 28 Apr 2022 20:36:27 +0000 Subject: [PATCH 520/655] increase findability of layer descriptions --- v1/constructs.md | 6 +++--- v2/constructs.md | 6 +++--- v2/migrating-v2.md | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/v1/constructs.md b/v1/constructs.md index 73ba8ef7..3fbe9bb5 100644 --- a/v1/constructs.md +++ b/v1/constructs.md @@ -15,11 +15,11 @@ The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-dynamodb.Table.html)` class represents an Amazon DynamoDB table\. -There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "layer 1"\) or Cfn \(short for CloudFormation\) resources\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. +There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "layer 1"\)\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. -The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#add-wbr-lifecycle-wbr-rulerule), which adds a lifecycle rule to the bucket\. +The next level of constructs, **L2**, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-s3.Bucket.html#add-wbr-lifecycle-wbr-rulerule), which adds a lifecycle rule to the bucket\. -Finally, the AWS Construct Library includes L3 constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs-patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. +Finally, the AWS Construct Library includes **L3** constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs-patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. For more information about how to navigate the library and discover constructs that can help you build your apps, see the [API Reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html)\. diff --git a/v2/constructs.md b/v2/constructs.md index f05b3c7c..e1d81f76 100644 --- a/v2/constructs.md +++ b/v2/constructs.md @@ -18,11 +18,11 @@ The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_dynamodb.Table.html)` class represents an Amazon DynamoDB table\. -There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or L1, short for "layer 1"\) or Cfn \(short for CloudFormation\) resources\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. +There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or **L1**, short for "layer 1"\)\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. -The next level of constructs, L2, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#addwbrlifecyclewbrrulerule), which adds a lifecycle rule to the bucket\. +The next level of constructs, **L2**, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#addwbrlifecyclewbrrulerule), which adds a lifecycle rule to the bucket\. -Finally, the AWS Construct Library includes L3 constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. +Finally, the AWS Construct Library includes **L3** constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. For more information about how to navigate the library and discover constructs that can help you build your apps, see the [API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html)\. diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index bf7bab59..570714c8 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -8,7 +8,7 @@ The main changes from AWS CDK v1 to CDK v2 are as follows\. L1 \(CfnXXXX\) constructs, which represent the exact resources available in AWS CloudFormation, are always considered stable and so are included in `aws-cdk-lib`\. + Experimental modules, where we're still working with the community to develop new [L2 or L3 constructs](constructs.md#constructs_lib), are not included in `aws-cdk-lib`; they are instead distributed as individual packages\. Experimental packages are named with an `alpha` suffix and a semantic version number that matches the first version of the AWS Construct Library with which they are compatible, also with an `alpha` suffix\. Constructs move into `aws-cdk-lib` after being designated stable, permitting the main Construct Library to adhere to strict semantic versioning\. - Stability is specified at the service level\. For example, if we begin creating one or more L2 constructs for Amazon AppFlow, which at this writing has only L1 constructs, they would first appear in a module named `@aws-cdk/aws-appflow-alpha`, then move to `aws-cdk-lib` when we feel the new constructs meet the fundamental needs of customers\. + Stability is specified at the service level\. For example, if we begin creating one or more [L2 constructs](constructs.md#constructs_lib) for Amazon AppFlow, which at this writing has only L1 constructs, they would first appear in a module named `@aws-cdk/aws-appflow-alpha`, then move to `aws-cdk-lib` when we feel the new constructs meet the fundamental needs of customers\. Once a module has been designated stable and incorporated into `aws-cdk-lib`, new APIs are added using the "BetaN" convention described in the next bullet\. From 46cd5e74d3691e0eb9c374c22d2bf46d527b98e3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 28 Apr 2022 21:41:25 +0000 Subject: [PATCH 521/655] fix incorrect imports --- v2/testing.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/v2/testing.md b/v2/testing.md index 690b74f8..4b8f6d8a 100644 --- a/v2/testing.md +++ b/v2/testing.md @@ -232,11 +232,11 @@ Place the following code in `state_machine/state_machine_stack.py`: ``` from typing import List -import aws-cdk.aws_lambda as lambda_ -import aws-cdk.aws_sns as sns -import aws-cdk.aws_sns_subscriptions as sns_subscriptions -import aws-cdk.aws_stepfunctions as sfn -import aws-cdk as cdk +import aws_cdk.aws_lambda as lambda_ +import aws_cdk.aws_sns as sns +import aws_cdk.aws_sns_subscriptions as sns_subscriptions +import aws_cdk.aws_stepfunctions as sfn +import aws_cdk as cdk class ProcessorStack(cdk.Stack): def __init__( From 643e7a206ac4563275a6069b968a4bb101920152 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 28 Apr 2022 21:41:49 +0000 Subject: [PATCH 522/655] add instruction for using the actual CDK Toolkit to bootstrap using a modified template --- v1/bootstrapping.md | 2 +- v2/bootstrapping.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/bootstrapping.md b/v1/bootstrapping.md index 6f87739d..a296cafb 100644 --- a/v1/bootstrapping.md +++ b/v1/bootstrapping.md @@ -87,7 +87,7 @@ powershell "cdk bootstrap --show-template | Out-File -encoding utf8 bootstrap-te The template is also available in the [AWS CDK GitHub repository](https://github.com/aws/aws-cdk/blob/master/packages/aws-cdk/lib/api/bootstrap/bootstrap-template.yaml)\. -Deploy this template using your preferred deployment mechanism for AWS CloudFormation templates\. For example, the following command deploys the template using the AWS CLI: +Deploy this template using cdk bootstrap \-\-template *TEMPLATE\_FILENAME* or your preferred deployment mechanism for AWS CloudFormation templates\. For example, the following command deploys the template using the AWS CLI: ------ #### [ macOS/Linux ] diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index 01ff48b7..fed84139 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -87,7 +87,7 @@ powershell "cdk bootstrap --show-template | Out-File -encoding utf8 bootstrap-te The template is also available in the [AWS CDK GitHub repository](https://github.com/aws/aws-cdk/blob/master/packages/aws-cdk/lib/api/bootstrap/bootstrap-template.yaml)\. -Deploy this template using your preferred deployment mechanism for AWS CloudFormation templates\. For example, the following command deploys the template using the AWS CLI: +Deploy this template using cdk bootstrap \-\-template *TEMPLATE\_FILENAME* or your preferred deployment mechanism for AWS CloudFormation templates\. For example, the following command deploys the template using the AWS CLI: ------ #### [ macOS/Linux ] From f862f3ac8d0b77cb3cb01ce0f21babe5dc4f990c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 03:37:51 +0000 Subject: [PATCH 523/655] remove information about subclassing App while investigating report that it doesn't work --- v1/apps.md | 90 ------------------------------------------------------ v2/apps.md | 90 ------------------------------------------------------ 2 files changed, 180 deletions(-) diff --git a/v1/apps.md b/v1/apps.md index 1beffaac..4f9339ad 100644 --- a/v1/apps.md +++ b/v1/apps.md @@ -127,96 +127,6 @@ app.Synth(); The `App` construct doesn't require any initialization arguments, because it's the only construct that can be used as a root for the construct tree\. You can now use the `App` instance as a scope for defining a single instance of your stack\. -You can also define constructs within an App\-derived class as follows\. - ------- -#### [ TypeScript ] - -``` -class MyApp extends App { - constructor() { - new MyFirstStack(this, 'hello-cdk'); - } -} - -new MyApp().synth(); -``` - ------- -#### [ JavaScript ] - -``` -class MyApp extends App { - constructor() { - new MyFirstStack(this, 'hello-cdk'); - } -} - -new MyApp().synth(); -``` - ------- -#### [ Python ] - -``` -class MyApp(App): - def __init__(self): - MyFirstStack(self, "hello-cdk") - -MyApp().synth() -``` - ------- -#### [ Java ] - -``` -// MyApp.java -package com.myorg; - -import software.amazon.awscdk.core.App; - -public class MyApp extends App{ - public MyApp() { - new MyFirstStack(this, "hello-cdk"); - } -} - -// Main.java -package com.myorg; - -public class Main { - public static void main(String[] args) { - new MyApp().synth(); - } -} -``` - ------- -#### [ C\# ] - -``` -public class MyApp : App -{ - public MyApp(AppProps props = null) : base(props) - { - new MyFirstStack(this, "hello-cdk"); - - } -} - -class Program -{ - static void Main(string[] args) - { - new MyApp().Synth(); - } -} -``` - ------- - -These two methods are equivalent\. - ## App lifecycle The following diagram shows the phases that the AWS CDK goes through when you call the cdk deploy\. This command deploys the resources that your app defines\. diff --git a/v2/apps.md b/v2/apps.md index baf6ca89..28406e7c 100644 --- a/v2/apps.md +++ b/v2/apps.md @@ -127,96 +127,6 @@ app.Synth(); The `App` construct doesn't require any initialization arguments, because it's the only construct that can be used as a root for the construct tree\. You can now use the `App` instance as a scope for defining a single instance of your stack\. -You can also define constructs within an App\-derived class as follows\. - ------- -#### [ TypeScript ] - -``` -class MyApp extends App { - constructor() { - new MyFirstStack(this, 'hello-cdk'); - } -} - -new MyApp().synth(); -``` - ------- -#### [ JavaScript ] - -``` -class MyApp extends App { - constructor() { - new MyFirstStack(this, 'hello-cdk'); - } -} - -new MyApp().synth(); -``` - ------- -#### [ Python ] - -``` -class MyApp(App): - def __init__(self): - MyFirstStack(self, "hello-cdk") - -MyApp().synth() -``` - ------- -#### [ Java ] - -``` -// MyApp.java -package com.myorg; - -import software.amazon.awscdk.App; - -public class MyApp extends App{ - public MyApp() { - new MyFirstStack(this, "hello-cdk"); - } -} - -// Main.java -package com.myorg; - -public class Main { - public static void main(String[] args) { - new MyApp().synth(); - } -} -``` - ------- -#### [ C\# ] - -``` -public class MyApp : App -{ - public MyApp(AppProps props = null) : base(props) - { - new MyFirstStack(this, "hello-cdk"); - - } -} - -class Program -{ - static void Main(string[] args) - { - new MyApp().Synth(); - } -} -``` - ------- - -These two methods are equivalent\. - ## App lifecycle The following diagram shows the phases that the AWS CDK goes through when you call the cdk deploy\. This command deploys the resources that your app defines\. From 3dd977c022e906c1d73cc9b794afba89ae57c543 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 15:34:14 +0000 Subject: [PATCH 524/655] fix incorrect reference to flag (should be option) --- v1/cli.md | 2 +- v2/cli.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index 371f9341..bc0e6ac0 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -64,7 +64,7 @@ Some options are flags \(Booleans\)\. You may specify `true` or `false` as their --staging false ``` -A few flags, namely `--context`, `--parameters`, `--plugin`, `--tags`, and `--trust`, may be specified more than once to specify multiple values\. These are noted as having `[array]` type in the CDK Toolkit help\. For example: +A few options, namely `--context`, `--parameters`, `--plugin`, `--tags`, and `--trust`, may be specified more than once to specify multiple values\. These are noted as having `[array]` type in the CDK Toolkit help\. For example: ``` cdk bootstrap --tags costCenter=0123 --tags responsibleParty=jdoe diff --git a/v2/cli.md b/v2/cli.md index c60a02af..9469c52b 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -58,7 +58,7 @@ Some options are flags \(Booleans\)\. You may specify `true` or `false` as their --staging false ``` -A few flags, namely `--context`, `--parameters`, `--plugin`, `--tags`, and `--trust`, may be specified more than once to specify multiple values\. These are noted as having `[array]` type in the CDK Toolkit help\. For example: +A few options, namely `--context`, `--parameters`, `--plugin`, `--tags`, and `--trust`, may be specified more than once to specify multiple values\. These are noted as having `[array]` type in the CDK Toolkit help\. For example: ``` cdk bootstrap --tags costCenter=0123 --tags responsibleParty=jdoe From 907859eed76ef5f7a48bfc1d00a78d51628cca88 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 16:01:06 +0000 Subject: [PATCH 525/655] point to SAM guide for canonical doc on CDK/SAM integration and remove dev preview notice (plus autogen churn) --- v1/assets.md | 2 +- v1/cli.md | 26 ++++++------- v1/index.md | 2 +- v1/manage-dependencies.md | 10 ++--- v1/sam.md | 79 +-------------------------------------- v1/tagging.md | 2 +- v1/tools.md | 2 +- v1/use_cfn_template.md | 2 +- v2/assets.md | 2 +- v2/cli.md | 26 ++++++------- v2/index.md | 2 +- v2/manage-dependencies.md | 10 ++--- v2/sam.md | 78 +------------------------------------- v2/tagging.md | 2 +- v2/tools.md | 2 +- v2/use_cfn_template.md | 2 +- 16 files changed, 50 insertions(+), 199 deletions(-) diff --git a/v1/assets.md b/v1/assets.md index bec9c384..18d54d04 100644 --- a/v1/assets.md +++ b/v1/assets.md @@ -872,7 +872,7 @@ In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.am ## AWS CloudFormation resource metadata **Note** -This section is relevant only for construct authors\. In certain situations, tools need to know that a certain CFN resource is using a local asset\. For example, you can use the AWS SAM CLI to invoke Lambda functions locally for debugging purposes\. See [SAM CLI](sam.md) for details\. +This section is relevant only for construct authors\. In certain situations, tools need to know that a certain CFN resource is using a local asset\. For example, you can use the AWS SAM CLI to invoke Lambda functions locally for debugging purposes\. See [AWS SAM integration](sam.md) for details\. To enable such use cases, external tools consult a set of metadata entries on AWS CloudFormation resources: + `aws:asset:path` – Points to the local path of the asset\. diff --git a/v1/cli.md b/v1/cli.md index bc0e6ac0..c81fb200 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -349,7 +349,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -368,7 +368,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -376,7 +376,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -444,7 +444,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -466,7 +466,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -723,7 +723,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -736,7 +736,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -757,7 +757,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -837,7 +837,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -915,7 +915,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -934,7 +934,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -960,7 +960,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -982,7 +982,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/index.md b/v1/index.md index b2ab465b..27c77013 100644 --- a/v1/index.md +++ b/v1/index.md @@ -64,7 +64,7 @@ Amazon's trademarks and trade dress may not be used in + [AWS CDK tools](tools.md) + [AWS CDK Toolkit (cdk command)](cli.md) + [AWS Toolkit for Visual Studio Code](vscode.md) - + [SAM CLI](sam.md) + + [AWS SAM integration](sam.md) + [Testing constructs](testing.md) + [Security for the AWS Cloud Development Kit (AWS CDK)](security.md) + [Identity and access management for the AWS Cloud Development Kit (AWS CDK)](security-iam.md) diff --git a/v1/manage-dependencies.md b/v1/manage-dependencies.md index 757723d1..1fbf83bd 100644 --- a/v1/manage-dependencies.md +++ b/v1/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -72,7 +72,7 @@ All AWS CDK dependencies must have the same version\. Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -99,7 +99,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -145,7 +145,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -169,7 +169,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v1/sam.md b/v1/sam.md index 522674a9..cebf3a74 100644 --- a/v1/sam.md +++ b/v1/sam.md @@ -1,78 +1,3 @@ -# SAM CLI +# AWS SAM integration -This topic describes how to use the AWS SAM CLI with the AWS CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. - -**Note** -Full AWS CDK integration with the AWS SAM CLI is currently in public preview\. This integration allows you to locally test and build serverless application defined using the CDK\. For more information, see [AWS Cloud Development Kit \(CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. -The instructions here apply to the current \(non\-preview\) version of the AWS SAM CLI\. - -1. The first step is to create a AWS CDK application and add the Lambda package\. - - ``` - mkdir cdk-sam-example - cd cdk-sam-example - cdk init app --language typescript - npm install @aws-cdk/aws-lambda - ``` - -1. Add a Lambda reference to `lib/cdk-sam-example-stack.ts`: - - ``` - import * as lambda from '@aws-cdk/aws-lambda'; - ``` - -1. Replace the comment in `lib/cdk-sam-example-stack.ts` with the following Lambda function: - - ``` - new lambda.Function(this, 'MyFunction', { - runtime: lambda.Runtime.PYTHON_3_7, - handler: 'app.lambda_handler', - code: lambda.Code.fromAsset('./my_function'), - }); - ``` - -1. Create the directory `my_function` - - ``` - mkdir my_function - ``` - -1. Create the file `app.py` in `my_function` with the following content: - - ``` - def lambda_handler(event, context): - return "This is a Lambda Function defined through CDK" - ``` - -1. Run your AWS CDK app and create a AWS CloudFormation template - - ``` - cdk synth --no-staging > template.yaml - ``` - -1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: - - ``` - Type: AWS::Lambda::Function - ``` - -1. Run the function by executing: - - ``` - sam local invoke MyFunction12345678 --no-event - ``` - - The output should look something like the following\. - - ``` - 2019-04-01 12:22:41 Found credentials in shared credentials file: ~/.aws/credentials - 2019-04-01 12:22:41 Invoking app.lambda_handler (python3.7) - - Fetching lambci/lambda:python3.7 Docker container image...... - 2019-04-01 12:22:43 Mounting D:\cdk-sam-example\.cdk.staging\a57f59883918e662ab3c46b964d2faa5 as /var/task:ro,delegated inside runtime container - START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST - END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 - REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB - - "This is a Lambda Function defined through CDK" - ``` \ No newline at end of file +The AWS CDK and the AWS Serverless Application Model \(AWS SAM\) can work together to let you to locally build and test serverless applications defined in the CDK\. For complete information, see [AWS Cloud Development Kit \(CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. \ No newline at end of file diff --git a/v1/tagging.md b/v1/tagging.md index ab4b3f58..e327f6d3 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v1/tools.md b/v1/tools.md index d0df8f1a..4eef2d2e 100644 --- a/v1/tools.md +++ b/v1/tools.md @@ -5,4 +5,4 @@ This section contains information about the AWS CDK tools listed below\. **Topics** + [AWS CDK Toolkit \(`cdk` command\)](cli.md) + [AWS Toolkit for Visual Studio Code](vscode.md) -+ [SAM CLI](sam.md) \ No newline at end of file ++ [AWS SAM integration](sam.md) \ No newline at end of file diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index 4273e248..974c5f1a 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/assets.md b/v2/assets.md index 91be33bc..ff8dcf9d 100644 --- a/v2/assets.md +++ b/v2/assets.md @@ -874,7 +874,7 @@ In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.am ## AWS CloudFormation resource metadata **Note** -This section is relevant only for construct authors\. In certain situations, tools need to know that a certain CFN resource is using a local asset\. For example, you can use the AWS SAM CLI to invoke Lambda functions locally for debugging purposes\. See [SAM CLI](sam.md) for details\. +This section is relevant only for construct authors\. In certain situations, tools need to know that a certain CFN resource is using a local asset\. For example, you can use the AWS SAM CLI to invoke Lambda functions locally for debugging purposes\. See [AWS SAM integration](sam.md) for details\. To enable such use cases, external tools consult a set of metadata entries on AWS CloudFormation resources: + `aws:asset:path` – Points to the local path of the asset\. diff --git a/v2/cli.md b/v2/cli.md index 9469c52b..0da8966d 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -341,7 +341,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -360,7 +360,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -368,7 +368,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -436,7 +436,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -458,7 +458,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -715,7 +715,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -728,7 +728,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -749,7 +749,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -829,7 +829,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -907,7 +907,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -926,7 +926,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -952,7 +952,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -974,7 +974,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/index.md b/v2/index.md index 072e9328..39268528 100644 --- a/v2/index.md +++ b/v2/index.md @@ -64,7 +64,7 @@ Amazon's trademarks and trade dress may not be used in + [AWS CDK tools](tools.md) + [AWS CDK Toolkit (cdk command)](cli.md) + [AWS Toolkit for Visual Studio Code](vscode.md) - + [SAM CLI](sam.md) + + [AWS SAM integration](sam.md) + [Testing constructs](testing.md) + [Security for the AWS Cloud Development Kit (AWS CDK)](security.md) + [Identity and access management for the AWS Cloud Development Kit (AWS CDK)](security-iam.md) diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index a35d9c53..0ad643e7 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -71,7 +71,7 @@ Specify exact versions for alpha construct library modules, which have APIs that Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -101,7 +101,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -147,7 +147,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -167,7 +167,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v2/sam.md b/v2/sam.md index 676576a2..cebf3a74 100644 --- a/v2/sam.md +++ b/v2/sam.md @@ -1,77 +1,3 @@ -# SAM CLI +# AWS SAM integration -This topic describes how to use the AWS SAM CLI with the AWS CDK to test a Lambda function locally\. For further information, see [Invoking Functions Locally](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html)\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. - -**Note** -Full AWS CDK integration with the AWS SAM CLI is currently in public preview\. This integration allows you to locally test and build serverless application defined using the CDK\. For more information, see [AWS Cloud Development Kit \(CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. -The instructions here apply to the current \(non\-preview\) version of the AWS SAM CLI\. - -1. The first step is to create a AWS CDK application and add the Lambda package\. - - ``` - mkdir cdk-sam-example - cd cdk-sam-example - cdk init app --language typescript - ``` - -1. Add a Lambda reference to `lib/cdk-sam-example-stack.ts`: - - ``` - import * as lambda from 'aws-cdk-lib/aws-lambda'; - ``` - -1. Replace the comment in `lib/cdk-sam-example-stack.ts` with the following Lambda function: - - ``` - new lambda.Function(this, 'MyFunction', { - runtime: lambda.Runtime.PYTHON_3_7, - handler: 'app.lambda_handler', - code: lambda.Code.fromAsset('./my_function'), - }); - ``` - -1. Create the directory `my_function` - - ``` - mkdir my_function - ``` - -1. Create the file `app.py` in `my_function` with the following content: - - ``` - def lambda_handler(event, context): - return "This is a Lambda Function defined through CDK" - ``` - -1. Run your AWS CDK app and create a AWS CloudFormation template - - ``` - cdk synth --no-staging > template.yaml - ``` - -1. Find the logical ID for your Lambda function in `template.yaml`\. It will look like `MyFunction`*12345678*, where *12345678* represents an 8\-character unique ID that the AWS CDK generates for all resources\. The line right after it should look like: - - ``` - Type: AWS::Lambda::Function - ``` - -1. Run the function by executing: - - ``` - sam local invoke MyFunction12345678 --no-event - ``` - - The output should look something like the following\. - - ``` - 2019-04-01 12:22:41 Found credentials in shared credentials file: ~/.aws/credentials - 2019-04-01 12:22:41 Invoking app.lambda_handler (python3.7) - - Fetching lambci/lambda:python3.7 Docker container image...... - 2019-04-01 12:22:43 Mounting D:\cdk-sam-example\.cdk.staging\a57f59883918e662ab3c46b964d2faa5 as /var/task:ro,delegated inside runtime container - START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST - END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 - REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB - - "This is a Lambda Function defined through CDK" - ``` \ No newline at end of file +The AWS CDK and the AWS Serverless Application Model \(AWS SAM\) can work together to let you to locally build and test serverless applications defined in the CDK\. For complete information, see [AWS Cloud Development Kit \(CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. \ No newline at end of file diff --git a/v2/tagging.md b/v2/tagging.md index fabd3c98..2f76c55d 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v2/tools.md b/v2/tools.md index d0df8f1a..4eef2d2e 100644 --- a/v2/tools.md +++ b/v2/tools.md @@ -5,4 +5,4 @@ This section contains information about the AWS CDK tools listed below\. **Topics** + [AWS CDK Toolkit \(`cdk` command\)](cli.md) + [AWS Toolkit for Visual Studio Code](vscode.md) -+ [SAM CLI](sam.md) \ No newline at end of file ++ [AWS SAM integration](sam.md) \ No newline at end of file diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 1df7fdf8..360db5f8 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From a669629b3f11699fb504b158d0db2dc1f1c6bdd4 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 16:19:01 +0000 Subject: [PATCH 526/655] passing separate context values to different stacks does not work that way! --- v1/context.md | 6 +----- v2/context.md | 6 +----- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/v1/context.md b/v1/context.md index b68fe94a..5cab3848 100644 --- a/v1/context.md +++ b/v1/context.md @@ -116,11 +116,7 @@ To specify multiple context values, repeat the \-\-context option any number of cdk synth --context key1=value1 --context key2=value2 MyStack ``` -When deploying multiple stacks, the specified context values are normally passed to all of them\. If you wish, you may specify different values for each stack by prefixing the stack name to the context value\. - -``` -cdk synth --context Stack1:key=value --context Stack2:key=value Stack1 Stack2 -``` +When synthesizing multiple stacks, the specified context values are passed to all stacks\. To provide different context values to individual stacks, either use different keys for the values, or use multiple cdk synth or cdk deploy commands\. ## Example diff --git a/v2/context.md b/v2/context.md index 77b471aa..93c41ab2 100644 --- a/v2/context.md +++ b/v2/context.md @@ -116,11 +116,7 @@ To specify multiple context values, repeat the \-\-context option any number of cdk synth --context key1=value1 --context key2=value2 MyStack ``` -When deploying multiple stacks, the specified context values are normally passed to all of them\. If you wish, you may specify different values for each stack by prefixing the stack name to the context value\. - -``` -cdk synth --context Stack1:key=value --context Stack2:key=value Stack1 Stack2 -``` +When synthesizing multiple stacks, the specified context values are passed to all stacks\. To provide different context values to individual stacks, either use different keys for the values, or use multiple cdk synth or cdk deploy commands\. ## Example From 9d9666ce3153b6a5d2a7edce2bd6f598930eb783 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 16:51:45 +0000 Subject: [PATCH 527/655] add notice about potential cost of leaving this example deployed --- v1/ecs_example.md | 3 +++ v2/ecs_example.md | 3 +++ 2 files changed, 6 insertions(+) diff --git a/v1/ecs_example.md b/v1/ecs_example.md index 7cfb79ee..1872d9e6 100644 --- a/v1/ecs_example.md +++ b/v1/ecs_example.md @@ -27,6 +27,9 @@ The Amazon ECS construct used in this tutorial helps you use AWS services by pro See [ECS](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-ecs-readme.html) for details\. +**Important** +The `ApplicationLoadBalancedFargateService` constructs we'll be using includes numerous AWS components, some of which can cost non\-trivial amounts of money if left provisioned in your AWS account, even if you don't use them\. Be sure to clean up \(cdk destroy\) after completing this example\. + ## Creating the directory and initializing the AWS CDK Let's start by creating a directory to hold the AWS CDK code, and then creating a AWS CDK app in that directory\. diff --git a/v2/ecs_example.md b/v2/ecs_example.md index 89c900e9..1438606c 100644 --- a/v2/ecs_example.md +++ b/v2/ecs_example.md @@ -27,6 +27,9 @@ The Amazon ECS construct used in this tutorial helps you use AWS services by pro See [ECS](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs-readme.html) for details\. +**Important** +The `ApplicationLoadBalancedFargateService` constructs we'll be using includes numerous AWS components, some of which can cost non\-trivial amounts of money if left provisioned in your AWS account, even if you don't use them\. Be sure to clean up \(cdk destroy\) after completing this example\. + ## Creating the directory and initializing the AWS CDK Let's start by creating a directory to hold the AWS CDK code, and then creating a AWS CDK app in that directory\. From 8442f13cab78d80d1f3946e757953e78871bf02f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 16:52:10 +0000 Subject: [PATCH 528/655] update link to tagging best practices --- v1/tagging.md | 2 +- v2/tagging.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/tagging.md b/v1/tagging.md index e327f6d3..82d064dc 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -3,7 +3,7 @@ Tags are informational key\-value elements that you can add to constructs in your AWS CDK app\. A tag applied to a given construct also applies to all of its taggable children\. Tags are included in the AWS CloudFormation template synthesized from your app and are applied to the AWS resources it deploys\. You can use tags to identify and categorize resources to simplify management, in cost allocation, and for access control, as well as for any other purposes you devise\. **Tip** -For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf)\. +For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/tagging-best-practices.html)\. The [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. + [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html#addkey-value-props](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html#addkey-value-props) applies a new tag to the given construct and all of its children\. diff --git a/v2/tagging.md b/v2/tagging.md index 2f76c55d..9c9b942a 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -3,7 +3,7 @@ Tags are informational key\-value elements that you can add to constructs in your AWS CDK app\. A tag applied to a given construct also applies to all of its taggable children\. Tags are included in the AWS CloudFormation template synthesized from your app and are applied to the AWS resources it deploys\. You can use tags to identify and categorize resources to simplify management, in cost allocation, and for access control, as well as for any other purposes you devise\. **Tip** -For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf)\. +For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/tagging-best-practices.html)\. The [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. + [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#addkey-value-props](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#addkey-value-props) applies a new tag to the given construct and all of its children\. From a32c508223448356363430970de7027eb8311758 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 16:56:06 +0000 Subject: [PATCH 529/655] improve wording --- v1/ecs_example.md | 2 +- v2/ecs_example.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/ecs_example.md b/v1/ecs_example.md index 1872d9e6..d767c48d 100644 --- a/v1/ecs_example.md +++ b/v1/ecs_example.md @@ -28,7 +28,7 @@ The Amazon ECS construct used in this tutorial helps you use AWS services by pro See [ECS](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-ecs-readme.html) for details\. **Important** -The `ApplicationLoadBalancedFargateService` constructs we'll be using includes numerous AWS components, some of which can cost non\-trivial amounts of money if left provisioned in your AWS account, even if you don't use them\. Be sure to clean up \(cdk destroy\) after completing this example\. +The `ApplicationLoadBalancedFargateService` constructs we'll be using includes numerous AWS components, some of which have non\-trivial costs if left provisioned in your AWS account, even if you don't use them\. Be sure to clean up \(cdk destroy\) after completing this example\. ## Creating the directory and initializing the AWS CDK diff --git a/v2/ecs_example.md b/v2/ecs_example.md index 1438606c..07206252 100644 --- a/v2/ecs_example.md +++ b/v2/ecs_example.md @@ -28,7 +28,7 @@ The Amazon ECS construct used in this tutorial helps you use AWS services by pro See [ECS](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs-readme.html) for details\. **Important** -The `ApplicationLoadBalancedFargateService` constructs we'll be using includes numerous AWS components, some of which can cost non\-trivial amounts of money if left provisioned in your AWS account, even if you don't use them\. Be sure to clean up \(cdk destroy\) after completing this example\. +The `ApplicationLoadBalancedFargateService` constructs we'll be using includes numerous AWS components, some of which have non\-trivial costs if left provisioned in your AWS account, even if you don't use them\. Be sure to clean up \(cdk destroy\) after completing this example\. ## Creating the directory and initializing the AWS CDK From 7af532a6900ea427af6c0f918905fd0b237f64f6 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 17:26:00 +0000 Subject: [PATCH 530/655] add note about jar files --- v1/assets.md | 3 +++ v2/assets.md | 3 +++ 2 files changed, 6 insertions(+) diff --git a/v1/assets.md b/v1/assets.md index 18d54d04..ce02d5db 100644 --- a/v1/assets.md +++ b/v1/assets.md @@ -270,6 +270,9 @@ public class HelloAssetStack : Stack The `Function` method uses assets to bundle the contents of the directory and use it for the function's code\. +**Tip** +Java `.jor` files are ZIP files with a different extension\. These will be uploaded as\-is to Amazon S3, but when they are deployed as a Lambda function, the files they contain will be extracted, which probably isn't what you want\. To avoid this, place the `.jar` file in a directory and specify that directory as the asset\. + #### Deploy\-time attributes example Amazon S3 asset types also expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. diff --git a/v2/assets.md b/v2/assets.md index ff8dcf9d..6fd2ad0b 100644 --- a/v2/assets.md +++ b/v2/assets.md @@ -272,6 +272,9 @@ public class HelloAssetStack : Stack The `Function` method uses assets to bundle the contents of the directory and use it for the function's code\. +**Tip** +Java `.jor` files are ZIP files with a different extension\. These will be uploaded as\-is to Amazon S3, but when they are deployed as a Lambda function, the files they contain will be extracted, which probably isn't what you want\. To avoid this, place the `.jar` file in a directory and specify that directory as the asset\. + #### Deploy\-time attributes example Amazon S3 asset types also expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. From 04c1a699c50c5522cab77af99c3b738b73761403 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 19:46:34 +0000 Subject: [PATCH 531/655] add lookup role to DefaultStackSynthesizer properties and link to API reference --- v1/bootstrapping.md | 25 ++++++++++++++++++++++--- v2/bootstrapping.md | 25 ++++++++++++++++++++++--- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/v1/bootstrapping.md b/v1/bootstrapping.md index a296cafb..3a1f5bc4 100644 --- a/v1/bootstrapping.md +++ b/v1/bootstrapping.md @@ -395,7 +395,7 @@ All the other `DefaultStackSynthesizer` properties relate to the names of the re All properties accept the special placeholders `${Qualifier}`, `${AWS::Partition}`, `${AWS::AccountId}`, and `${AWS::Region}`\. These placeholders are replaced with the values of the `qualifier` parameter and with the values of the AWS partition, account ID, and region for the stack's environment, respectively\. -The following example shows all the available properties for `DefaultStackSynthesizer` along with their default values, as if you were instantiating the synthesizer\. +The following example shows the most commonly\-used properties for `DefaultStackSynthesizer` along with their default values, as if you were instantiating the synthesizer\. For a complete list, see [DefaultStackSynthesizerProps](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.DefaultStackSynthesizerProps.html#properties)\. ------ #### [ TypeScript ] @@ -424,11 +424,16 @@ new DefaultStackSynthesizer({ // ARN of the role passed to CloudFormation to execute the deployments cloudFormationExecutionRole: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}', + // ARN of the role used to look up context information in an environment + lookupRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-lookup-role-${AWS::AccountId}-${AWS::Region}', + lookupRoleExternalId: '', + // Name of the SSM parameter which describes the bootstrap stack version number bootstrapStackVersionSsmParameter: '/cdk-bootstrap/${Qualifier}/version', // Add a rule to every template which verifies the required bootstrap stack version generateBootstrapVersionRule: true, + }) ``` @@ -459,6 +464,10 @@ new DefaultStackSynthesizer({ // ARN of the role passed to CloudFormation to execute the deployments cloudFormationExecutionRole: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}', + // ARN of the role used to look up context information in an environment + lookupRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-lookup-role-${AWS::AccountId}-${AWS::Region}', + lookupRoleExternalId: '', + // Name of the SSM parameter which describes the bootstrap stack version number bootstrapStackVersionSsmParameter: '/cdk-bootstrap/${Qualifier}/version', @@ -492,8 +501,12 @@ DefaultStackSynthesizer( image_asset_publishing_external_id="", # ARN of the role passed to CloudFormation to execute the deployments - cloud_formation_execution_role="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" + cloud_formation_execution_role="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + # ARN of the role used to look up context information in an environment + lookup_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-lookup-role-${AWS::AccountId}-${AWS::Region}", + lookup_role_external_id="", + # Name of the SSM parameter which describes the bootstrap stack version number bootstrap_stack_version_ssm_parameter="/cdk-bootstrap/${Qualifier}/version", @@ -529,6 +542,9 @@ DefaultStackSynthesizer.Builder.create() // ARN of the role passed to CloudFormation to execute the deployments .cloudFormationExecutionRole("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}") + .lookupRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-lookup-role-${AWS::AccountId}-${AWS::Region}") + .lookupRoleExternalId("") + // Name of the SSM parameter which describes the bootstrap stack version number .bootstrapStackVersionSsmParameter("/cdk-bootstrap/${Qualifier}/version") @@ -563,8 +579,11 @@ new DefaultStackSynthesizer(new DefaultStackSynthesizerProps ImageAssetPublishingExternalId = "", // ARN of the role passed to CloudFormation to execute the deployments - CloudFormationExecutionRole = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" + CloudFormationExecutionRole = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + LookupRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-lookup-role-${AWS::AccountId}-${AWS::Region}", + LookupRoleExternalId = "", + // Name of the SSM parameter which describes the bootstrap stack version number BootstrapStackVersionSsmParameter = "/cdk-bootstrap/${Qualifier}/version", diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index fed84139..ed37b426 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -323,7 +323,7 @@ All the other `DefaultStackSynthesizer` properties relate to the names of the re All properties accept the special placeholders `${Qualifier}`, `${AWS::Partition}`, `${AWS::AccountId}`, and `${AWS::Region}`\. These placeholders are replaced with the values of the `qualifier` parameter and with the values of the AWS partition, account ID, and region for the stack's environment, respectively\. -The following example shows all the available properties for `DefaultStackSynthesizer` along with their default values, as if you were instantiating the synthesizer\. +The following example shows the most commonly\-used properties for `DefaultStackSynthesizer` along with their default values, as if you were instantiating the synthesizer\. For a complete list, see [DefaultStackSynthesizerProps](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.DefaultStackSynthesizerProps.html#properties)\. ------ #### [ TypeScript ] @@ -352,11 +352,16 @@ new DefaultStackSynthesizer({ // ARN of the role passed to CloudFormation to execute the deployments cloudFormationExecutionRole: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}', + // ARN of the role used to look up context information in an environment + lookupRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-lookup-role-${AWS::AccountId}-${AWS::Region}', + lookupRoleExternalId: '', + // Name of the SSM parameter which describes the bootstrap stack version number bootstrapStackVersionSsmParameter: '/cdk-bootstrap/${Qualifier}/version', // Add a rule to every template which verifies the required bootstrap stack version generateBootstrapVersionRule: true, + }) ``` @@ -387,6 +392,10 @@ new DefaultStackSynthesizer({ // ARN of the role passed to CloudFormation to execute the deployments cloudFormationExecutionRole: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}', + // ARN of the role used to look up context information in an environment + lookupRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-lookup-role-${AWS::AccountId}-${AWS::Region}', + lookupRoleExternalId: '', + // Name of the SSM parameter which describes the bootstrap stack version number bootstrapStackVersionSsmParameter: '/cdk-bootstrap/${Qualifier}/version', @@ -420,8 +429,12 @@ DefaultStackSynthesizer( image_asset_publishing_external_id="", # ARN of the role passed to CloudFormation to execute the deployments - cloud_formation_execution_role="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" + cloud_formation_execution_role="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + # ARN of the role used to look up context information in an environment + lookup_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-lookup-role-${AWS::AccountId}-${AWS::Region}", + lookup_role_external_id="", + # Name of the SSM parameter which describes the bootstrap stack version number bootstrap_stack_version_ssm_parameter="/cdk-bootstrap/${Qualifier}/version", @@ -457,6 +470,9 @@ DefaultStackSynthesizer.Builder.create() // ARN of the role passed to CloudFormation to execute the deployments .cloudFormationExecutionRole("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}") + .lookupRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-lookup-role-${AWS::AccountId}-${AWS::Region}") + .lookupRoleExternalId("") + // Name of the SSM parameter which describes the bootstrap stack version number .bootstrapStackVersionSsmParameter("/cdk-bootstrap/${Qualifier}/version") @@ -491,8 +507,11 @@ new DefaultStackSynthesizer(new DefaultStackSynthesizerProps ImageAssetPublishingExternalId = "", // ARN of the role passed to CloudFormation to execute the deployments - CloudFormationExecutionRole = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}" + CloudFormationExecutionRole = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + LookupRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-lookup-role-${AWS::AccountId}-${AWS::Region}", + LookupRoleExternalId = "", + // Name of the SSM parameter which describes the bootstrap stack version number BootstrapStackVersionSsmParameter = "/cdk-bootstrap/${Qualifier}/version", From 325d9988b3ee05a1e5de4d030e2b9fdd71d3b4da Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 19:47:38 +0000 Subject: [PATCH 532/655] add tip about JARs --- v1/assets.md | 2 +- v2/assets.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/assets.md b/v1/assets.md index ce02d5db..bddb2319 100644 --- a/v1/assets.md +++ b/v1/assets.md @@ -271,7 +271,7 @@ public class HelloAssetStack : Stack The `Function` method uses assets to bundle the contents of the directory and use it for the function's code\. **Tip** -Java `.jor` files are ZIP files with a different extension\. These will be uploaded as\-is to Amazon S3, but when they are deployed as a Lambda function, the files they contain will be extracted, which probably isn't what you want\. To avoid this, place the `.jar` file in a directory and specify that directory as the asset\. +Java `.jar` files are ZIP files with a different extension\. These will be uploaded as\-is to Amazon S3, but when they are deployed as a Lambda function, the files they contain will be extracted, which probably isn't what you want\. To avoid this, place the `.jar` file in a directory and specify that directory as the asset\. #### Deploy\-time attributes example diff --git a/v2/assets.md b/v2/assets.md index 6fd2ad0b..3cd8f188 100644 --- a/v2/assets.md +++ b/v2/assets.md @@ -273,7 +273,7 @@ public class HelloAssetStack : Stack The `Function` method uses assets to bundle the contents of the directory and use it for the function's code\. **Tip** -Java `.jor` files are ZIP files with a different extension\. These will be uploaded as\-is to Amazon S3, but when they are deployed as a Lambda function, the files they contain will be extracted, which probably isn't what you want\. To avoid this, place the `.jar` file in a directory and specify that directory as the asset\. +Java `.jar` files are ZIP files with a different extension\. These will be uploaded as\-is to Amazon S3, but when they are deployed as a Lambda function, the files they contain will be extracted, which probably isn't what you want\. To avoid this, place the `.jar` file in a directory and specify that directory as the asset\. #### Deploy\-time attributes example From 4031a9ca680e22fdfda6f709afb8c3b80552ade5 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 19:48:03 +0000 Subject: [PATCH 533/655] autogeneration churn --- v1/cli.md | 26 +++++++++++++------------- v1/manage-dependencies.md | 10 +++++----- v1/tagging.md | 2 +- v1/use_cfn_template.md | 2 +- v2/cli.md | 26 +++++++++++++------------- v2/getting_started.md | 2 +- v2/manage-dependencies.md | 10 +++++----- v2/tagging.md | 2 +- v2/use_cfn_template.md | 2 +- 9 files changed, 41 insertions(+), 41 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index c81fb200..bc0e6ac0 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -349,7 +349,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -368,7 +368,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -376,7 +376,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -444,7 +444,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -466,7 +466,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -723,7 +723,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -736,7 +736,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -757,7 +757,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -837,7 +837,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -915,7 +915,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -934,7 +934,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -960,7 +960,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -982,7 +982,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/manage-dependencies.md b/v1/manage-dependencies.md index 1fbf83bd..757723d1 100644 --- a/v1/manage-dependencies.md +++ b/v1/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -72,7 +72,7 @@ All AWS CDK dependencies must have the same version\. Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -99,7 +99,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -145,7 +145,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -169,7 +169,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v1/tagging.md b/v1/tagging.md index 82d064dc..0ebe951c 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index 974c5f1a..4273e248 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/cli.md b/v2/cli.md index 0da8966d..9469c52b 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -341,7 +341,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -360,7 +360,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -368,7 +368,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -436,7 +436,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -458,7 +458,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -715,7 +715,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -728,7 +728,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -749,7 +749,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -829,7 +829,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -907,7 +907,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -926,7 +926,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -952,7 +952,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -974,7 +974,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/getting_started.md b/v2/getting_started.md index 49786bdb..05c803bd 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -34,7 +34,7 @@ The actual package name of the main CDK package varies by language\. | Install | `npm install aws-cdk-lib` | | --- |--- | -| Import | `const cdk = require('aws-cdk-lib');` | +| Import | `import 'aws-cdk-lib' as cdk;` | | --- |--- | ------ diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index 0ad643e7..a35d9c53 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -71,7 +71,7 @@ Specify exact versions for alpha construct library modules, which have APIs that Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -101,7 +101,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -147,7 +147,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -167,7 +167,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v2/tagging.md b/v2/tagging.md index 9c9b942a..d6c8dece 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 360db5f8..1df7fdf8 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 719d811a1455a6338c4996b207bd30494b3251ee Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 20:19:19 +0000 Subject: [PATCH 534/655] promote pre-deployment testing to its own section --- v2/migrating-v2.md | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 570714c8..dc237f74 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -314,6 +314,23 @@ using Amazon.CDK.Codestar.Alpha; // for experimental constructs ------ +## Testing your migrated app before deploying + +Before deploying your stacks, use `cdk diff` to check for unexpected changes to the resources\. Changes to logical IDs \(causing replacement of resources\) are **not** expected\. + +Expected changes include but are not limited to: ++ Changes to the `CDKMetadata` resource ++ Updated asset hashes ++ Changes related to the new\-style stack synthesis, if your app used the legacy stack synthesizer in v1 \(CDK v2 does not support the legacy stack synthesizer\) ++ The addition of a `CheckBootstrapVersion` rule + +Unexpected changes are typically not caused by upgrading to AWS CDK v2 in itself, but are usually the result of deprecated behavior that was previously changed by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, removing feature flags, revising your code as necessary, deploying, and then upgrading to v2\. + +**Note** +If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. + +When you are ready to deploy the stacks in your app, consider deploying a copy first so you can test it\. The easiest way to do this is to deploy it into a different region\. However, you can also simply change the IDs of your stack\(s\)\. After testing, be sure to destroy the testing copy with cdk destroy\. + ## Troubleshooting **Typescript `'from' expected` or `';' expected` error in imports** @@ -329,17 +346,4 @@ If you see an error like this one: MyStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) ``` -AWS CDK v2 requires a new bootstrap stack, so you must re\-bootstrap your deployment environment\(s\)\. See [Bootstrapping](bootstrapping.md) for complete details\. - -**Unexpected infrastructure changes** -Before deploying your app, use `cdk diff` to check for unexpected changes to its resources\. Changes to logical IDs \(causing replacement of resources\) are **not** expected\. - -Expected changes include but are not limited to: -+ Changes to the `CDKMetadata` resource -+ Updated asset hashes -+ Changes related to the new\-style stack synthesis, if your app used the legacy stack synthesizer in v1 \(CDK v2 does not support the legacy stack synthesizer\) -+ The addition of a `CheckBootstrapVersion` rule - -Unexpected changes are typically not caused by upgrading to AWS CDK v2 in itself, but are usually the result of deprecated behavior that was previously changed by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, removing feature flags, revising your code as necessary, deploying, and then upgrading to v2\. - -If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. \ No newline at end of file +AWS CDK v2 requires a new bootstrap stack, so you must re\-bootstrap your deployment environment\(s\)\. See [Bootstrapping](bootstrapping.md) for complete details\. \ No newline at end of file From f439e5a372d68ba9debf3f643076b845a5316644 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 22:34:31 +0000 Subject: [PATCH 535/655] update document history --- v1/doc-history.md | 3 +++ v2/doc-history.md | 3 +++ 2 files changed, 6 insertions(+) diff --git a/v1/doc-history.md b/v1/doc-history.md index de724922..769a4d45 100644 --- a/v1/doc-history.md +++ b/v1/doc-history.md @@ -7,6 +7,9 @@ The table below represents significant documentation milestones\. We fix errors | Change | Description | Date | | --- |--- |--- | +| [Document `cdk.json`](#doc-history) | Add documentation of `cdk.json` configuration values\. | April 20, 2022 | +| [Dependency management](#doc-history) | Add topic on managing dependencies with the AWS CDK\. | April 7, 2022 | +| [Remove double\-braces from Java examples](#doc-history) | Replace this anti\-pattern throughout with Java 9 `Map.of` throughout\. | March 9, 2022 | | [AWS CDK v2 release](#doc-history) | Improvements to CDK v1 Developer Guide to coincide with the release of CDK v2 and its documentation\. | December 4, 2021 | | [`cdk watch`](#doc-history) | Add description of `cdk watch` command for incremental deployments\. | November 19, 2021 | | [Testing with `assertions`](#doc-history) | Revise testing topic to use new `assertions` library\. | November 17, 2021 | diff --git a/v2/doc-history.md b/v2/doc-history.md index bc4d93ce..99a82b81 100644 --- a/v2/doc-history.md +++ b/v2/doc-history.md @@ -7,4 +7,7 @@ The table below represents significant documentation milestones\. We fix errors | Change | Description | Date | | --- |--- |--- | +| [Document `cdk.json`](#doc-history) | Add documentation of `cdk.json` configuration values\. | April 20, 2022 | +| [Dependency management](#doc-history) | Add topic on managing dependencies with the AWS CDK\. | April 7, 2022 | +| [Remove double\-braces from Java examples](#doc-history) | Replace this anti\-pattern throughout with Java 9 `Map.of` throughout\. | March 9, 2022 | | [AWS CDK v2 release](#doc-history) | Version 2 of the AWS CDK Developer Guide is released\. [Document history](../../v1/guide/doc-history.html) for CDK v1\. | December 4, 2021 | \ No newline at end of file From e3294c1087a94b3e1fd9e4613ed590e1bade1742 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 22:35:33 +0000 Subject: [PATCH 536/655] add bootstrapping templates v11 and v12 --- v1/bootstrapping.md | 4 +++- v2/bootstrapping.md | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/v1/bootstrapping.md b/v1/bootstrapping.md index 3a1f5bc4..4c3eb6ea 100644 --- a/v1/bootstrapping.md +++ b/v1/bootstrapping.md @@ -649,4 +649,6 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | | 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | | 9 | 1\.135\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | -| 10 | 1\.139\.0 | ECR ScanOnPush is now enabled by default\. | \ No newline at end of file +| 10 | 1\.139\.0 | ECR ScanOnPush is now enabled by default\. | +| 11 | 1\.150\.0 | Adds policy allowing Lambda to pull from Amazon ECR repos so it survives rebootstrapping\. | +| 12 | 1\.152\.0 | Adds support for experimental cdk import\. | \ No newline at end of file diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index ed37b426..c42803f8 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -577,4 +577,6 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | | 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | | 9 | 2\.1\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | -| 10 | 2\.4\.0 | ECR ScanOnPush is now enabled by default\. | \ No newline at end of file +| 10 | 2\.4\.0 | ECR ScanOnPush is now enabled by default\. | +| 11 | 2\.18\.0 | Adds policy allowing Lambda to pull from Amazon ECR repos so it survives rebootstrapping\. | +| 12 | 2\.20\.0 | Adds support for experimental cdk import\. | \ No newline at end of file From e7268db2a5f7c63de332967b71e429b33671951d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 29 Apr 2022 22:36:04 +0000 Subject: [PATCH 537/655] remove spurious account/region specification --- v1/cdk_pipeline.md | 12 ++++-------- v2/cdk_pipeline.md | 12 ++++-------- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/v1/cdk_pipeline.md b/v1/cdk_pipeline.md index f5f426cf..466a158d 100644 --- a/v1/cdk_pipeline.md +++ b/v1/cdk_pipeline.md @@ -30,8 +30,7 @@ You may omit the \-\-profile option if your default AWS profile contains the nec ``` export CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ - --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ - aws://ACCOUNT-NUMBER/REGION + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ``` ------ @@ -40,8 +39,7 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ ``` set CDK_NEW_BOOTSTRAP=1 cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ - --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ - aws://ACCOUNT-NUMBER/REGION + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ``` ------ @@ -57,8 +55,7 @@ Again, you may omit the \-\-profile option if your default AWS profile contains export CDK_NEW_BOOTSTRAP=1 cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ - --trust PIPELINE-ACCOUNT-NUMBER \ - aws://ACCOUNT-NUMBER/REGION + --trust PIPELINE-ACCOUNT-NUMBER ``` ------ @@ -68,8 +65,7 @@ cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ set CDK_NEW_BOOTSTRAP=1 cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ - --trust PIPELINE-ACCOUNT-NUMBER ^ - aws://ACCOUNT-NUMBER/REGION + --trust PIPELINE-ACCOUNT-NUMBER ``` ------ diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index 5493f8a5..8ab55f93 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -30,8 +30,7 @@ You may omit the \-\-profile option if your default AWS profile contains the nec ``` export CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ - --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ - aws://ACCOUNT-NUMBER/REGION + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ``` ------ @@ -40,8 +39,7 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ ``` set CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ - --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ - aws://ACCOUNT-NUMBER/REGION + --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ``` ------ @@ -57,8 +55,7 @@ Again, you may omit the \-\-profile option if your default AWS profile contains export CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ - --trust PIPELINE-ACCOUNT-NUMBER \ - aws://ACCOUNT-NUMBER/REGION + --trust PIPELINE-ACCOUNT-NUMBER ``` ------ @@ -68,8 +65,7 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ set CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ - --trust PIPELINE-ACCOUNT-NUMBER ^ - aws://ACCOUNT-NUMBER/REGION + --trust PIPELINE-ACCOUNT-NUMBER ``` ------ From 0aaa559bd813de5cec0c42e712bbf075c3bfa8eb Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 3 May 2022 19:36:22 +0000 Subject: [PATCH 538/655] remove extraneous "throughout" --- v1/doc-history.md | 2 +- v2/doc-history.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/doc-history.md b/v1/doc-history.md index 769a4d45..35f54e6e 100644 --- a/v1/doc-history.md +++ b/v1/doc-history.md @@ -9,7 +9,7 @@ The table below represents significant documentation milestones\. We fix errors | --- |--- |--- | | [Document `cdk.json`](#doc-history) | Add documentation of `cdk.json` configuration values\. | April 20, 2022 | | [Dependency management](#doc-history) | Add topic on managing dependencies with the AWS CDK\. | April 7, 2022 | -| [Remove double\-braces from Java examples](#doc-history) | Replace this anti\-pattern throughout with Java 9 `Map.of` throughout\. | March 9, 2022 | +| [Remove double\-braces from Java examples](#doc-history) | Replace this anti\-pattern with Java 9 `Map.of` throughout\. | March 9, 2022 | | [AWS CDK v2 release](#doc-history) | Improvements to CDK v1 Developer Guide to coincide with the release of CDK v2 and its documentation\. | December 4, 2021 | | [`cdk watch`](#doc-history) | Add description of `cdk watch` command for incremental deployments\. | November 19, 2021 | | [Testing with `assertions`](#doc-history) | Revise testing topic to use new `assertions` library\. | November 17, 2021 | diff --git a/v2/doc-history.md b/v2/doc-history.md index 99a82b81..58aba4d6 100644 --- a/v2/doc-history.md +++ b/v2/doc-history.md @@ -9,5 +9,5 @@ The table below represents significant documentation milestones\. We fix errors | --- |--- |--- | | [Document `cdk.json`](#doc-history) | Add documentation of `cdk.json` configuration values\. | April 20, 2022 | | [Dependency management](#doc-history) | Add topic on managing dependencies with the AWS CDK\. | April 7, 2022 | -| [Remove double\-braces from Java examples](#doc-history) | Replace this anti\-pattern throughout with Java 9 `Map.of` throughout\. | March 9, 2022 | +| [Remove double\-braces from Java examples](#doc-history) | Replace this anti\-pattern with Java 9 `Map.of` throughout\. | March 9, 2022 | | [AWS CDK v2 release](#doc-history) | Version 2 of the AWS CDK Developer Guide is released\. [Document history](../../v1/guide/doc-history.html) for CDK v1\. | December 4, 2021 | \ No newline at end of file From 43f112ed0241af8440ea31f511e0b39f6008a6b1 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 3 May 2022 21:13:30 +0000 Subject: [PATCH 539/655] clarify --cloudformation-execution-policies --- v1/bootstrapping.md | 8 ++++---- v2/bootstrapping.md | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/v1/bootstrapping.md b/v1/bootstrapping.md index 4c3eb6ea..738bfd8a 100644 --- a/v1/bootstrapping.md +++ b/v1/bootstrapping.md @@ -172,15 +172,15 @@ The following command\-line options, when used with CDK Toolkit's cdk bootstrap, + \-\-termination\-protection prevents the bootstrap stack from being deleted \(see [Protecting a stack from being deleted](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html) in the AWS CloudFormation User Guide\) The following additional switches are available only with the modern bootstrapping template\. -+ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. -**Tip** -The policies must be passed as a single string argument, with the policy ARNs separated by commas, like this: ++ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. By default, stacks are deployed with full administrator privileges using the `AdministratorAccess` policy\. + + The policy ARNs must be passed as a single string argument, with the individual ARNs separated by commas\. For example: ``` --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess". ``` **Important** -At least one policy should be specified; otherwise, AWS CloudFormation will deploy using full administrator permissions from the `AdministratorAccess` policy\. +To avoid deployment failures, be sure the policies you specify are sufficient for any deployments you will perform in the environment being bootstrapped\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. + \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index c42803f8..66504ca7 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -128,15 +128,15 @@ There are two ways to customize the bootstrapping resources\. The following command\-line options, when used with CDK Toolkit's cdk bootstrap, provide commonly\-needed adjustments to the bootstrapping template\. + \-\-bootstrap\-bucket\-name overrides the name of the Amazon S3 bucket\. May require changes to your CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + \-\-bootstrap\-kms\-key\-id overrides the AWS KMS key used to encrypt the S3 bucket\. -+ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. At least one policy is required; otherwise, AWS CloudFormation will attempt to deploy without permissions and deployments will fail\. -**Tip** -The policies must be passed as a single string argument, with the policy ARNs separated by commas, like this: ++ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. By default, stacks are deployed with full administrator privileges using the `AdministratorAccess` policy\. + + The policy ARNs must be passed as a single string argument, with the individual ARNs separated by commas\. For example: ``` --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess". ``` **Important** -At least one policy should be specified; otherwise, AWS CloudFormation will deploy using full administrator permissions from the `AdministratorAccess` policy\. +To avoid deployment failures, be sure the policies you specify are sufficient for any deployments you will perform in the environment being bootstrapped\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. From 643449709dba3c1a4627a3d66abedc9464efcde9 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 5 May 2022 15:21:48 +0000 Subject: [PATCH 540/655] add guidance about values passed using --context flag, which are always strings --- v1/context.md | 2 ++ v2/context.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/v1/context.md b/v1/context.md index 5cab3848..94e303ac 100644 --- a/v1/context.md +++ b/v1/context.md @@ -118,6 +118,8 @@ cdk synth --context key1=value1 --context key2=value2 MyStack When synthesizing multiple stacks, the specified context values are passed to all stacks\. To provide different context values to individual stacks, either use different keys for the values, or use multiple cdk synth or cdk deploy commands\. +Context values passed from the command line are always strings\. If a value is usually of some other type, your code must be prepared to convert or parse the value\. To allow non\-string context values provided in other ways \(for example, in `cdk.context.json`\) to work as expected, make sure the value is a string before converting it\. + ## Example Below is an example of importing an existing Amazon VPC using AWS CDK context\. diff --git a/v2/context.md b/v2/context.md index 93c41ab2..1dff902d 100644 --- a/v2/context.md +++ b/v2/context.md @@ -118,6 +118,8 @@ cdk synth --context key1=value1 --context key2=value2 MyStack When synthesizing multiple stacks, the specified context values are passed to all stacks\. To provide different context values to individual stacks, either use different keys for the values, or use multiple cdk synth or cdk deploy commands\. +Context values passed from the command line are always strings\. If a value is usually of some other type, your code must be prepared to convert or parse the value\. To allow non\-string context values provided in other ways \(for example, in `cdk.context.json`\) to work as expected, make sure the value is a string before converting it\. + ## Example Below is an example of importing an existing Amazon VPC using AWS CDK context\. From 551f4ef95988e564e347c5929eba20b917f0a81b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 10 May 2022 15:37:01 +0000 Subject: [PATCH 541/655] change list to array --- v1/cfn_layer.md | 2 +- v2/cfn_layer.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/cfn_layer.md b/v1/cfn_layer.md index a57b63fe..1e0a9602 100644 --- a/v1/cfn_layer.md +++ b/v1/cfn_layer.md @@ -158,7 +158,7 @@ new CfnResource(this, "MyBucket", new CfnResourceProps Type = "AWS::S3::Bucket", Properties = new Dictionary { // Note the PascalCase here! These are CloudFormation identifiers - ["AnalyticsConfigurations"] = new List> + ["AnalyticsConfigurations"] = new Dictionary[] { new Dictionary { ["Id"] = "Config" diff --git a/v2/cfn_layer.md b/v2/cfn_layer.md index 34b897b9..9501075d 100644 --- a/v2/cfn_layer.md +++ b/v2/cfn_layer.md @@ -158,7 +158,7 @@ new CfnResource(this, "MyBucket", new CfnResourceProps Type = "AWS::S3::Bucket", Properties = new Dictionary { // Note the PascalCase here! These are CloudFormation identifiers - ["AnalyticsConfigurations"] = new List> + ["AnalyticsConfigurations"] = new Dictionary[] { new Dictionary { ["Id"] = "Config" From 3aa31bcc7a2bb02ae11997d9d3060dae17b54389 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 10 May 2022 17:23:43 +0000 Subject: [PATCH 542/655] add missing "s" to construct library name --- v2/migrating-v2.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index dc237f74..f512f519 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -18,7 +18,7 @@ The main changes from AWS CDK v1 to CDK v2 are as follows\. For example, if we add a new method `grantPower()` to a construct, it initially appears as `grantPowerBeta1().` If breaking changes are needed \(for example, a new required parameter or property\), the next version of the method would be named `grantPowerBeta2()`, and so on\. When work is complete and the API is finalized, the method `grantPower()` \(with no suffix\) is added, and the BetaN methods are deprecated\. All the beta APIs remain in the Construct Library until the next major version \(3\.0\) release, and their signatures will not change\. You'll see deprecation warnings if you use them, so you should move to the final version of the API at your earliest convenience, but a future AWS CDK 2\.x release will not break your application\. -+ The `Construct` class has been extracted from the AWS CDK into a separate library, along with related types, to support efforts to apply the Construct Programming Model to other domains\. If you are writing your own constructs or using related APIs, you must declare the `construct` module as a dependency and make minor changes to your imports\. If you are using advanced features, such as hooking into the CDK app lifecycle, more changes may be needed\. [See the RFC](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0192-remove-constructs-compat.md#release-notes) for full details\. ++ The `Construct` class has been extracted from the AWS CDK into a separate library, along with related types, to support efforts to apply the Construct Programming Model to other domains\. If you are writing your own constructs or using related APIs, you must declare the `constructs` module as a dependency and make minor changes to your imports\. If you are using advanced features, such as hooking into the CDK app lifecycle, more changes may be needed\. [See the RFC](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0192-remove-constructs-compat.md#release-notes) for full details\. + Deprecated properties, methods, and types in AWS CDK v1\.x and its Construct Library have been removed completely from the CDK v2 API\. In most supported languages, these APIs produce warnings under v1\.x, so you may have already migrated to the replacement APIs\. A complete [list of deprecated APIs](https://github.com/aws/aws-cdk/blob/master/DEPRECATED_APIs.md) in CDK v1\.x is available on GitHub\. + Behavior that was gated by feature flags in AWS CDK v1\.x is enabled by default in CDK v2, and the old feature flags are no longer needed or, in most cases, supported\. A handful are still available to let you to revert to CDK v1 behavior in very specific circumstances; see [Updating feature flags](#migrating-v2-v1-upgrade-cdk-json)\. + CDK v2 requires that the environments you deploy into be boostrapped using the modern bootstrap stack; the legacy bootstrap stack \(the default under v1\) is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. Simply re\-bootstrap your existing environments to upgrade them\. It is no longer necessary to set any feature flags or environment variables to specify the modern bootstrap stack\. From b1af72647822984ab111f69547ed4635100a9dfa Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 10 May 2022 17:39:15 +0000 Subject: [PATCH 543/655] remove spurious new from Java example --- v1/cdk_pipeline.md | 2 +- v2/cdk_pipeline.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/cdk_pipeline.md b/v1/cdk_pipeline.md index 466a158d..cfde18e1 100644 --- a/v1/cdk_pipeline.md +++ b/v1/cdk_pipeline.md @@ -411,7 +411,7 @@ public class MyPipelineApp { App app = new App(); new MyPipelineStack(app, "PipelineStack", StackProps.builder() - .env(new Environment.builder() + .env(Environment.builder() .account("111111111111") .region("eu-west-1") .build()) diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index 8ab55f93..376eedc3 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -328,7 +328,7 @@ public class MyPipelineApp { App app = new App(); new MyPipelineStack(app, "PipelineStack", StackProps.builder() - .env(new Environment.builder() + .env(Environment.builder() .account("111111111111") .region("eu-west-1") .build()) From 7839ef57f2197c574c508ddae089b11226f571bc Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 10 May 2022 17:39:29 +0000 Subject: [PATCH 544/655] add info about skipping synthesis using --app cdk.out --- v1/cli.md | 16 +++++++++++++--- v2/cli.md | 16 +++++++++++++--- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index bc0e6ac0..6bbff26e 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -221,6 +221,8 @@ If you are in some other directory, or if you want to run your app via a command cdk --app "npx ts-node bin/hello-cdk.ts" ls ``` +When deploying, you may also specify a directory containing synthesized cloud assemblies, such as `cdk.out`, as the value of \-\-app\. The specified stacks are deployed from this directory; the app is not synthesized\. + ## Specifying stacks Many CDK Toolkit commands \(for example, `cdk deploy`\) work on stacks defined in your app\. If your app contains only one stack, the CDK Toolkit assumes you mean that one if you don't specify a stack explicitly\. @@ -398,7 +400,15 @@ cdk deploy "*" # all stacks in app **Note** The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates before deploying anything\. Therefore, most command line options you can use with `cdk synth` \(for example, `--context`\) can also be used with `cdk deploy`\. -See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. +See `cdk deploy --help` for all available options\. A few of the most useful options are covered below\. + +### Skipping synthesis + +The cdk deploy command normally synthesizes your app's stacks before deploying to make sure the deployment reflects the latest version of your app\. If you know that you haven't made any changes to your code since your last cdk synth, you may suppress the redundant synthesis step when deploying\. Simply specify your project's `cdk.out` directory in the \-\-app option\. + +``` +cdk deploy --app cdk.out StackOne StackTwo +``` ### Disabling rollback @@ -444,7 +454,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -466,7 +476,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. diff --git a/v2/cli.md b/v2/cli.md index 9469c52b..b2e1d503 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -215,6 +215,8 @@ If you are in some other directory, or if you want to run your app via a command cdk --app "npx ts-node bin/hello-cdk.ts" ls ``` +When deploying, you may also specify a directory containing synthesized cloud assemblies, such as `cdk.out`, as the value of \-\-app\. The specified stacks are deployed from this directory; the app is not synthesized\. + ## Specifying stacks Many CDK Toolkit commands \(for example, `cdk deploy`\) work on stacks defined in your app\. If your app contains only one stack, the CDK Toolkit assumes you mean that one if you don't specify a stack explicitly\. @@ -390,7 +392,15 @@ cdk deploy "*" # all stacks in app **Note** The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates before deploying anything\. Therefore, most command line options you can use with `cdk synth` \(for example, `--context`\) can also be used with `cdk deploy`\. -See `cdk deploy --help` for all available options\. A few of the most\-frequently\-used options are covered below\. +See `cdk deploy --help` for all available options\. A few of the most useful options are covered below\. + +### Skipping synthesis + +The cdk deploy command normally synthesizes your app's stacks before deploying to make sure the deployment reflects the latest version of your app\. If you know that you haven't made any changes to your code since your last cdk synth, you may suppress the redundant synthesis step when deploying\. Simply specify your project's `cdk.out` directory in the \-\-app option\. + +``` +cdk deploy --app cdk.out StackOne StackTwo +``` ### Disabling rollback @@ -436,7 +446,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -458,7 +468,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. From d87a052a723038b87737cbe925bc147b29a2e3cb Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 10 May 2022 22:10:05 +0000 Subject: [PATCH 545/655] improve context context --- v1/context.md | 34 ++++++++++++++++++++++------------ v2/context.md | 34 ++++++++++++++++++++++------------ 2 files changed, 44 insertions(+), 24 deletions(-) diff --git a/v1/context.md b/v1/context.md index 94e303ac..24ba7dd8 100644 --- a/v1/context.md +++ b/v1/context.md @@ -1,12 +1,21 @@ # Runtime context -Context values are key\-value pairs that can be associated with an app, stack, or construct\. The AWS CDK uses context to cache information from your AWS account, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs used to start your instances\. [Feature flags](featureflags.md) are also context values\. You can create your own context values for use by your apps or constructs\. +Context values are key\-value pairs that can be associated with an app, stack, or construct\. They may be supplied to your app from a file \(usually either `cdk.json` or `cdk.context.json` in your project directory\) or on the command line\. -Context keys are strings, and values may be any type supported by JSON: numbers, strings, arrays, or objects\. +The CDK Toolkit uses context to cache values retrieved from your AWS account during synthesis, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs currently available for Amazon EC2 instances\. Because these values are provided by your AWS account, they can change between runs of your CDK application, which makes them a potential source of unintended change\. The CDK Toolkit's caching behavior "freezes" these values for your CDK app until you decide to accept the new values\. -If your constructs create their own context values, incorporate your library's package name in its keys so they won't conflict with other package's context values\. +Without context caching, if you had specified "latest Amazon Linux" as the AMI for your Amazon EC2 instances, and a new version of this AMI were released, then the next time you deployed your CDK stack, your already\-deployed instances would be using the outdated \("wrong"\) AMI and would therefore need to be upgraded\. Upgrading would result in replacing all your existing instances with new ones, which would probably be unexpected and undesired\. -Since most context values are associated with a particular AWS environment, and a given CDK app can be deployed in more than one environment, it is important to be able to set context values for each environment\. This is achieved by including the AWS account and region in the context key, so that values from different environments do not conflict\. +Instead, the CDK records your account's available AMIs in your project's `cdk.context.json` file, and uses the stored value for future synthesis operations\. This way, the list of AMIs is no longer a potential source of change, and you can be sure that your stacks will always synthesize to the same AWS CloudFormation templates\. + +Not all context values are cached values from your AWS environment\. [Feature flags](featureflags.md) are also context values\. You can also create your own context values for use by your apps or constructs\. + +Context keys are strings\. Values may be any type supported by JSON: numbers, strings, arrays, or objects\. + +**Tip** +If your constructs create their own context values, incorporate your library's package name in its keys so they won't conflict with other packages' context values\. + +Many context values are associated with a particular AWS environment, and a given CDK app can be deployed in more than one environment\. The key for such values includes the AWS account and region so that values from different environments do not conflict\. The context key below illustrates the format used by the AWS CDK, including the account and region\. @@ -15,9 +24,9 @@ availability-zones:account=123456789012:region=eu-central-1 ``` **Important** -Context values are managed by the AWS CDK and its constructs, including constructs you may write\. In general, you should not add or change context values by manually editing files\. It can be useful to review `cdk.context.json` to see what values are being cached\. +Cached context values are managed by the AWS CDK and its constructs, including constructs you may write\. Do not add or change cached context values by manually editing files\. It can be useful, however, to review `cdk.context.json` occasionally to see what values are being cached\. Context values that do not represent cached values should be stored under the `context` key of `cdk.json` so they won't be cleared when cached values are cleared\. -## Construct context +## Sources of context values Context values can be provided to your AWS CDK app in six different ways: + Automatically from the current AWS account\. @@ -27,17 +36,18 @@ Context values can be provided to your AWS CDK app in six different ways: + In the `context` key of your `~/.cdk.json` file\. + In your AWS CDK app using the `construct.node.setContext()` method\. -The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, changing your Auto Scaling group\. The AWS CDK does not write context data to any of the other files listed\. +The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Availability Zone is introduced\. The AWS CDK does not write context data to any of the other files listed\. -We recommend that `cdk.context.json` be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. It is also critical to successful automated deployment of stacks that rely on context values \(for example, using [CDK Pipelines](cdk_pipeline.md)\)\. +**Important** +Because they are part of your application's state, `cdk.json` and `cdk.context.json` must be committed to source control along with the rest of your app's source code\. Otherwise, deployments in other environments \(for example, a CI pipeline\) may produce inconsistent results\. -Context values are scoped to the construct that created them; they are visible to child constructs, but not to siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), whether automatically, from a file, or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in the app\. +Context values are scoped to the construct that created them; they are visible to child constructs, but not to parents or siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), whether automatically, from a file, or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in every stack in the app\. -You can get a context value using the `construct.node.tryGetContext` method\. If the requested entry is not found on the current construct or any of its parents, the result is `undefined` \(or your language's equivalent, such as `None` in Python\)\. +Your app can read a context value using the `construct.node.tryGetContext` method\. If the requested entry is not found on the current construct or any of its parents, the result is `undefined` \(or your language's equivalent, such as `None` in Python\)\. ## Context methods -The AWS CDK supports several context methods that enable AWS CDK apps to get contextual information\. For example, you can get a list of Availability Zones that are available in a given AWS account and region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html#availabilityzones) method\. +The AWS CDK supports several context methods that enable AWS CDK apps to obtain contextual information from the AWS environment\. For example, you can get a list of Availability Zones that are available in a given AWS account and region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html#availabilityzones) method\. The following are the context methods: @@ -56,7 +66,7 @@ Gets the existing Amazon Virtual Private Clouds in your accounts\. [LookupMachineImage](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.LookupMachineImage.html) Looks up a machine image for use with a NAT instance in an Amazon Virtual Private Cloud\. -If a required context value isn't available, the AWS CDK app notifies the AWS CDK CLI that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. +If a required context value isn't available, the AWS CDK app notifies the CDK Toolkit that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. ## Viewing and managing context diff --git a/v2/context.md b/v2/context.md index 1dff902d..b504a0f1 100644 --- a/v2/context.md +++ b/v2/context.md @@ -1,12 +1,21 @@ # Runtime context -Context values are key\-value pairs that can be associated with an app, stack, or construct\. The AWS CDK uses context to cache information from your AWS account, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs used to start your instances\. [Feature flags](featureflags.md) are also context values\. You can create your own context values for use by your apps or constructs\. +Context values are key\-value pairs that can be associated with an app, stack, or construct\. They may be supplied to your app from a file \(usually either `cdk.json` or `cdk.context.json` in your project directory\) or on the command line\. -Context keys are strings, and values may be any type supported by JSON: numbers, strings, arrays, or objects\. +The CDK Toolkit uses context to cache values retrieved from your AWS account during synthesis, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs currently available for Amazon EC2 instances\. Because these values are provided by your AWS account, they can change between runs of your CDK application, which makes them a potential source of unintended change\. The CDK Toolkit's caching behavior "freezes" these values for your CDK app until you decide to accept the new values\. -If your constructs create their own context values, incorporate your library's package name in its keys so they won't conflict with other package's context values\. +Without context caching, if you had specified "latest Amazon Linux" as the AMI for your Amazon EC2 instances, and a new version of this AMI were released, then the next time you deployed your CDK stack, your already\-deployed instances would be using the outdated \("wrong"\) AMI and would therefore need to be upgraded\. Upgrading would result in replacing all your existing instances with new ones, which would probably be unexpected and undesired\. -Since most context values are associated with a particular AWS environment, and a given CDK app can be deployed in more than one environment, it is important to be able to set context values for each environment\. This is achieved by including the AWS account and region in the context key, so that values from different environments do not conflict\. +Instead, the CDK records your account's available AMIs in your project's `cdk.context.json` file, and uses the stored value for future synthesis operations\. This way, the list of AMIs is no longer a potential source of change, and you can be sure that your stacks will always synthesize to the same AWS CloudFormation templates\. + +Not all context values are cached values from your AWS environment\. [Feature flags](featureflags.md) are also context values\. You can also create your own context values for use by your apps or constructs\. + +Context keys are strings\. Values may be any type supported by JSON: numbers, strings, arrays, or objects\. + +**Tip** +If your constructs create their own context values, incorporate your library's package name in its keys so they won't conflict with other packages' context values\. + +Many context values are associated with a particular AWS environment, and a given CDK app can be deployed in more than one environment\. The key for such values includes the AWS account and region so that values from different environments do not conflict\. The context key below illustrates the format used by the AWS CDK, including the account and region\. @@ -15,9 +24,9 @@ availability-zones:account=123456789012:region=eu-central-1 ``` **Important** -Context values are managed by the AWS CDK and its constructs, including constructs you may write\. In general, you should not add or change context values by manually editing files\. It can be useful to review `cdk.context.json` to see what values are being cached\. +Cached context values are managed by the AWS CDK and its constructs, including constructs you may write\. Do not add or change cached context values by manually editing files\. It can be useful, however, to review `cdk.context.json` occasionally to see what values are being cached\. Context values that do not represent cached values should be stored under the `context` key of `cdk.json` so they won't be cleared when cached values are cleared\. -## Construct context +## Sources of context values Context values can be provided to your AWS CDK app in six different ways: + Automatically from the current AWS account\. @@ -27,17 +36,18 @@ Context values can be provided to your AWS CDK app in six different ways: + In the `context` key of your `~/.cdk.json` file\. + In your AWS CDK app using the `construct.node.setContext()` method\. -The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Amazon Linux AMI is released, changing your Auto Scaling group\. The AWS CDK does not write context data to any of the other files listed\. +The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Availability Zone is introduced\. The AWS CDK does not write context data to any of the other files listed\. -We recommend that `cdk.context.json` be placed under version control along with the rest of your application, as the information in them is part of your app's state and is critical to being able to synthesize and deploy consistently\. It is also critical to successful automated deployment of stacks that rely on context values \(for example, using [CDK Pipelines](cdk_pipeline.md)\)\. +**Important** +Because they are part of your application's state, `cdk.json` and `cdk.context.json` must be committed to source control along with the rest of your app's source code\. Otherwise, deployments in other environments \(for example, a CI pipeline\) may produce inconsistent results\. -Context values are scoped to the construct that created them; they are visible to child constructs, but not to siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), whether automatically, from a file, or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in the app\. +Context values are scoped to the construct that created them; they are visible to child constructs, but not to parents or siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), whether automatically, from a file, or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in every stack in the app\. -You can get a context value using the `construct.node.tryGetContext` method\. If the requested entry is not found on the current construct or any of its parents, the result is `undefined` \(or your language's equivalent, such as `None` in Python\)\. +Your app can read a context value using the `construct.node.tryGetContext` method\. If the requested entry is not found on the current construct or any of its parents, the result is `undefined` \(or your language's equivalent, such as `None` in Python\)\. ## Context methods -The AWS CDK supports several context methods that enable AWS CDK apps to get contextual information\. For example, you can get a list of Availability Zones that are available in a given AWS account and region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones) method\. +The AWS CDK supports several context methods that enable AWS CDK apps to obtain contextual information from the AWS environment\. For example, you can get a list of Availability Zones that are available in a given AWS account and region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones) method\. The following are the context methods: @@ -56,7 +66,7 @@ Gets the existing Amazon Virtual Private Clouds in your accounts\. [LookupMachineImage](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.LookupMachineImage.html) Looks up a machine image for use with a NAT instance in an Amazon Virtual Private Cloud\. -If a required context value isn't available, the AWS CDK app notifies the AWS CDK CLI that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. +If a required context value isn't available, the AWS CDK app notifies the CDK Toolkit that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. ## Viewing and managing context From defaf828066def845732d502ee5f3dc8a51d96f2 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 10 May 2022 22:32:23 +0000 Subject: [PATCH 546/655] avoid "import" language for references to external resources to avoid confusion with importing CFN templates --- v1/best-practices.md | 2 +- v1/constructs.md | 2 +- v1/context.md | 2 +- v1/permissions.md | 6 +++--- v1/resources.md | 8 ++++---- v2/best-practices.md | 2 +- v2/constructs.md | 2 +- v2/context.md | 2 +- v2/permissions.md | 6 +++--- v2/resources.md | 8 ++++---- v2/work-with.md | 6 +++--- 11 files changed, 23 insertions(+), 23 deletions(-) diff --git a/v1/best-practices.md b/v1/best-practices.md index e96964cc..717c4a1d 100644 --- a/v1/best-practices.md +++ b/v1/best-practices.md @@ -129,7 +129,7 @@ A better approach is to specify as few names as possible\. If you leave out reso If the place you need it is another AWS CDK stack, that's even easier\. Given one stack that defines the resource and another than needs to use it: + If the two stacks are in the same AWS CDK app, just pass a reference between the two stacks\. For example, save a reference to the resource's construct as an attribute of the defining stack \(`this.stack.uploadBucket = myBucket`\), then pass that attribute to the constructor of the stack that needs the resource\. -+ When the two stacks are in different AWS CDK apps, use a static `from` method to import an externally\-defined resource based on its ARN, name, or other attributes \(for example, `Table.fromArn()` for a DynamoDB table\)\. Use the `CfnOutput` construct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS console\. Or the second app can parse the CloudFormation template generated by the first app and retrieve that value from the Outputs section\. ++ When the two stacks are in different AWS CDK apps, use a static `from` method to use an externally\-defined resource based on its ARN, name, or other attributes \(for example, `Table.fromArn()` for a DynamoDB table\)\. Use the `CfnOutput` construct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS console\. Or the second app can parse the CloudFormation template generated by the first app and retrieve that value from the Outputs section\. ### Define removal policies and log retention diff --git a/v1/constructs.md b/v1/constructs.md index 3fbe9bb5..3b711866 100644 --- a/v1/constructs.md +++ b/v1/constructs.md @@ -635,7 +635,7 @@ For information about the most common API patterns in the AWS Construct Library, ## Writing your own constructs -In addition to using existing constructs like `s3.Bucket`, you can also write your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct imported from a third\-party library that someone published via NPM or Maven or PyPI—or to your company's internal package repository\. +In addition to using existing constructs like `s3.Bucket`, you can also write your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct from a third\-party library that someone published via NPM or Maven or PyPI—or to your company's internal package repository\. To declare a new construct, create a class that extends the [Construct](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html) base class, then follow the pattern for initializer arguments\. diff --git a/v1/context.md b/v1/context.md index 24ba7dd8..6ca690ff 100644 --- a/v1/context.md +++ b/v1/context.md @@ -132,7 +132,7 @@ Context values passed from the command line are always strings\. If a value is u ## Example -Below is an example of importing an existing Amazon VPC using AWS CDK context\. +Below is an example of referencing an existing Amazon VPC using AWS CDK context\. ------ #### [ TypeScript ] diff --git a/v1/permissions.md b/v1/permissions.md index b52fa972..863a766d 100644 --- a/v1/permissions.md +++ b/v1/permissions.md @@ -350,7 +350,7 @@ var project = new Project(this, "Project", new ProjectProps ------ -Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. This property is not available on imported resources, however, so such constructs have an `addToRolePolicy` \(Python: `add_to_role_policy`\) method that does nothing if the construct is an imported resource, and calls the `addToPolicy` \(Python: `add_to_policy`\) method of the `role` property otherwise, saving you the trouble of handling the undefined case explicitly\. The following example demonstrates: +Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. This property is not available on external resources, however, so such constructs have an `addToRolePolicy` \(Python: `add_to_role_policy`\) method that does nothing if the construct is a reference to an external resource, and calls the `addToPolicy` \(Python: `add_to_policy`\) method of the `role` property otherwise, saving you the trouble of handling the undefined case explicitly\. The following example demonstrates: ------ #### [ TypeScript ] @@ -496,11 +496,11 @@ If you have defined an IAM user, principal, group, or role outside your AWS CDK + For groups, call `[Group\.fromGroupArn\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Group.html#static-fromwbrgroupwbrarnscope-id-grouparn)` or `[Group\.fromGroupName\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Group.html#static-fromwbrgroupwbrnamescope-id-groupname)`\. + For roles, call `[Role\.fromRoleArn\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html#static-fromwbrrolewbrarnscope-id-rolearn-options)` or `[Role\.fromRoleName\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html#static-fromwbrrolewbrnamescope-id-rolename)`\. -Policies \(including managed policies\) can be imported in similar fashion using the methods listed below\. You can use references to these objects anywhere an IAM policy is required\. +Policies \(including managed policies\) can be referenced in similar fashion using the methods listed below\. You can use references to these objects anywhere an IAM policy is required\. + `[Policy\.fromPolicyName](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Policy.html#static-fromwbrpolicywbrnamescope-id-policyname)` + `[ManagedPolicy\.fromManagedPolicyArn](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ManagedPolicy.html#static-fromwbrmanagedwbrpolicywbrarnscope-id-managedpolicyarn)` + `[ManagedPolicy\.fromManagedPolicyName](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ManagedPolicy.html#static-fromwbrmanagedwbrpolicywbrnamescope-id-managedpolicyname)` + `[ManagedPolicy\.fromAwsManagedPolicyName](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ManagedPolicy.html#static-fromwbrawswbrmanagedwbrpolicywbrnamemanagedpolicyname)` **Note** -As with all references to external AWS resources, you cannot modify imported IAM objects in your CDK app\. \ No newline at end of file +As with all references to external AWS resources, you cannot modify IAM references returned by the above methods in your CDK app\. \ No newline at end of file diff --git a/v1/resources.md b/v1/resources.md index e6f9140a..1f878f15 100644 --- a/v1/resources.md +++ b/v1/resources.md @@ -575,9 +575,9 @@ Vpc.FromVpcAttributes(this, "MyVpc", new VpcAttributes ------ -Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables, it can be difficult to import those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. +Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables, it can be difficult to specify those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. -You must provide attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want to import the VPC marked as the default is sufficient\. +You must provide attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want the VPC marked as the default is sufficient\. ------ #### [ TypeScript ] @@ -673,7 +673,7 @@ Vpc.FromLookup(this, id = "PublicVpc", new VpcLookupOptions Results of `Vpc.fromLookup()` are cached in the project's `cdk.context.json` file\. Commit this file to version control if you will be deploying the stack in an environment that does not have access to the AWS account that defines the VPC, such as [CDK Pipelines](cdk_pipeline.md)\. -Although you can use an imported resource anywhere, you cannot modify the imported resource\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an imported `s3.Bucket` does nothing\. +Although you can use an external resource anywhere you'd use a similar resource defined in your AWS CDK app, you cannot modify it\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an external `s3.Bucket` does nothing\. ## Permission grants @@ -728,7 +728,7 @@ if (bucket.GrantReadWrite(func).Success) ------ -The grant methods return an `iam.Grant` object\. Use the `success` attribute of the `Grant` object to determine whether the grant was effectively applied \(for example, it may not have been applied on [imported resources](#resources_referencing)\)\. You can also use the `assertSuccess` \(Python: `assert_success`\) method of the `Grant` object to enforce that the grant was successfully applied\. +The grant methods return an `iam.Grant` object\. Use the `success` attribute of the `Grant` object to determine whether the grant was effectively applied \(for example, it may not have been applied on [external resources](#resources_referencing)\)\. You can also use the `assertSuccess` \(Python: `assert_success`\) method of the `Grant` object to enforce that the grant was successfully applied\. If a specific grant method isn't available for the particular use case, you can use a generic grant method to define a new grant with a specified list of actions\. diff --git a/v2/best-practices.md b/v2/best-practices.md index dbe776f7..12758a87 100644 --- a/v2/best-practices.md +++ b/v2/best-practices.md @@ -129,7 +129,7 @@ A better approach is to specify as few names as possible\. If you leave out reso If the place you need it is another AWS CDK stack, that's even easier\. Given one stack that defines the resource and another than needs to use it: + If the two stacks are in the same AWS CDK app, just pass a reference between the two stacks\. For example, save a reference to the resource's construct as an attribute of the defining stack \(`this.stack.uploadBucket = myBucket`\), then pass that attribute to the constructor of the stack that needs the resource\. -+ When the two stacks are in different AWS CDK apps, use a static `from` method to import an externally\-defined resource based on its ARN, name, or other attributes \(for example, `Table.fromArn()` for a DynamoDB table\)\. Use the `CfnOutput` construct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS console\. Or the second app can parse the CloudFormation template generated by the first app and retrieve that value from the Outputs section\. ++ When the two stacks are in different AWS CDK apps, use a static `from` method to use an externally\-defined resource based on its ARN, name, or other attributes \(for example, `Table.fromArn()` for a DynamoDB table\)\. Use the `CfnOutput` construct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS console\. Or the second app can parse the CloudFormation template generated by the first app and retrieve that value from the Outputs section\. ### Define removal policies and log retention diff --git a/v2/constructs.md b/v2/constructs.md index e1d81f76..52c234f2 100644 --- a/v2/constructs.md +++ b/v2/constructs.md @@ -639,7 +639,7 @@ For information about the most common API patterns in the AWS Construct Library, ## Writing your own constructs -In addition to using existing constructs like `s3.Bucket`, you can also write your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct imported from a third\-party library that someone published via NPM or Maven or PyPI—or to your company's internal package repository\. +In addition to using existing constructs like `s3.Bucket`, you can also write your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct from a third\-party library that someone published via NPM or Maven or PyPI—or to your company's internal package repository\. To declare a new construct, create a class that extends the [Construct](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) base class, in the `constructs` package, then follow the pattern for initializer arguments\. diff --git a/v2/context.md b/v2/context.md index b504a0f1..f8ab0e3a 100644 --- a/v2/context.md +++ b/v2/context.md @@ -132,7 +132,7 @@ Context values passed from the command line are always strings\. If a value is u ## Example -Below is an example of importing an existing Amazon VPC using AWS CDK context\. +Below is an example of using an existing Amazon VPC using AWS CDK context\. ------ #### [ TypeScript ] diff --git a/v2/permissions.md b/v2/permissions.md index 31aca148..a0662fae 100644 --- a/v2/permissions.md +++ b/v2/permissions.md @@ -350,7 +350,7 @@ var project = new Project(this, "Project", new ProjectProps ------ -Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. This property is not available on imported resources, however, so such constructs have an `addToRolePolicy` \(Python: `add_to_role_policy`\) method that does nothing if the construct is an imported resource, and calls the `addToPolicy` \(Python: `add_to_policy`\) method of the `role` property otherwise, saving you the trouble of handling the undefined case explicitly\. The following example demonstrates: +Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. This property is not available on external resources, however, so such constructs have an `addToRolePolicy` \(Python: `add_to_role_policy`\) method that does nothing if the construct is an external resource, and calls the `addToPolicy` \(Python: `add_to_policy`\) method of the `role` property otherwise, saving you the trouble of handling the undefined case explicitly\. The following example demonstrates: ------ #### [ TypeScript ] @@ -496,11 +496,11 @@ If you have defined an IAM user, principal, group, or role outside your AWS CDK + For groups, call `[Group\.fromGroupArn\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Group.html#static-fromwbrgroupwbrarnscope-id-grouparn)` or `[Group\.fromGroupName\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Group.html#static-fromwbrgroupwbrnamescope-id-groupname)`\. + For roles, call `[Role\.fromRoleArn\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html#static-fromwbrrolewbrarnscope-id-rolearn-options)` or `[Role\.fromRoleName\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html#static-fromwbrrolewbrnamescope-id-rolename)`\. -Policies \(including managed policies\) can be imported in similar fashion using the methods listed below\. You can use references to these objects anywhere an IAM policy is required\. +Policies \(including managed policies\) can be used in similar fashion using the methods listed below\. You can use references to these objects anywhere an IAM policy is required\. + `[Policy\.fromPolicyName](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Policy.html#static-fromwbrpolicywbrnamescope-id-policyname)` + `[ManagedPolicy\.fromManagedPolicyArn](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ManagedPolicy.html#static-fromwbrmanagedwbrpolicywbrarnscope-id-managedpolicyarn)` + `[ManagedPolicy\.fromManagedPolicyName](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ManagedPolicy.html#static-fromwbrmanagedwbrpolicywbrnamescope-id-managedpolicyname)` + `[ManagedPolicy\.fromAwsManagedPolicyName](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ManagedPolicy.html#static-fromwbrawswbrmanagedwbrpolicywbrnamemanagedpolicyname)` **Note** -As with all references to external AWS resources, you cannot modify imported IAM objects in your CDK app\. \ No newline at end of file +As with all references to external AWS resources, you cannot modify external IAM objects in your CDK app\. \ No newline at end of file diff --git a/v2/resources.md b/v2/resources.md index a8ddf966..4edd125e 100644 --- a/v2/resources.md +++ b/v2/resources.md @@ -579,9 +579,9 @@ Vpc.FromVpcAttributes(this, "MyVpc", new VpcAttributes ------ -Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables, it can be difficult to import those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. +Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables, it can be difficult to specify those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. -You must provide attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want to import the VPC marked as the default is sufficient\. +You must provide attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want the VPC marked as the default is sufficient\. ------ #### [ TypeScript ] @@ -677,7 +677,7 @@ Vpc.FromLookup(this, id = "PublicVpc", new VpcLookupOptions Results of `Vpc.fromLookup()` are cached in the project's `cdk.context.json` file\. Commit this file to version control if you will be deploying the stack in an environment that does not have access to the AWS account that defines the VPC, such as [CDK Pipelines](cdk_pipeline.md)\. -Although you can use an imported resource anywhere, you cannot modify the imported resource\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an imported `s3.Bucket` does nothing\. +Although you can use an external resource anywhere you'd use a similar resource defined in your app, you cannot modify the external resource\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an external `s3.Bucket` does nothing\. ## Permission grants @@ -732,7 +732,7 @@ if (bucket.GrantReadWrite(func).Success) ------ -The grant methods return an `iam.Grant` object\. Use the `success` attribute of the `Grant` object to determine whether the grant was effectively applied \(for example, it may not have been applied on [imported resources](#resources_referencing)\)\. You can also use the `assertSuccess` \(Python: `assert_success`\) method of the `Grant` object to enforce that the grant was successfully applied\. +The grant methods return an `iam.Grant` object\. Use the `success` attribute of the `Grant` object to determine whether the grant was effectively applied \(for example, it may not have been applied on [external resources](#resources_referencing)\)\. You can also use the `assertSuccess` \(Python: `assert_success`\) method of the `Grant` object to enforce that the grant was successfully applied\. If a specific grant method isn't available for the particular use case, you can use a generic grant method to define a new grant with a specified list of actions\. diff --git a/v2/work-with.md b/v2/work-with.md index b1e64809..b08fcea9 100644 --- a/v2/work-with.md +++ b/v2/work-with.md @@ -99,7 +99,7 @@ Each module's reference material is broken into the following sections\. + *Constructs*: Library classes that represent one or more concrete AWS resources\. These are the "curated" \(L2\) resources or patterns \(L3 resources\) that provide a high\-level interface with sane defaults\. + *Classes*: Non\-construct classes that provide functionality used by constructs in the module\. + *Structs*: Data structures \(attribute bundles\) that define the structure of composite values such as properties \(the `props` argument of constructs\) and options\. -+ *Interfaces*: Interfaces, whose names all begin with "I", define the absolute minimum functionality for the corresponding construct or other class\. The CDK uses construct interfaces to represent AWS resources that are defined outside your AWS CDK app and imported by methods such as `Bucket.fromBucketArn()`\. ++ *Interfaces*: Interfaces, whose names all begin with "I", define the absolute minimum functionality for the corresponding construct or other class\. The CDK uses construct interfaces to represent AWS resources that are defined outside your AWS CDK app and referenced by methods such as `Bucket.fromBucketArn()`\. + *Enums*: Collections of named values for use in specifying certain construct parameters\. Using an enumerated value allows the CDK to check these values for validity during synthesis\. + *CloudFormation Resources*: These L1 constructs, whose names begin with "Cfn", represent exactly the resources defined in the CloudFormation specification\. They are automatically generated from that specification with each CDK release\. Each L2 or L3 construct encapsulates one or more CloudFormation resources\. + *CloudFormation Property Types*: The collection of named values that define the properties for each CloudFormation Resource\. @@ -108,9 +108,9 @@ Each module's reference material is broken into the following sections\. The AWS CDK uses interfaces in a specific way that might not be obvious even if you are familiar with interfaces as a programming concept\. -The AWS CDK supports importing resources defined outside CDK applications using methods such as `Bucket.fromBucketArn()`\. Imported resources cannot be modified and may not have all the functionality available with resources defined in your CDK app using e\.g\. the `Bucket` class\. Interfaces, then, represent the bare minimum functionality available in the CDK for a given AWS resource type, *including imported resources\.* +The AWS CDK supports using resources defined outside CDK applications using methods such as `Bucket.fromBucketArn()`\. External resources cannot be modified and may not have all the functionality available with resources defined in your CDK app using e\.g\. the `Bucket` class\. Interfaces, then, represent the bare minimum functionality available in the CDK for a given AWS resource type, *including external resources\.* -When instantiating resources in your CDK app, then, you should always use concrete classes such as `Bucket`\. When specifying the type of an argument you are accepting in one of your own constructs, use the interface type such as `IBucket` if you are prepared to deal with imported resources \(that is, you won't need to change them\)\. If you require a CDK\-defined construct, specify the most general type you can use\. +When instantiating resources in your CDK app, then, you should always use concrete classes such as `Bucket`\. When specifying the type of an argument you are accepting in one of your own constructs, use the interface type such as `IBucket` if you are prepared to deal with external resources \(that is, you won't need to change them\)\. If you require a CDK\-defined construct, specify the most general type you can use\. Some interfaces are minimum versions of properties or options bundles \(shown in the AWS CDK API Reference as Structs\) that are associated with specific constructs\. For example, `IBucketProps` is the smallest set of properties required to instantiate a bucket\. Such interfaces can be useful when subclassing constructs to accept arguments that you'll pass on to your parent class\. If you require one or more additional properties, you'll want to implement or derive from this interface, or from a more specific type such as `BucketProps`\. From 9e0f7aebff68bf31e6fa4a6da88511b030bf8b0e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 10 May 2022 22:39:20 +0000 Subject: [PATCH 547/655] improve tip about committing context values --- v1/cdk_pipeline.md | 4 ++-- v2/cdk_pipeline.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/v1/cdk_pipeline.md b/v1/cdk_pipeline.md index cfde18e1..871b270b 100644 --- a/v1/cdk_pipeline.md +++ b/v1/cdk_pipeline.md @@ -139,8 +139,8 @@ If you are using Visual Studio, open the solution file in the `src` directory\. Install the CDK Pipelines module along with any others you'll be using\. -**Tip** -Be sure to commit your `cdk.json` and `cdk.context.json` files in source control\. The context information \(such as feature flags and cached values retrieved from your AWS account\) are part of your project's state\. The values may be different in another environment, which can cause instability \(unexpected changes\) in your results\. +**Important** +Be sure to commit your `cdk.json` and `cdk.context.json` files to source control\. The context information \(such as feature flags and cached values retrieved from your AWS account\) are part of your project's state\. The values may be different in another environment, which can cause unexpected changes in your results\. For more information, see [Runtime context](context.md)\. ------ #### [ TypeScript ] diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index 376eedc3..14911ac8 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -137,8 +137,8 @@ If you are using Visual Studio, open the solution file in the `src` directory\. ------ -**Tip** -Be sure to commit your `cdk.json` and `cdk.context.json` files in source control\. The context information \(such as feature flags and cached values retrieved from your AWS account\) are part of your project's state\. The values may be different in another environment, which can cause instability \(unexpected changes\) in your results\. +**Important** +Be sure to commit your `cdk.json` and `cdk.context.json` files to source control\. The context information \(such as feature flags and cached values retrieved from your AWS account\) are part of your project's state\. The values may be different in another environment, which can cause unexpected changes in your results\. For more information, see [Runtime context](context.md)\. ## Define a pipeline From 9cbc0dce3458efc4607e54fe5f5782506a116d13 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 11 May 2022 20:30:53 +0000 Subject: [PATCH 548/655] improve definition of scope argument --- v1/constructs.md | 8 ++++---- v2/constructs.md | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/v1/constructs.md b/v1/constructs.md index 3b711866..beffcfe1 100644 --- a/v1/constructs.md +++ b/v1/constructs.md @@ -32,9 +32,9 @@ Composition lets you define reusable components and share them like any other co ## Initialization Constructs are implemented in classes that extend the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html) base class\. You define a construct by instantiating the class\. All constructs take three parameters when they are initialized: -+ **Scope** – The construct within which this construct is defined\. You should usually pass `this` for the scope, because it represents the current scope in which you are defining the construct\. -+ **id** – An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to allocate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. -+ **Props** – A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. ++ **scope** — The construct's parent or owner, either a stack or another construct, which determines its place in the [construct tree](#constructs_tree)\. You should usually pass `this` \(or `self` in Python\), which represents the current object, for the scope\. ++ **id** — An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to generate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. ++ **props** — A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tag.html) or for specifying where the constructs will be deployed\. @@ -995,7 +995,7 @@ Constructs are *always* explicitly defined within the scope of another construct Passing the scope explicitly allows each construct to add itself to the tree, with this behavior entirely contained within the [`Construct` base class](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html)\. It works the same way in every language supported by the AWS CDK and does not require introspection or other "magic\." **Important** -Technically, it's possible to pass some scope other than `this` when instantiating a construct, which allows you to add constructs anywhere in the tree, even in another stack entirely\. For example, you could write a mixin\-style function that adds constructs to a scope passed in as an argument\. The practical difficulty here is that you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope\. The practice also makes your code more difficult to understand, maintain, and reuse\. It is virtually always better to find a way to express your intent without resorting to abusing the `scope` argument\. +Technically, it's possible to pass some scope other than `this` when instantiating a construct, which allows you to add constructs anywhere in the tree, or even in another stack in the same app\. For example, you could write a mixin\-style function that adds constructs to a scope passed in as an argument\. The practical difficulty here is that you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope\. The practice also makes your code more difficult to understand, maintain, and reuse\. It is virtually always better to find a way to express your intent without resorting to abusing the `scope` argument\. The AWS CDK uses the IDs of all constructs in the path from the tree's root to each child construct to generate the unique IDs required by AWS CloudFormation\. This approach means that construct IDs need be unique only within their scope, rather than within the entire stack as in native AWS CloudFormation\. It does, however, mean that if you move a construct to a different scope, its generated stack\-unique ID will change, and AWS CloudFormation will no longer consider it the same resource\. diff --git a/v2/constructs.md b/v2/constructs.md index 52c234f2..0992ce7b 100644 --- a/v2/constructs.md +++ b/v2/constructs.md @@ -35,9 +35,9 @@ Composition lets you define reusable components and share them like any other co ## Initialization Constructs are implemented in classes that extend the [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) base class\. You define a construct by instantiating the class\. All constructs take three parameters when they are initialized: -+ **Scope** – The construct within which this construct is defined\. You should usually pass `this` for the scope, because it represents the current scope in which you are defining the construct\. -+ **id** – An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to allocate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. -+ **Props** – A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. ++ **scope** — The construct's parent or owner, either a stack or another construct, which determines its place in the [construct tree](#constructs_tree)\. You should usually pass `this` \(or `self` in Python\), which represents the current object, for the scope\. ++ **id** — An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to generate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. ++ **props** — A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tag.html) or for specifying where the constructs will be deployed\. @@ -999,7 +999,7 @@ Constructs are *always* explicitly defined within the scope of another construct Passing the scope explicitly allows each construct to add itself to the tree, with this behavior entirely contained within the [`Construct` base class](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html)\. It works the same way in every language supported by the AWS CDK and does not require introspection or other "magic\." **Important** -Technically, it's possible to pass some scope other than `this` when instantiating a construct, which allows you to add constructs anywhere in the tree, even in another stack entirely\. For example, you could write a mixin\-style function that adds constructs to a scope passed in as an argument\. The practical difficulty here is that you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope\. The practice also makes your code more difficult to understand, maintain, and reuse\. It is virtually always better to find a way to express your intent without resorting to abusing the `scope` argument\. +Technically, it's possible to pass some scope other than `this` when instantiating a construct, which allows you to add constructs anywhere in the tree, or even in another stack in the same app\. For example, you could write a mixin\-style function that adds constructs to a scope passed in as an argument\. The practical difficulty here is that you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope\. The practice also makes your code more difficult to understand, maintain, and reuse\. It is virtually always better to find a way to express your intent without resorting to abusing the `scope` argument\. The AWS CDK uses the IDs of all constructs in the path from the tree's root to each child construct to generate the unique IDs required by AWS CloudFormation\. This approach means that construct IDs need be unique only within their scope, rather than within the entire stack as in native AWS CloudFormation\. It does, however, mean that if you move a construct to a different scope, its generated stack\-unique ID will change, and AWS CloudFormation will no longer consider it the same resource\. From d0a9f6e1681c364dd8c1a37efd2a6a254f7f63c1 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 11 May 2022 20:34:29 +0000 Subject: [PATCH 549/655] identities should be identifiers --- v1/constructs.md | 2 +- v2/constructs.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/constructs.md b/v1/constructs.md index beffcfe1..d481a0e2 100644 --- a/v1/constructs.md +++ b/v1/constructs.md @@ -33,7 +33,7 @@ Composition lets you define reusable components and share them like any other co Constructs are implemented in classes that extend the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Construct.html) base class\. You define a construct by instantiating the class\. All constructs take three parameters when they are initialized: + **scope** — The construct's parent or owner, either a stack or another construct, which determines its place in the [construct tree](#constructs_tree)\. You should usually pass `this` \(or `self` in Python\), which represents the current object, for the scope\. -+ **id** — An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to generate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. ++ **id** — An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to generate unique identifiers such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. + **props** — A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tag.html) or for specifying where the constructs will be deployed\. diff --git a/v2/constructs.md b/v2/constructs.md index 0992ce7b..44e5ada4 100644 --- a/v2/constructs.md +++ b/v2/constructs.md @@ -36,7 +36,7 @@ Composition lets you define reusable components and share them like any other co Constructs are implemented in classes that extend the [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) base class\. You define a construct by instantiating the class\. All constructs take three parameters when they are initialized: + **scope** — The construct's parent or owner, either a stack or another construct, which determines its place in the [construct tree](#constructs_tree)\. You should usually pass `this` \(or `self` in Python\), which represents the current object, for the scope\. -+ **id** — An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to generate unique identities such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. ++ **id** — An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to generate unique identifiers such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. + **props** — A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tag.html) or for specifying where the constructs will be deployed\. From 11f401a9d7cf6ba1368646401e40e48a814cc626 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 16 May 2022 16:48:55 +0000 Subject: [PATCH 550/655] clarify --qualname, remove CDK_NEW_BOOTSTRAP env var in v2 --- v1/bootstrapping.md | 2 +- v2/bootstrapping.md | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/v1/bootstrapping.md b/v1/bootstrapping.md index 738bfd8a..280895fd 100644 --- a/v1/bootstrapping.md +++ b/v1/bootstrapping.md @@ -183,7 +183,7 @@ The following additional switches are available only with the modern bootstrappi To avoid deployment failures, be sure the policies you specify are sufficient for any deployments you will perform in the environment being bootstrapped\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. + \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. -+ \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. ++ \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid resource name clashes when you provision multiple bootstrap stacks in the same environment using \-\-toolkit\-stack\-name\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier also requires that your CDK app pass the changed value to the stack synthesizer\(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. **Important** The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index 66504ca7..b7c86f91 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -137,7 +137,7 @@ The following command\-line options, when used with CDK Toolkit's cdk bootstrap, ``` **Important** To avoid deployment failures, be sure the policies you specify are sufficient for any deployments you will perform in the environment being bootstrapped\. -+ \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid name clashes when you provision two bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier will require changes to your AWS CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. ++ \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid resource name clashes when you provision multiple bootstrap stacks in the same environment using \-\-toolkit\-stack\-name\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier also requires that your CDK app pass the changed value to the stack synthesizer\(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. + \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. @@ -151,7 +151,6 @@ The modern bootstrap template effectively grants the permissions implied by the When you need more customization than the AWS CDK Toolkit switches can provide, you can modify the bootstrap template to suit your needs\. Remember that you can obtain the template by using the \-\-show\-template flag\. ``` -export CDK_NEW_BOOTSTRAP=1 cdk bootstrap --show-template ``` From 8b6dfffdfdb323973869e8ef4ab5536732dac002 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 31 May 2022 01:05:47 +0000 Subject: [PATCH 551/655] remove verbiage referring to Go as developer preview --- v1/get_context_var.md | 2 +- v1/getting_started.md | 9 +++------ v1/hello_world.md | 2 +- v1/home.md | 2 +- v1/reference.md | 2 +- v1/work-with-cdk-go.md | 2 +- v1/work-with-cdk-v2.md | 2 +- v1/work-with.md | 6 +++--- v2/get_context_var.md | 2 +- v2/getting_started.md | 7 ++----- v2/hello_world.md | 3 --- v2/home.md | 2 +- v2/reference.md | 2 +- v2/work-with-cdk-go.md | 2 +- v2/work-with.md | 6 +++--- 15 files changed, 21 insertions(+), 30 deletions(-) diff --git a/v1/get_context_var.md b/v1/get_context_var.md index 74cbd767..33a839cf 100644 --- a/v1/get_context_var.md +++ b/v1/get_context_var.md @@ -18,7 +18,7 @@ To specify the same context variable and value in the `cdk.json` file, use the f } ``` -To get the value of a context variable in your app, use the `TryGetContext` method in the context of a construct \(that is, when `this`, or `self` in Python, is an instance of some construct\)\. The example gets the context value **bucket\_name**\. If the requested value is not defined, `TryGetContext` returns `undefined` \(`None` in Python; `null` in Java and C\#\) rather than raising an exception\. +To get the value of a context variable in your app, use the `TryGetContext` method in the context of a construct \(that is, when `this`, or `self` in Python, is an instance of some construct\)\. The example gets the context value **bucket\_name**\. If the requested value is not defined, `TryGetContext` returns `undefined` \(`None` in Python; `null` in Java and C\#; `nil` in Go\) rather than raising an exception\. ------ #### [ TypeScript ] diff --git a/v1/getting_started.md b/v1/getting_started.md index ca4da450..b4e476a5 100644 --- a/v1/getting_started.md +++ b/v1/getting_started.md @@ -16,10 +16,7 @@ Finally, you should be proficient in the programming language you intend to use The AWS CDK is designed around a handful of important concepts\. We will introduce a few of these here briefly\. Follow the links to learn more, or see the Concepts topics in this guide's Table of Contents\. -An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, Python, Java, or C\# that uses the AWS CDK to define AWS infrastructure\. An app defines one or more [stacks](stacks.md)\. Stacks \(equivalent to AWS CloudFormation stacks\) contain [constructs](constructs.md), each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on\. - -**Note** -The AWS CDK also supports Go in a developer preview\. This Guide does not include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. +An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, Python, Java, C\#, or Go that uses the AWS CDK to define AWS infrastructure\. An app defines one or more [stacks](stacks.md)\. Stacks \(equivalent to AWS CloudFormation stacks\) contain [constructs](constructs.md), each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on\. Constructs \(as well as stacks and apps\) are represented as classes \(types\) in your programming language of choice\. You instantiate constructs within a stack to declare them to AWS, and connect them to each other using well\-defined interfaces\. @@ -42,7 +39,7 @@ Numerous third parties have also published constructs compatible with the AWS CD ## Supported programming languages -The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) Go support is available as a Developer Preview\. +The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, C\#, and Go\. Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\. To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. @@ -120,7 +117,7 @@ TypeScript was the first language supported by the AWS CDK, and much AWS CDK exa Here's what you need to install to use the AWS CDK\. -All AWS CDK developers, even those working in Python, Java, or C\#, need [Node\.js](https://nodejs.org/en/download/) 10\.13\.0 or later\. All supported languages use the same back end, which runs on Node\.js\. We recommend a version in [active long\-term support](https://nodejs.org/en/about/releases/), which, at this writing, is the latest 16\.x release\. Your organization may have a different recommendation\. +All AWS CDK developers, even those working in Python, Java, C\#, or Go, need [Node\.js](https://nodejs.org/en/download/) 10\.13\.0 or later\. All supported languages use the same back end, which runs on Node\.js\. We recommend a version in [active long\-term support](https://nodejs.org/en/about/releases/), which, at this writing, is the latest 16\.x release\. Your organization may have a different recommendation\. **Important** Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. diff --git a/v1/hello_world.md b/v1/hello_world.md index 78842295..40b7eb85 100644 --- a/v1/hello_world.md +++ b/v1/hello_world.md @@ -3,7 +3,7 @@ You've read [Getting started with the AWS CDK](getting_started.md) and set up your development environment for writing AWS CDK apps? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. **Note** -The AWS CDK supports Go in a developer preview\. This tutorial does not include instructions or code examples for Go\. +This tutorial does not currently include instructions or code examples for Go\. In this tutorial, you'll learn about the structure of a AWS CDK project, how to use the AWS Construct Library to define AWS resources using code, and how to synthesize, diff, and deploy collections of resources using the AWS CDK Toolkit command\-line tool\. diff --git a/v1/home.md b/v1/home.md index 508e92fa..055afdc4 100644 --- a/v1/home.md +++ b/v1/home.md @@ -16,7 +16,7 @@ The AWS CDK lets you build reliable, scalable, cost\-effective applications in t + Use the power of AWS CloudFormation to perform infrastructure deployments predictably and repeatedly, with rollback on error\. + Easily share infrastructure design patterns among teams within your organization or even with the public\. -The AWS CDK supports TypeScript, JavaScript, Python, Java, C\#/\.Net, and \(in developer preview\) Go\. Developers can use one of these supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. +The AWS CDK supports TypeScript, JavaScript, Python, Java, C\#/\.Net, and Go\. Developers can use one of these supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v1/guide/images/AppStacks.png) diff --git a/v1/reference.md b/v1/reference.md index 0aa959e1..3489ad05 100644 --- a/v1/reference.md +++ b/v1/reference.md @@ -4,7 +4,7 @@ The [API Reference](https://docs.aws.amazon.com/cdk/api/v1) contains information Each module has an overview that includes information about how to use its APIs\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-s3-readme.html) overview demonstrates how to set default encryption on an Amazon S3 bucket\. -Separate versions of the API Reference are provided for TypeScript/JavaScript, Python, Java, and C\#/\.NET\. +Separate versions of the API Reference are provided for TypeScript/JavaScript, Python, Java, C\#/\.NET\., and Go\. ## Versioning diff --git a/v1/work-with-cdk-go.md b/v1/work-with-cdk-go.md index b6f38a38..e4ef8608 100644 --- a/v1/work-with-cdk-go.md +++ b/v1/work-with-cdk-go.md @@ -1,6 +1,6 @@ # Working with the AWS CDK in Go -The Go language binding for the AWS CDK is now available as a Developer Preview\. It is not suitable for production use and may undergo significant changes before being designated stable\. To follow development, see the [Project Board](https://github.com/aws/jsii/projects/3) on GitHub\. Please [report any issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. +Go is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in Go uses familiar tools\. The Go version of the AWS CDK even uses Go\-style identifiers\. Unlike the other languages the CDK supports, Go is not a traditional object\-oriented programming language\. Go uses composition where other languages often leverage inheritance\. We have tried to employ idiomatic Go approaches as much as possible, but there are places where the CDK charts its own course\. diff --git a/v1/work-with-cdk-v2.md b/v1/work-with-cdk-v2.md index cab61f83..b8f9a7d0 100644 --- a/v1/work-with-cdk-v2.md +++ b/v1/work-with-cdk-v2.md @@ -1,6 +1,6 @@ # Migrating to AWS CDK v2 -Version 2 of the AWS CDK, now Generally Available, provides an improved development experience that aims to make Infrastructure as Code \(IAC\) even simpler\. +Version 2 of the AWS CDK provides an improved development experience that aims to make Infrastructure as Code \(IAC\) even simpler\. CDK v1 will continue to be fully supported until June 1, 2022, at which time it will enter maintenance\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 1, 2023, support will end entirely for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. diff --git a/v1/work-with.md b/v1/work-with.md index c2b371c8..944e9e81 100644 --- a/v1/work-with.md +++ b/v1/work-with.md @@ -1,9 +1,9 @@ # Working with the AWS CDK -The AWS Cloud Development Kit \(CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and \(in developer preview\) Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. +The AWS Cloud Development Kit \(CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. **Note** -This Guide does not currently include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. Go support is currently in developer preview\. +This Guide does not currently include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. We develop the AWS CDK in TypeScript and use [JSII](https://github.com/aws/jsii) to provide a "native" experience in other supported languages\. For example, we distribute AWS Construct Library modules using your preferred language's standard repository, and you install them using the language's standard package manager\. Methods and properties are even named using your language's recommended naming patterns\. @@ -18,7 +18,7 @@ If you have the [AWS CLI](https://aws.amazon.com/cli/) installed, the simplest w aws configure ``` -All AWS CDK applications require Node\.js 10\.13 or later, even if you work in Python, Java, or C\#\. You may download a compatible version at [nodejs\.org](https://nodejs.org/)\. We recommend the [active LTS version](https://nodejs.org/en/about/releases/) \(at this writing, the latest 16\.x release\)\. Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. +All AWS CDK applications require Node\.js 10\.13 or later, even if you work in Python, Java, C\#, or Go\. You may download a compatible version at [nodejs\.org](https://nodejs.org/)\. We recommend the [active LTS version](https://nodejs.org/en/about/releases/) \(at this writing, the latest 16\.x release\)\. Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. After installing Node\.js, install the AWS CDK Toolkit \(the `cdk` command\): diff --git a/v2/get_context_var.md b/v2/get_context_var.md index 74cbd767..33a839cf 100644 --- a/v2/get_context_var.md +++ b/v2/get_context_var.md @@ -18,7 +18,7 @@ To specify the same context variable and value in the `cdk.json` file, use the f } ``` -To get the value of a context variable in your app, use the `TryGetContext` method in the context of a construct \(that is, when `this`, or `self` in Python, is an instance of some construct\)\. The example gets the context value **bucket\_name**\. If the requested value is not defined, `TryGetContext` returns `undefined` \(`None` in Python; `null` in Java and C\#\) rather than raising an exception\. +To get the value of a context variable in your app, use the `TryGetContext` method in the context of a construct \(that is, when `this`, or `self` in Python, is an instance of some construct\)\. The example gets the context value **bucket\_name**\. If the requested value is not defined, `TryGetContext` returns `undefined` \(`None` in Python; `null` in Java and C\#; `nil` in Go\) rather than raising an exception\. ------ #### [ TypeScript ] diff --git a/v2/getting_started.md b/v2/getting_started.md index 05c803bd..dc79b35f 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -16,10 +16,7 @@ Finally, you should be proficient in the programming language you intend to use The AWS CDK is designed around a handful of important concepts\. We will introduce a few of these here briefly\. Follow the links to learn more, or see the Concepts topics in this guide's Table of Contents\. -An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, Python, Java, or C\# that uses the AWS CDK to define AWS infrastructure\. An app defines one or more [stacks](stacks.md)\. Stacks \(equivalent to AWS CloudFormation stacks\) contain [constructs](constructs.md), each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on\. - -**Note** -The AWS CDK also supports Go in a developer preview\. This Guide does not include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. +An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, Python, Java, C\# or Go that uses the AWS CDK to define AWS infrastructure\. An app defines one or more [stacks](stacks.md)\. Stacks \(equivalent to AWS CloudFormation stacks\) contain [constructs](constructs.md), each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on\. Constructs \(as well as stacks and apps\) are represented as classes \(types\) in your programming language of choice\. You instantiate constructs within a stack to declare them to AWS, and connect them to each other using well\-defined interfaces\. @@ -92,7 +89,7 @@ Numerous third parties have also published constructs compatible with the AWS CD ## Supported programming languages -The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, and C\#\. \(Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\.\) Go support is available as a Developer Preview\. +The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, C\#, and Go\. Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\. To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. diff --git a/v2/hello_world.md b/v2/hello_world.md index 3a32efa7..549081e0 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -2,9 +2,6 @@ You've read [Getting started with the AWS CDK](getting_started.md) and set up your development environment for writing AWS CDK apps? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. -**Note** -The AWS CDK supports Go in a developer preview\. This tutorial does not include instructions or code examples for Go\. - In this tutorial, you'll learn about the structure of a AWS CDK project, how to use the AWS Construct Library to define AWS resources using code, and how to synthesize, diff, and deploy collections of resources using the AWS CDK Toolkit command\-line tool\. The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps\. diff --git a/v2/home.md b/v2/home.md index db15ec55..04806634 100644 --- a/v2/home.md +++ b/v2/home.md @@ -15,7 +15,7 @@ The AWS CDK lets you build reliable, scalable, cost\-effective applications in t + Use the power of AWS CloudFormation to perform infrastructure deployments predictably and repeatedly, with rollback on error\. + Easily share infrastructure design patterns among teams within your organization or even with the public\. -The AWS CDK supports TypeScript, JavaScript, Python, Java, C\#/\.Net, and \(in developer preview\) Go\. Developers can use one of these supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. +The AWS CDK supports TypeScript, JavaScript, Python, Java, C\#/\.Net, and Go\. Developers can use one of these supported programming languages to define reusable cloud components known as [Constructs](constructs.md)\. You compose these together into [Stacks](stacks.md) and [Apps](apps.md)\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/AppStacks.png) diff --git a/v2/reference.md b/v2/reference.md index 258ffce6..aa23927e 100644 --- a/v2/reference.md +++ b/v2/reference.md @@ -4,7 +4,7 @@ The [API Reference](https://docs.aws.amazon.com/cdk/api/v2) contains information Each submodule has an overview that includes information about how to use its APIs\. For example, the [S3](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3-readme.html) overview demonstrates how to set default encryption on an Amazon S3 bucket\. -Separate versions of the API Reference are provided for TypeScript/JavaScript, Python, Java, and C\#/\.NET\. +Separate versions of the API Reference are provided for TypeScript/JavaScript, Python, Java, C\#/\.NET, and Go\. ## Versioning diff --git a/v2/work-with-cdk-go.md b/v2/work-with-cdk-go.md index eb4e80a5..2dac2823 100644 --- a/v2/work-with-cdk-go.md +++ b/v2/work-with-cdk-go.md @@ -1,6 +1,6 @@ # Working with the AWS CDK in Go -The Go language binding for the AWS CDK is now available as a Developer Preview\. It is not suitable for production use and may undergo significant changes before being designated stable\. To follow development, see the [Project Board](https://github.com/aws/jsii/projects/3) on GitHub\. Please [report any issues](https://github.com/aws/aws-cdk/issues/new/choose) you encounter\. +Go is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in Go uses familiar tools\. The Go version of the AWS CDK even uses Go\-style identifiers\. Unlike the other languages the CDK supports, Go is not a traditional object\-oriented programming language\. Go uses composition where other languages often leverage inheritance\. We have tried to employ idiomatic Go approaches as much as possible, but there are places where the CDK charts its own course\. diff --git a/v2/work-with.md b/v2/work-with.md index b08fcea9..f0202de6 100644 --- a/v2/work-with.md +++ b/v2/work-with.md @@ -1,9 +1,9 @@ # Working with the AWS CDK -The AWS Cloud Development Kit \(CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and \(in developer preview\) Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. +The AWS Cloud Development Kit \(CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. **Note** -This Guide does not currently include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. Go support is currently in developer preview\. +This Guide does not currently include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. We develop the AWS CDK in TypeScript and use [JSII](https://github.com/aws/jsii) to provide a "native" experience in other supported languages\. For example, we distribute AWS Construct Library modules using your preferred language's standard repository, and you install them using the language's standard package manager\. Methods and properties are even named using your language's recommended naming patterns\. @@ -18,7 +18,7 @@ If you have the [AWS CLI](https://aws.amazon.com/cli/) installed, the simplest w aws configure ``` -All AWS CDK applications require Node\.js 10\.13 or later, even if you work in Python, Java, or C\#\. You may download a compatible version at [nodejs\.org](https://nodejs.org/)\. We recommend the [active LTS version](https://nodejs.org/en/about/releases/) \(at this writing, the latest 16\.x release\)\. Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. +All AWS CDK applications require Node\.js 10\.13 or later, even if you work in Python, Java, C\#, or Go\. You may download a compatible version at [nodejs\.org](https://nodejs.org/)\. We recommend the [active LTS version](https://nodejs.org/en/about/releases/) \(at this writing, the latest 16\.x release\)\. Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. After installing Node\.js, install the AWS CDK Toolkit \(the `cdk` command\): From 17b4747f906cadbb417eb5f7345f7eb2712d6143 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 3 Jun 2022 03:55:49 +0000 Subject: [PATCH 552/655] CDK v1 enters maintenance --- v1/home.md | 2 +- v1/work-with-cdk-v2.md | 2 +- v2/home.md | 2 +- v2/migrating-v2.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/v1/home.md b/v1/home.md index 055afdc4..88a537b1 100644 --- a/v1/home.md +++ b/v1/home.md @@ -4,7 +4,7 @@ Welcome to the *AWS Cloud Development Kit \(CDK\) Developer Guide*\. This docume **Important** The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v1\. -CDK v1 will continue to be fully supported until June 1, 2022, at which time it will enter maintenance\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 1, 2023, support will end for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. +CDK v1 entered maintenance on June 1, 2022\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 1, 2023, support will end for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. The AWS CDK lets you build reliable, scalable, cost\-effective applications in the cloud with the considerable expressive power of a programming language\. This approach yields many benefits, including: + Build with high\-level constructs that automatically provide sensible, secure defaults for your AWS resources, defining more infrastructure with less code\. diff --git a/v1/work-with-cdk-v2.md b/v1/work-with-cdk-v2.md index b8f9a7d0..07094a46 100644 --- a/v1/work-with-cdk-v2.md +++ b/v1/work-with-cdk-v2.md @@ -2,7 +2,7 @@ Version 2 of the AWS CDK provides an improved development experience that aims to make Infrastructure as Code \(IAC\) even simpler\. -CDK v1 will continue to be fully supported until June 1, 2022, at which time it will enter maintenance\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 1, 2023, support will end entirely for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. +CDK v1 entered maintenance on June 1, 2022\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only, and new features will be developed exclusively for CDK v2\. On June 1, 2023, support will end entirely for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. For information on migrating your apps to AWS CDK v2, see [Migrating to AWS CDK v2](../../v2/guide/migrating-v2.html) in the AWS CDK v2 Developer Guide\. diff --git a/v2/home.md b/v2/home.md index 04806634..50167436 100644 --- a/v2/home.md +++ b/v2/home.md @@ -3,7 +3,7 @@ Welcome to the *AWS Cloud Development Kit \(CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. **Note** -The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v2\. +The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v2\. CDK v1 entered maintenance on June 1, 2022\. The AWS CDK lets you build reliable, scalable, cost\-effective applications in the cloud with the considerable expressive power of a programming language\. This approach yields many benefits, including: + Build with high\-level constructs that automatically provide sensible, secure defaults for your AWS resources, defining more infrastructure with less code\. diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index f512f519..1803df8a 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -171,7 +171,7 @@ Note that `aws-cdk-lib` appears both as a peer dependency and a dev dependency\. **Note** You should perform a major version bump on your library's version number when releasing a v2\-compatible library, as this will be a breaking change for consumers of the library\. It is not possible to support both CDK v1 and v2 with a single library\. To continue to support customers who are still using v1, you could maintain the older release in parallel, or create a new package for v2\. -It's up to you how long you want to continue supporting AWS CDK v1 customers, but you could take your cue from the lifecycle of CDK v1 itself, and continue supporting v1 until AWS CDK v1 enters maintenance \(June 1, 2022\) or end\-of\-life \(June 1, 2023\)\. For full details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy) +It's up to you how long you want to continue supporting AWS CDK v1 customers, but you could take your cue from the lifecycle of CDK v1 itself, which entered maintenance on June 1, 2022 and will reach end\-of\-life on June 1, 2023\. For full details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy) **Both libraries and apps** Install the new dependencies by running `npm install` or `yarn install`\. From fadb71f420d2d065a60ea53a597306f33459245c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 16 Jun 2022 19:13:26 +0000 Subject: [PATCH 553/655] tweak --- v2/migrating-v2.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 1803df8a..b4256004 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -346,4 +346,14 @@ If you see an error like this one: MyStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) ``` -AWS CDK v2 requires a new bootstrap stack, so you must re\-bootstrap your deployment environment\(s\)\. See [Bootstrapping](bootstrapping.md) for complete details\. \ No newline at end of file +AWS CDK v2 requires a new bootstrap stack, so you must re\-bootstrap your deployment environment\(s\)\. See [Bootstrapping](bootstrapping.md) for complete details\. + +## Finding v1 stacks + +When working on migrating your CDK application from v1 to v2, you might want to identify the deployed AWS CloudFormation stacks that were created using v1\. To do this, run the following command: + +``` +npx awscdk-v1-stack-finder +``` + +See the awscdk\-v1\-stack\-finder [README](https://github.com/cdklabs/awscdk-v1-stack-finder/blob/main/README.md) for usage details\. \ No newline at end of file From de91fcf10a70526ca54070cbe45490240ed055de Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 20 Jun 2022 23:25:03 +0000 Subject: [PATCH 554/655] remove possibility that you won't need to bootstrap (all v2 depoyments need bootstrap resources) --- v2/bootstrapping.md | 8 ++------ v2/cdk_pipeline.md | 8 ++------ v2/cli.md | 4 ++-- v2/environments.md | 2 +- v2/getting_started.md | 2 +- v2/hello_world.md | 2 +- v2/migrating-v2.md | 4 ++-- v2/serverless_example.md | 2 +- v2/troubleshooting.md | 2 +- 9 files changed, 13 insertions(+), 21 deletions(-) diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index b7c86f91..a06fe1c0 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -1,10 +1,6 @@ # Bootstrapping -Deploying AWS CDK apps into an AWS [environment](environments.md) \(a combination of an AWS account and region\) may require that you provision resources the AWS CDK needs to perform the deployment\. These resources include an Amazon S3 bucket for storing files and IAM roles that grant permissions needed to perform deployments\. The process of provisioning these initial resources is called *bootstrapping*\. - -An environment needs to be bootstrapped if any of the following apply\. -+ An AWS CDK stack being deployed uses [Assets](assets.md)\. -+ An AWS CloudFormation template generated by the app exceeds 50 kilobytes\. +Deploying AWS CDK apps into an AWS [environment](environments.md) \(a combination of an AWS account and region\) requires that you provision resources the AWS CDK needs to perform the deployment\. These resources include an Amazon S3 bucket for storing files and IAM roles that grant permissions needed to perform deployments\. The process of provisioning these initial resources is called *bootstrapping*\. The required resources are defined in a AWS CloudFormation stack, called the *bootstrap stack*, which is usually named `CDKToolkit`\. Like any AWS CloudFormation stack, it appears in the AWS CloudFormation console once it has been deployed\. @@ -19,7 +15,7 @@ You may incur AWS charges for data stored in the bootstrapped resources\. **Note** Older versions of the bootstrap template created a Customer Master Key \(CMK\) in each bootstrapped environment by default\. To avoid charges for the CMK, re\-bootstrap these environments using `--no-bootstrap-customer-key`\. The current default is to not use a CMK to avoid these charges\. -If you attempt to deploy an AWS CDK application that requires bootstrap resources into an environment that does not have them, you receive an error message telling you that you need to bootstrap the environment\. +If you attempt to deploy an AWS CDK application into an environment that does not have the necessary resources, you receive an error message telling you that you need to bootstrap the environment\. If you are using CDK Pipelines to deploy into another account's environment, and you receive a message like the following: diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index 14911ac8..d3351a19 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -14,9 +14,9 @@ Before you can use CDK Pipelines, you must bootstrap the AWS environment\(s\) to **Note** See [Bootstrapping](bootstrapping.md) for more information on the kinds of resources created by bootstrapping and how to customize the bootstrap stack\. -You may have already bootstrapped one or more environments so you can deploy assets and Lambda functions using the AWS CDK\. Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include additional resources, so the bootstrap stack has been extended to include an additional Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. This new style of CDK Toolkit stack will eventually become the default, but at this writing, you must opt in\. The AWS CDK Toolkit will upgrade your existing bootstrap stack or create a new one, as necessary\. +Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include an Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. The CDK Toolkitwill upgrade your existing bootstrap stack or create a new one, as necessary\. -To bootstrap an environment that can provision an AWS CDK pipeline, set the environment variable `CDK_NEW_BOOTSTRAP` before invoking `cdk bootstrap`, as shown below\. Invoking the AWS CDK Toolkit via the `npx` command installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. +To bootstrap an environment that can provision an AWS CDK pipeline, invoke `cdk bootstrap` as shown below\. Invoking the AWS CDK Toolkit via the `npx` command temporarily installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. \-\-cloudformation\-execution\-policies specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The default `AdministratorAccess` policy ensures that your pipeline can deploy every type of AWS resource\. If you use this policy, make sure you trust all the code and dependencies that make up your AWS CDK app\. @@ -28,7 +28,6 @@ You may omit the \-\-profile option if your default AWS profile contains the nec #### [ macOS/Linux ] ``` -export CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ``` @@ -37,7 +36,6 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ #### [ Windows ] ``` -set CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ``` @@ -52,7 +50,6 @@ Again, you may omit the \-\-profile option if your default AWS profile contains #### [ macOS/Linux ] ``` -export CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ --trust PIPELINE-ACCOUNT-NUMBER @@ -62,7 +59,6 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE \ #### [ Windows ] ``` -set CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess ^ --trust PIPELINE-ACCOUNT-NUMBER diff --git a/v2/cli.md b/v2/cli.md index b2e1d503..1825f462 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -251,7 +251,7 @@ The order in which you specify the stacks is not necessarily the order in which ## Bootstrapping your AWS environment -Deploying stacks that contain [assets](assets.md), synthesize to large templates, or use [CDK Pipelines](cdk_pipeline.md) require special dedicated AWS CDK resources to be provisioned\. The `cdk bootstrap` command creates the necessary resources for you\. You only need to bootstrap if you are deploying a stack that requires these dedicated resources\. See [Bootstrapping](bootstrapping.md) for details\. +Deploying stacks with the CDK requires special dedicated AWS CDK resources to be provisioned\. The `cdk bootstrap` command creates the necessary resources for you\. You only need to bootstrap if you are deploying a stack that requires these dedicated resources\. See [Bootstrapping](bootstrapping.md) for details\. ``` cdk bootstrap @@ -276,7 +276,7 @@ You may incur AWS charges for what the AWS CDK stores in the bootstrapped resour Older versions of the bootstrap template created a Customer Master Key by default\. To avoid charges, re\-bootstrap using `--no-bootstrap-customer-key`\. **Note** -CDK Toolkit v2 does not support the original bootstrap template, dubbed the legacy template, used with CDK v1\. +CDK Toolkit v2 does not support the original bootstrap template, dubbed the legacy template, used by default with CDK v1\. **Important** The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. diff --git a/v2/environments.md b/v2/environments.md index a33400bd..686b57b0 100644 --- a/v2/environments.md +++ b/v2/environments.md @@ -3,7 +3,7 @@ Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and region into which the stack is intended to be deployed\. **Note** -For all but the simplest deployments, you will need to [bootstrap](bootstrapping.md) each environment you will deploy into\. Deployment requires certain AWS resources to be available, and these resources are provisioned by bootstrapping\. +You must [bootstrap](bootstrapping.md) each environment you will deploy CDK stacks into\. Bootstrapping provisions certain AWS resources that are used during deployment\. If you don't specify an environment when you instantiate a stack, the stack is said to be *environment\-agnostic*\. AWS CloudFormation templates synthesized from such a stack will try to use deploy\-time resolution on environment\-related attributes such as `stack.account`, `stack.region`, and `stack.availabilityZones` \(Python: `availability_zones`\)\. diff --git a/v2/getting_started.md b/v2/getting_started.md index dc79b35f..a0bc2d49 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -254,7 +254,7 @@ CDK Toolkit; v2 works with your existing CDK v1 projects\. However, it can't ini ## Bootstrapping -Many AWS CDK stacks that you write will include [assets](assets.md): external files that are deployed with the stack, such as AWS Lambda functions or Docker images\. The AWS CDK uploads these to an Amazon S3 bucket or other container so they are available to AWS CloudFormation during deployment\. Deployment requires that these containers already exist in the account and region you are deploying into\. Creating them is called [bootstrapping](bootstrapping.md)\. To bootstrap, issue: +Deploying stacks with the AWS CDK requires dedicated Amazon S3 buckets and other containers to be available to AWS CloudFormation during deployment\. Creating these is called [bootstrapping](bootstrapping.md)\. To bootstrap, issue: ``` cdk bootstrap aws://ACCOUNT-NUMBER/REGION diff --git a/v2/hello_world.md b/v2/hello_world.md index 549081e0..756eff8b 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -466,7 +466,7 @@ You may be curious about why we specified `RemovalPolicy` in our AWS CDK app but It's informative to compare the output of cdk synth here with the previous output and see the many additional lines of AWS CloudFormation template that the AWS CDK generated for us based on these relatively small changes\. **Important** -Since the `autoDeleteObjects` property is implemented using a AWS CloudFormation custom resource, which is implemented using an AWS Lambda function, our stack contains an [asset](assets.md)\. This fact requires that our AWS account and region be [bootstrapped](bootstrapping.md) so that there's an Amazon S3 bucket to hold the asset during deployment\. If you haven't already bootstrapped, issue: +All AWS CDK v2 deployments use dedicated AWS resources to hold data during deployment, so your AWS account and region must be [bootstrapped](bootstrapping.md) to create these resources before you can deploy\. If you haven't already bootstrapped, issue: ``` cdk bootstrap aws://ACCOUNT-NUMBER/REGION diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index b4256004..fbfad49d 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -346,11 +346,11 @@ If you see an error like this one: MyStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) ``` -AWS CDK v2 requires a new bootstrap stack, so you must re\-bootstrap your deployment environment\(s\)\. See [Bootstrapping](bootstrapping.md) for complete details\. +AWS CDK v2 requires an updated bootstrap stack, and furthermore, all v2 deployments require bootstrap resources \(v1 allowed you to deploy simple stacks without having bootstrapped\)\. See [Bootstrapping](bootstrapping.md) for complete details\. ## Finding v1 stacks -When working on migrating your CDK application from v1 to v2, you might want to identify the deployed AWS CloudFormation stacks that were created using v1\. To do this, run the following command: +When migrating your CDK application from v1 to v2, you might want to identify the deployed AWS CloudFormation stacks that were created using v1\. To do this, run the following command: ``` npx awscdk-v1-stack-finder diff --git a/v2/serverless_example.md b/v2/serverless_example.md index 101c4063..1576bfef 100644 --- a/v2/serverless_example.md +++ b/v2/serverless_example.md @@ -533,7 +533,7 @@ cdk synth ## Deploy and test the app -Before you can deploy your first AWS CDK app containing a lambda function, you must bootstrap your AWS environment\. This creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see [Bootstrapping your AWS environment](cli.md#cli-bootstrap)\. If you've already bootstrapped, you'll get a warning and nothing will change\. +Before you can deploy your first AWS CDK app, you must bootstrap your AWS environment\. This creates \(among other resources\) a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see [Bootstrapping your AWS environment](cli.md#cli-bootstrap)\. If you've already bootstrapped, you'll get a warning and nothing will change\. ``` cdk bootstrap aws://ACCOUNT-NUMBER/REGION diff --git a/v2/troubleshooting.md b/v2/troubleshooting.md index 35d7dc30..e6570f19 100644 --- a/v2/troubleshooting.md +++ b/v2/troubleshooting.md @@ -53,7 +53,7 @@ doskey cdk=npx aws-cdk $* \([back to list](#troubleshooting_top)\) **When deploying my AWS CDK stack, I receive a `NoSuchBucket` error** -Your AWS environment has not been bootstrapped, and so does not have an Amazon S3 bucket to hold resources during deployment\. Stacks require this bucket if they contain [Assets](assets.md) or synthesize to AWS CloudFormation templates larger than 50 kilobytes or if they contain assets such as Lambda function code or container images\. You can create the staging bucket with the following command: +Your AWS environment has not been bootstrapped, and so does not have an Amazon S3 bucket to hold resources during deployment\. You can create the staging bucket and other required resources with the following command: ``` cdk bootstrap aws://ACCOUNT-NUMBER/REGION From a27ffceace7c95d2887873e704e07481ac9ff4f6 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 25 Jul 2022 15:40:21 +0000 Subject: [PATCH 555/655] update mentions of AWS SSO to use entites for rebranding --- v1/getting_started.md | 2 +- v2/getting_started.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/getting_started.md b/v1/getting_started.md index b4e476a5..cc6a6b22 100644 --- a/v1/getting_started.md +++ b/v1/getting_started.md @@ -147,7 +147,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials **Note** Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. -AWS CDK does not natively support Single Sign\-On \(SSO\)\. To use SSO with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. +AWS CDK does not natively support AWS Single Sign\-On\. To use AWS SSO with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. diff --git a/v2/getting_started.md b/v2/getting_started.md index a0bc2d49..35e514c9 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -197,7 +197,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials **Note** Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. -AWS CDK does not natively support Single Sign\-On \(SSO\)\. To use SSO with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. +AWS CDK does not natively support AWS Single Sign\-On\. To use AWS SSO with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. From a9c7719bf5db95c4b45fee216e2a54a158ef5f95 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 26 Jul 2022 15:37:46 +0000 Subject: [PATCH 556/655] branding change for AWS SSO --- v1/getting_started.md | 2 +- v2/getting_started.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/getting_started.md b/v1/getting_started.md index cc6a6b22..77633cfb 100644 --- a/v1/getting_started.md +++ b/v1/getting_started.md @@ -147,7 +147,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials **Note** Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. -AWS CDK does not natively support AWS Single Sign\-On\. To use AWS SSO with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. +AWS CDK does not natively support AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. diff --git a/v2/getting_started.md b/v2/getting_started.md index 35e514c9..922e7197 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -197,7 +197,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials **Note** Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. -AWS CDK does not natively support AWS Single Sign\-On\. To use AWS SSO with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. +AWS CDK does not natively support AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. From b12e1feaeb019aae8cb43cf4c572b48d32896742 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 1 Aug 2022 17:28:16 +0000 Subject: [PATCH 557/655] updates to entities and add bootstrap stack 13 info --- v1/getting_started.md | 2 +- v1/home.md | 2 +- v1/index.md | 2 +- v1/sam.md | 2 +- v1/videos.md | 2 +- v1/work-with.md | 2 +- v2/bootstrapping.md | 3 ++- v2/getting_started.md | 2 +- v2/home.md | 2 +- v2/index.md | 2 +- v2/migrating-v2.md | 2 +- v2/sam.md | 2 +- v2/videos.md | 2 +- v2/work-with.md | 2 +- 14 files changed, 15 insertions(+), 14 deletions(-) diff --git a/v1/getting_started.md b/v1/getting_started.md index 77633cfb..b5ac653c 100644 --- a/v1/getting_started.md +++ b/v1/getting_started.md @@ -4,7 +4,7 @@ This topic introduces you to important AWS CDK concepts and describes how to ins ## Your background -The AWS Cloud Development Kit \(CDK\) lets you define your cloud infrastructure as code in one of its supported programming languages\. It is intended for moderately to highly experienced AWS users\. +The AWS Cloud Development Kit \(AWS CDK\) lets you define your cloud infrastructure as code in one of its supported programming languages\. It is intended for moderately to highly experienced AWS users\. Ideally, you already have experience with popular AWS services, particularly [AWS Identity and Access Management](https://aws.amazon.com/iam/) \(IAM\)\. You might already have AWS credentials on your workstation for use with an AWS SDK or the AWS CLI and experience working with AWS resources programmatically\. diff --git a/v1/home.md b/v1/home.md index 88a537b1..615c36fd 100644 --- a/v1/home.md +++ b/v1/home.md @@ -1,6 +1,6 @@ # What is the AWS CDK? -Welcome to the *AWS Cloud Development Kit \(CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. +Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. **Important** The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v1\. diff --git a/v1/index.md b/v1/index.md index 27c77013..69b24731 100644 --- a/v1/index.md +++ b/v1/index.md @@ -1,4 +1,4 @@ -# AWS Cloud Development Kit (CDK) v1 Developer Guide +# AWS Cloud Development Kit (AWS CDK) v1 Developer Guide ----- *****Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** diff --git a/v1/sam.md b/v1/sam.md index cebf3a74..e61e0367 100644 --- a/v1/sam.md +++ b/v1/sam.md @@ -1,3 +1,3 @@ # AWS SAM integration -The AWS CDK and the AWS Serverless Application Model \(AWS SAM\) can work together to let you to locally build and test serverless applications defined in the CDK\. For complete information, see [AWS Cloud Development Kit \(CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. \ No newline at end of file +The AWS CDK and the AWS Serverless Application Model \(AWS SAM\) can work together to let you to locally build and test serverless applications defined in the CDK\. For complete information, see [AWS Cloud Development Kit \(AWS CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. \ No newline at end of file diff --git a/v1/videos.md b/v1/videos.md index 795a00db..4912590d 100644 --- a/v1/videos.md +++ b/v1/videos.md @@ -7,7 +7,7 @@ Since the AWS CDK is always evolving, some of the code presented in these videos ## Infrastructure *is* Code with the AWS CDK -## Deep dive into AWS Cloud Development Kit \(CDK\) +## Deep dive into AWS Cloud Development Kit \(AWS CDK\) ## Contributing to the AWS Construct Library diff --git a/v1/work-with.md b/v1/work-with.md index 944e9e81..b5748cf7 100644 --- a/v1/work-with.md +++ b/v1/work-with.md @@ -1,6 +1,6 @@ # Working with the AWS CDK -The AWS Cloud Development Kit \(CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. +The AWS Cloud Development Kit \(AWS CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. **Note** This Guide does not currently include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index a06fe1c0..e83d795e 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -574,4 +574,5 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 9 | 2\.1\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | | 10 | 2\.4\.0 | ECR ScanOnPush is now enabled by default\. | | 11 | 2\.18\.0 | Adds policy allowing Lambda to pull from Amazon ECR repos so it survives rebootstrapping\. | -| 12 | 2\.20\.0 | Adds support for experimental cdk import\. | \ No newline at end of file +| 12 | 2\.20\.0 | Adds support for experimental cdk import\. | +| 13 | 2\.25\.0 | Makes container images in bootstrap\-created Amazon ECR repositories immutable\. | \ No newline at end of file diff --git a/v2/getting_started.md b/v2/getting_started.md index 922e7197..bcf4e433 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -4,7 +4,7 @@ This topic introduces you to important AWS CDK concepts and describes how to ins ## Your background -The AWS Cloud Development Kit \(CDK\) lets you define your cloud infrastructure as code in one of its supported programming languages\. It is intended for moderately to highly experienced AWS users\. +The AWS Cloud Development Kit \(AWS CDK\) lets you define your cloud infrastructure as code in one of its supported programming languages\. It is intended for moderately to highly experienced AWS users\. Ideally, you already have experience with popular AWS services, particularly [AWS Identity and Access Management](https://aws.amazon.com/iam/) \(IAM\)\. You might already have AWS credentials on your workstation for use with an AWS SDK or the AWS CLI and experience working with AWS resources programmatically\. diff --git a/v2/home.md b/v2/home.md index 50167436..6998e83e 100644 --- a/v2/home.md +++ b/v2/home.md @@ -1,6 +1,6 @@ # What is the AWS CDK? -Welcome to the *AWS Cloud Development Kit \(CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. +Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. **Note** The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v2\. CDK v1 entered maintenance on June 1, 2022\. diff --git a/v2/index.md b/v2/index.md index 39268528..064acd35 100644 --- a/v2/index.md +++ b/v2/index.md @@ -1,4 +1,4 @@ -# AWS Cloud Development Kit (CDK) v2 Developer Guide +# AWS Cloud Development Kit (AWS CDK) v2 Developer Guide ----- *****Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index fbfad49d..99db546c 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -1,6 +1,6 @@ # Migrating to AWS CDK v2 -Version 2 of the AWS Cloud Development Kit \(CDK\) is designed to make writing infrastructure as code in your preferred programming language even easier\. +Version 2 of the AWS Cloud Development Kit \(AWS CDK\) is designed to make writing infrastructure as code in your preferred programming language even easier\. The main changes from AWS CDK v1 to CDK v2 are as follows\. + AWS CDK v2 consolidates the stable parts of the AWS Construct Library, including the core library, into a single package, `aws-cdk-lib`\. Developers no longer need to install additional packages for the individual AWS services they use\. This single\-package approach also eliminates the need to synchronize the versions of the various CDK library packages\. diff --git a/v2/sam.md b/v2/sam.md index cebf3a74..e61e0367 100644 --- a/v2/sam.md +++ b/v2/sam.md @@ -1,3 +1,3 @@ # AWS SAM integration -The AWS CDK and the AWS Serverless Application Model \(AWS SAM\) can work together to let you to locally build and test serverless applications defined in the CDK\. For complete information, see [AWS Cloud Development Kit \(CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. \ No newline at end of file +The AWS CDK and the AWS Serverless Application Model \(AWS SAM\) can work together to let you to locally build and test serverless applications defined in the CDK\. For complete information, see [AWS Cloud Development Kit \(AWS CDK\)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) in the AWS SAM Developer Guide\. To install the SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\. \ No newline at end of file diff --git a/v2/videos.md b/v2/videos.md index 3735eda2..61b0dd42 100644 --- a/v2/videos.md +++ b/v2/videos.md @@ -7,7 +7,7 @@ Since the AWS CDK is always evolving, some of the code presented in these videos ## Infrastructure *is* Code with the AWS CDK -## Deep dive into AWS Cloud Development Kit \(CDK\) +## Deep dive into AWS Cloud Development Kit \(AWS CDK\) ## Contributing to the AWS Construct Library diff --git a/v2/work-with.md b/v2/work-with.md index f0202de6..d3274b13 100644 --- a/v2/work-with.md +++ b/v2/work-with.md @@ -1,6 +1,6 @@ # Working with the AWS CDK -The AWS Cloud Development Kit \(CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. +The AWS Cloud Development Kit \(AWS CDK\) lets you define your AWS cloud infrastructure in a general\-purpose programming language\. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C\#, and Go\. It is also possible to use other JVM and \.NET languages, though we are unable to provide support for every such language\. **Note** This Guide does not currently include instructions or code examples for Go aside from [Working with the AWS CDK in Go](work-with-cdk-go.md)\. From bb6b8c91bd7ec345734abec83764ded68f8a3d39 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 8 Aug 2022 19:54:36 +0000 Subject: [PATCH 558/655] don't mention parameters since CDK v2 uses known names for bootstrap resources --- v2/assets.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/v2/assets.md b/v2/assets.md index 3cd8f188..53bda1cc 100644 --- a/v2/assets.md +++ b/v2/assets.md @@ -10,11 +10,9 @@ When you refer to an asset in your app, the [cloud assembly](apps.md#apps_cloud_ The AWS CDK generates a source hash for assets, which can be used at construction time to determine whether the contents of an asset have changed\. -By default, the AWS CDK creates a copy of the asset in the cloud assembly directory, which defaults to `cdk.out`, under the source hash\. This is so that the cloud assembly is self\-contained and moved over to a different host for deployment\. See [Cloud assemblies](apps.md#apps_cloud_assembly) for details\. +By default, the AWS CDK creates a copy of the asset in the cloud assembly directory, which defaults to `cdk.out`, under the source hash\. This way, the cloud assembly is self\-contained, so if it moved over to a different host for deployment, it can still be deployed\. See [Cloud assemblies](apps.md#apps_cloud_assembly) for details\. -The AWS CDK also synthesizes AWS CloudFormation parameters that the AWS CDK CLI specifies during deployment\. The AWS CDK uses those parameters to refer to the deploy\-time values of the asset\. - -When the AWS CDK deploys an app that references assets \(either directly by the app code or through a library\), the AWS CDK CLI first prepares and publishes them to Amazon S3 or Amazon ECR, and only then deploys the stack\. The AWS CDK specifies the locations of the published assets as AWS CloudFormation parameters to the relevant stacks, and uses that information to enable referencing these locations within an AWS CDK app\. +When the AWS CDK deploys an app that references assets \(either directly by the app code or through a library\), the AWS CDK CLI first prepares and publishes the assets to an Amazon S3 bucket or Amazon ECR repository, which was created during bootstrapping\. Only then are the resources defined in the stack deployed\. This section describes the low\-level APIs available in the framework\. From 1d9685a95e6ffc189d89c8343cdc6ab31ca5742c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 11 Aug 2022 03:12:14 +0000 Subject: [PATCH 559/655] update PGP keys --- v1/pgp-keys.md | 211 ++++++++++++++++++++++++++++++++++++++++++++++++- v2/pgp-keys.md | 211 ++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 414 insertions(+), 8 deletions(-) diff --git a/v1/pgp-keys.md b/v1/pgp-keys.md index 333f8d9d..1ce1bbf1 100644 --- a/v1/pgp-keys.md +++ b/v1/pgp-keys.md @@ -1,8 +1,211 @@ -# OpenPGP keys for the AWS CDK and JSII +# OpenPGP keys for the AWS CDK and jsii -This topic contains the OpenPGP keys for the AWS CDK and JSII\. +This topic contains current and historical OpenPGP keys for the AWS CDK and jsii\. -## AWS CDK OpenPGP key +## Current keys + +These keys should be used to validate current releases of the AWS CDK and jsii\. + +### AWS CDK OpenPGP key + + +| | | +| --- |--- | +| Key ID: | 0x42B9CF2286CD987A | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2022\-07\-05 | +| Expires: | 2026\-07\-04 | +| User ID: | AWS Cloud Development Kit | +| Key fingerprint: | 69B5 2D5B A295 1D11 FA65 413B 42B9 CF22 86CD 987A | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGLEgOsBEADCoAMwvnszMLybJ+AD9cHhVyX6+rYIUEXYSgVnfkl6Z7qawIwv +wgd/a5fEs9Kiz2XJmfwS9Rxb4d+0+Y1ls1A+gnpw9FMLcZlqkC9KLnS2MqvuXWLB +t3z4kjZaL9fQ+58PoD4gy/M2hDg6gZrYqR3gtJuw8FcFpb/1KlkzRQUM8eAMFxf2 +TyfjP0V0tSHwcB+84oushX7fUXVMyc3+OHsCPOe/WBFMIlWgKA+n33JKIQlUUC8f +kCWBAsAFupil0lCveT6mZu5slNRlc1I3iBLjUZ3/MtLygfqAMKwUVXeawtDvRIZe +PrAFc2NyODEhly2JG6K0FW7eIcvBqR3rg8U49t9Y74ELTM0kKnfd+flvq35xWqQC +0zghnk3kDppRTN4zWBgTKiCMxBcsHXGOoGn57t4B9VY9Zy3vkeySigeiwl/Tw9nJ +PE0SRnwEc/HnjTTfX+GTG1aQVE0xSVyZ4m5ymRNCu6+rNH8lKwo5FujlXJ+GXPkp +qT+Lx6Ix/Ny7PaoweWxwtZUkLRS4pWUsg0yotZrGyIbS+X3yMEG8WBTFI9hf6HTq +0ryfi5/TsBrdrGKqWB99EC9xYEGgtHp4fKO5X0ynOagVOhf0jSe8t1uyuJPGb2Gc +MQagSys5xMhdG/ZnEY4Cb+JDtH/4jc3tca0+4Z5RQ7kF9IhCncFtrbjJbwARAQAB +tC5BV1MgQ2xvdWQgRGV2ZWxvcG1lbnQgS2l0IDxhd3MtY2RrQGFtYXpvbi5jb20+ +iQI/BBMBAgApBQJixIDrAhsvBQkHhM4ABwsJCAcDAgEGFQgCCQoLBBYCAwECHgEC +F4AACgkQQrnPIobNmHo2qg//Zt9p/kN1DevflzxWKouUX0AS7UmUtRYXu5k/EEbu +wkYNHpUr7+lZ+Me5YyjcIpt6UwuG9cW4SvwuxIfXucyKAWiwEbydCQauvnrYDxDa +J6Yr/ntk7Sii6An9re99qic3IsvX+xlUXh+qJ/34ooP/1PHziCMqykvW/DwAIyhx +2qvTXy+9+OlOWSUbhkCnNz5XKb4XQGq73DqalZX1nH4dG6fckZmYRX+dpw2njfTw +ZLdZ7bkrfiL84FI4A21RfSbEU4s4ngiV17lZ9ivilBKTbDv3da7+yc919M7C5N4J +yrlxvtyYNDoqKAD2WYZAnpEbG/shu3f56RyOJd56tXGwl9nKPh+F9y+379XthSwA +xZTURFtjWf7wWHaDZadU0DKi+Oeeszjg2f/VJaGmmS8PIg7q6GiSHHpqHqNvACHm +ZXMw12QFd3qt3xu0JMmE11ZC5VBgblwpkQTrO04Sq1rOpJwXI9ODMS/ZEhAIoYmT +OR7ouknlAx6mj9fwpavWDAAJHLdVUMYBZTXiQYFzDvx51ivvTRWkB1zTJcFdqShY +B37+Jz2jLDNdMrcHk2yfVp/VvfbxKcexg8wEwrrtQUslTUenl5jBZJouoz/wW81s +Y4U1nCPCdTK5/C7JCKzR2gVnCpe6uaxAWkkM2feQhjqJZkTC4cFVgBT+4M6WcT1r +yq4= +=ahbs +-----END PGP PUBLIC KEY BLOCK----- +``` + +### jsii OpenPGP key + + +| | | +| --- |--- | +| Key ID: | 0x056C4E15DAE3D8D9 | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2022\-07\-05 | +| Expires: | 2026\-07\-04 | +| User ID: | AWS JSII Team | +| Key fingerprint: | 1E07 31D4 57E5 FE87 87E5 530A 056C 4E15 DAE3 D8D9 | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGLEgOkBEAD27EPVG9g2mHQ3+M6tF6le+tfhARJ2EV7m7NKIrTdSlCZATLWn +AVLlxG1unW34NlkKZbcbR86gAxRnnAhuEhPuloU/S5wAqPGbRiFl58YjYZDNJw6U +1SSMpE4O1sfjxv9yAbiRihLYtvksyHHZmaDhYner2aK1PdeWu+BKq/tjfm3Yzsd2 +uuVEduJ72YoQk/29dEiGOHfT+2kUKxUX+0tJSJ9MGlEf4NtQE4WLzrT6Xqb2SG4+ +alIiIVxIEi0XKDn7n8ZLjFwfJwOYxVYLtEUkqFWM8e8vgoc9/nYc+vDXZVED2g3Z +FWrwSnDSXbQpnMa2cLhD4xLpDHUS3i2p7r3dkJQGLo/5JGOopLibrOAbYZ72izhu +H/TuPFogSz0mNFPglrWdnLF04UIjIq420+06V4WQZC9n55Zjcbki/OhnC3B9pAdU +tiy8zg070bWq45dPGf5STkPPn7G8A2zmKefyO51iLIi26ZzW78siB+FvcGRhdg25 +39sHJ1cmrTeC+B+k4KeV5sQ/m3UucimrZnk1xdaiVp8mWzRqWb8bB6Rs8K9RMrMV +tFBOKOBAT2QxOQtRGAantVgm193E1T1cmNpD0FKAKkDdPs64rKBEwFiHxccXHbah +eMd1weVwn3AKFD6uAm8ZRMV+dyssfcQxqpo/kfT1XpA6cQeOmGDOcKBfdwARAQAB +tCNBV1MgSlNJSSBUZWFtIDxhd3MtanNpaUBhbWF6b24uY29tPokCPwQTAQIAKQUC +YsSA6QIbLwUJB4TOAAcLCQgHAwIBBhUIAgkKCwQWAgMBAh4BAheAAAoJEAVsThXa +49jZjU4QANoyqOJUT4gRrXshE3N0mW5Ad4i8Ke09GA62HyvTtfbsA+2nkNVGJpXm +sFMzdaFO95Q65RkLS9vW4nhhjXBEc2XYNCt2AnARudA/41ykjDPwU112z9ZTB9he +y4ItIeNGpHvMWr51fihl0y2nkpODOBeiv44jscLbHyOmZfki1f5fuIu2U2IbUGK3 +5FtYyeHcgRHnpYkzLuzK4PfayOywqQPJ7M9DWrHf+v5Cu4ZCZDOIKfzF+ew7MWwc +6KaoWHCYbFpX8jxFppbGsSFOQ8Sl2quoP0TLz9Wsq70Khi6C2P8JI6lm0HRLO+1M +jFbQxNOwAcN3k4HSwunAjXBlmT/6oc1RsdBdpXBaZ2AWseIXwSYZqNXp+5L179uZ +vSiD3DSSUqLJbdQRVOsJi3/87V5QU59byq2dToHveRjtSbVnK0TkTx9ZlgkcpjvM +BwHNqWhratV6af2Upjq2YQ0fdSB42f3pgopInxNJPMvlAb+cCfr0Pfwu7ge7UooQ +WHTxbpCvwtn/HNctMGpWscO02WsWgoYVjnVFay/XphE77pQ9rRUkhMe6VKXfxj/n +OCZJKrydluIIwR8vvONNqO+QwZ1xDEhO7MaSZlOm1AuUZIXFPgaWQkPZHKiiwFA/ +QWnL/+shuRtMH2geTjkev198Jgb5HyXFm4SyYtZferQROyliEhik +=BuGv +-----END PGP PUBLIC KEY BLOCK----- +``` + +## Historical keys + +These keys may be used to validate releases of the AWS CDK and jsii before 2022\-07\-05\. + +**Important** +New keys are created before the previous one has expired\. As a result, at any given moment in time, more than one key may be valid\. Keys are used to sign artifacts starting the day they are created, so use the more recently\-issued key where keys' validity overlaps\. + +### AWS CDK OpenPGP key \(2022\-04\-07\) + +**Note** +This key was not used to sign AWS CDK artifacts after 2022\-07\-05\. + + +| | | +| --- |--- | +| Key ID: | 0x015584281F44A3C3 | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2022\-04\-07 | +| Expires: | 2026\-04\-06 | +| User ID: | AWS Cloud Development Kit | +| Key fingerprint: | EAE1 1A24 82B0 AA86 456E 6C67 0155 8428 1F44 A3C3 | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGJPLgUBEADtlR5jQtxtBmROQvmWlPOViqqnJNhk0dULc3tXnq8NS/l6X81r +wHk+/CHG5kBunwvM0qaqLFRC6z9NnnNDxEHcTi47n+OAjWyDM6unxxWOPz8Dfaps +Uq/ZWa4by292ZeqRC9Ir2wdrizb69JbRjeshBwlJDAS/qtqCAqBRH/f7Zw7QSD6/ +XTxyIy+KOVjZwFPFNHMRQ/NmgUc/Rfxsa0pUjk1YAj/AkvQlwwD8DEnASoBhO0DP +QonZxouLqIpgp4LsGo8TZdQv30ocIj0C9DuYUiUXWlCPlYPgDj6IWf3rgpMQ6nB9 +wC9lx4t/L3Zg1HUD52y8aymndmbdHVn90mzlNg4XWyc58rioYrEk57YwbDnea/Kk +Hv4kVHZRfJ4/OFPyqs5ex1X3X6rb07VvA1tfLgPywO9XF2Xws8YWOWcEobaWTcnb +AzyVC6wKya8rEQzxkYJ6UkJlhDB6g6bZwIpsI2zlimG+kSBsyFvE2oRYMS0cXPqU +o+tX0+4TvxEyW3RrUQzQHIpqXrb0X1Q8Z2idPn5dwsipDEa4gsFXtrSXmbB/0Cee +eJVvKWQAsxol3+NE9L/yozq3cz5PWh0SSbmCLRcs78lMJ23MmzbMWV7BWC9DXdY+ +TywY5IkDUPjGCKlD8VlrI3TgC222bH6qaua6LYCiTtRtvpDYuJNAlUjhawARAQAB +tC5BV1MgQ2xvdWQgRGV2ZWxvcG1lbnQgS2l0IDxhd3MtY2RrQGFtYXpvbi5jb20+ +iQI/BBMBAgApBQJiTy4FAhsvBQkHhM4ABwsJCAcDAgEGFQgCCQoLBBYCAwECHgEC +F4AACgkQAVWEKB9Eo8NpbxAAiBF0kR/lVw3vuam60mk4l0iGMVsP8Xq6g/buzbEO +2MEB4Ftk04qOnoa+93S0ZiLR9PqxrwsGSp4ADDX3Vtc4uxwzUlKUi1ywEhQ1cwyL +YHQI3Hd75K1J81ozMEu6qJH+yF0TtTDZMeZHtH/XvuIYJW3Lx4o5ZFlsEegFPAgX +YCCpUS+k9qC6M8g2VjcltQJpyjGswsKm6FWaKHW+B9dfjdOHlImB9E2jaknJ8eoY +zb9zHgFANluMzpZ6rYVSiCuXiEgYmazQWCvlPcMOP7nX+1hq1z11LMqeSnfE09gX +H+OYho9cMEJkb1dzx1H9MRpylFIn9tL+2iCp4UPJjnqi6uawWyLZ2tp4G11haqQq +1yAh69u233I8GZKFUySzjHwH5qWGRgBTjrZ6FdcjSS2w/wMkVKuCPkWtdvo/TJrm +msCd1Reye8SEKYqrs0ujTwmlvWmUZmO06AdUjo1kWiBKeslTJrWEuG7Yk4pFOoA4 +dsaq83gxpOJNVCh6M3y4DLNrvl7dhF95NwTWMROPj2otw7NIjF4/cdzve2+P7YNN +pVAtyCtTJdD3eZbQPVaL3T8cf1VGqt6++pnLGnWJ0+X3TyvfmTohdJvN3TE+tq7A +7cprDX/q9c56HaXdJzVpxEzuf/YC+JuYKeHwsX3QouDhyRg3PsigdZES/02Wr8so +l6U= +=MQI4 +-----END PGP PUBLIC KEY BLOCK----- +``` + +### jsii OpenPGP key \(2022\-04\-07\) + +**Note** +This key was not used to sign jsii artifacts after 2022\-07\-05\. + + +| | | +| --- |--- | +| Key ID: | 0x985F5BC974B79356 | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2022\-04\-07 | +| Expires: | 2026\-04\-06 | +| User ID: | AWS JSII Team | +| Key fingerprint: | 35A7 1785 8FA6 282D C5AC CD95 985F 5BC9 74B7 9356 | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGJPLewBEADHH4TXup/gOlHrKDZRbj8MvsMTdM6eDteA6/c32UYV/YsK9rDA +jN8Jv/xlfosOebcHrfnFpHF9VTkmjuOpN695XdwMrW/NvlEPISTGEJf21x6ZTQ2r +1xWFYzC3sl3FZmvj9XAXTmygdv+XM3TqsFgZeCaBkZVdiLbQf+FhYrovUlgotb5D +YiCQI3ofV5QTE+141jhO5Pkd3ZIoBG+P826LaT8NXhwS0o1XqVk39DCZNoFshNmR +WFZpkVCTHyv5ZhVey1NWXnD8opO375htGNV4AeSmSIH9YkURD1g5F+2t7RiosKFo +kJrfPmUjhHn8IFpReGc8qmMMZX0WaV3t+VAWfOHGGyrXDfQ4xz1VCot75C2+qypM ++qhwOAOOP0zA7CfI96ULZzSH/j8HuQk3O0DsUCybpMuKEazEMxP3tgGtRerwDaFG +jQvAlK8Rbq3v8buBI6YJuXTwSzJE8KLjleUiTFumE6WP4rsAvlP/5rBvubeMfa3n +NIMm5Rkl36Z+jt3e2Z2ZqWDPpBRta8m7QHccrZhkvqu3YC3Gl6kdnm4Vio3Xfpg2 +qtWhIQutQ6DmItewV+weQHas3hl88RPJtSrfWWIIMkpbF7Y4vbX9xcnsYCLlp2Mz +tWbbnU+EWATNSsufml/Kdnu9iEEuLmeovE11I69nwjNOq9P+GJ3r/FUb2wARAQAB +tCNBV1MgSlNJSSBUZWFtIDxhd3MtanNpaUBhbWF6b24uY29tPokCPwQTAQIAKQUC +Yk8t7AIbLwUJB4TOAAcLCQgHAwIBBhUIAgkKCwQWAgMBAh4BAheAAAoJEJhfW8l0 +t5NWo64P/2y7gcMRylLLW/wbrCjton2O4+YRocwQxKm1cBml9FVDUR5967YczNuu +EwEOfH/Pu3UAlrBfKAfxPNhKchLwYiOBNh2Wk5UUxRcldNHTLb5jn5gxCeWNAsl/ +Tc46qY+ObdBMdOf2Vu33UCOg83WLbg1bfBoA8Bm1cd0XObtLGucu606EBt1dBrKq +9UTcbJfuGivY2Xjy5r4kEiMHBoLKcFrSo2Mm7VtYlE4Mabjyj9+orqUio7qxOl60 +aa7Psa6rMvs1Ip9IOrAdG7o5Y29tQpeINH0R1/u47BrlTEAgG63Dfy49w2h/1g0G +c9KPXVuN55OWRIu0hsiySDMk/2ERsF348TU3NURZltnCOxp6pHlbPJIxRVTNa9Cn +f8tbLB3y3HfA80516g+qwNYIYiqksDdV2bz+VbvmCWcO+FellDZli831gyMGa5JJ +rq7d0lEr6nqjcnKiVwItTQXyFYmKTAXweQtVC72g1sd3oZIyqa7T8pvhWpKXxoJV +WP+OPBhGg/JEVC9sguhuv53tzVwayrNwb54JxJsD2nemfhQm1Wyvb2bPTEaJ3mrv +mhPUvXZj/I9rgsEq3L/sm2Xjy09nra4o3oe3bhEL8nOj11wkIodi17VaGP0y+H3s +I5zB5UztS6dy+cH+J7DoRaxzVzq7qtH/ZY2quClt30wwqDHUX1ef +=+iYX +-----END PGP PUBLIC KEY BLOCK----- +``` + +### AWS CDK OpenPGP key \(2018\-06\-19\) | | | @@ -48,7 +251,7 @@ EkSlc/RoDqZCpBGgcoy1FFWvV/ZLgNU6OTQlYH6oYOWiylSJnaTDyurrktsxJI6d -----END PGP PUBLIC KEY BLOCK----- ``` -## JSII OpenPGP key +### jsii OpenPGP key \(2018\-08\-06\) | | | diff --git a/v2/pgp-keys.md b/v2/pgp-keys.md index 333f8d9d..1ce1bbf1 100644 --- a/v2/pgp-keys.md +++ b/v2/pgp-keys.md @@ -1,8 +1,211 @@ -# OpenPGP keys for the AWS CDK and JSII +# OpenPGP keys for the AWS CDK and jsii -This topic contains the OpenPGP keys for the AWS CDK and JSII\. +This topic contains current and historical OpenPGP keys for the AWS CDK and jsii\. -## AWS CDK OpenPGP key +## Current keys + +These keys should be used to validate current releases of the AWS CDK and jsii\. + +### AWS CDK OpenPGP key + + +| | | +| --- |--- | +| Key ID: | 0x42B9CF2286CD987A | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2022\-07\-05 | +| Expires: | 2026\-07\-04 | +| User ID: | AWS Cloud Development Kit | +| Key fingerprint: | 69B5 2D5B A295 1D11 FA65 413B 42B9 CF22 86CD 987A | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGLEgOsBEADCoAMwvnszMLybJ+AD9cHhVyX6+rYIUEXYSgVnfkl6Z7qawIwv +wgd/a5fEs9Kiz2XJmfwS9Rxb4d+0+Y1ls1A+gnpw9FMLcZlqkC9KLnS2MqvuXWLB +t3z4kjZaL9fQ+58PoD4gy/M2hDg6gZrYqR3gtJuw8FcFpb/1KlkzRQUM8eAMFxf2 +TyfjP0V0tSHwcB+84oushX7fUXVMyc3+OHsCPOe/WBFMIlWgKA+n33JKIQlUUC8f +kCWBAsAFupil0lCveT6mZu5slNRlc1I3iBLjUZ3/MtLygfqAMKwUVXeawtDvRIZe +PrAFc2NyODEhly2JG6K0FW7eIcvBqR3rg8U49t9Y74ELTM0kKnfd+flvq35xWqQC +0zghnk3kDppRTN4zWBgTKiCMxBcsHXGOoGn57t4B9VY9Zy3vkeySigeiwl/Tw9nJ +PE0SRnwEc/HnjTTfX+GTG1aQVE0xSVyZ4m5ymRNCu6+rNH8lKwo5FujlXJ+GXPkp +qT+Lx6Ix/Ny7PaoweWxwtZUkLRS4pWUsg0yotZrGyIbS+X3yMEG8WBTFI9hf6HTq +0ryfi5/TsBrdrGKqWB99EC9xYEGgtHp4fKO5X0ynOagVOhf0jSe8t1uyuJPGb2Gc +MQagSys5xMhdG/ZnEY4Cb+JDtH/4jc3tca0+4Z5RQ7kF9IhCncFtrbjJbwARAQAB +tC5BV1MgQ2xvdWQgRGV2ZWxvcG1lbnQgS2l0IDxhd3MtY2RrQGFtYXpvbi5jb20+ +iQI/BBMBAgApBQJixIDrAhsvBQkHhM4ABwsJCAcDAgEGFQgCCQoLBBYCAwECHgEC +F4AACgkQQrnPIobNmHo2qg//Zt9p/kN1DevflzxWKouUX0AS7UmUtRYXu5k/EEbu +wkYNHpUr7+lZ+Me5YyjcIpt6UwuG9cW4SvwuxIfXucyKAWiwEbydCQauvnrYDxDa +J6Yr/ntk7Sii6An9re99qic3IsvX+xlUXh+qJ/34ooP/1PHziCMqykvW/DwAIyhx +2qvTXy+9+OlOWSUbhkCnNz5XKb4XQGq73DqalZX1nH4dG6fckZmYRX+dpw2njfTw +ZLdZ7bkrfiL84FI4A21RfSbEU4s4ngiV17lZ9ivilBKTbDv3da7+yc919M7C5N4J +yrlxvtyYNDoqKAD2WYZAnpEbG/shu3f56RyOJd56tXGwl9nKPh+F9y+379XthSwA +xZTURFtjWf7wWHaDZadU0DKi+Oeeszjg2f/VJaGmmS8PIg7q6GiSHHpqHqNvACHm +ZXMw12QFd3qt3xu0JMmE11ZC5VBgblwpkQTrO04Sq1rOpJwXI9ODMS/ZEhAIoYmT +OR7ouknlAx6mj9fwpavWDAAJHLdVUMYBZTXiQYFzDvx51ivvTRWkB1zTJcFdqShY +B37+Jz2jLDNdMrcHk2yfVp/VvfbxKcexg8wEwrrtQUslTUenl5jBZJouoz/wW81s +Y4U1nCPCdTK5/C7JCKzR2gVnCpe6uaxAWkkM2feQhjqJZkTC4cFVgBT+4M6WcT1r +yq4= +=ahbs +-----END PGP PUBLIC KEY BLOCK----- +``` + +### jsii OpenPGP key + + +| | | +| --- |--- | +| Key ID: | 0x056C4E15DAE3D8D9 | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2022\-07\-05 | +| Expires: | 2026\-07\-04 | +| User ID: | AWS JSII Team | +| Key fingerprint: | 1E07 31D4 57E5 FE87 87E5 530A 056C 4E15 DAE3 D8D9 | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGLEgOkBEAD27EPVG9g2mHQ3+M6tF6le+tfhARJ2EV7m7NKIrTdSlCZATLWn +AVLlxG1unW34NlkKZbcbR86gAxRnnAhuEhPuloU/S5wAqPGbRiFl58YjYZDNJw6U +1SSMpE4O1sfjxv9yAbiRihLYtvksyHHZmaDhYner2aK1PdeWu+BKq/tjfm3Yzsd2 +uuVEduJ72YoQk/29dEiGOHfT+2kUKxUX+0tJSJ9MGlEf4NtQE4WLzrT6Xqb2SG4+ +alIiIVxIEi0XKDn7n8ZLjFwfJwOYxVYLtEUkqFWM8e8vgoc9/nYc+vDXZVED2g3Z +FWrwSnDSXbQpnMa2cLhD4xLpDHUS3i2p7r3dkJQGLo/5JGOopLibrOAbYZ72izhu +H/TuPFogSz0mNFPglrWdnLF04UIjIq420+06V4WQZC9n55Zjcbki/OhnC3B9pAdU +tiy8zg070bWq45dPGf5STkPPn7G8A2zmKefyO51iLIi26ZzW78siB+FvcGRhdg25 +39sHJ1cmrTeC+B+k4KeV5sQ/m3UucimrZnk1xdaiVp8mWzRqWb8bB6Rs8K9RMrMV +tFBOKOBAT2QxOQtRGAantVgm193E1T1cmNpD0FKAKkDdPs64rKBEwFiHxccXHbah +eMd1weVwn3AKFD6uAm8ZRMV+dyssfcQxqpo/kfT1XpA6cQeOmGDOcKBfdwARAQAB +tCNBV1MgSlNJSSBUZWFtIDxhd3MtanNpaUBhbWF6b24uY29tPokCPwQTAQIAKQUC +YsSA6QIbLwUJB4TOAAcLCQgHAwIBBhUIAgkKCwQWAgMBAh4BAheAAAoJEAVsThXa +49jZjU4QANoyqOJUT4gRrXshE3N0mW5Ad4i8Ke09GA62HyvTtfbsA+2nkNVGJpXm +sFMzdaFO95Q65RkLS9vW4nhhjXBEc2XYNCt2AnARudA/41ykjDPwU112z9ZTB9he +y4ItIeNGpHvMWr51fihl0y2nkpODOBeiv44jscLbHyOmZfki1f5fuIu2U2IbUGK3 +5FtYyeHcgRHnpYkzLuzK4PfayOywqQPJ7M9DWrHf+v5Cu4ZCZDOIKfzF+ew7MWwc +6KaoWHCYbFpX8jxFppbGsSFOQ8Sl2quoP0TLz9Wsq70Khi6C2P8JI6lm0HRLO+1M +jFbQxNOwAcN3k4HSwunAjXBlmT/6oc1RsdBdpXBaZ2AWseIXwSYZqNXp+5L179uZ +vSiD3DSSUqLJbdQRVOsJi3/87V5QU59byq2dToHveRjtSbVnK0TkTx9ZlgkcpjvM +BwHNqWhratV6af2Upjq2YQ0fdSB42f3pgopInxNJPMvlAb+cCfr0Pfwu7ge7UooQ +WHTxbpCvwtn/HNctMGpWscO02WsWgoYVjnVFay/XphE77pQ9rRUkhMe6VKXfxj/n +OCZJKrydluIIwR8vvONNqO+QwZ1xDEhO7MaSZlOm1AuUZIXFPgaWQkPZHKiiwFA/ +QWnL/+shuRtMH2geTjkev198Jgb5HyXFm4SyYtZferQROyliEhik +=BuGv +-----END PGP PUBLIC KEY BLOCK----- +``` + +## Historical keys + +These keys may be used to validate releases of the AWS CDK and jsii before 2022\-07\-05\. + +**Important** +New keys are created before the previous one has expired\. As a result, at any given moment in time, more than one key may be valid\. Keys are used to sign artifacts starting the day they are created, so use the more recently\-issued key where keys' validity overlaps\. + +### AWS CDK OpenPGP key \(2022\-04\-07\) + +**Note** +This key was not used to sign AWS CDK artifacts after 2022\-07\-05\. + + +| | | +| --- |--- | +| Key ID: | 0x015584281F44A3C3 | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2022\-04\-07 | +| Expires: | 2026\-04\-06 | +| User ID: | AWS Cloud Development Kit | +| Key fingerprint: | EAE1 1A24 82B0 AA86 456E 6C67 0155 8428 1F44 A3C3 | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGJPLgUBEADtlR5jQtxtBmROQvmWlPOViqqnJNhk0dULc3tXnq8NS/l6X81r +wHk+/CHG5kBunwvM0qaqLFRC6z9NnnNDxEHcTi47n+OAjWyDM6unxxWOPz8Dfaps +Uq/ZWa4by292ZeqRC9Ir2wdrizb69JbRjeshBwlJDAS/qtqCAqBRH/f7Zw7QSD6/ +XTxyIy+KOVjZwFPFNHMRQ/NmgUc/Rfxsa0pUjk1YAj/AkvQlwwD8DEnASoBhO0DP +QonZxouLqIpgp4LsGo8TZdQv30ocIj0C9DuYUiUXWlCPlYPgDj6IWf3rgpMQ6nB9 +wC9lx4t/L3Zg1HUD52y8aymndmbdHVn90mzlNg4XWyc58rioYrEk57YwbDnea/Kk +Hv4kVHZRfJ4/OFPyqs5ex1X3X6rb07VvA1tfLgPywO9XF2Xws8YWOWcEobaWTcnb +AzyVC6wKya8rEQzxkYJ6UkJlhDB6g6bZwIpsI2zlimG+kSBsyFvE2oRYMS0cXPqU +o+tX0+4TvxEyW3RrUQzQHIpqXrb0X1Q8Z2idPn5dwsipDEa4gsFXtrSXmbB/0Cee +eJVvKWQAsxol3+NE9L/yozq3cz5PWh0SSbmCLRcs78lMJ23MmzbMWV7BWC9DXdY+ +TywY5IkDUPjGCKlD8VlrI3TgC222bH6qaua6LYCiTtRtvpDYuJNAlUjhawARAQAB +tC5BV1MgQ2xvdWQgRGV2ZWxvcG1lbnQgS2l0IDxhd3MtY2RrQGFtYXpvbi5jb20+ +iQI/BBMBAgApBQJiTy4FAhsvBQkHhM4ABwsJCAcDAgEGFQgCCQoLBBYCAwECHgEC +F4AACgkQAVWEKB9Eo8NpbxAAiBF0kR/lVw3vuam60mk4l0iGMVsP8Xq6g/buzbEO +2MEB4Ftk04qOnoa+93S0ZiLR9PqxrwsGSp4ADDX3Vtc4uxwzUlKUi1ywEhQ1cwyL +YHQI3Hd75K1J81ozMEu6qJH+yF0TtTDZMeZHtH/XvuIYJW3Lx4o5ZFlsEegFPAgX +YCCpUS+k9qC6M8g2VjcltQJpyjGswsKm6FWaKHW+B9dfjdOHlImB9E2jaknJ8eoY +zb9zHgFANluMzpZ6rYVSiCuXiEgYmazQWCvlPcMOP7nX+1hq1z11LMqeSnfE09gX +H+OYho9cMEJkb1dzx1H9MRpylFIn9tL+2iCp4UPJjnqi6uawWyLZ2tp4G11haqQq +1yAh69u233I8GZKFUySzjHwH5qWGRgBTjrZ6FdcjSS2w/wMkVKuCPkWtdvo/TJrm +msCd1Reye8SEKYqrs0ujTwmlvWmUZmO06AdUjo1kWiBKeslTJrWEuG7Yk4pFOoA4 +dsaq83gxpOJNVCh6M3y4DLNrvl7dhF95NwTWMROPj2otw7NIjF4/cdzve2+P7YNN +pVAtyCtTJdD3eZbQPVaL3T8cf1VGqt6++pnLGnWJ0+X3TyvfmTohdJvN3TE+tq7A +7cprDX/q9c56HaXdJzVpxEzuf/YC+JuYKeHwsX3QouDhyRg3PsigdZES/02Wr8so +l6U= +=MQI4 +-----END PGP PUBLIC KEY BLOCK----- +``` + +### jsii OpenPGP key \(2022\-04\-07\) + +**Note** +This key was not used to sign jsii artifacts after 2022\-07\-05\. + + +| | | +| --- |--- | +| Key ID: | 0x985F5BC974B79356 | +| Type: | RSA | +| Size: | 4096/4096 | +| Created: | 2022\-04\-07 | +| Expires: | 2026\-04\-06 | +| User ID: | AWS JSII Team | +| Key fingerprint: | 35A7 1785 8FA6 282D C5AC CD95 985F 5BC9 74B7 9356 | + +Select the "Copy" icon to copy the following OpenPGP key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGJPLewBEADHH4TXup/gOlHrKDZRbj8MvsMTdM6eDteA6/c32UYV/YsK9rDA +jN8Jv/xlfosOebcHrfnFpHF9VTkmjuOpN695XdwMrW/NvlEPISTGEJf21x6ZTQ2r +1xWFYzC3sl3FZmvj9XAXTmygdv+XM3TqsFgZeCaBkZVdiLbQf+FhYrovUlgotb5D +YiCQI3ofV5QTE+141jhO5Pkd3ZIoBG+P826LaT8NXhwS0o1XqVk39DCZNoFshNmR +WFZpkVCTHyv5ZhVey1NWXnD8opO375htGNV4AeSmSIH9YkURD1g5F+2t7RiosKFo +kJrfPmUjhHn8IFpReGc8qmMMZX0WaV3t+VAWfOHGGyrXDfQ4xz1VCot75C2+qypM ++qhwOAOOP0zA7CfI96ULZzSH/j8HuQk3O0DsUCybpMuKEazEMxP3tgGtRerwDaFG +jQvAlK8Rbq3v8buBI6YJuXTwSzJE8KLjleUiTFumE6WP4rsAvlP/5rBvubeMfa3n +NIMm5Rkl36Z+jt3e2Z2ZqWDPpBRta8m7QHccrZhkvqu3YC3Gl6kdnm4Vio3Xfpg2 +qtWhIQutQ6DmItewV+weQHas3hl88RPJtSrfWWIIMkpbF7Y4vbX9xcnsYCLlp2Mz +tWbbnU+EWATNSsufml/Kdnu9iEEuLmeovE11I69nwjNOq9P+GJ3r/FUb2wARAQAB +tCNBV1MgSlNJSSBUZWFtIDxhd3MtanNpaUBhbWF6b24uY29tPokCPwQTAQIAKQUC +Yk8t7AIbLwUJB4TOAAcLCQgHAwIBBhUIAgkKCwQWAgMBAh4BAheAAAoJEJhfW8l0 +t5NWo64P/2y7gcMRylLLW/wbrCjton2O4+YRocwQxKm1cBml9FVDUR5967YczNuu +EwEOfH/Pu3UAlrBfKAfxPNhKchLwYiOBNh2Wk5UUxRcldNHTLb5jn5gxCeWNAsl/ +Tc46qY+ObdBMdOf2Vu33UCOg83WLbg1bfBoA8Bm1cd0XObtLGucu606EBt1dBrKq +9UTcbJfuGivY2Xjy5r4kEiMHBoLKcFrSo2Mm7VtYlE4Mabjyj9+orqUio7qxOl60 +aa7Psa6rMvs1Ip9IOrAdG7o5Y29tQpeINH0R1/u47BrlTEAgG63Dfy49w2h/1g0G +c9KPXVuN55OWRIu0hsiySDMk/2ERsF348TU3NURZltnCOxp6pHlbPJIxRVTNa9Cn +f8tbLB3y3HfA80516g+qwNYIYiqksDdV2bz+VbvmCWcO+FellDZli831gyMGa5JJ +rq7d0lEr6nqjcnKiVwItTQXyFYmKTAXweQtVC72g1sd3oZIyqa7T8pvhWpKXxoJV +WP+OPBhGg/JEVC9sguhuv53tzVwayrNwb54JxJsD2nemfhQm1Wyvb2bPTEaJ3mrv +mhPUvXZj/I9rgsEq3L/sm2Xjy09nra4o3oe3bhEL8nOj11wkIodi17VaGP0y+H3s +I5zB5UztS6dy+cH+J7DoRaxzVzq7qtH/ZY2quClt30wwqDHUX1ef +=+iYX +-----END PGP PUBLIC KEY BLOCK----- +``` + +### AWS CDK OpenPGP key \(2018\-06\-19\) | | | @@ -48,7 +251,7 @@ EkSlc/RoDqZCpBGgcoy1FFWvV/ZLgNU6OTQlYH6oYOWiylSJnaTDyurrktsxJI6d -----END PGP PUBLIC KEY BLOCK----- ``` -## JSII OpenPGP key +### jsii OpenPGP key \(2018\-08\-06\) | | | From 9fccf5ab1b87dc91a7418a4472e705b90f7928fb Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 11 Aug 2022 03:13:03 +0000 Subject: [PATCH 560/655] update PGP keys --- v1/index.md | 2 +- v2/index.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/index.md b/v1/index.md index 69b24731..851eafc0 100644 --- a/v1/index.md +++ b/v1/index.md @@ -73,5 +73,5 @@ Amazon's trademarks and trade dress may not be used in + [Infrastructure security for the AWS Cloud Development Kit (AWS CDK)](infrastructure-security.md) + [Troubleshooting common AWS CDK issues](troubleshooting.md) + [Videos](videos.md) -+ [OpenPGP keys for the AWS CDK and JSII](pgp-keys.md) ++ [OpenPGP keys for the AWS CDK and jsii](pgp-keys.md) + [AWS CDK Developer Guide history](doc-history.md) \ No newline at end of file diff --git a/v2/index.md b/v2/index.md index 064acd35..dab06c11 100644 --- a/v2/index.md +++ b/v2/index.md @@ -73,5 +73,5 @@ Amazon's trademarks and trade dress may not be used in + [Infrastructure security for the AWS Cloud Development Kit (AWS CDK)](infrastructure-security.md) + [Troubleshooting common AWS CDK issues](troubleshooting.md) + [Videos](videos.md) -+ [OpenPGP keys for the AWS CDK and JSII](pgp-keys.md) ++ [OpenPGP keys for the AWS CDK and jsii](pgp-keys.md) + [AWS CDK Developer Guide history](doc-history.md) \ No newline at end of file From 28d455486198e1c62259aabf9d71abdd7aa33d12 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 11 Aug 2022 03:14:06 +0000 Subject: [PATCH 561/655] update PGP keys --- v1/home.md | 2 +- v2/home.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/home.md b/v1/home.md index 615c36fd..33eebd68 100644 --- a/v1/home.md +++ b/v1/home.md @@ -241,7 +241,7 @@ In addition to this guide, the following other resources are available to AWS CD + [License](https://github.com/awslabs/aws-cdk/blob/master/LICENSE) + [Releases](https://github.com/awslabs/aws-cdk/releases) + [AWS CDK OpenPGP key](pgp-keys.md#cdk_pgp_key) - + [JSII OpenPGP key](pgp-keys.md#jsii_pgp_key) + + [jsii OpenPGP key](pgp-keys.md#jsii_pgp_key) + [AWS CDK Sample for Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/sample-cdk.html) + [AWS CloudFormation Concepts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html) + [AWS Glossary](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html) diff --git a/v2/home.md b/v2/home.md index 6998e83e..4eaaf7bd 100644 --- a/v2/home.md +++ b/v2/home.md @@ -240,7 +240,7 @@ In addition to this guide, the following other resources are available to AWS CD + [License](https://github.com/awslabs/aws-cdk/blob/master/LICENSE) + [Releases](https://github.com/awslabs/aws-cdk/releases) + [AWS CDK OpenPGP key](pgp-keys.md#cdk_pgp_key) - + [JSII OpenPGP key](pgp-keys.md#jsii_pgp_key) + + [jsii OpenPGP key](pgp-keys.md#jsii_pgp_key) + [AWS CDK Sample for Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/sample-cdk.html) + [AWS CloudFormation Concepts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html) + [AWS Glossary](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html) From 2e10eab550376a492e68852b91d1f1b1d8cf28c0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 11 Aug 2022 03:14:30 +0000 Subject: [PATCH 562/655] fix typos --- v1/work-with-cdk-csharp.md | 4 ++-- v2/troubleshooting.md | 2 +- v2/work-with-cdk-csharp.md | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/v1/work-with-cdk-csharp.md b/v1/work-with-cdk-csharp.md index 3aa81daf..0a5dd6ab 100644 --- a/v1/work-with-cdk-csharp.md +++ b/v1/work-with-cdk-csharp.md @@ -125,8 +125,8 @@ class MimeBucket : Bucket { } } -// instantiate our MyBucket class -var bucket = new MyBucket(this, "MyBucket", new MimeBucketProps { +// instantiate our MimeBucket class +var bucket = new MimeBucket(this, "MyBucket", new MimeBucketProps { Versioned = true, MimeType = "image/jpeg" }); diff --git a/v2/troubleshooting.md b/v2/troubleshooting.md index e6570f19..985bf0f2 100644 --- a/v2/troubleshooting.md +++ b/v2/troubleshooting.md @@ -198,7 +198,7 @@ module.exports = { CdkTestStack } ``` import aws_cdk as cdk -from constructs import Constroct +from constructs import Construct import aws_cdk.aws_s3 as s3 class CdkTestStack(cdk.stack): diff --git a/v2/work-with-cdk-csharp.md b/v2/work-with-cdk-csharp.md index a02ced8f..ef1cc7df 100644 --- a/v2/work-with-cdk-csharp.md +++ b/v2/work-with-cdk-csharp.md @@ -118,8 +118,8 @@ class MimeBucket : Bucket { } } -// instantiate our MyBucket class -var bucket = new MyBucket(this, "MyBucket", new MimeBucketProps { +// instantiate our MimeBucket class +var bucket = new MimeBucket(this, "MyBucket", new MimeBucketProps { Versioned = true, MimeType = "image/jpeg" }); From e688bfed679ff1b2d15b448fb0f2419652329c05 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 11 Aug 2022 23:32:02 +0000 Subject: [PATCH 563/655] fix tense --- v1/pgp-keys.md | 2 +- v2/pgp-keys.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/pgp-keys.md b/v1/pgp-keys.md index 1ce1bbf1..05c1957b 100644 --- a/v1/pgp-keys.md +++ b/v1/pgp-keys.md @@ -104,7 +104,7 @@ QWnL/+shuRtMH2geTjkev198Jgb5HyXFm4SyYtZferQROyliEhik These keys may be used to validate releases of the AWS CDK and jsii before 2022\-07\-05\. **Important** -New keys are created before the previous one has expired\. As a result, at any given moment in time, more than one key may be valid\. Keys are used to sign artifacts starting the day they are created, so use the more recently\-issued key where keys' validity overlaps\. +New keys are created before the previous ones expire\. As a result, at any given moment in time, more than one key may be valid\. Keys are used to sign artifacts starting the day they are created, so use the more recently\-issued key where keys' validity overlaps\. ### AWS CDK OpenPGP key \(2022\-04\-07\) diff --git a/v2/pgp-keys.md b/v2/pgp-keys.md index 1ce1bbf1..05c1957b 100644 --- a/v2/pgp-keys.md +++ b/v2/pgp-keys.md @@ -104,7 +104,7 @@ QWnL/+shuRtMH2geTjkev198Jgb5HyXFm4SyYtZferQROyliEhik These keys may be used to validate releases of the AWS CDK and jsii before 2022\-07\-05\. **Important** -New keys are created before the previous one has expired\. As a result, at any given moment in time, more than one key may be valid\. Keys are used to sign artifacts starting the day they are created, so use the more recently\-issued key where keys' validity overlaps\. +New keys are created before the previous ones expire\. As a result, at any given moment in time, more than one key may be valid\. Keys are used to sign artifacts starting the day they are created, so use the more recently\-issued key where keys' validity overlaps\. ### AWS CDK OpenPGP key \(2022\-04\-07\) From d986999fbba73a9839f3b3c6e85d5e0e55320d54 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 12 Aug 2022 23:10:43 +0000 Subject: [PATCH 564/655] update example to correctly describe the code in terms of evaluation periods --- v1/how_to_set_cw_alarm.md | 4 +--- v2/how_to_set_cw_alarm.md | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/v1/how_to_set_cw_alarm.md b/v1/how_to_set_cw_alarm.md index 247bcdcc..284fcaab 100644 --- a/v1/how_to_set_cw_alarm.md +++ b/v1/how_to_set_cw_alarm.md @@ -111,9 +111,7 @@ var metric = new Metric(this, "Metric", new MetricProps ## Creating the alarm -Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three seconds\. You can use comparisons such as less\-than in your alarms via the `comparisonOperator` property; greater\-than\-or\-equal\-to is the AWS CDK default, so we don't need to specify it\. - -Assuming the metric is the **ApproximateNumberOfMessagesVisible** metric from an Amazon SQS queue, it would raise when 100 messages are visible in the queue in two of the last three seconds\. +Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three evaluation periods\. You can use comparisons such as less\-than in your alarms via the `comparisonOperator` property; greater\-than\-or\-equal\-to is the AWS CDK default, so we don't need to specify it\. ------ #### [ TypeScript ] diff --git a/v2/how_to_set_cw_alarm.md b/v2/how_to_set_cw_alarm.md index 8a1ea880..fe2304ea 100644 --- a/v2/how_to_set_cw_alarm.md +++ b/v2/how_to_set_cw_alarm.md @@ -111,9 +111,7 @@ var metric = new Metric(this, "Metric", new MetricProps ## Creating the alarm -Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three seconds\. You can use comparisons such as less\-than in your alarms via the `comparisonOperator` property; greater\-than\-or\-equal\-to is the AWS CDK default, so we don't need to specify it\. - -Assuming the metric is the **ApproximateNumberOfMessagesVisible** metric from an Amazon SQS queue, it would raise when 100 messages are visible in the queue in two of the last three seconds\. +Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three evaluation periods\. You can use comparisons such as less\-than in your alarms via the `comparisonOperator` property; greater\-than\-or\-equal\-to is the AWS CDK default, so we don't need to specify it\. ------ #### [ TypeScript ] From 96214ff08abbad871bf5de5ef1e573a115c75d50 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 12 Aug 2022 23:37:54 +0000 Subject: [PATCH 565/655] correct namespace for generic collections --- v1/work-with-cdk-csharp.md | 6 +++--- v2/work-with-cdk-csharp.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/v1/work-with-cdk-csharp.md b/v1/work-with-cdk-csharp.md index 0a5dd6ab..ef6298b5 100644 --- a/v1/work-with-cdk-csharp.md +++ b/v1/work-with-cdk-csharp.md @@ -141,11 +141,11 @@ A future release of the AWS CDK could coincidentally add a new property with a n In some APIs, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codebuild.BuildSpec.html#to-wbr-build-wbr-spec) method\.\) In C\#, these objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` in C\#\. **Tip** -You might define short aliases to make it easier to work with these sepecific dictionary types\. +You might define short aliases to make it easier to work with these specific dictionary types\. ``` -using StringDict = System.Collections.Dictionary; -using ObjectDict = System.Collections.Dictionary; +using StringDict = System.Collections.Generic.Dictionary; +using ObjectDict = System.Collections.Generic.Dictionary; ``` ### Missing values diff --git a/v2/work-with-cdk-csharp.md b/v2/work-with-cdk-csharp.md index ef1cc7df..8497a335 100644 --- a/v2/work-with-cdk-csharp.md +++ b/v2/work-with-cdk-csharp.md @@ -134,11 +134,11 @@ A future release of the AWS CDK could coincidentally add a new property with a n In some APIs, the AWS CDK uses JavaScript arrays or untyped objects as input to a method\. \(See, for example, AWS CodeBuild's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codebuild.BuildSpec.html) method\.\) In C\#, these objects are represented as `System.Collections.Generic.Dictionary`\. In cases where the values are all strings, you can use `Dictionary`\. JavaScript arrays are represented as `object[]` or `string[]` array types in C\#\. **Tip** -You might define short aliases to make it easier to work with these sepecific dictionary types\. +You might define short aliases to make it easier to work with these specific dictionary types\. ``` -using StringDict = System.Collections.Dictionary; -using ObjectDict = System.Collections.Dictionary; +using StringDict = System.Collections.Generic.Dictionary; +using ObjectDict = System.Collections.Generic.Dictionary; ``` ### Missing values From 012880d5e46c1944f6be4bfc16f224fd316d2d1e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 13 Aug 2022 00:01:11 +0000 Subject: [PATCH 566/655] return reasonable result on add widget operation --- v1/serverless_example.md | 2 +- v2/serverless_example.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/serverless_example.md b/v1/serverless_example.md index 5b8ffcdd..c1d06ca2 100644 --- a/v1/serverless_example.md +++ b/v1/serverless_example.md @@ -716,7 +716,7 @@ exports.main = async function(event, context) { return { statusCode: 200, headers: {}, - body: JSON.stringify(event.widgets) + body: data }; } diff --git a/v2/serverless_example.md b/v2/serverless_example.md index 1576bfef..2dda3780 100644 --- a/v2/serverless_example.md +++ b/v2/serverless_example.md @@ -655,7 +655,7 @@ exports.main = async function(event, context) { return { statusCode: 200, headers: {}, - body: JSON.stringify(event.widgets) + body: data }; } From 4db47dcf02a05661e8b39b560df25fa3c9fa7117 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 17 Aug 2022 15:33:20 +0000 Subject: [PATCH 567/655] remove spurious semicolons --- v1/cli.md | 2 +- v1/use_cfn_public_registry.md | 2 +- v2/cli.md | 2 +- v2/getting_started.md | 2 +- v2/use_cfn_public_registry.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index 6bbff26e..3c370c04 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -416,7 +416,7 @@ One of AWS CloudFormation's marquee features is its ability to roll back changes Rollback makes sure your resources are in a consistent state at all times, which is vital for production stacks\. However, while you're still developing your infrastructure, some failures are inevitable, and rolling back failed deployments just slows you down\. -For this reason, the CDK Toolkit; allows you to disable rollback by adding `--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. +For this reason, the CDK Toolkit allows you to disable rollback by adding `--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. ### Hot swapping diff --git a/v1/use_cfn_public_registry.md b/v1/use_cfn_public_registry.md index ce3a2de0..647dd309 100644 --- a/v1/use_cfn_public_registry.md +++ b/v1/use_cfn_public_registry.md @@ -92,7 +92,7 @@ CfnResource.Builder.create(this, "MyUltimateBucket") .type("MY::S5::UltimateBucket::MODULE") .properties(java.util.Map.of( // Map.of requires Java 9+ "BucketName", "UltimateBucket")) - .build();; + .build(); ``` ------ diff --git a/v2/cli.md b/v2/cli.md index 1825f462..9e781f1b 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -408,7 +408,7 @@ One of AWS CloudFormation's marquee features is its ability to roll back changes Rollback makes sure your resources are in a consistent state at all times, which is vital for production stacks\. However, while you're still developing your infrastructure, some failures are inevitable, and rolling back failed deployments just slows you down\. -For this reason, the CDK Toolkit; allows you to disable rollback by adding `--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. +For this reason, the CDK Toolkit allows you to disable rollback by adding `--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. ### Hot swapping diff --git a/v2/getting_started.md b/v2/getting_started.md index bcf4e433..50d93186 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -250,7 +250,7 @@ cdk --version ``` **Note** -CDK Toolkit; v2 works with your existing CDK v1 projects\. However, it can't initialize new CDK; v1 projects\. See [New prerequisites](migrating-v2.md#migrating-v2-prerequisites) if you need to be able to do that\. +CDK Toolkit v2 works with your existing CDK v1 projects\. However, it can't initialize new CDK v1 projects\. See [New prerequisites](migrating-v2.md#migrating-v2-prerequisites) if you need to be able to do that\. ## Bootstrapping diff --git a/v2/use_cfn_public_registry.md b/v2/use_cfn_public_registry.md index 819a3ae5..0d89f351 100644 --- a/v2/use_cfn_public_registry.md +++ b/v2/use_cfn_public_registry.md @@ -92,7 +92,7 @@ CfnResource.Builder.create(this, "MyUltimateBucket") .type("MY::S5::UltimateBucket::MODULE") .properties(java.util.Map.of( // Map.of requires Java 9+ "BucketName", "UltimateBucket")) - .build();; + .build(); ``` ------ From 976c3668f583e3fa77d5cd545eef7021801ee43d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 23 Aug 2022 23:39:54 +0000 Subject: [PATCH 568/655] improve Resources topic, plus some ID churn --- v1/cli.md | 26 +-- v1/manage-dependencies.md | 10 +- v1/resources.md | 358 ++++++++++++++++---------------- v1/tagging.md | 2 +- v1/use_cfn_template.md | 2 +- v2/cli.md | 26 +-- v2/manage-dependencies.md | 10 +- v2/resources.md | 424 +++++++++++++++++++------------------- v2/tagging.md | 2 +- v2/use_cfn_template.md | 2 +- 10 files changed, 432 insertions(+), 430 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index 3c370c04..1613e6a3 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -351,7 +351,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -370,7 +370,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -378,7 +378,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -454,7 +454,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -476,7 +476,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -733,7 +733,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -746,7 +746,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -767,7 +767,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -847,7 +847,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -925,7 +925,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -944,7 +944,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -970,7 +970,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -992,7 +992,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/manage-dependencies.md b/v1/manage-dependencies.md index 757723d1..e34c2c09 100644 --- a/v1/manage-dependencies.md +++ b/v1/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -72,7 +72,7 @@ All AWS CDK dependencies must have the same version\. Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -99,7 +99,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -145,7 +145,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -169,7 +169,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v1/resources.md b/v1/resources.md index 1f878f15..03735ad9 100644 --- a/v1/resources.md +++ b/v1/resources.md @@ -1,8 +1,8 @@ # Resources -As described in [Constructs](constructs.md), the AWS CDK provides a rich class library of constructs, called *AWS constructs*, that represent all AWS resources\. This section describes some common patterns and best practices for how to use these constructs\. +As described in [Constructs](constructs.md), the AWS CDK provides a rich class library of constructs, called *AWS constructs*, that represent all AWS resources\. -Defining AWS resources in your CDK app is exactly like defining any other construct\. You create an instance of the construct class, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here's how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. +To create an instance of a resource using its corresponding construct, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here's how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. ------ #### [ TypeScript ] @@ -117,15 +117,13 @@ See [Tokens](tokens.md) for information about how the AWS CDK encodes deploy\-ti ## Referencing resources -Many AWS CDK classes require properties that are AWS CDK resource objects \(resources\)\. To satisfy these requirements, you can refer to a resource in one of two ways: -+ By passing the resource directly -+ By passing the resource's unique identifier, which is typically an ARN, but it could also be an ID or a name - -For example, an Amazon ECS service requires a reference to the cluster on which it runs; an Amazon CloudFront distribution requires a reference to the bucket containing source code\. +Many AWS CDK classes require properties that are AWS CDK resource objects \(resources\)\. For example, an Amazon ECS resource requires a reference to the cluster on which it runs; an Amazon CloudFront distribution requires a reference to the bucket containing source code\. To satisfy these requirements, you can refer to a resource in one of two ways: ++ By passing a resource defined in your CDK app, either in the same stack or in a different one ++ By passing a proxy object referencing a resource defined in your AWS account, created from a unique identifier of the resource \(such as an ARN\) If a construct property represents another AWS construct, its type is that of the interface type of that construct\. For example, the Amazon ECS service takes a property `cluster` of type `ecs.ICluster`; the CloudFront distribution takes a property `sourceBucket` \(Python: `source_bucket`\) of type `s3.IBucket`\. -Because every resource implements its corresponding interface, you can directly pass any resource object you're defining in the same AWS CDK app\. The following example defines an Amazon ECS cluster and then uses it to define an Amazon ECS service\. +You can directly pass any resource object of the proper type defined in the same AWS CDK app\. The following example defines an Amazon ECS cluster and then uses it to define an Amazon ECS service\. ------ #### [ TypeScript ] @@ -173,9 +171,9 @@ var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cl ------ -## Accessing resources in a different stack +## Referencing resources in a different stack -You can access resources in a different stack, as long as they are in the same account and AWS Region\. The following example defines the stack `stack1`, which defines an Amazon S3 bucket\. Then it defines a second stack, `stack2`, which takes the bucket from `stack1` as a constructor property\. +You can directly reference resources in a different stack, as long as they are defined in the same app and are in the same AWS account and region\. The following example defines the stack `stack1`, which defines an Amazon S3 bucket\. Then it defines a second stack, `stack2`, which takes the bucket from `stack1` as a constructor property\. ------ #### [ TypeScript ] @@ -183,7 +181,7 @@ You can access resources in a different stack, as long as they are in the same a ``` const prod = { account: '123456789012', region: 'us-east-1' }; -const stack1 = new StackThatProvidesABucket(app, 'Stack1' , { env: prod }); +const stack1 = new StackThatProvidesABucket(app, 'Stack1', { env: prod }); // stack2 will take a property { bucket: IBucket } const stack2 = new StackThatExpectsABucket(app, 'Stack2', { @@ -198,7 +196,7 @@ const stack2 = new StackThatExpectsABucket(app, 'Stack2', { ``` const prod = { account: '123456789012', region: 'us-east-1' }; -const stack1 = new StackThatProvidesABucket(app, 'Stack1' , { env: prod }); +const stack1 = new StackThatProvidesABucket(app, 'Stack1', { env: prod }); // stack2 will take a property { bucket: IBucket } const stack2 = new StackThatExpectsABucket(app, 'Stack2', { @@ -261,26 +259,35 @@ var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = p ------ -If the AWS CDK determines that the resource is in the same account and Region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. +If the AWS CDK determines that the resource is in the same account and region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. + +### Resolving dependency deadlocks -Referencing a resource from one stack in a different stack creates a dependency between the two stacks\. Once this dependency is established, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure if the AWS CDK Toolkit deploys the producing stack before the consuming stack\. This happens if there is another dependency between the two stacks, but it can also happen that the producing stack is chosen by the AWS CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it is no longer needed, but the exported resource is still being used in the consuming stack because its update has not yet been deployed, so deploying the producer stack fails\. +Referencing a resource from one stack in a different stack creates a dependency between the two stacks to ensure that they are deployed in the right order\. Once this dependency has been made concrete by deploying the stacks, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure\. This happens if there is another dependency between the two stacks that force them to be deployed in the same order, but it can also happen without a dependency if the producing stack is simply chosen by the CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it is no longer needed, but the exported resource is still being used in the consuming stack because its update has not yet been deployed, so deploying the producer stack fails\. To break this deadlock, remove the use of the shared resource from the consuming stack \(which will remove the automatic export from the producing stack\), then manually add the same export to the producing stack using exactly the same logical ID as the automatically\-generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then remove the manual export \(and the shared resource if it is no longer needed\), and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Stack.html#exportwbrvalueexportedvalue-options)` method is a convenient way to create the manual export for this purpose \(see the example in the linked method reference\)\. -## Physical names +## Referencing resources in your AWS account -The logical names of resources in AWS CloudFormation are different from the names of resources that are shown in the AWS Management Console after AWS CloudFormation has deployed the resources\. The AWS CDK calls these final names *physical names*\. +Suppose you want to use a resource already available in your AWS account in your AWS CDK app: for example, a resource that was defined through the console, an AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into a proxy object that serves as a reference to the resource by calling a static factory method on the resource's class\. -For example, AWS CloudFormation might create the Amazon S3 bucket with the logical ID **Stack2MyBucket4DD88B4F** from the previous example with the physical name **stack2mybucket4dd88b4f\-iuv1rbv9z3to**\. +When you create such a proxy, the external resource **does not** become a part of your AWS CDK app, and therefore, changes you make to the proxy in your AWS CDK app do not affect the deployed resource\. The proxy can, however, be passed to any AWS CDK method that requires a resource of that type\. -You can specify a physical name when creating constructs that represent resources by using the property Name\. The following example creates an Amazon S3 bucket with the physical name **my\-bucket\-name**\. +The following example shows how to reference a bucket based on an existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a Amazon Virtual Private Cloud based on an existing VPC having a specific ID\. ------ #### [ TypeScript ] ``` -const bucket = new s3.Bucket(this, 'MyBucket', { - bucketName: 'my-bucket-name', +// Construct a proxy for a bucket by its name (must be same account) +s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); + +// Construct a proxy for a bucket by its full ARN (can be another account) +s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); + +// Construct a proxy for an existing VPC from its attribute(s) +ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { + vpcId: 'vpc-1234567890abcde', }); ``` @@ -288,8 +295,15 @@ const bucket = new s3.Bucket(this, 'MyBucket', { #### [ JavaScript ] ``` -const bucket = new s3.Bucket(this, 'MyBucket', { - bucketName: 'my-bucket-name' +// Construct a proxy for a bucket by its name (must be same account) +s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); + +// Construct a proxy for a bucket by its full ARN (can be another account) +s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); + +// Construct a proxy for an existing VPC from its attribute(s) +ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { + vpcId: 'vpc-1234567890abcde' }); ``` @@ -297,36 +311,65 @@ const bucket = new s3.Bucket(this, 'MyBucket', { #### [ Python ] ``` -bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket-name") +# Construct a proxy for a bucket by its name (must be same account) +s3.Bucket.from_bucket_name(self, "MyBucket", "my-bucket-name") + +# Construct a proxy for a bucket by its full ARN (can be another account) +s3.Bucket.from_bucket_arn(self, "MyBucket", "arn:aws:s3:::my-bucket-name") + +# Construct a proxy for an existing VPC from its attribute(s) +ec2.Vpc.from_vpc_attributes(self, "MyVpc", vpc_id="vpc-1234567890abcdef") ``` ------ #### [ Java ] ``` -Bucket bucket = Bucket.Builder.create(this, "MyBucket") - .bucketName("my-bucket-name").build(); +// Construct a proxy for a bucket by its name (must be same account) +Bucket.fromBucketName(this, "MyBucket", "my-bucket-name"); + +// Construct a proxy for a bucket by its full ARN (can be another account) +Bucket.fromBucketArn(this, "MyBucket", + "arn:aws:s3:::my-bucket-name"); + +// Construct a proxy for an existing VPC from its attribute(s) +Vpc.fromVpcAttributes(this, "MyVpc", VpcAttributes.builder() + .vpcId("vpc-1234567890abcdef").build()); ``` ------ #### [ C\# ] ``` -var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-bucket-name" }); +// Construct a proxy for a bucket by its name (must be same account) +Bucket.FromBucketName(this, "MyBucket", "my-bucket-name"); + +// Construct a proxy for a bucket by its full ARN (can be another account) +Bucket.FromBucketArn(this, "MyBucket", "arn:aws:s3:::my-bucket-name"); + +// Construct a proxy for an existing VPC from its attribute(s) +Vpc.FromVpcAttributes(this, "MyVpc", new VpcAttributes +{ + VpcId = "vpc-1234567890abcdef" +}); ``` ------ -Assigning physical names to resources has some disadvantages in AWS CloudFormation\. Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource's properties that are immutable after creation, will fail if a resource has a physical name assigned\. If you end up in that state, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again\. See the [AWS CloudFormation documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) for details\. +Let's take a closer look at the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.Vpc.html#static-fromwbrlookupscope-id-options](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.Vpc.html#static-fromwbrlookupscope-id-options) method\. Because the `ec2.Vpc` construct is complex, there are many ways you might want to select the VPC to be used with your CDK app\. To address this, the VPC construct has a `fromLookup` static method \(Python: `from_lookup`\) that lets you look up the desired Amazon VPC by querying your AWS account at synthesis time\. -In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value `PhysicalName.GENERATE_IF_NEEDED`, as follows\. +To use `Vpc.fromLookup()`, the system that synthesizes the stack must have access to the account that owns the Amazon VPC, since the CDK Toolkit queries the account to find the right Amazon VPC at synthesis time\. + +Furthermore, `Vpc.fromLookup()` works only in stacks that are defined with an explicit **account** and **region** \(see [Environments](environments.md)\)\. If the AWS CDK attempts to look up an Amazon VPC from an [environment\-agnostic stack](stacks.md#stack_api), the CDK Toolkit does not know which environment to query to find the VPC\. + +You must provide `Vpc.fromLookup()` attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want the VPC marked as the default is sufficient\. ------ #### [ TypeScript ] ``` -const bucket = new s3.Bucket(this, 'MyBucket', { - bucketName: core.PhysicalName.GENERATE_IF_NEEDED, +ec2.Vpc.fromLookup(this, 'DefaultVpc', { + isDefault: true }); ``` @@ -334,8 +377,8 @@ const bucket = new s3.Bucket(this, 'MyBucket', { #### [ JavaScript ] ``` -const bucket = new s3.Bucket(this, 'MyBucket', { - bucketName: core.PhysicalName.GENERATE_IF_NEEDED +ec2.Vpc.fromLookup(this, 'DefaultVpc', { + isDefault: true }); ``` @@ -343,96 +386,92 @@ const bucket = new s3.Bucket(this, 'MyBucket', { #### [ Python ] ``` -bucket = s3.Bucket(self, "MyBucket", - bucket_name=core.PhysicalName.GENERATE_IF_NEEDED) +ec2.Vpc.from_lookup(self, "DefaultVpc", is_default=True) ``` ------ #### [ Java ] ``` -Bucket bucket = Bucket.Builder.create(this, "MyBucket") - .bucketName(PhysicalName.GENERATE_IF_NEEDED).build(); +Vpc.fromLookup(this, "DefaultVpc", VpcLookupOptions.builder() + .isDefault(true).build()); ``` ------ #### [ C\# ] ``` -var bucket = new Bucket(this, "MyBucket", new BucketProps - { BucketName = PhysicalName.GENERATE_IF_NEEDED }); +Vpc.FromLookup(this, id = "DefaultVpc", new VpcLookupOptions { IsDefault = true }); ``` ------ -## Passing unique identifiers - -Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. For example, when you are using the low\-level AWS CloudFormation resources, or need to expose resources to the runtime components of an AWS CDK application, such as when referring to Lambda functions through environment variables\. - -These identifiers are available as attributes on the resources, such as the following\. +You can also use the `tags` property to query for VPCs by tag\. Tags may be added to the Amazon VPC at the time of its creation using AWS CloudFormation or the AWS CDK, and they may be edited at any time after creation using the AWS Management Console, the AWS CLI, or an AWS SDK\. In addition to any tags you have added yourself, the AWS CDK automatically adds the following tags to all VPCs it creates\. ++ *Name* – The name of the VPC\. ++ *aws\-cdk:subnet\-name* – The name of the subnet\. ++ *aws\-cdk:subnet\-type* – The type of the subnet: Public, Private, or Isolated\. ------ #### [ TypeScript ] ``` -bucket.bucketName -lambdaFunc.functionArn -securityGroup.groupArn +ec2.Vpc.fromLookup(this, 'PublicVpc', + {tags: {'aws-cdk:subnet-type': "Public"}}); ``` ------ #### [ JavaScript ] ``` -bucket.bucketName -lambdaFunc.functionArn -securityGroup.groupArn +ec2.Vpc.fromLookup(this, 'PublicVpc', + {tags: {'aws-cdk:subnet-type': "Public"}}); ``` ------ #### [ Python ] ``` -bucket.bucket_name -lambda_func.function_arn -security_group_arn +ec2.Vpc.from_lookup(self, "PublicVpc", + tags={"aws-cdk:subnet-type": "Public"}) ``` ------ #### [ Java ] -The Java AWS CDK binding uses getter methods for attributes\. - ``` -bucket.getBucketName() -lambdaFunc.getFunctionArn() -securityGroup.getGroupArn() +Vpc.fromLookup(this, "PublicVpc", VpcLookupOptions.builder() + .tags(java.util.Map.of("aws-cdk:subnet-type", "Public")) // Java 9 or later + .build()); ``` ------ #### [ C\# ] ``` -bucket.BucketName -lambdaFunc.FunctionArn -securityGroup.GroupArn +Vpc.FromLookup(this, id = "PublicVpc", new VpcLookupOptions + { Tags = new Dictionary { ["aws-cdk:subnet-type"] = "Public" }); ``` ------ -The following example shows how to pass a generated bucket name to an AWS Lambda function\. +Results of `Vpc.fromLookup()` are cached in the project's `cdk.context.json` file\. \(See [Runtime context](context.md)\.\) Commit this file to version control so that your app will continue to refer to the same Amazon VPC even if you later change the attributes of your VPCs in a way that would result in a different VPC being selected\. This is particularly important if you will be deploying the stack in an environment that does not have access to the AWS account that defines the VPC, such as [CDK Pipelines](cdk_pipeline.md)\. + +Although you can use an external resource anywhere you'd use a similar resource defined in your AWS CDK app, you cannot modify it\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an external `s3.Bucket` does nothing\. + +## Physical names + +The logical names of resources in AWS CloudFormation are different from the names of resources that are shown in the AWS Management Console after AWS CloudFormation has deployed the resources\. The AWS CDK calls these final names *physical names*\. + +For example, AWS CloudFormation might create the Amazon S3 bucket with the logical ID **Stack2MyBucket4DD88B4F** from the previous example with the physical name **stack2mybucket4dd88b4f\-iuv1rbv9z3to**\. + +You can specify a physical name when creating constructs that represent resources by using the property Name\. The following example creates an Amazon S3 bucket with the physical name **my\-bucket\-name**\. ------ #### [ TypeScript ] ``` -const bucket = new s3.Bucket(this, 'Bucket'); - -new lambda.Function(this, 'MyLambda', { - // ... - environment: { - BUCKET_NAME: bucket.bucketName, - }, +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket-name', }); ``` @@ -440,13 +479,8 @@ new lambda.Function(this, 'MyLambda', { #### [ JavaScript ] ``` -const bucket = new s3.Bucket(this, 'Bucket'); - -new lambda.Function(this, 'MyLambda', { - // ... - environment: { - BUCKET_NAME: bucket.bucketName - } +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket-name' }); ``` @@ -454,59 +488,36 @@ new lambda.Function(this, 'MyLambda', { #### [ Python ] ``` -bucket = s3.Bucket(self, "Bucket") - -lambda.Function(self, "MyLambda", environment=dict(BUCKET_NAME=bucket.bucket_name)) +bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket-name") ``` ------ #### [ Java ] ``` -final Bucket bucket = new Bucket(this, "Bucket"); - -Function.Builder.create(this, "MyLambda") - .environment(java.util.Map.of( // Java 9 or later - "BUCKET_NAME", bucket.getBucketName())) - .build(); +Bucket bucket = Bucket.Builder.create(this, "MyBucket") + .bucketName("my-bucket-name").build(); ``` ------ #### [ C\# ] ``` -var bucket = new Bucket(this, "Bucket"); - -new Function(this, "MyLambda", new FunctionProps -{ - Environment = new Dictionary - { - ["BUCKET_NAME"] = bucket.BucketName - } -}); +var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-bucket-name" }); ``` ------ -## Importing existing external resources - -Sometimes you already have a resource in your AWS account and want to use it in your AWS CDK app, for example, a resource that was defined through the console, an AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into an AWS CDK object in the current stack by calling a static factory method on the resource's class\. +Assigning physical names to resources has some disadvantages in AWS CloudFormation\. Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource's properties that are immutable after creation, will fail if a resource has a physical name assigned\. If you end up in that state, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again\. See the [AWS CloudFormation documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) for details\. -The following example shows how to define a bucket based on an existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a Amazon Virtual Private Cloud based on an existing VPC having a specific ID\. +In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value `PhysicalName.GENERATE_IF_NEEDED`, as follows\. ------ #### [ TypeScript ] ``` -// Construct a resource (bucket) just by its name (must be same account) -s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); - -// Construct a resource (bucket) by its full ARN (can be cross account) -s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); - -// Construct a resource by giving attribute(s) (complex resources) -ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { - vpcId: 'vpc-1234567890abcde', +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: core.PhysicalName.GENERATE_IF_NEEDED, }); ``` @@ -514,15 +525,8 @@ ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { #### [ JavaScript ] ``` -// Construct a resource (bucket) just by its name (must be same account) -s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); - -// Construct a resource (bucket) by its full ARN (can be cross account) -s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); - -// Construct a resource by giving attribute(s) (complex resources) -ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { - vpcId: 'vpc-1234567890abcde' +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: core.PhysicalName.GENERATE_IF_NEEDED }); ``` @@ -530,151 +534,151 @@ ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { #### [ Python ] ``` -# Construct a resource (bucket) just by its name (must be same account) -s3.Bucket.from_bucket_name(self, "MyBucket", "my-bucket-name") - -# Construct a resource (bucket) by its full ARN (can be cross account) -s3.Bucket.from_bucket_arn(self, "MyBucket", "arn:aws:s3:::my-bucket-name") - -# Construct a resource by giving attribute(s) (complex resources) -ec2.Vpc.from_vpc_attributes(self, "MyVpc", vpc_id="vpc-1234567890abcdef") +bucket = s3.Bucket(self, "MyBucket", + bucket_name=core.PhysicalName.GENERATE_IF_NEEDED) ``` ------ #### [ Java ] ``` -// Construct a resource (bucket) just by its name (must be same account) -Bucket.fromBucketName(this, "MyBucket", "my-bucket-name"); - -// Construct a resource (bucket) by its full ARN (can be cross account) -Bucket.fromBucketArn(this, "MyBucket", - "arn:aws:s3:::my-bucket-name"); - -// Construct a resource by giving attribute(s) (complex resources) -Vpc.fromVpcAttributes(this, "MyVpc", VpcAttributes.builder() - .vpcId("vpc-1234567890abcdef").build()); +Bucket bucket = Bucket.Builder.create(this, "MyBucket") + .bucketName(PhysicalName.GENERATE_IF_NEEDED).build(); ``` ------ #### [ C\# ] ``` -// Construct a resource (bucket) just by its name (must be same account) -Bucket.FromBucketName(this, "MyBucket", "my-bucket-name"); - -// Construct a resource (bucket) by its full ARN (can be cross account) -Bucket.FromBucketArn(this, "MyBucket", "arn:aws:s3:::my-bucket-name"); - -// Construct a resource by giving attribute(s) (complex resources) -Vpc.FromVpcAttributes(this, "MyVpc", new VpcAttributes -{ - VpcId = "vpc-1234567890abcdef" -}); +var bucket = new Bucket(this, "MyBucket", new BucketProps + { BucketName = PhysicalName.GENERATE_IF_NEEDED }); ``` ------ -Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables, it can be difficult to specify those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. +## Passing unique identifiers -You must provide attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want the VPC marked as the default is sufficient\. +Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. For example, when you are using the low\-level AWS CloudFormation resources, or need to expose resources to the runtime components of an AWS CDK application, such as when referring to Lambda functions through environment variables\. + +These identifiers are available as attributes on the resources, such as the following\. ------ #### [ TypeScript ] ``` -ec2.Vpc.fromLookup(this, 'DefaultVpc', { - isDefault: true -}); +bucket.bucketName +lambdaFunc.functionArn +securityGroup.groupArn ``` ------ #### [ JavaScript ] ``` -ec2.Vpc.fromLookup(this, 'DefaultVpc', { - isDefault: true -}); +bucket.bucketName +lambdaFunc.functionArn +securityGroup.groupArn ``` ------ #### [ Python ] ``` -ec2.Vpc.from_lookup(self, "DefaultVpc", is_default=True) +bucket.bucket_name +lambda_func.function_arn +security_group_arn ``` ------ #### [ Java ] +The Java AWS CDK binding uses getter methods for attributes\. + ``` -Vpc.fromLookup(this, "DefaultVpc", VpcLookupOptions.builder() - .isDefault(true).build()); +bucket.getBucketName() +lambdaFunc.getFunctionArn() +securityGroup.getGroupArn() ``` ------ #### [ C\# ] ``` -Vpc.FromLookup(this, id = "DefaultVpc", new VpcLookupOptions { IsDefault = true }); +bucket.BucketName +lambdaFunc.FunctionArn +securityGroup.GroupArn ``` ------ -You can use the `tags` property to query by tag\. Tags may be added to the VPC at the time of its creation using AWS CloudFormation or the AWS CDK, and they may be edited at any time after creation using the AWS Management Console, the AWS CLI, or an AWS SDK\. In addition to any tags you have added yourself, the AWS CDK automatically adds the following tags to all VPCs it creates\. -+ *Name* – The name of the VPC\. -+ *aws\-cdk:subnet\-name* – The name of the subnet\. -+ *aws\-cdk:subnet\-type* – The type of the subnet: Public, Private, or Isolated\. +The following example shows how to pass a generated bucket name to an AWS Lambda function\. ------ #### [ TypeScript ] ``` -ec2.Vpc.fromLookup(this, 'PublicVpc', - {tags: {'aws-cdk:subnet-type': "Public"}}); +const bucket = new s3.Bucket(this, 'Bucket'); + +new lambda.Function(this, 'MyLambda', { + // ... + environment: { + BUCKET_NAME: bucket.bucketName, + }, +}); ``` ------ #### [ JavaScript ] ``` -ec2.Vpc.fromLookup(this, 'PublicVpc', - {tags: {'aws-cdk:subnet-type': "Public"}}); +const bucket = new s3.Bucket(this, 'Bucket'); + +new lambda.Function(this, 'MyLambda', { + // ... + environment: { + BUCKET_NAME: bucket.bucketName + } +}); ``` ------ #### [ Python ] ``` -ec2.Vpc.from_lookup(self, "PublicVpc", - tags={"aws-cdk:subnet-type": "Public"}) +bucket = s3.Bucket(self, "Bucket") + +lambda.Function(self, "MyLambda", environment=dict(BUCKET_NAME=bucket.bucket_name)) ``` ------ #### [ Java ] ``` -Vpc.fromLookup(this, "PublicVpc", VpcLookupOptions.builder() - .tags(java.util.Map.of("aws-cdk:subnet-type", "Public")) // Java 9 or later - .build()); +final Bucket bucket = new Bucket(this, "Bucket"); + +Function.Builder.create(this, "MyLambda") + .environment(java.util.Map.of( // Java 9 or later + "BUCKET_NAME", bucket.getBucketName())) + .build(); ``` ------ #### [ C\# ] ``` -Vpc.FromLookup(this, id = "PublicVpc", new VpcLookupOptions - { Tags = new Dictionary { ["aws-cdk:subnet-type"] = "Public" }); +var bucket = new Bucket(this, "Bucket"); + +new Function(this, "MyLambda", new FunctionProps +{ + Environment = new Dictionary + { + ["BUCKET_NAME"] = bucket.BucketName + } +}); ``` ------ -`Vpc.fromLookup()` works only in stacks that are defined with an explicit **account** and **region** in their `env` property\. If the AWS CDK attempts to look up an Amazon VPC from an [environment\-agnostic stack](stacks.md#stack_api), the CLI does not know which environment to query to find the VPC\. - -Results of `Vpc.fromLookup()` are cached in the project's `cdk.context.json` file\. Commit this file to version control if you will be deploying the stack in an environment that does not have access to the AWS account that defines the VPC, such as [CDK Pipelines](cdk_pipeline.md)\. - -Although you can use an external resource anywhere you'd use a similar resource defined in your AWS CDK app, you cannot modify it\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an external `s3.Bucket` does nothing\. - ## Permission grants AWS constructs make least\-privilege permissions easy to achieve by offering simple, intent\-based APIs to express permission requirements\. Many AWS constructs offer grant methods that enable you to easily grant an entity, such as an IAM role or a user, permission to work with the resource without having to manually craft one or more IAM permission statements\. diff --git a/v1/tagging.md b/v1/tagging.md index 0ebe951c..9cdcc43d 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index 4273e248..6381181f 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/cli.md b/v2/cli.md index 9e781f1b..665d6f14 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -343,7 +343,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -362,7 +362,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -370,7 +370,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -446,7 +446,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -468,7 +468,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -725,7 +725,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -738,7 +738,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -759,7 +759,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -839,7 +839,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -917,7 +917,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -936,7 +936,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -962,7 +962,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -984,7 +984,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index a35d9c53..2c03193f 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -71,7 +71,7 @@ Specify exact versions for alpha construct library modules, which have APIs that Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -101,7 +101,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -147,7 +147,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -167,7 +167,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v2/resources.md b/v2/resources.md index 4edd125e..f0c7d9ad 100644 --- a/v2/resources.md +++ b/v2/resources.md @@ -1,14 +1,14 @@ # Resources -As described in [Constructs](constructs.md), the AWS CDK provides a rich class library of constructs, called *AWS constructs*, that represent all AWS resources\. This section describes some common patterns and best practices for how to use these constructs\. +As described in [Constructs](constructs.md), the AWS CDK provides a rich class library of constructs, called *AWS constructs*, that represent all AWS resources\. -Defining AWS resources in your CDK app is exactly like defining any other construct\. You create an instance of the construct class, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here's how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sqs.Queue.html) construct from the AWS Construct Library\. +To create an instance of a resource using its corresponding construct, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here's how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. ------ #### [ TypeScript ] ``` -import * as sqs from 'aws-cdk-lib/aws-sqs'; +import * as sqs from '@aws-cdk/aws-sqs'; new sqs.Queue(this, 'MyQueue', { encryption: sqs.QueueEncryption.KMS_MANAGED @@ -19,7 +19,7 @@ new sqs.Queue(this, 'MyQueue', { #### [ JavaScript ] ``` -const sqs = require('aws-cdk-lib/aws-sqs'); +const sqs = require('@aws-cdk/aws-sqs'); new sqs.Queue(this, 'MyQueue', { encryption: sqs.QueueEncryption.KMS_MANAGED @@ -69,7 +69,7 @@ Most resources in the AWS Construct Library expose attributes, which are resolve #### [ TypeScript ] ``` -import * as sqs from 'aws-cdk-lib/aws-sqs'; +import * as sqs from '@aws-cdk/aws-sqs'; const queue = new sqs.Queue(this, 'MyQueue'); const url = queue.queueUrl; // => A string representing a deploy-time value @@ -79,7 +79,7 @@ const url = queue.queueUrl; // => A string representing a deploy-time value #### [ JavaScript ] ``` -const sqs = require('aws-cdk-lib/aws-sqs'); +const sqs = require('@aws-cdk/aws-sqs'); const queue = new sqs.Queue(this, 'MyQueue'); const url = queue.queueUrl; // => A string representing a deploy-time value @@ -99,8 +99,6 @@ url = queue.queue_url # => A string representing a deploy-time value #### [ Java ] ``` -import software.amazon.awscdk.services.sqs.*; - Queue queue = new Queue(this, "MyQueue"); String url = queue.getQueueUrl(); // => A string representing a deploy-time value ``` @@ -109,8 +107,6 @@ String url = queue.getQueueUrl(); // => A string representing a deploy-time v #### [ C\# ] ``` -using Amazon.CDK.AWS.SQS; - var queue = new Queue(this, "MyQueue"); var url = queue.QueueUrl; // => A string representing a deploy-time value ``` @@ -121,15 +117,13 @@ See [Tokens](tokens.md) for information about how the AWS CDK encodes deploy\-ti ## Referencing resources -Many AWS CDK classes require properties that are AWS CDK resource objects \(resources\)\. To satisfy these requirements, you can refer to a resource in one of two ways: -+ By passing the resource directly -+ By passing the resource's unique identifier, which is typically an ARN, but it could also be an ID or a name - -For example, an Amazon ECS service requires a reference to the cluster on which it runs; an Amazon CloudFront distribution requires a reference to the bucket containing source code\. +Many AWS CDK classes require properties that are AWS CDK resource objects \(resources\)\. For example, an Amazon ECS resource requires a reference to the cluster on which it runs; an Amazon CloudFront distribution requires a reference to the bucket containing source code\. To satisfy these requirements, you can refer to a resource in one of two ways: ++ By passing a resource defined in your CDK app, either in the same stack or in a different one ++ By passing a proxy object referencing a resource defined in your AWS account, created from a unique identifier of the resource \(such as an ARN\) If a construct property represents another AWS construct, its type is that of the interface type of that construct\. For example, the Amazon ECS service takes a property `cluster` of type `ecs.ICluster`; the CloudFront distribution takes a property `sourceBucket` \(Python: `source_bucket`\) of type `s3.IBucket`\. -Because every resource implements its corresponding interface, you can directly pass any resource object you're defining in the same AWS CDK app\. The following example defines an Amazon ECS cluster and then uses it to define an Amazon ECS service\. +You can directly pass any resource object of the proper type defined in the same AWS CDK app\. The following example defines an Amazon ECS cluster and then uses it to define an Amazon ECS service\. ------ #### [ TypeScript ] @@ -177,9 +171,9 @@ var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cl ------ -## Accessing resources in a different stack +## Referencing resources in a different stack -You can access resources in a different stack, as long as they are in the same account and AWS Region\. The following example defines the stack `stack1`, which defines an Amazon S3 bucket\. Then it defines a second stack, `stack2`, which takes the bucket from `stack1` as a constructor property\. +You can directly reference resources in a different stack, as long as they are defined in the same app and are in the same AWS account and region\. The following example defines the stack `stack1`, which defines an Amazon S3 bucket\. Then it defines a second stack, `stack2`, which takes the bucket from `stack1` as a constructor property\. ------ #### [ TypeScript ] @@ -187,7 +181,7 @@ You can access resources in a different stack, as long as they are in the same a ``` const prod = { account: '123456789012', region: 'us-east-1' }; -const stack1 = new StackThatProvidesABucket(app, 'Stack1' , { env: prod }); +const stack1 = new StackThatProvidesABucket(app, 'Stack1', { env: prod }); // stack2 will take a property { bucket: IBucket } const stack2 = new StackThatExpectsABucket(app, 'Stack2', { @@ -202,7 +196,7 @@ const stack2 = new StackThatExpectsABucket(app, 'Stack2', { ``` const prod = { account: '123456789012', region: 'us-east-1' }; -const stack1 = new StackThatProvidesABucket(app, 'Stack1' , { env: prod }); +const stack1 = new StackThatProvidesABucket(app, 'Stack1', { env: prod }); // stack2 will take a property { bucket: IBucket } const stack2 = new StackThatExpectsABucket(app, 'Stack2', { @@ -215,7 +209,7 @@ const stack2 = new StackThatExpectsABucket(app, 'Stack2', { #### [ Python ] ``` -prod = cdk.Environment(account="123456789012", region="us-east-1") +prod = core.Environment(account="123456789012", region="us-east-1") stack1 = StackThatProvidesABucket(app, "Stack1", env=prod) @@ -265,26 +259,35 @@ var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = p ------ -If the AWS CDK determines that the resource is in the same account and Region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. +If the AWS CDK determines that the resource is in the same account and region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. -Referencing a resource from one stack in a different stack creates a dependency between the two stacks\. Once this dependency is established, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure if the AWS CDK Toolkit deploys the producing stack before the consuming stack\. This happens if there is another dependency between the two stacks, but it can also happen that the producing stack is chosen by the AWS CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it is no longer needed, but the exported resource is still being used in the consuming stack because its update has not yet been deployed, so deploying the producer stack fails\. +### Resolving dependency deadlocks -To break this deadlock, remove the use of the shared resource from the consuming stack \(which will remove the automatic export from the producing stack\), then manually add the same export to the producing stack using exactly the same logical ID as the automatically\-generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then remove the manual export \(and the shared resource if it is no longer nededed\), and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#exportwbrvalueexportedvalue-options)` method is a convenient way to create the manual export for this purpose \(see the example in the linked method reference\)\. +Referencing a resource from one stack in a different stack creates a dependency between the two stacks to ensure that they are deployed in the right order\. Once this dependency has been made concrete by deploying the stacks, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure\. This happens if there is another dependency between the two stacks that force them to be deployed in the same order, but it can also happen without a dependency if the producing stack is simply chosen by the CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it is no longer needed, but the exported resource is still being used in the consuming stack because its update has not yet been deployed, so deploying the producer stack fails\. -## Physical names +To break this deadlock, remove the use of the shared resource from the consuming stack \(which will remove the automatic export from the producing stack\), then manually add the same export to the producing stack using exactly the same logical ID as the automatically\-generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then remove the manual export \(and the shared resource if it is no longer needed\), and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html#static-fromwbrlookupscope-id-options)` method is a convenient way to create the manual export for this purpose \(see the example in the linked method reference\)\. -The logical names of resources in AWS CloudFormation are different from the names of resources that are shown in the AWS Management Console after AWS CloudFormation has deployed the resources\. The AWS CDK calls these final names *physical names*\. +## Referencing resources in your AWS account -For example, AWS CloudFormation might create the Amazon S3 bucket with the logical ID **Stack2MyBucket4DD88B4F** from the previous example with the physical name **stack2mybucket4dd88b4f\-iuv1rbv9z3to**\. +Suppose you want to use a resource already available in your AWS account in your AWS CDK app: for example, a resource that was defined through the console, an AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into a proxy object that serves as a reference to the resource by calling a static factory method on the resource's class\. -You can specify a physical name when creating constructs that represent resources by using the property Name\. The following example creates an Amazon S3 bucket with the physical name **my\-bucket\-name**\. +When you create such a proxy, the external resource **does not** become a part of your AWS CDK app, and therefore, changes you make to the proxy in your AWS CDK app do not affect the deployed resource\. The proxy can, however, be passed to any AWS CDK method that requires a resource of that type\. + +The following example shows how to reference a bucket based on an existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a Amazon Virtual Private Cloud based on an existing VPC having a specific ID\. ------ #### [ TypeScript ] ``` -const bucket = new s3.Bucket(this, 'MyBucket', { - bucketName: 'my-bucket-name', +// Construct a proxy for a bucket by its name (must be same account) +s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); + +// Construct a proxy for a bucket by its full ARN (can be another account) +s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); + +// Construct a proxy for an existing VPC from its attribute(s) +ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { + vpcId: 'vpc-1234567890abcde', }); ``` @@ -292,8 +295,15 @@ const bucket = new s3.Bucket(this, 'MyBucket', { #### [ JavaScript ] ``` -const bucket = new s3.Bucket(this, 'MyBucket', { - bucketName: 'my-bucket-name' +// Construct a proxy for a bucket by its name (must be same account) +s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); + +// Construct a proxy for a bucket by its full ARN (can be another account) +s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); + +// Construct a proxy for an existing VPC from its attribute(s) +ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { + vpcId: 'vpc-1234567890abcde' }); ``` @@ -301,36 +311,65 @@ const bucket = new s3.Bucket(this, 'MyBucket', { #### [ Python ] ``` -bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket-name") +# Construct a proxy for a bucket by its name (must be same account) +s3.Bucket.from_bucket_name(self, "MyBucket", "my-bucket-name") + +# Construct a proxy for a bucket by its full ARN (can be another account) +s3.Bucket.from_bucket_arn(self, "MyBucket", "arn:aws:s3:::my-bucket-name") + +# Construct a proxy for an existing VPC from its attribute(s) +ec2.Vpc.from_vpc_attributes(self, "MyVpc", vpc_id="vpc-1234567890abcdef") ``` ------ #### [ Java ] ``` -Bucket bucket = Bucket.Builder.create(this, "MyBucket") - .bucketName("my-bucket-name").build(); +// Construct a proxy for a bucket by its name (must be same account) +Bucket.fromBucketName(this, "MyBucket", "my-bucket-name"); + +// Construct a proxy for a bucket by its full ARN (can be another account) +Bucket.fromBucketArn(this, "MyBucket", + "arn:aws:s3:::my-bucket-name"); + +// Construct a proxy for an existing VPC from its attribute(s) +Vpc.fromVpcAttributes(this, "MyVpc", VpcAttributes.builder() + .vpcId("vpc-1234567890abcdef").build()); ``` ------ #### [ C\# ] ``` -var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-bucket-name" }); +// Construct a proxy for a bucket by its name (must be same account) +Bucket.FromBucketName(this, "MyBucket", "my-bucket-name"); + +// Construct a proxy for a bucket by its full ARN (can be another account) +Bucket.FromBucketArn(this, "MyBucket", "arn:aws:s3:::my-bucket-name"); + +// Construct a proxy for an existing VPC from its attribute(s) +Vpc.FromVpcAttributes(this, "MyVpc", new VpcAttributes +{ + VpcId = "vpc-1234567890abcdef" +}); ``` ------ -Assigning physical names to resources has some disadvantages in AWS CloudFormation\. Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource's properties that are immutable after creation, will fail if a resource has a physical name assigned\. If you end up in that state, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again\. See the [AWS CloudFormation documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) for details\. +Let's take a closer look at the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.Vpc.html#static-fromwbrlookupscope-id-options](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.Vpc.html#static-fromwbrlookupscope-id-options) method\. Because the `ec2.Vpc` construct is complex, there are many ways you might want to select the VPC to be used with your CDK app\. To address this, the VPC construct has a `fromLookup` static method \(Python: `from_lookup`\) that lets you look up the desired Amazon VPC by querying your AWS account at synthesis time\. -In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value `PhysicalName.GENERATE_IF_NEEDED`, as follows\. +To use `Vpc.fromLookup()`, the system that synthesizes the stack must have access to the account that owns the Amazon VPC, since the CDK Toolkit queries the account to find the right Amazon VPC at synthesis time\. + +Furthermore, `Vpc.fromLookup()` works only in stacks that are defined with an explicit **account** and **region** \(see [Environments](environments.md)\)\. If the AWS CDK attempts to look up an Amazon VPC from an [environment\-agnostic stack](stacks.md#stack_api), the CDK Toolkit does not know which environment to query to find the VPC\. + +You must provide `Vpc.fromLookup()` attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want the VPC marked as the default is sufficient\. ------ #### [ TypeScript ] ``` -const bucket = new s3.Bucket(this, 'MyBucket', { - bucketName: cdk.PhysicalName.GENERATE_IF_NEEDED, +ec2.Vpc.fromLookup(this, 'DefaultVpc', { + isDefault: true }); ``` @@ -338,8 +377,8 @@ const bucket = new s3.Bucket(this, 'MyBucket', { #### [ JavaScript ] ``` -const bucket = new s3.Bucket(this, 'MyBucket', { - bucketName: cdk.PhysicalName.GENERATE_IF_NEEDED +ec2.Vpc.fromLookup(this, 'DefaultVpc', { + isDefault: true }); ``` @@ -347,96 +386,92 @@ const bucket = new s3.Bucket(this, 'MyBucket', { #### [ Python ] ``` -bucket = s3.Bucket(self, "MyBucket", - bucket_name=cdk.PhysicalName.GENERATE_IF_NEEDED) +ec2.Vpc.from_lookup(self, "DefaultVpc", is_default=True) ``` ------ #### [ Java ] ``` -Bucket bucket = Bucket.Builder.create(this, "MyBucket") - .bucketName(PhysicalName.GENERATE_IF_NEEDED).build(); +Vpc.fromLookup(this, "DefaultVpc", VpcLookupOptions.builder() + .isDefault(true).build()); ``` ------ #### [ C\# ] ``` -var bucket = new Bucket(this, "MyBucket", new BucketProps - { BucketName = PhysicalName.GENERATE_IF_NEEDED }); +Vpc.FromLookup(this, id = "DefaultVpc", new VpcLookupOptions { IsDefault = true }); ``` ------ -## Passing unique identifiers - -Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. For example, when you are using the low\-level AWS CloudFormation resources, or need to expose resources to the runtime components of an AWS CDK application, such as when referring to Lambda functions through environment variables\. - -These identifiers are available as attributes on the resources, such as the following\. +You can also use the `tags` property to query for VPCs by tag\. Tags may be added to the Amazon VPC at the time of its creation using AWS CloudFormation or the AWS CDK, and they may be edited at any time after creation using the AWS Management Console, the AWS CLI, or an AWS SDK\. In addition to any tags you have added yourself, the AWS CDK automatically adds the following tags to all VPCs it creates\. ++ *Name* – The name of the VPC\. ++ *aws\-cdk:subnet\-name* – The name of the subnet\. ++ *aws\-cdk:subnet\-type* – The type of the subnet: Public, Private, or Isolated\. ------ #### [ TypeScript ] ``` -bucket.bucketName -lambdaFunc.functionArn -securityGroup.groupArn +ec2.Vpc.fromLookup(this, 'PublicVpc', + {tags: {'aws-cdk:subnet-type': "Public"}}); ``` ------ #### [ JavaScript ] ``` -bucket.bucketName -lambdaFunc.functionArn -securityGroup.groupArn +ec2.Vpc.fromLookup(this, 'PublicVpc', + {tags: {'aws-cdk:subnet-type': "Public"}}); ``` ------ #### [ Python ] ``` -bucket.bucket_name -lambda_func.function_arn -security_group_arn +ec2.Vpc.from_lookup(self, "PublicVpc", + tags={"aws-cdk:subnet-type": "Public"}) ``` ------ #### [ Java ] -The Java AWS CDK binding uses getter methods for attributes\. - ``` -bucket.getBucketName() -lambdaFunc.getFunctionArn() -securityGroup.getGroupArn() +Vpc.fromLookup(this, "PublicVpc", VpcLookupOptions.builder() + .tags(java.util.Map.of("aws-cdk:subnet-type", "Public")) // Java 9 or later + .build()); ``` ------ #### [ C\# ] ``` -bucket.BucketName -lambdaFunc.FunctionArn -securityGroup.GroupArn +Vpc.FromLookup(this, id = "PublicVpc", new VpcLookupOptions + { Tags = new Dictionary { ["aws-cdk:subnet-type"] = "Public" }); ``` ------ -The following example shows how to pass a generated bucket name to an AWS Lambda function\. +Results of `Vpc.fromLookup()` are cached in the project's `cdk.context.json` file\. \(See [Runtime context](context.md)\.\) Commit this file to version control so that your app will continue to refer to the same Amazon VPC even if you later change the attributes of your VPCs in a way that would result in a different VPC being selected\. This is particularly important if you will be deploying the stack in an environment that does not have access to the AWS account that defines the VPC, such as [CDK Pipelines](cdk_pipeline.md)\. + +Although you can use an external resource anywhere you'd use a similar resource defined in your AWS CDK app, you cannot modify it\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an external `s3.Bucket` does nothing\. + +## Physical names + +The logical names of resources in AWS CloudFormation are different from the names of resources that are shown in the AWS Management Console after AWS CloudFormation has deployed the resources\. The AWS CDK calls these final names *physical names*\. + +For example, AWS CloudFormation might create the Amazon S3 bucket with the logical ID **Stack2MyBucket4DD88B4F** from the previous example with the physical name **stack2mybucket4dd88b4f\-iuv1rbv9z3to**\. + +You can specify a physical name when creating constructs that represent resources by using the property Name\. The following example creates an Amazon S3 bucket with the physical name **my\-bucket\-name**\. ------ #### [ TypeScript ] ``` -const bucket = new s3.Bucket(this, 'Bucket'); - -new lambda.Function(this, 'MyLambda', { - // ... - environment: { - BUCKET_NAME: bucket.bucketName, - }, +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket-name', }); ``` @@ -444,13 +479,8 @@ new lambda.Function(this, 'MyLambda', { #### [ JavaScript ] ``` -const bucket = new s3.Bucket(this, 'Bucket'); - -new lambda.Function(this, 'MyLambda', { - // ... - environment: { - BUCKET_NAME: bucket.bucketName - } +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: 'my-bucket-name' }); ``` @@ -458,59 +488,36 @@ new lambda.Function(this, 'MyLambda', { #### [ Python ] ``` -bucket = s3.Bucket(self, "Bucket") - -lambda.Function(self, "MyLambda", environment=dict(BUCKET_NAME=bucket.bucket_name)) +bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket-name") ``` ------ #### [ Java ] ``` -final Bucket bucket = new Bucket(this, "Bucket"); - -Function.Builder.create(this, "MyLambda") - .environment(java.util.Map.of( // Java 9 or later - "BUCKET_NAME", bucket.getBucketName())) - .build(); +Bucket bucket = Bucket.Builder.create(this, "MyBucket") + .bucketName("my-bucket-name").build(); ``` ------ #### [ C\# ] ``` -var bucket = new Bucket(this, "Bucket"); - -new Function(this, "MyLambda", new FunctionProps -{ - Environment = new Dictionary - { - ["BUCKET_NAME"] = bucket.BucketName - } -}); +var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-bucket-name" }); ``` ------ -## Importing existing external resources - -Sometimes you already have a resource in your AWS account and want to use it in your AWS CDK app, for example, a resource that was defined through the console, an AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into an AWS CDK object in the current stack by calling a static factory method on the resource's class\. +Assigning physical names to resources has some disadvantages in AWS CloudFormation\. Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource's properties that are immutable after creation, will fail if a resource has a physical name assigned\. If you end up in that state, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again\. See the [AWS CloudFormation documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) for details\. -The following example shows how to define a bucket based on an existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a Amazon Virtual Private Cloud based on an existing VPC having a specific ID\. +In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value `PhysicalName.GENERATE_IF_NEEDED`, as follows\. ------ #### [ TypeScript ] ``` -// Construct a resource (bucket) just by its name (must be same account) -s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); - -// Construct a resource (bucket) by its full ARN (can be cross account) -s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); - -// Construct a resource by giving attribute(s) (complex resources) -ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { - vpcId: 'vpc-1234567890abcde', +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: core.PhysicalName.GENERATE_IF_NEEDED, }); ``` @@ -518,15 +525,8 @@ ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { #### [ JavaScript ] ``` -// Construct a resource (bucket) just by its name (must be same account) -s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); - -// Construct a resource (bucket) by its full ARN (can be cross account) -s3.Bucket.fromBucketArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); - -// Construct a resource by giving attribute(s) (complex resources) -ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { - vpcId: 'vpc-1234567890abcde' +const bucket = new s3.Bucket(this, 'MyBucket', { + bucketName: core.PhysicalName.GENERATE_IF_NEEDED }); ``` @@ -534,151 +534,151 @@ ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { #### [ Python ] ``` -# Construct a resource (bucket) just by its name (must be same account) -s3.Bucket.from_bucket_name(self, "MyBucket", "my-bucket-name") - -# Construct a resource (bucket) by its full ARN (can be cross account) -s3.Bucket.from_bucket_arn(self, "MyBucket", "arn:aws:s3:::my-bucket-name") - -# Construct a resource by giving attribute(s) (complex resources) -ec2.Vpc.from_vpc_attributes(self, "MyVpc", vpc_id="vpc-1234567890abcdef") +bucket = s3.Bucket(self, "MyBucket", + bucket_name=core.PhysicalName.GENERATE_IF_NEEDED) ``` ------ #### [ Java ] ``` -// Construct a resource (bucket) just by its name (must be same account) -Bucket.fromBucketName(this, "MyBucket", "my-bucket-name"); - -// Construct a resource (bucket) by its full ARN (can be cross account) -Bucket.fromBucketArn(this, "MyBucket", - "arn:aws:s3:::my-bucket-name"); - -// Construct a resource by giving attribute(s) (complex resources) -Vpc.fromVpcAttributes(this, "MyVpc", VpcAttributes.builder() - .vpcId("vpc-1234567890abcdef").build()); +Bucket bucket = Bucket.Builder.create(this, "MyBucket") + .bucketName(PhysicalName.GENERATE_IF_NEEDED).build(); ``` ------ #### [ C\# ] ``` -// Construct a resource (bucket) just by its name (must be same account) -Bucket.FromBucketName(this, "MyBucket", "my-bucket-name"); - -// Construct a resource (bucket) by its full ARN (can be cross account) -Bucket.FromBucketArn(this, "MyBucket", "arn:aws:s3:::my-bucket-name"); - -// Construct a resource by giving attribute(s) (complex resources) -Vpc.FromVpcAttributes(this, "MyVpc", new VpcAttributes -{ - VpcId = "vpc-1234567890abcdef" -}); +var bucket = new Bucket(this, "MyBucket", new BucketProps + { BucketName = PhysicalName.GENERATE_IF_NEEDED }); ``` ------ -Because the `ec2.Vpc` construct is complex, composed of many AWS resources, such as the VPC itself, subnets, security groups, and routing tables, it can be difficult to specify those resources using attributes\. To address this, the VPC construct contains a `fromLookup` method \(Python: `from_lookup`\) that uses a [context method](context.md#context_methods) to resolve all the required attributes at synthesis time, and cache the values for future use in `cdk.context.json`\. +## Passing unique identifiers -You must provide attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want the VPC marked as the default is sufficient\. +Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. For example, when you are using the low\-level AWS CloudFormation resources, or need to expose resources to the runtime components of an AWS CDK application, such as when referring to Lambda functions through environment variables\. + +These identifiers are available as attributes on the resources, such as the following\. ------ #### [ TypeScript ] ``` -ec2.Vpc.fromLookup(this, 'DefaultVpc', { - isDefault: true -}); +bucket.bucketName +lambdaFunc.functionArn +securityGroup.groupArn ``` ------ #### [ JavaScript ] ``` -ec2.Vpc.fromLookup(this, 'DefaultVpc', { - isDefault: true -}); +bucket.bucketName +lambdaFunc.functionArn +securityGroup.groupArn ``` ------ #### [ Python ] ``` -ec2.Vpc.from_lookup(self, "DefaultVpc", is_default=True) +bucket.bucket_name +lambda_func.function_arn +security_group_arn ``` ------ #### [ Java ] +The Java AWS CDK binding uses getter methods for attributes\. + ``` -Vpc.fromLookup(this, "DefaultVpc", VpcLookupOptions.builder() - .isDefault(true).build()); +bucket.getBucketName() +lambdaFunc.getFunctionArn() +securityGroup.getGroupArn() ``` ------ #### [ C\# ] ``` -Vpc.FromLookup(this, id = "DefaultVpc", new VpcLookupOptions { IsDefault = true }); +bucket.BucketName +lambdaFunc.FunctionArn +securityGroup.GroupArn ``` ------ -You can use the `tags` property to query by tag\. Tags may be added to the VPC at the time of its creation using AWS CloudFormation or the AWS CDK, and they may be edited at any time after creation using the AWS Management Console, the AWS CLI, or an AWS SDK\. In addition to any tags you have added yourself, the AWS CDK automatically adds the following tags to all VPCs it creates\. -+ *Name* – The name of the VPC\. -+ *aws\-cdk:subnet\-name* – The name of the subnet\. -+ *aws\-cdk:subnet\-type* – The type of the subnet: Public, Private, or Isolated\. +The following example shows how to pass a generated bucket name to an AWS Lambda function\. ------ #### [ TypeScript ] ``` -ec2.Vpc.fromLookup(this, 'PublicVpc', - {tags: {'aws-cdk:subnet-type': "Public"}}); +const bucket = new s3.Bucket(this, 'Bucket'); + +new lambda.Function(this, 'MyLambda', { + // ... + environment: { + BUCKET_NAME: bucket.bucketName, + }, +}); ``` ------ #### [ JavaScript ] ``` -ec2.Vpc.fromLookup(this, 'PublicVpc', - {tags: {'aws-cdk:subnet-type': "Public"}}); +const bucket = new s3.Bucket(this, 'Bucket'); + +new lambda.Function(this, 'MyLambda', { + // ... + environment: { + BUCKET_NAME: bucket.bucketName + } +}); ``` ------ #### [ Python ] ``` -ec2.Vpc.from_lookup(self, "PublicVpc", - tags={"aws-cdk:subnet-type": "Public"}) +bucket = s3.Bucket(self, "Bucket") + +lambda.Function(self, "MyLambda", environment=dict(BUCKET_NAME=bucket.bucket_name)) ``` ------ #### [ Java ] ``` -Vpc.fromLookup(this, "PublicVpc", VpcLookupOptions.builder() - .tags(java.util.Map.of("aws-cdk:subnet-type", "Public")) // Java 9 or later - .build()); +final Bucket bucket = new Bucket(this, "Bucket"); + +Function.Builder.create(this, "MyLambda") + .environment(java.util.Map.of( // Java 9 or later + "BUCKET_NAME", bucket.getBucketName())) + .build(); ``` ------ #### [ C\# ] ``` -Vpc.FromLookup(this, id = "PublicVpc", new VpcLookupOptions - { Tags = new Dictionary { ["aws-cdk:subnet-type"] = "Public" }); +var bucket = new Bucket(this, "Bucket"); + +new Function(this, "MyLambda", new FunctionProps +{ + Environment = new Dictionary + { + ["BUCKET_NAME"] = bucket.BucketName + } +}); ``` ------ -`Vpc.fromLookup()` works only in stacks that are defined with an explicit **account** and **region** in their `env` property\. If the AWS CDK attempts to look up an Amazon VPC from an [environment\-agnostic stack](stacks.md#stack_api), the CLI does not know which environment to query to find the VPC\. - -Results of `Vpc.fromLookup()` are cached in the project's `cdk.context.json` file\. Commit this file to version control if you will be deploying the stack in an environment that does not have access to the AWS account that defines the VPC, such as [CDK Pipelines](cdk_pipeline.md)\. - -Although you can use an external resource anywhere you'd use a similar resource defined in your app, you cannot modify the external resource\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an external `s3.Bucket` does nothing\. - ## Permission grants AWS constructs make least\-privilege permissions easy to achieve by offering simple, intent\-based APIs to express permission requirements\. Many AWS constructs offer grant methods that enable you to easily grant an entity, such as an IAM role or a user, permission to work with the resource without having to manually craft one or more IAM permission statements\. @@ -777,7 +777,7 @@ table.Grant(func, "dynamodb:CreateBackup"); Many resources, such as Lambda functions, require a role to be assumed when executing code\. A configuration property enables you to specify an `iam.IRole`\. If no role is specified, the function automatically creates a role specifically for this use\. You can then use grant methods on the resources to add statements to the role\. -The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyDocument.html) objects\. Add statements directly to roles \(or a construct's attached role\) using the `addToRolePolicy` method \(Python: `add_to_role_policy`\), or to a resource's policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` \(Python: `add_to_resource_policy`\) method\. +The grant methods are built using lower\-level APIs for handling with IAM policies\. Policies are modeled as [PolicyDocument](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-iam-readme.html) objects\. Add statements directly to roles \(or a construct's attached role\) using the `addToRolePolicy` method \(Python: `add_to_role_policy`\), or to a resource's policy \(such as a `Bucket` policy\) using the `addToResourcePolicy` \(Python: `add_to_resource_policy`\) method\. ## Metrics and alarms @@ -789,9 +789,9 @@ The following example shows how to define an alarm when the `ApproximateNumberOf #### [ TypeScript ] ``` -import * as cw from 'aws-cdk-lib/aws-cloudwatch'; -import * as sqs from 'aws-cdk-lib/aws-sqs'; -import { Duration } from 'aws-cdk-lib'; +import * as cw from '@aws-cdk/aws-cloudwatch'; +import * as sqs from '@aws-cdk/aws-sqs'; +import { Duration } from '@aws-cdk/core'; const queue = new sqs.Queue(this, 'MyQueue'); @@ -811,9 +811,9 @@ metric.createAlarm(this, 'TooManyMessagesAlarm', { #### [ JavaScript ] ``` -const cw = require('aws-cdk-lib/aws-cloudwatch'); -const sqs = require('aws-cdk-lib/aws-sqs'); -const { Duration } = require('aws-cdk-lib'); +const cw = require('@aws-cdk/aws-cloudwatch'); +const sqs = require('@aws-cdk/aws-sqs'); +const { Duration } = require('@aws-cdk/core'); const queue = new sqs.Queue(this, 'MyQueue'); @@ -835,7 +835,7 @@ metric.createAlarm(this, 'TooManyMessagesAlarm', { ``` import aws_cdk.aws_cloudwatch as cw import aws_cdk.aws_sqs as sqs -from aws_cdk import Duration +from aws_cdk.core import Duration queue = sqs.Queue(self, "MyQueue") metric = queue.metric_approximate_number_of_messages_not_visible( @@ -854,7 +854,7 @@ metric.create_alarm(self, "TooManyMessagesAlarm", #### [ Java ] ``` -import software.amazon.awscdk.Duration; +import software.amazon.awscdk.core.Duration; import software.amazon.awscdk.services.sqs.Queue; import software.amazon.awscdk.services.cloudwatch.Metric; import software.amazon.awscdk.services.cloudwatch.MetricOptions; @@ -916,8 +916,8 @@ You enable data to flow on a given network path by using `allow` methods\. The f #### [ TypeScript ] ``` -import * as asg from 'aws-cdk-lib/aws-autoscaling'; -import * as ec2 from 'aws-cdk-lib/aws-ec2'; +import * as asg from '@aws-cdk/aws-autoscaling'; +import * as ec2 from '@aws-cdk/aws-ec2'; const fleet1: asg.AutoScalingGroup = asg.AutoScalingGroup(/*...*/); @@ -932,8 +932,8 @@ fleet1.connections.allowFrom(fleet2, ec2.Port.AllTraffic()); #### [ JavaScript ] ``` -const asg = require('aws-cdk-lib/aws-autoscaling'); -const ec2 = require('aws-cdk-lib/aws-ec2'); +const asg = require('@aws-cdk/aws-autoscaling'); +const ec2 = require('@aws-cdk/aws-ec2'); const fleet1 = asg.AutoScalingGroup(); @@ -1061,7 +1061,7 @@ The following example shows how to trigger a Lambda function when an object is a #### [ TypeScript ] ``` -import * as s3nots from 'aws-cdk-lib/aws-s3-notifications'; +import * as s3nots from '@aws-cdk/aws-s3-notifications'; const handler = new lambda.Function(this, 'Handler', { /*…*/ }); const bucket = new s3.Bucket(this, 'Bucket'); @@ -1072,7 +1072,7 @@ bucket.addObjectCreatedNotification(new s3nots.LambdaDestination(handler)); #### [ JavaScript ] ``` -const s3nots = require('aws-cdk-lib/aws-s3-notifications'); +const s3nots = require('@aws-cdk/aws-s3-notifications'); const handler = new lambda.Function(this, 'Handler', { /*…*/ }); const bucket = new s3.Bucket(this, 'Bucket'); @@ -1120,7 +1120,7 @@ bucket.AddObjectCreatedNotification(new s3Nots.LambdaDestination(handler)); ## Removal policies -Resources that maintain persistent data, such as databases and Amazon S3 buckets and even Amazon ECR registries, have a *removal policy* that indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the `aws-cdk-lib` module\. +Resources that maintain persistent data, such as databases and Amazon S3 buckets and even Amazon ECR registries, have a *removal policy* that indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the AWS CDK `core` module\. **Note** Resources besides those that store data persistently may also have a `removalPolicy` that is used for a different purpose\. For example, a Lambda function version uses a `removalPolicy` attribute to determine whether a given version is retained when a new version is deployed\. These have different meanings and defaults compared to the removal policy on an Amazon S3 bucket or DynamoDB table\. @@ -1139,12 +1139,11 @@ Following is an example of creating an Amazon S3 bucket with `RemovalPolicy` of #### [ TypeScript ] ``` -import * as cdk from 'aws-cdk-lib'; -import { Construct } from 'constructs'; -import * as s3 from 'aws-cdk-lib/aws-s3'; +import * as cdk from '@aws-cdk/core'; +import * as s3 from '@aws-cdk/aws-s3'; export class CdkTestStack extends cdk.Stack { - constructor(scope: Construct, id: string, props?: cdk.StackProps) { + constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const bucket = new s3.Bucket(this, 'Bucket', { @@ -1159,8 +1158,8 @@ export class CdkTestStack extends cdk.Stack { #### [ JavaScript ] ``` -const cdk = require('aws-cdk-lib'); -const s3 = require('aws-cdk-lib/aws-s3'); +const cdk = require('@aws-cdk/core'); +const s3 = require('@aws-cdk/aws-s3'); class CdkTestStack extends cdk.Stack { constructor(scope, id, props) { @@ -1180,12 +1179,11 @@ module.exports = { CdkTestStack } #### [ Python ] ``` -import aws_cdk as cdk -from constructs import Construct +import aws_cdk.core as cdk import aws_cdk.aws_s3 as s3 class CdkTestStack(cdk.stack): - def __init__(self, scope: Construct, id: str, **kwargs): + def __init__(self, scope: cdk.Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) bucket = s3.Bucket(self, "Bucket", @@ -1197,7 +1195,7 @@ class CdkTestStack(cdk.stack): #### [ Java ] ``` -software.amazon.awscdk.*; +software.amazon.awscdk.core.*; import software.amazon.awscdk.services.s3.*; public class CdkTestStack extends Stack { diff --git a/v2/tagging.md b/v2/tagging.md index d6c8dece..44abe2f7 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 1df7fdf8..dca32d9d 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 0296d4e1a5223a0990af0ff5b0868d4d0a46888b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 25 Aug 2022 21:38:42 +0000 Subject: [PATCH 569/655] improve visibilty of escape hatches and add context about abstraction levels (plus some churn) --- v1/cfn_layer.md | 26 ++++++++++---- v1/cli.md | 26 +++++++------- v1/getting_started.md | 2 +- v1/hello_world.md | 2 +- v1/index.md | 2 +- v1/use_cfn_template.md | 2 +- v2/cfn_layer.md | 78 +++++++++++++++++++++++++++++++++++++++--- v2/cli.md | 26 +++++++------- v2/getting_started.md | 2 +- v2/hello_world.md | 2 +- v2/index.md | 2 +- v2/use_cfn_template.md | 2 +- 12 files changed, 127 insertions(+), 45 deletions(-) diff --git a/v1/cfn_layer.md b/v1/cfn_layer.md index 1e0a9602..6c1c17d8 100644 --- a/v1/cfn_layer.md +++ b/v1/cfn_layer.md @@ -1,9 +1,23 @@ -# Escape hatches +# Abstractions and escape hatches -It's possible that neither the high\-level constructs nor the low\-level CFN Resource constructs have a specific feature you are looking for\. There are three possible reasons for this lack of functionality: -+ The AWS service feature is available through AWS CloudFormation, but there are no Construct classes for the service\. -+ The AWS service feature is available through AWS CloudFormation, and there are Construct classes for the service, but the Construct classes don't yet expose the feature\. -+ The feature is not yet available through AWS CloudFormation\. +The AWS CDK lets you describe AWS resources using constructs that operate at varying levels of abstraction\. ++ *Layer 1 \(L1\)* constructs directly represent AWS CloudFormation resources as defined by the CloudFormation specification\. These constructs can be identified via a name beginning with "Cfn," so they are also referred to as "Cfn constructs\." If a resource exists in AWS CloudFormation, it exists in the CDK as a L1 construct\. ++ *Layer 2 \(L2\)* or "curated" constructs are thoughtfully developed to provide a more ergonomic developer experience compared to the L1 construct they're built upon\. In a typical CDK app, L2 constructs are usually the most widely used type\. Often, L2 constructs define additional supporting resources, such as IAM policies, Amazon SNS topics, or AWS KMS keys\. L1 constructs sensible defaults, best\-practice security policies, and\. ++ *Layer 3 \(L3\)* constructs or *patterns* define entire collections of AWS resources for specific use cases, making it easy to stand up a build pipeline, an Amazon ECS application, or one of many other types of common deployment scenarios\. Because they can constitute complete system designs, or substantial parts of a larger system, L3 constructs are often "opinionated"—they are built around a very particular approach toward solving the problem at hand, and things work out best when you follow their lead\. + +**Tip** +For more details on AWS CDK constructs, see [Constructs](constructs.md)\. + +At the highest level, your AWS CDK application and the stacks in it are themselves abstractions of your entire cloud infrastructure, or significant chunks of it, and may be parameterized to deploy them in different environments or for different needs\. + +Abstractions are powerful tools for designing and implementing cloud applications\. The AWS CDK gives you the power not only to build with its abstractions, but also to create new abstractions\. Using the existing open\-source L2 and L3 constructs as guidance, you can build your own L2 and L3 constructs to reflect your own organization's best practices and opinions\. + +No abstraction is perfect, and even good abstractions cannot cover every possible use case\. While the value of the AWS CDK's model is plain, sometimes you'll come upon a construct that's perfect for your needs—if only you could make a small \(or large\) tweak\. For this reason, the AWS CDK provides ways to "break out" of the construct model, moving to a lower level of abstraction or to a different model entirely\. As their name implies, the CDK's *escape hatches* let you "escape" the AWS CDK paradigm and extend it in ways the AWS CDK designers never anticipated\. Then you can wrap all that in a new construct to hide the underlying complexity and provide a clean API for developers\. + +Some situations in which you'll reach for escape hatches include: ++ An AWS service feature is available through AWS CloudFormation, but there are no Construct constructs for it\. ++ An AWS service feature is available through AWS CloudFormation, and there are Construct constructs for the service, but these don't yet expose the feature\. Because Construct constructs are developed "by hand," they may sometimes lag behind the CFN Resource constructs\. ++ The feature is not yet available through AWS CloudFormation at all\. To determine whether a feature is available through AWS CloudFormation, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. @@ -434,5 +448,5 @@ Building a custom resource involves writing a Lambda function that responds to a The subject is too broad to completely cover here, but the following links should get you started: + [Custom Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) -+ [Custom\-Resource Example](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1/typescript/custom-resource/) ++ [Custom\-Resource Example](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) + For a more fully fledged example, see the [DnsValidatedCertificate](https://github.com/awslabs/aws-cdk/blob/master/packages/@aws-cdk/aws-certificatemanager/lib/dns-validated-certificate.ts) class in the CDK standard library\. This is implemented as a custom resource\. \ No newline at end of file diff --git a/v1/cli.md b/v1/cli.md index 1613e6a3..6bf76ce5 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -351,7 +351,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -370,7 +370,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -378,7 +378,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -454,7 +454,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -476,7 +476,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -733,7 +733,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -746,7 +746,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -767,7 +767,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -847,7 +847,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -925,7 +925,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -944,7 +944,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -970,7 +970,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -992,7 +992,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/getting_started.md b/v1/getting_started.md index b5ac653c..4397f7d6 100644 --- a/v1/getting_started.md +++ b/v1/getting_started.md @@ -238,7 +238,7 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. + See the [API reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) to begin exploring the provided constructs available for your favorite AWS services\. + Visit the [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=1&sort=downloadsDesc&offset=0) to find constructs from the CDK community as well as from AWS\. -+ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. ++ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Abstractions and escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1) of using the AWS CDK\. The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/v1/hello_world.md b/v1/hello_world.md index 40b7eb85..e942bb86 100644 --- a/v1/hello_world.md +++ b/v1/hello_world.md @@ -584,7 +584,7 @@ If we hadn't changed the bucket's `RemovalPolicy`, the stack deletion would comp Where do you go now that you've dipped your toes in the AWS CDK? + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. -+ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. ++ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Abstractions and escape hatches](cfn_layer.md)\. + See the [API reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite AWS services\. + Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=1&sort=downloadsDesc&offset=0) to discover constructs created by AWS and others\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1) of using the AWS CDK\. diff --git a/v1/index.md b/v1/index.md index 851eafc0..548eb7cc 100644 --- a/v1/index.md +++ b/v1/index.md @@ -42,8 +42,8 @@ Amazon's trademarks and trade dress may not be used in + [Runtime context](context.md) + [Feature flags](featureflags.md) + [Aspects](aspects.md) - + [Escape hatches](cfn_layer.md) + [Bootstrapping](bootstrapping.md) ++ [Abstractions and escape hatches](cfn_layer.md) + [Best practices for developing and deploying cloud infrastructure with the AWS CDK](best-practices.md) + [API reference](reference.md) + [Examples](examples.md) diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index 6381181f..497b21bb 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/cfn_layer.md b/v2/cfn_layer.md index 9501075d..43755f50 100644 --- a/v2/cfn_layer.md +++ b/v2/cfn_layer.md @@ -1,9 +1,23 @@ -# Escape hatches +# Abstractions and escape hatches -It's possible that neither the high\-level constructs nor the low\-level CFN Resource constructs have a specific feature you are looking for\. There are three possible reasons for this lack of functionality: -+ The AWS service feature is available through AWS CloudFormation, but there are no Construct classes for the service\. -+ The AWS service feature is available through AWS CloudFormation, and there are Construct classes for the service, but the Construct classes don't yet expose the feature\. -+ The feature is not yet available through AWS CloudFormation\. +The AWS CDK lets you describe AWS resources using constructs that operate at varying levels of abstraction\. ++ *Layer 1 \(L1\)* constructs directly represent AWS CloudFormation resources as defined by the CloudFormation specification\. These constructs can be identified via a name beginning with "Cfn," so they are also referred to as "Cfn constructs\." If a resource exists in AWS CloudFormation, it exists in the CDK as a L1 construct\. ++ *Layer 2 \(L2\)* or "curated" constructs are thoughtfully developed to provide a more ergonomic developer experience compared to the L1 construct they're built upon\. In a typical CDK app, L2 constructs are usually the most widely used type\. Often, L2 constructs define additional supporting resources, such as IAM policies, Amazon SNS topics, or AWS KMS keys\. L1 constructs sensible defaults, best\-practice security policies, and\. ++ *Layer 3 \(L3\)* constructs or *patterns* define entire collections of AWS resources for specific use cases, making it easy to stand up a build pipeline, an Amazon ECS application, or one of many other types of common deployment scenarios\. Because they can constitute complete system designs, or substantial parts of a larger system, L3 constructs are often "opinionated"—they are built around a very particular approach toward solving the problem at hand, and things work out best when you follow their lead\. + +**Tip** +For more details on AWS CDK constructs, see [Constructs](constructs.md)\. + +At the highest level, your AWS CDK application and the stacks in it are themselves abstractions of your entire cloud infrastructure, or significant chunks of it, and may be parameterized to deploy them in different environments or for different needs\. + +Abstractions are powerful tools for designing and implementing cloud applications\. The AWS CDK gives you the power not only to build with its abstractions, but also to create new abstractions\. Using the existing open\-source L2 and L3 constructs as guidance, you can build your own L2 and L3 constructs to reflect your own organization's best practices and opinions\. + +No abstraction is perfect, and even good abstractions cannot cover every possible use case\. While the value of the AWS CDK's model is plain, sometimes you'll come upon a construct that's perfect for your needs—if only you could make a small \(or large\) tweak\. For this reason, the AWS CDK provides ways to "break out" of the construct model, moving to a lower level of abstraction or to a different model entirely\. As their name implies, the CDK's *escape hatches* let you "escape" the AWS CDK paradigm and extend it in ways the AWS CDK designers never anticipated\. Then you can wrap all that in a new construct to hide the underlying complexity and provide a clean API for developers\. + +Some situations in which you'll reach for escape hatches include: ++ An AWS service feature is available through AWS CloudFormation, but there are no Construct constructs for it\. ++ An AWS service feature is available through AWS CloudFormation, and there are Construct constructs for the service, but these don't yet expose the feature\. Because Construct constructs are developed "by hand," they may sometimes lag behind the CFN Resource constructs\. ++ The feature is not yet available through AWS CloudFormation at all\. To determine whether a feature is available through AWS CloudFormation, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. @@ -308,6 +322,60 @@ cfnBucket.CfnOptions.Metadata = new Dictionary ------ +## An unescape hatch + +The AWS CDK also provides the capability to go *up* an abstraction level, which we might cheekily refer to as an "unescape" hatch\. If you have an L1 construct, such as `CfnBucket`, you can create a new L2 construct \(`Bucket` in this case\) to wrap the L1 construct\. This is convenient when you have created an L1 resource but want to use it with a construct that requires an L2 resource, or want to use convenience methods like `.grantXxxxx()` that aren't available on the L1 construct\. + +You move to the higher abstraction level using a static method on the L2 class called `.fromCfnXxxxx()`—for example, `Bucket.fromCfnBucket()` for Amazon S3 buckets\. The L1 resource is the only parameter\. + +------ +#### [ TypeScript ] + +``` +b1 = new s3.CfnBucket(this, "buck09", { ... }); +b2 = s3.Bucket.fromCfnBucket(b1); +``` + +------ +#### [ JavaScript ] + +``` +b1 = new s3.CfnBucket(this, "buck09", { ...} ); +b2 = s3.Bucket.fromCfnBucket(b1); +``` + +------ +#### [ Python ] + +``` +b1 = s3.CfnBucket(self, "buck09", ...) + b2 = s3.from_cfn_bucket(b1) +``` + +------ +#### [ Java ] + +``` +CfnBucket b1 = CfnBucket.Builder.create(this, "buck09") + // .... + .build(); +IBucket b2 = Bucket.fromCfnBucket(b1); +``` + +------ +#### [ C\# ] + +``` +var b1 = new CfnBucket(this, "buck09", new CfnBucketProps { ... }); +var v2 = Bucket.FromCfnBucket(b1); +``` + +------ + +L2 constructs created from L1 constructs are proxy objects that refer to the L1 resource, similar to those created from resource names, ARNs, or lookups\. Modifications to these constructs do not affect the final synthesized AWS CloudFormation template \(since you have the L1 resource, however, you can modify that instead\)\. For more information on proxy objects, see [Referencing resources in your AWS account](resources.md#resources_external)\. + +To avoid confusion, do not create multiple L2 constructs that refer to the same L1 construct\. For example, if you extract the `CfnBucket` from a `Bucket` using the technique in the [previous section](#cfn_layer_resource), you shouldn't create a second `Bucket` instance by calling `Bucket.fromCfnBucket()` with that `CfnBucket`\. It actually works as you'd expect \(only one `AWS::S3::Bucket` is synthesized\) but it makes your code more difficult to maintain\.\. + ## Raw overrides If there are properties that are missing from the CFN Resource, you can bypass all typing using raw overrides\. This also makes it possible to delete synthesized properties\. diff --git a/v2/cli.md b/v2/cli.md index 665d6f14..e0515b8e 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -343,7 +343,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -362,7 +362,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -370,7 +370,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -446,7 +446,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -468,7 +468,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -725,7 +725,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -738,7 +738,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -759,7 +759,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -839,7 +839,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -917,7 +917,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -936,7 +936,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -962,7 +962,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -984,7 +984,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/getting_started.md b/v2/getting_started.md index 50d93186..084a13fb 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -291,7 +291,7 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. + See the [API reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) to begin exploring the provided constructs available for your favorite AWS services\. + Visit the [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) to find constructs from the CDK community as well as from AWS\. -+ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. ++ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Abstractions and escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file diff --git a/v2/hello_world.md b/v2/hello_world.md index 756eff8b..eb5c2516 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -525,7 +525,7 @@ If we hadn't changed the bucket's `RemovalPolicy`, the stack deletion would comp Where do you go now that you've dipped your toes in the AWS CDK? + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. -+ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Escape hatches](cfn_layer.md)\. ++ Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Abstractions and escape hatches](cfn_layer.md)\. + See the [API reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) to begin exploring the CDK constructs available for your favorite AWS services\. + Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) to discover constructs created by AWS and others\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. diff --git a/v2/index.md b/v2/index.md index dab06c11..5dda212f 100644 --- a/v2/index.md +++ b/v2/index.md @@ -42,8 +42,8 @@ Amazon's trademarks and trade dress may not be used in + [Runtime context](context.md) + [Feature flags](featureflags.md) + [Aspects](aspects.md) - + [Escape hatches](cfn_layer.md) + [Bootstrapping](bootstrapping.md) ++ [Abstractions and escape hatches](cfn_layer.md) + [Best practices for developing and deploying cloud infrastructure with the AWS CDK](best-practices.md) + [API reference](reference.md) + [Examples](examples.md) diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index dca32d9d..d42a3f21 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From bbd0a021db441b0f60412d66a326c26751c11d34 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 29 Aug 2022 22:46:35 +0000 Subject: [PATCH 570/655] recent changes from AWS docs master --- v1/apps.md | 6 ++++-- v1/cli.md | 26 +++++++++++------------ v1/getting_started.md | 3 +++ v1/manage-dependencies.md | 10 ++++----- v1/tagging.md | 2 +- v1/use_cfn_template.md | 2 +- v1/work-with-cdk-csharp.md | 3 +++ v1/work-with-cdk-go.md | 3 +++ v1/work-with-cdk-java.md | 3 +++ v1/work-with-cdk-javascript.md | 3 +++ v1/work-with-cdk-python.md | 3 +++ v1/work-with-cdk-typescript.md | 3 +++ v1/work-with-cdk-v2.md | 3 +++ v1/work-with.md | 3 +++ v2/apps.md | 8 ++++--- v2/cli.md | 26 +++++++++++------------ v2/getting_started.md | 3 +++ v2/manage-dependencies.md | 10 ++++----- v2/migrating-v2.md | 5 ++++- v2/stack_how_to_create_multiple_stacks.md | 2 +- v2/tagging.md | 2 +- v2/use_cfn_template.md | 2 +- v2/work-with-cdk-csharp.md | 3 +++ v2/work-with-cdk-go.md | 3 +++ v2/work-with-cdk-java.md | 3 +++ v2/work-with-cdk-javascript.md | 3 +++ v2/work-with-cdk-python.md | 3 +++ v2/work-with-cdk-typescript.md | 3 +++ v2/work-with.md | 3 +++ 29 files changed, 105 insertions(+), 47 deletions(-) diff --git a/v1/apps.md b/v1/apps.md index 4f9339ad..5280e2ff 100644 --- a/v1/apps.md +++ b/v1/apps.md @@ -1,6 +1,6 @@ # Apps -As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/v1/docs/core/stack.html) construct\. +As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/v1/docs/core/stack.html) construct\. An [App](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.App.html) is a container for one or more stacks: it serves as each stack's scope\. Stacks within a single `App` can easily refer to each others' resources \(and attributes of those resources\)\. The AWS CDK infers dependencies between stacks so that they can be deployed in the correct order\. You can deploy any or all of the stacks defined within an app at with a single `cdk deploy` command\. The following example declares a stack class named `MyFirstStack` that includes a single Amazon S3 bucket\. However, this only declares a stack\. You still need to define \(also known as to instantiate\) it in some scope to deploy it\. @@ -74,6 +74,8 @@ public class MyFirstStack : Stack ------ +However, this code has only *declared* a stack\. For the stack to actually be synthesized into a AWS CloudFormation template and deployed, it needs to be instantiated\. And, like all CDK constructs, it must be instantiated in some context\. The `App` is that context\. + ## The app construct To define the previous stack within the scope of an application, use the [App](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.App.html) construct\. The following example app instantiates a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. @@ -151,7 +153,7 @@ This is the final stage of the execution of your AWS CDK app\. It's triggered by In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: -+ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1/typescript/custom-resource/) example\. ++ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you may inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1/typescript/custom-resource/) example\. + The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)` \(Python: `is_token`\)\. See [Tokens](tokens.md) for details\. ## Cloud assemblies diff --git a/v1/cli.md b/v1/cli.md index 6bf76ce5..376ef849 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -351,7 +351,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -370,7 +370,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -378,7 +378,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -454,7 +454,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -476,7 +476,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -733,7 +733,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -746,7 +746,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -767,7 +767,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -847,7 +847,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -925,7 +925,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -944,7 +944,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -970,7 +970,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -992,7 +992,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/getting_started.md b/v1/getting_started.md index 4397f7d6..d5c53d4e 100644 --- a/v1/getting_started.md +++ b/v1/getting_started.md @@ -185,6 +185,9 @@ Visual Studio 2019 \(any edition\) or Visual Studio Code recommended\. ------ +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## Install the AWS CDK Install the AWS CDK Toolkit globally using the following Node Package Manager command\. diff --git a/v1/manage-dependencies.md b/v1/manage-dependencies.md index e34c2c09..7ce395a8 100644 --- a/v1/manage-dependencies.md +++ b/v1/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -72,7 +72,7 @@ All AWS CDK dependencies must have the same version\. Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -99,7 +99,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -145,7 +145,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -169,7 +169,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v1/tagging.md b/v1/tagging.md index 9cdcc43d..ff296092 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index 497b21bb..cd8d1dfe 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v1/work-with-cdk-csharp.md b/v1/work-with-cdk-csharp.md index ef6298b5..53824b88 100644 --- a/v1/work-with-cdk-csharp.md +++ b/v1/work-with-cdk-csharp.md @@ -12,6 +12,9 @@ To work with the AWS CDK, you must have an AWS account and credentials and have C\# AWS CDK applications require \.NET Core v3\.1 or later, [available here](https://dotnet.microsoft.com/download/dotnet-core/3.1)\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + The \.NET toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if you work mainly in Visual Studio, this command can be useful for batch operations and for installing AWS Construct Library packages\. ## Creating a project diff --git a/v1/work-with-cdk-go.md b/v1/work-with-cdk-go.md index e4ef8608..c934358b 100644 --- a/v1/work-with-cdk-go.md +++ b/v1/work-with-cdk-go.md @@ -12,6 +12,9 @@ To work with the AWS CDK, you must have an AWS account and credentials and have The Go bindings for the AWS CDK use the standard [Go toolchain](https://golang.org/dl/), v1\.16 or later\. You can use the editor of your choice\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. diff --git a/v1/work-with-cdk-java.md b/v1/work-with-cdk-java.md index 8b1aa2d2..5c0be3a5 100644 --- a/v1/work-with-cdk-java.md +++ b/v1/work-with-cdk-java.md @@ -17,6 +17,9 @@ To work with the AWS CDK, you must have an AWS account and credentials and have Java AWS CDK applications require Java 8 \(v1\.8\) or later\. We recommend [Amazon Corretto](https://aws.amazon.com/corretto/), but you can use any OpenJDK distribution or [Oracle's JDK](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)\. You will also need [Apache Maven](https://maven.apache.org/download.cgi) 3\.5 or later\. You can also use tools such as Gradle, but the application skeletons generated by the AWS CDK Toolkit are Maven projects\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. diff --git a/v1/work-with-cdk-javascript.md b/v1/work-with-cdk-javascript.md index b669e9f9..7a918fee 100644 --- a/v1/work-with-cdk-javascript.md +++ b/v1/work-with-cdk-javascript.md @@ -10,6 +10,9 @@ To work with the AWS CDK, you must have an AWS account and credentials and have JavaScript AWS CDK applications require no additional prerequisites beyond these\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. diff --git a/v1/work-with-cdk-python.md b/v1/work-with-cdk-python.md index 529ca48e..55561845 100644 --- a/v1/work-with-cdk-python.md +++ b/v1/work-with-cdk-python.md @@ -10,6 +10,9 @@ To work with the AWS CDK, you must have an AWS account and credentials and have Python AWS CDK applications require Python 3\.6 or later\. If you don't already have it installed, [download a compatible version](https://www.python.org/downloads/) for your operating system at [python\.org](https://www.python.org/)\. If you run Linux, your system may have come with a compatible version, or you may install it using your distro's package manager \(`yum`, `apt`, etc\.\)\. Mac users may be interested in [Homebrew](https://brew.sh/), a Linux\-style package manager for macOS\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + The Python package installer, `pip`, and virtual environment manager, `virtualenv`, are also required\. Windows installations of compatible Python versions include these tools\. On Linux, `pip` and `virtualenv` may be provided as separate packages in your package manager\. Alternatively, you may install them with the following commands: ``` diff --git a/v1/work-with-cdk-typescript.md b/v1/work-with-cdk-typescript.md index 696f22b6..f4772f52 100644 --- a/v1/work-with-cdk-typescript.md +++ b/v1/work-with-cdk-typescript.md @@ -19,6 +19,9 @@ If you get a permission error, and have administrator access on your system, try Keep TypeScript up to date with a regular `npm update -g typescript`\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. diff --git a/v1/work-with-cdk-v2.md b/v1/work-with-cdk-v2.md index 07094a46..03f02e00 100644 --- a/v1/work-with-cdk-v2.md +++ b/v1/work-with-cdk-v2.md @@ -6,6 +6,9 @@ CDK v1 entered maintenance on June 1, 2022\. During the maintenance phase, CDK v For information on migrating your apps to AWS CDK v2, see [Migrating to AWS CDK v2](../../v2/guide/migrating-v2.html) in the AWS CDK v2 Developer Guide\. +**Tip** +To identify stacks deployed with AWS CDK v1, use the [awscdk\-v1\-stack\-finder](https://www.npmjs.com/package/awscdk-v1-stack-finder) utility\. + ## CDK Toolkit v2 compatibility CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compatible with CDK v1 apps, so you can use a single globally\-installed version of CDK Toolkit with all your AWS CDK projects, whether they use v1 or v2\. An exception is that CDK Toolkit v2 creates CDK v2 projects\. diff --git a/v1/work-with.md b/v1/work-with.md index b5748cf7..09e79c33 100644 --- a/v1/work-with.md +++ b/v1/work-with.md @@ -43,6 +43,9 @@ The specific language you work in also has its own prerequisites, described in t + [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) + [Working with the AWS CDK in Go](work-with-cdk-go.md) +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## AWS Construct Library The AWS CDK includes the AWS Construct Library, a collection of construct modules organized by AWS service\. The [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html) provides detailed documentation of the constructs \(and other components\) in the library\. A version of the API Reference is provided for each supported programming language\. diff --git a/v2/apps.md b/v2/apps.md index 28406e7c..482a56a7 100644 --- a/v2/apps.md +++ b/v2/apps.md @@ -1,8 +1,8 @@ # Apps -As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html) construct\. +As described in [Constructs](constructs.md), to provision infrastructure resources, all constructs that represent AWS resources must be defined, directly or indirectly, within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html) construct\. An [App](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.App.html) is a container for one or more stacks: it serves as each stack's scope\. Stacks within a single `App` can easily refer to each others' resources \(and attributes of those resources\)\. The AWS CDK infers dependencies between stacks so that they can be deployed in the correct order\. You can deploy any or all of the stacks defined within an app at with a single `cdk deploy` command\. -The following example declares a stack class named `MyFirstStack` that includes a single Amazon S3 bucket\. However, this only declares a stack\. You still need to define \(also known as to instantiate\) it in some scope to deploy it\. +The following example declares a stack class named `MyFirstStack` that includes a single Amazon S3 bucket\. ------ #### [ TypeScript ] @@ -74,6 +74,8 @@ public class MyFirstStack : Stack ------ +However, this code has only *declared* a stack\. For the stack to actually be synthesized into a AWS CloudFormation template and deployed, it needs to be instantiated\. And, like all CDK constructs, it must be instantiated in some context\. The `App` is that context\. + ## The app construct To define the previous stack within the scope of an application, use the [App](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.App.html) construct\. The following example app instantiates a `MyFirstStack` and produces the AWS CloudFormation template that the stack defined\. @@ -151,7 +153,7 @@ This is the final stage of the execution of your AWS CDK app\. It's triggered by In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: -+ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you have to inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. ++ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you may inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. + The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)` \(Python: `is_token`\)\. See [Tokens](tokens.md) for details\. ## Cloud assemblies diff --git a/v2/cli.md b/v2/cli.md index e0515b8e..31cdb8b6 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -343,7 +343,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -362,7 +362,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -370,7 +370,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -446,7 +446,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -468,7 +468,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -725,7 +725,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -738,7 +738,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -759,7 +759,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -839,7 +839,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -917,7 +917,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -936,7 +936,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -962,7 +962,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -984,7 +984,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/getting_started.md b/v2/getting_started.md index 084a13fb..f3f22f96 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -235,6 +235,9 @@ Visual Studio 2019 \(any edition\) or Visual Studio Code recommended\. ------ +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## Install the AWS CDK Install the AWS CDK Toolkit globally using the following Node Package Manager command\. diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index 2c03193f..d74ad6ff 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -71,7 +71,7 @@ Specify exact versions for alpha construct library modules, which have APIs that Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -101,7 +101,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -147,7 +147,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -167,7 +167,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 99db546c..f72f9a28 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -1,6 +1,9 @@ # Migrating to AWS CDK v2 -Version 2 of the AWS Cloud Development Kit \(AWS CDK\) is designed to make writing infrastructure as code in your preferred programming language even easier\. +Version 2 of the AWS Cloud Development Kit \(AWS CDK\) is designed to make writing infrastructure as code in your preferred programming language even easier\. This topic describes the changes between v1 and v2 of the AWS CDK\. + +**Tip** +To identify stacks deployed with AWS CDK v1, use the [awscdk\-v1\-stack\-finder](https://www.npmjs.com/package/awscdk-v1-stack-finder) utility\. The main changes from AWS CDK v1 to CDK v2 are as follows\. + AWS CDK v2 consolidates the stable parts of the AWS Construct Library, including the core library, into a single package, `aws-cdk-lib`\. Developers no longer need to install additional packages for the individual AWS services they use\. This single\-package approach also eliminates the need to synchronize the versions of the various CDK library packages\. diff --git a/v2/stack_how_to_create_multiple_stacks.md b/v2/stack_how_to_create_multiple_stacks.md index 46346220..e2963465 100644 --- a/v2/stack_how_to_create_multiple_stacks.md +++ b/v2/stack_how_to_create_multiple_stacks.md @@ -121,7 +121,7 @@ Python does not have an interface feature, so we'll extend our stack to accept t ``` import aws_cdk as cdk -import Construct from constructs +from constructs import Construct class MultistackStack(cdk.Stack): diff --git a/v2/tagging.md b/v2/tagging.md index 44abe2f7..5fd2afda 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index d42a3f21..02b148e5 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/work-with-cdk-csharp.md b/v2/work-with-cdk-csharp.md index 8497a335..a3b29eb1 100644 --- a/v2/work-with-cdk-csharp.md +++ b/v2/work-with-cdk-csharp.md @@ -12,6 +12,9 @@ To work with the AWS CDK, you must have an AWS account and credentials and have C\# AWS CDK applications require \.NET Core v3\.1 or later, [available here](https://dotnet.microsoft.com/download/dotnet-core/3.1)\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + The \.NET toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if you work mainly in Visual Studio, this command can be useful for batch operations and for installing AWS Construct Library packages\. ## Creating a project diff --git a/v2/work-with-cdk-go.md b/v2/work-with-cdk-go.md index 2dac2823..1221680f 100644 --- a/v2/work-with-cdk-go.md +++ b/v2/work-with-cdk-go.md @@ -12,6 +12,9 @@ To work with the AWS CDK, you must have an AWS account and credentials and have The Go bindings for the AWS CDK use the standard [Go toolchain](https://golang.org/dl/), v1\.16 or later\. You can use the editor of your choice\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. diff --git a/v2/work-with-cdk-java.md b/v2/work-with-cdk-java.md index 0a9eba42..d0ee5b8c 100644 --- a/v2/work-with-cdk-java.md +++ b/v2/work-with-cdk-java.md @@ -17,6 +17,9 @@ To work with the AWS CDK, you must have an AWS account and credentials and have Java AWS CDK applications require Java 8 \(v1\.8\) or later\. We recommend [Amazon Corretto](https://aws.amazon.com/corretto/), but you can use any OpenJDK distribution or [Oracle's JDK](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)\. You will also need [Apache Maven](https://maven.apache.org/download.cgi) 3\.5 or later\. You can also use tools such as Gradle, but the application skeletons generated by the AWS CDK Toolkit are Maven projects\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. diff --git a/v2/work-with-cdk-javascript.md b/v2/work-with-cdk-javascript.md index 4dda0702..c1d945cc 100644 --- a/v2/work-with-cdk-javascript.md +++ b/v2/work-with-cdk-javascript.md @@ -10,6 +10,9 @@ To work with the AWS CDK, you must have an AWS account and credentials and have JavaScript AWS CDK applications require no additional prerequisites beyond these\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. diff --git a/v2/work-with-cdk-python.md b/v2/work-with-cdk-python.md index dbf4cc48..81653c06 100644 --- a/v2/work-with-cdk-python.md +++ b/v2/work-with-cdk-python.md @@ -10,6 +10,9 @@ To work with the AWS CDK, you must have an AWS account and credentials and have Python AWS CDK applications require Python 3\.6 or later\. If you don't already have it installed, [download a compatible version](https://www.python.org/downloads/) for your operating system at [python\.org](https://www.python.org/)\. If you run Linux, your system may have come with a compatible version, or you may install it using your distro's package manager \(`yum`, `apt`, etc\.\)\. Mac users may be interested in [Homebrew](https://brew.sh/), a Linux\-style package manager for macOS\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + The Python package installer, `pip`, and virtual environment manager, `virtualenv`, are also required\. Windows installations of compatible Python versions include these tools\. On Linux, `pip` and `virtualenv` may be provided as separate packages in your package manager\. Alternatively, you may install them with the following commands: ``` diff --git a/v2/work-with-cdk-typescript.md b/v2/work-with-cdk-typescript.md index e61056c4..ddce401e 100644 --- a/v2/work-with-cdk-typescript.md +++ b/v2/work-with-cdk-typescript.md @@ -19,6 +19,9 @@ If you get a permission error, and have administrator access on your system, try Keep TypeScript up to date with a regular `npm update -g typescript`\. +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. diff --git a/v2/work-with.md b/v2/work-with.md index d3274b13..34452937 100644 --- a/v2/work-with.md +++ b/v2/work-with.md @@ -43,6 +43,9 @@ The specific language you work in also has its own prerequisites, described in t + [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) + [Working with the AWS CDK in Go](work-with-cdk-go.md) +**Note** +Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. + ## AWS Construct Library The AWS CDK includes the AWS Construct Library, a collection of constructs organized by AWS service\. The library's constructs are mainly in a single module, colloquially called `aws-cdk-lib` because that's its name in TypeScript\. The actual package name of the main CDK package varies by language\. From fa18faef18db2c667750a89782d73febce0ee66b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 2 Sep 2022 20:12:37 +0000 Subject: [PATCH 571/655] add some details on a common pattern for producing/consuming resources between stacks --- v1/resources.md | 12 ++++++++---- v2/resources.md | 12 ++++++++---- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/v1/resources.md b/v1/resources.md index 03735ad9..f1865ffe 100644 --- a/v1/resources.md +++ b/v1/resources.md @@ -173,7 +173,11 @@ var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cl ## Referencing resources in a different stack -You can directly reference resources in a different stack, as long as they are defined in the same app and are in the same AWS account and region\. The following example defines the stack `stack1`, which defines an Amazon S3 bucket\. Then it defines a second stack, `stack2`, which takes the bucket from `stack1` as a constructor property\. +You can refer to resources in a different stack as long as they are defined in the same app and are in the same AWS account and region\. The pattern generally used is: ++ Store a reference to the construct as an attribute of the stack that produces the resource\. \(To get a reference to the current construct's stack, use `Stack.of(this)`\.\) ++ Pass this reference to the constructor of the stack that consumes the resource as a parameter or a property\. The consuming stack then passes it as a property to any construct that needs it\. + +The following example defines a stack `stack1`\. This stack defines an Amazon S3 bucket and stores a reference to the bucket construct as an attribute of the stack\. Then the app defines a second stack, `stack2`, which accepts a bucket at instantiation\. `stack2` might, for example, define an AWS Glue Table that uses the bucket for data storage\. ------ #### [ TypeScript ] @@ -198,7 +202,7 @@ const prod = { account: '123456789012', region: 'us-east-1' }; const stack1 = new StackThatProvidesABucket(app, 'Stack1', { env: prod }); -// stack2 will take a property { bucket: IBucket } +// stack2 will take a property { bucket } const stack2 = new StackThatExpectsABucket(app, 'Stack2', { bucket: stack1.bucket, env: prod @@ -236,7 +240,7 @@ StackThatProvidesABucket stack1 = new StackThatProvidesABucket(app, "Stack1", // stack2 will take an argument "bucket" StackThatExpectsABucket stack2 = new StackThatExpectsABucket(app, "Stack,", - StackProps.builder().env(prod).build(), stack1.getBucket()); + StackProps.builder().env(prod).build(), stack1.bucket); ``` ------ @@ -252,7 +256,7 @@ var prod = makeEnv(account: "123456789012", region: "us-east-1"); var stack1 = new StackThatProvidesABucket(app, "Stack1", new StackProps { Env = prod }); -// stack2 will take an argument "bucket" +// stack2 will take a property "bucket" var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = prod, bucket = stack1.Bucket}); ``` diff --git a/v2/resources.md b/v2/resources.md index f0c7d9ad..e704f8a9 100644 --- a/v2/resources.md +++ b/v2/resources.md @@ -173,7 +173,11 @@ var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cl ## Referencing resources in a different stack -You can directly reference resources in a different stack, as long as they are defined in the same app and are in the same AWS account and region\. The following example defines the stack `stack1`, which defines an Amazon S3 bucket\. Then it defines a second stack, `stack2`, which takes the bucket from `stack1` as a constructor property\. +You can refer to resources in a different stack as long as they are defined in the same app and are in the same AWS account and region\. The pattern generally used is: ++ Store a reference to the construct as an attribute of the stack that produces the resource\. \(To get a reference to the current construct's stack, use `Stack.of(this)`\.\) ++ Pass this reference to the constructor of the stack that consumes the resource as a parameter or a property\. The consuming stack then passes it as a property to any construct that needs it\. + +The following example defines a stack `stack1`\. This stack defines an Amazon S3 bucket and stores a reference to the bucket construct as an attribute of the stack\. Then the app defines a second stack, `stack2`, which accepts a bucket at instantiation\. `stack2` might, for example, define an AWS Glue Table that uses the bucket for data storage\. ------ #### [ TypeScript ] @@ -236,7 +240,7 @@ StackThatProvidesABucket stack1 = new StackThatProvidesABucket(app, "Stack1", // stack2 will take an argument "bucket" StackThatExpectsABucket stack2 = new StackThatExpectsABucket(app, "Stack,", - StackProps.builder().env(prod).build(), stack1.getBucket()); + StackProps.builder().env(prod).build(), stack1.bucket); ``` ------ @@ -252,7 +256,7 @@ var prod = makeEnv(account: "123456789012", region: "us-east-1"); var stack1 = new StackThatProvidesABucket(app, "Stack1", new StackProps { Env = prod }); -// stack2 will take an argument "bucket" +// stack2 will take a property "bucket" var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = prod, bucket = stack1.Bucket}); ``` @@ -679,7 +683,7 @@ new Function(this, "MyLambda", new FunctionProps ------ -## Permission grants +## Granting permissions AWS constructs make least\-privilege permissions easy to achieve by offering simple, intent\-based APIs to express permission requirements\. Many AWS constructs offer grant methods that enable you to easily grant an entity, such as an IAM role or a user, permission to work with the resource without having to manually craft one or more IAM permission statements\. From 197f684c95581b9138d9e2541228038262bf424a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 2 Sep 2022 23:29:54 +0000 Subject: [PATCH 572/655] add note about using Python on Windows --- v1/best-practices.md | 2 +- v1/work-with-cdk-python.md | 4 ++++ v2/best-practices.md | 2 +- v2/work-with-cdk-python.md | 4 ++++ 4 files changed, 10 insertions(+), 2 deletions(-) diff --git a/v1/best-practices.md b/v1/best-practices.md index 717c4a1d..23787f26 100644 --- a/v1/best-practices.md +++ b/v1/best-practices.md @@ -19,7 +19,7 @@ In addition to the guidance in this document, you should also consider [best pra ## Organization best practices -In the beginning stages of AWS CDK adoption, it's important to consider how to set up your organization for success\. It's a best practice to have a team of experts responsible for training and guiding the rest of the company as they adopt the CDK The size of this team may vary, from one or two people at a small company to a full\-fledged Cloud Center of Excellence \(CCoE\) at a larger company\. This team is responsible for setting standards and policies for how cloud infrastructure will be done at your company, as well as for training and mentoring developers\. +In the beginning stages of AWS CDK adoption, it's important to consider how to set up your organization for success\. It's a best practice to have a team of experts responsible for training and guiding the rest of the company as they adopt the CDK\. The size of this team may vary, from one or two people at a small company to a full\-fledged Cloud Center of Excellence \(CCoE\) at a larger company\. This team is responsible for setting standards and policies for how cloud infrastructure will be done at your company, as well as for training and mentoring developers\. The CCoE may provide guidance on what programming languages should be used for cloud infrastructure\. The details will vary from one organization to the next, but a good policy helps make sure developers can easily understand and maintain all cloud infrastructure throughout the company\. diff --git a/v1/work-with-cdk-python.md b/v1/work-with-cdk-python.md index 55561845..c11aeb4e 100644 --- a/v1/work-with-cdk-python.md +++ b/v1/work-with-cdk-python.md @@ -26,6 +26,10 @@ If you encounter a permission error, run the above commands with the `--user` fl **Note** It is common for Linux distros to use the executable name `python3` for Python 3\.x, and have `python` refer to a Python 2\.x installation\. Some distros have an optional package you can install that makes the `python` command refer to Python 3\. Failing that, you can adjust the command used to run your application by editing `cdk.json` in the project's main directory\. +**Note** +On Windows, you may want to invoke Python \(and pip\) using the py executable, the [>Python launcher for Windows](https://docs.python.org/3/using/windows.html#launcher)\. Among other things, the launcher allows you to easily specify which installed version of Python you want to use\. +If typing python at the command line results in a message about installing Python from the Windows Store, even after installing a Windows version of Python, open Windows' Manage App Execution Aliases settings panel and turn off the two App Installer entries for Python\. + ## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. diff --git a/v2/best-practices.md b/v2/best-practices.md index 12758a87..ffa6e4e8 100644 --- a/v2/best-practices.md +++ b/v2/best-practices.md @@ -19,7 +19,7 @@ In addition to the guidance in this document, you should also consider [best pra ## Organization best practices -In the beginning stages of AWS CDK adoption, it's important to consider how to set up your organization for success\. It's a best practice to have a team of experts responsible for training and guiding the rest of the company as they adopt the CDK The size of this team may vary, from one or two people at a small company to a full\-fledged Cloud Center of Excellence \(CCoE\) at a larger company\. This team is responsible for setting standards and policies for how cloud infrastructure will be done at your company, as well as for training and mentoring developers\. +In the beginning stages of AWS CDK adoption, it's important to consider how to set up your organization for success\. It's a best practice to have a team of experts responsible for training and guiding the rest of the company as they adopt the CDK\. The size of this team may vary, from one or two people at a small company to a full\-fledged Cloud Center of Excellence \(CCoE\) at a larger company\. This team is responsible for setting standards and policies for how cloud infrastructure will be done at your company, as well as for training and mentoring developers\. The CCoE may provide guidance on what programming languages should be used for cloud infrastructure\. The details will vary from one organization to the next, but a good policy helps make sure developers can easily understand and maintain all cloud infrastructure throughout the company\. diff --git a/v2/work-with-cdk-python.md b/v2/work-with-cdk-python.md index 81653c06..4eaafc7b 100644 --- a/v2/work-with-cdk-python.md +++ b/v2/work-with-cdk-python.md @@ -26,6 +26,10 @@ If you encounter a permission error, run the above commands with the `--user` fl **Note** It is common for Linux distros to use the executable name `python3` for Python 3\.x, and have `python` refer to a Python 2\.x installation\. Some distros have an optional package you can install that makes the `python` command refer to Python 3\. Failing that, you can adjust the command used to run your application by editing `cdk.json` in the project's main directory\. +**Note** +On Windows, you may want to invoke Python \(and pip\) using the py executable, the [>Python launcher for Windows](https://docs.python.org/3/using/windows.html#launcher)\. Among other things, the launcher allows you to easily specify which installed version of Python you want to use\. +If typing python at the command line results in a message about installing Python from the Windows Store, even after installing a Windows version of Python, open Windows' Manage App Execution Aliases settings panel and turn off the two App Installer entries for Python\. + ## Creating a project You create a new AWS CDK project by invoking `cdk init` in an empty directory\. From 8e24d2b27c58550b53b269ce164e1afa3a6d1d21 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 2 Sep 2022 23:30:39 +0000 Subject: [PATCH 573/655] correct how CloudFormation replaces resources --- v1/identifiers.md | 2 +- v2/identifiers.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/identifiers.md b/v1/identifiers.md index 3220ae14..3a99daaa 100644 --- a/v1/identifiers.md +++ b/v1/identifiers.md @@ -274,4 +274,4 @@ For example, the Amazon S3 bucket in the previous example that is created within ### Logical ID stability -Avoid changing the logical ID of a resource after it has been created\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID, which may cause service interruption or data loss\. \ No newline at end of file +Avoid changing the logical ID of a resource after it has been created\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation creates a new resource with the new logical ID, then deletes the existing one\. Depending on the type of resource, this may cause service interruption or data loss, or both\. \ No newline at end of file diff --git a/v2/identifiers.md b/v2/identifiers.md index 985d5ad7..5715003d 100644 --- a/v2/identifiers.md +++ b/v2/identifiers.md @@ -278,4 +278,4 @@ For example, the Amazon S3 bucket in the previous example that is created within ### Logical ID stability -Avoid changing the logical ID of a resource after it has been created\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID, which may cause service interruption or data loss\. \ No newline at end of file +Avoid changing the logical ID of a resource after it has been created\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation creates a new resource with the new logical ID, then deletes the existing one\. Depending on the type of resource, this may cause service interruption or data loss, or both\. \ No newline at end of file From 8cbdc1f686ec9d81cc292e86e6515861ab913f1f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 9 Sep 2022 16:19:29 +0000 Subject: [PATCH 574/655] fix typo --- v2/cfn_layer.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/cfn_layer.md b/v2/cfn_layer.md index 43755f50..bec4a45b 100644 --- a/v2/cfn_layer.md +++ b/v2/cfn_layer.md @@ -374,7 +374,7 @@ var v2 = Bucket.FromCfnBucket(b1); L2 constructs created from L1 constructs are proxy objects that refer to the L1 resource, similar to those created from resource names, ARNs, or lookups\. Modifications to these constructs do not affect the final synthesized AWS CloudFormation template \(since you have the L1 resource, however, you can modify that instead\)\. For more information on proxy objects, see [Referencing resources in your AWS account](resources.md#resources_external)\. -To avoid confusion, do not create multiple L2 constructs that refer to the same L1 construct\. For example, if you extract the `CfnBucket` from a `Bucket` using the technique in the [previous section](#cfn_layer_resource), you shouldn't create a second `Bucket` instance by calling `Bucket.fromCfnBucket()` with that `CfnBucket`\. It actually works as you'd expect \(only one `AWS::S3::Bucket` is synthesized\) but it makes your code more difficult to maintain\.\. +To avoid confusion, do not create multiple L2 constructs that refer to the same L1 construct\. For example, if you extract the `CfnBucket` from a `Bucket` using the technique in the [previous section](#cfn_layer_resource), you shouldn't create a second `Bucket` instance by calling `Bucket.fromCfnBucket()` with that `CfnBucket`\. It actually works as you'd expect \(only one `AWS::S3::Bucket` is synthesized\) but it makes your code more difficult to maintain\. ## Raw overrides From 95ce162637cdd71b84e8d68aed83807e8a07ac0f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 9 Sep 2022 22:45:16 +0000 Subject: [PATCH 575/655] clarify that "two of them" means two AZs --- v1/environments.md | 2 +- v2/environments.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/environments.md b/v1/environments.md index 10dc4205..16a54b2d 100644 --- a/v1/environments.md +++ b/v1/environments.md @@ -15,7 +15,7 @@ The file `app.py` in your project's main directory\. The file named `ProjectNameApp.java`, for example `HelloCdkApp.java`, nested deep under the `src/main` directory\. The file named `Program.cs` under `src\ProjectName`, for example `src\HelloCdk\Program.cs`\. -In an environment\-agnostic stack, any constructs that use availability zones will see two of them, allowing the stack to be deployed to any region\. +In an environment\-agnostic stack, any constructs that use availability zones will see two AZs, allowing the stack to be deployed to any region\. When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations in your AWS account\. See [AWS CDK Toolkit \(`cdk` command\)](cli.md) for details\. diff --git a/v2/environments.md b/v2/environments.md index 686b57b0..4421d5d6 100644 --- a/v2/environments.md +++ b/v2/environments.md @@ -15,7 +15,7 @@ The file `app.py` in your project's main directory\. The file named `ProjectNameApp.java`, for example `HelloCdkApp.java`, nested deep under the `src/main` directory\. The file named `Program.cs` under `src\ProjectName`, for example `src\HelloCdk\Program.cs`\. -In an environment\-agnostic stack, any constructs that use availability zones will see two of them, allowing the stack to be deployed to any region\. +In an environment\-agnostic stack, any constructs that use availability zones will see two AZs, allowing the stack to be deployed to any region\. When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations in your AWS account\. See [AWS CDK Toolkit \(`cdk` command\)](cli.md) for details\. From 8a1c1eca27c79d5fe14319d7b26f4214f3a7f1c7 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 12 Sep 2022 14:16:04 +0000 Subject: [PATCH 576/655] fix casing of bucket name --- v1/parameters.md | 6 +++--- v2/parameters.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/v1/parameters.md b/v1/parameters.md index 37bfd443..b6e3bd0e 100644 --- a/v1/parameters.md +++ b/v1/parameters.md @@ -190,19 +190,19 @@ A generated template containing parameters can be deployed in the usual way thro The AWS CDK Toolkit \(`cdk` command\-line tool\) also supports specifying parameters at deployment\. You may provide these on the command line following the `--parameters` flag\. You might deploy a stack that uses the `uploadBucketName` parameter like this\. ``` -cdk deploy MyStack --parameters uploadBucketName=UploadBucket +cdk deploy MyStack --parameters uploadBucketName=uploadbucket ``` To define multiple parameters, use multiple `--parameters` flags\. ``` -cdk deploy MyStack --parameters uploadBucketName=UpBucket --parameters downloadBucketName=DownBucket +cdk deploy MyStack --parameters uploadBucketName=upbucket --parameters downloadBucketName=downbucket ``` If you are deploying multiple stacks, you can specify a different value of each parameter for each stack by prefixing the name of the parameter with the stack name and a colon\. ``` -cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket --parameters YourStack:uploadBucketName=UpBucket +cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=uploadbucket --parameters YourStack:uploadBucketName=upbucket ``` By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the `--no-previous-parameters flag` to require all parameters to be specified\. \ No newline at end of file diff --git a/v2/parameters.md b/v2/parameters.md index 098145cf..fc7af332 100644 --- a/v2/parameters.md +++ b/v2/parameters.md @@ -190,19 +190,19 @@ A generated template containing parameters can be deployed in the usual way thro The AWS CDK Toolkit \(`cdk` command\-line tool\) also supports specifying parameters at deployment\. You may provide these on the command line following the `--parameters` flag\. You might deploy a stack that uses the `uploadBucketName` parameter like this\. ``` -cdk deploy MyStack --parameters uploadBucketName=UploadBucket +cdk deploy MyStack --parameters uploadBucketName=uploadbucket ``` To define multiple parameters, use multiple `--parameters` flags\. ``` -cdk deploy MyStack --parameters uploadBucketName=UpBucket --parameters downloadBucketName=DownBucket +cdk deploy MyStack --parameters uploadBucketName=upbucket --parameters downloadBucketName=downbucket ``` If you are deploying multiple stacks, you can specify a different value of each parameter for each stack by prefixing the name of the parameter with the stack name and a colon\. ``` -cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket --parameters YourStack:uploadBucketName=UpBucket +cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=uploadbucket --parameters YourStack:uploadBucketName=upbucket ``` By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the `--no-previous-parameters flag` to require all parameters to be specified\. \ No newline at end of file From af6640523998d40d353505baab302f4f26e8544c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 12 Sep 2022 14:16:30 +0000 Subject: [PATCH 577/655] fix tense of sentence --- v2/cdk_pipeline.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index d3351a19..b9871571 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -14,7 +14,7 @@ Before you can use CDK Pipelines, you must bootstrap the AWS environment\(s\) to **Note** See [Bootstrapping](bootstrapping.md) for more information on the kinds of resources created by bootstrapping and how to customize the bootstrap stack\. -Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include an Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. The CDK Toolkitwill upgrade your existing bootstrap stack or create a new one, as necessary\. +Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include an Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. The CDK Toolkit will upgrade your existing bootstrap stack or create a new one, as necessary\. To bootstrap an environment that can provision an AWS CDK pipeline, invoke `cdk bootstrap` as shown below\. Invoking the AWS CDK Toolkit via the `npx` command temporarily installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. From 8c7669d8c928eb25bc80a0f9494946fc6d2cf5c7 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 12 Sep 2022 20:35:00 +0000 Subject: [PATCH 578/655] remove erroneous information about --trust-for-lookup --- v1/bootstrapping.md | 2 +- v2/bootstrapping.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/bootstrapping.md b/v1/bootstrapping.md index 280895fd..a6a3ee3a 100644 --- a/v1/bootstrapping.md +++ b/v1/bootstrapping.md @@ -182,7 +182,7 @@ The following additional switches are available only with the modern bootstrappi **Important** To avoid deployment failures, be sure the policies you specify are sufficient for any deployments you will perform in the environment being bootstrapped\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. -+ \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. ++ \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid resource name clashes when you provision multiple bootstrap stacks in the same environment using \-\-toolkit\-stack\-name\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier also requires that your CDK app pass the changed value to the stack synthesizer\(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. **Important** diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index e83d795e..a0e4a804 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -136,7 +136,7 @@ To avoid deployment failures, be sure the policies you specify are sufficient fo + \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid resource name clashes when you provision multiple bootstrap stacks in the same environment using \-\-toolkit\-stack\-name\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier also requires that your CDK app pass the changed value to the stack synthesizer\(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. + \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. -+ \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. Accounts specified under \-\-trust are always trusted for context lookup\. ++ \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. + \-\-termination\-protection prevents the bootstrap stack from being deleted \(see [Protecting a stack from being deleted](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html) in the AWS CloudFormation User Guide\) **Important** From d774b2cb639976d52d65b72c35bec7f78790a053 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 13 Sep 2022 21:36:15 +0000 Subject: [PATCH 579/655] add instructions for SSO --- v1/getting_started.md | 2 +- v2/getting_started.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/getting_started.md b/v1/getting_started.md index d5c53d4e..4ff585b1 100644 --- a/v1/getting_started.md +++ b/v1/getting_started.md @@ -147,7 +147,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials **Note** Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. -AWS CDK does not natively support AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. +The AWS CDK natively AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, first create a profile using aws config sso\. Then log in using aws sso login\. Finally, specify this profile when issuing cdk commands using the \-\-profile option or the `AWS_PROFILE` environment variable\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. diff --git a/v2/getting_started.md b/v2/getting_started.md index f3f22f96..b286f8de 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -197,7 +197,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials **Note** Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. -AWS CDK does not natively support AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, use a tool such as [yawsso](https://github.com/victorskl/yawsso)\. +The AWS CDK natively AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, first create a profile using aws config sso\. Then log in using aws sso login\. Finally, specify this profile when issuing cdk commands using the \-\-profile option or the `AWS_PROFILE` environment variable\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. From ace61cfd4794ecf3bbddddfe9e81a6e3449bfd76 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 13 Sep 2022 21:48:16 +0000 Subject: [PATCH 580/655] change documented default of publicLoadBalancer property --- v1/ecs_example.md | 54 ++++++++++++++++++++++++++++++++++++++++++----- v2/ecs_example.md | 10 ++++----- 2 files changed, 54 insertions(+), 10 deletions(-) diff --git a/v1/ecs_example.md b/v1/ecs_example.md index d767c48d..0ad3cd64 100644 --- a/v1/ecs_example.md +++ b/v1/ecs_example.md @@ -228,6 +228,26 @@ Replace the comment at the end of the constructor with the following code\. #### [ TypeScript ] ``` +// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// This file is licensed under the Apache License, Version 2.0 (the "License"). +// You may not use this file except in compliance with the License. A copy of the +// License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS +// OF ANY KIND, either express or implied. See the License for the specific +// language governing permissions and limitations under the License. +import * as core from "@aws-cdk/core"; +import * as ec2 from "@aws-cdk/aws-ec2"; +import * as ecs from "@aws-cdk/aws-ecs"; +import * as ecs_patterns from "@aws-cdk/aws-ecs-patterns"; + +export class MyEcsConstructStack extends core.Stack { + constructor(scope: core.App, id: string, props?: core.StackProps) { + super(scope, id, props); + const vpc = new ec2.Vpc(this, "MyVpc", { maxAzs: 3 // Default is all AZs in region }); @@ -243,14 +263,36 @@ Replace the comment at the end of the constructor with the following code\. desiredCount: 6, // Default is 1 taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, memoryLimitMiB: 2048, // Default is 512 - publicLoadBalancer: true // Default is false + publicLoadBalancer: true // Default is true }); + } +} ``` ------ #### [ JavaScript ] ``` +// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// This file is licensed under the Apache License, Version 2.0 (the "License"). +// You may not use this file except in compliance with the License. A copy of the +// License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS +// OF ANY KIND, either express or implied. See the License for the specific +// language governing permissions and limitations under the License. +import * as core from "@aws-cdk/core"; +import * as ec2 from "@aws-cdk/aws-ec2"; +import * as ecs from "@aws-cdk/aws-ecs"; +import * as ecs_patterns from "@aws-cdk/aws-ecs-patterns"; + +export class MyEcsConstructStack extends core.Stack { + constructor(scope: core.App, id: string, props?: core.StackProps) { + super(scope, id, props); + const vpc = new ec2.Vpc(this, "MyVpc", { maxAzs: 3 // Default is all AZs in region }); @@ -266,8 +308,10 @@ Replace the comment at the end of the constructor with the following code\. desiredCount: 6, // Default is 1 taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, memoryLimitMiB: 2048, // Default is 512 - publicLoadBalancer: true // Default is false + publicLoadBalancer: true // Default is true }); + } +} ``` ------ @@ -285,7 +329,7 @@ Replace the comment at the end of the constructor with the following code\. task_image_options=ecs_patterns.ApplicationLoadBalancedTaskImageOptions( image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")), memory_limit_mib=2048, # Default is 512 - public_load_balancer=True) # Default is False + public_load_balancer=True) # Default is True ``` ------ @@ -309,7 +353,7 @@ Replace the comment at the end of the constructor with the following code\. .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample")) .build()) .memoryLimitMiB(2048) // Default is 512 - .publicLoadBalancer(true) // Default is false + .publicLoadBalancer(true) // Default is true .build(); ``` @@ -338,7 +382,7 @@ Replace the comment at the end of the constructor with the following code\. Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample") }, MemoryLimitMiB = 2048, // Default is 256 - PublicLoadBalancer = true // Default is false + PublicLoadBalancer = true // Default is true } ); ``` diff --git a/v2/ecs_example.md b/v2/ecs_example.md index 07206252..a3fb5945 100644 --- a/v2/ecs_example.md +++ b/v2/ecs_example.md @@ -180,7 +180,7 @@ Replace the comment at the end of the constructor with the following code\. desiredCount: 6, // Default is 1 taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, memoryLimitMiB: 2048, // Default is 512 - publicLoadBalancer: true // Default is false + publicLoadBalancer: true // Default is true }); ``` @@ -203,7 +203,7 @@ Replace the comment at the end of the constructor with the following code\. desiredCount: 6, // Default is 1 taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample") }, memoryLimitMiB: 2048, // Default is 512 - publicLoadBalancer: true // Default is false + publicLoadBalancer: true // Default is true }); ``` @@ -222,7 +222,7 @@ Replace the comment at the end of the constructor with the following code\. task_image_options=ecs_patterns.ApplicationLoadBalancedTaskImageOptions( image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")), memory_limit_mib=2048, # Default is 512 - public_load_balancer=True) # Default is False + public_load_balancer=True) # Default is True ``` ------ @@ -246,7 +246,7 @@ Replace the comment at the end of the constructor with the following code\. .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample")) .build()) .memoryLimitMiB(2048) // Default is 512 - .publicLoadBalancer(true) // Default is false + .publicLoadBalancer(true) // Default is true .build(); ``` @@ -275,7 +275,7 @@ Replace the comment at the end of the constructor with the following code\. Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample") }, MemoryLimitMiB = 2048, // Default is 256 - PublicLoadBalancer = true // Default is false + PublicLoadBalancer = true // Default is true } ); ``` From ae65fd66437eaaf1a6ff2d597eab18a4f2c2b4a2 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 15 Sep 2022 01:57:54 +0000 Subject: [PATCH 581/655] add information tagging specific constructs and using per-construct values --- v1/tagging.md | 127 +++++++++++++++++++++++++++++++++++++++++++++++++- v2/tagging.md | 127 +++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 252 insertions(+), 2 deletions(-) diff --git a/v1/tagging.md b/v1/tagging.md index ff296092..7e491f34 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -412,4 +412,129 @@ Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps { }); ``` ------- \ No newline at end of file +------ + +## Tagging single constructs + +`Tags.of(scope).add(key, value)` is the standard way to add tags to constructs in the AWS CDK\. Its tree\-walking behavior, which recursively tags all taggable resources under the given scope, is almost always what you want\. Sometimes, however, you may want to tag only some constructs, even just one\. + +One such case involves applying tags whose value is derived from some property of the construct being tagged\. The standard tagging approach recursively applies the same key and value to all matching resources in the scope, but here, the value could be different for each tagged construct\. + +Tags are implemented using [aspects](aspects.md), and the CDK calls the tag's `visit()` method for each construct under the scope you specified using `Tags.of(scope)`\. We can call `visit()` directly to apply the tag to a single construct\. + +------ +#### [ TypeScript ] + +``` +new cdk.Tag(key, value).visit(scope); +``` + +------ +#### [ JavaScript ] + +``` +new cdk.Tag(key, value).visit(scope); +``` + +------ +#### [ Python ] + +``` +cdk.Tag(key, value).visit(scope) +``` + +------ +#### [ Java ] + +``` +Tag.Builder.create(key, value).build().visit(scope); +``` + +------ +#### [ C\# ] + +``` +new Tag(key, value).Visit(scope); +``` + +------ + +To tag all constructs under a scope but allow the values of the tags to be derived from properties of each construct, write an aspect, apply the tag in the aspect's `visit()` method as shown above, and add the aspect to the desired scope using `Aspects.of(scope).add(aspect)`\. + +The example below applies a tag to each resource in a stack containing the resource's path\. + +------ +#### [ TypeScript ] + +``` +class PathTagger implements cdk.IAspect { + visit(node: IConstruct) { + new cdk.Tag("aws-cdk-path", node.node.path).visit(scope); + } +} + +stack = new MyStack(app); +cdk.Aspects.of(stack).add(new PathTagger()) +``` + +------ +#### [ JavaScript ] + +``` +class PathTagger { + visit(node) { + new cdk.Tag("aws-cdk-path", node.node.path).visit(scope); + } +} + +stack = new MyStack(app); +cdk.Aspects.of(stack).add(new PathTagger()) +``` + +------ +#### [ Python ] + +``` +@jsii.implements(cdk.IAspect) +class PathTagger: + def visit(self, node: IConstruct): + cdk.Tag("aws-cdk-path", node.node.path).visit(scope) + +stack = MyStack(app) +cdk.Aspects.of(stack).add(PathTagger()) +``` + +------ +#### [ Java ] + +``` +final class PathTagger implements IAspect { + public void visit(IConstruct node) { + Tag.Builder.create("aws-cdk-path", node.getNode().getPath()).build().visit(node); + } +} + +stack stack = new MyStack(app); +Aspects.of(stack).add(new PathTagger()); +``` + +------ +#### [ C\# ] + +``` +public class PathTagger : IAspect +{ + public void Visit(IConstruct node) + { + new Tag("aws-cdk-path", node.Node.Path).Visit(node); + } +} + +var stack = new MyStack(app); +Aspects.Of(stack).Add(new PathTagger); +``` + +------ + +**Tip** +The logic of what constructs should be tagged, including priorities, resource types, and so on, are built into the `Tag` class, so you don't need to test whether a construct is taggable before applying a tag\. \ No newline at end of file diff --git a/v2/tagging.md b/v2/tagging.md index 5fd2afda..923cfdf9 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -412,4 +412,129 @@ Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps { }); ``` ------- \ No newline at end of file +------ + +## Tagging single constructs + +`Tags.of(scope).add(key, value)` is the standard way to add tags to constructs in the AWS CDK\. Its tree\-walking behavior, which recursively tags all taggable resources under the given scope, is almost always what you want\. Sometimes, however, you may want to tag only some constructs, even just one\. + +One such case involves applying tags whose value is derived from some property of the construct being tagged\. The standard tagging approach recursively applies the same key and value to all matching resources in the scope, but here, the value could be different for each tagged construct\. + +Tags are implemented using [aspects](aspects.md), and the CDK calls the tag's `visit()` method for each construct under the scope you specified using `Tags.of(scope)`\. We can call `visit()` directly to apply the tag to a single construct\. + +------ +#### [ TypeScript ] + +``` +new cdk.Tag(key, value).visit(scope); +``` + +------ +#### [ JavaScript ] + +``` +new cdk.Tag(key, value).visit(scope); +``` + +------ +#### [ Python ] + +``` +cdk.Tag(key, value).visit(scope) +``` + +------ +#### [ Java ] + +``` +Tag.Builder.create(key, value).build().visit(scope); +``` + +------ +#### [ C\# ] + +``` +new Tag(key, value).Visit(scope); +``` + +------ + +To tag all constructs under a scope but allow the values of the tags to be derived from properties of each construct, write an aspect, apply the tag in the aspect's `visit()` method as shown above, and add the aspect to the desired scope using `Aspects.of(scope).add(aspect)`\. + +The example below applies a tag to each resource in a stack containing the resource's path\. + +------ +#### [ TypeScript ] + +``` +class PathTagger implements cdk.IAspect { + visit(node: IConstruct) { + new cdk.Tag("aws-cdk-path", node.node.path).visit(scope); + } +} + +stack = new MyStack(app); +cdk.Aspects.of(stack).add(new PathTagger()) +``` + +------ +#### [ JavaScript ] + +``` +class PathTagger { + visit(node) { + new cdk.Tag("aws-cdk-path", node.node.path).visit(scope); + } +} + +stack = new MyStack(app); +cdk.Aspects.of(stack).add(new PathTagger()) +``` + +------ +#### [ Python ] + +``` +@jsii.implements(cdk.IAspect) +class PathTagger: + def visit(self, node: IConstruct): + cdk.Tag("aws-cdk-path", node.node.path).visit(scope) + +stack = MyStack(app) +cdk.Aspects.of(stack).add(PathTagger()) +``` + +------ +#### [ Java ] + +``` +final class PathTagger implements IAspect { + public void visit(IConstruct node) { + Tag.Builder.create("aws-cdk-path", node.getNode().getPath()).build().visit(node); + } +} + +stack stack = new MyStack(app); +Aspects.of(stack).add(new PathTagger()); +``` + +------ +#### [ C\# ] + +``` +public class PathTagger : IAspect +{ + public void Visit(IConstruct node) + { + new Tag("aws-cdk-path", node.Node.Path).Visit(node); + } +} + +var stack = new MyStack(app); +Aspects.Of(stack).Add(new PathTagger); +``` + +------ + +**Tip** +The logic of what constructs should be tagged, including priorities, resource types, and so on, are built into the `Tag` class, so you don't need to test whether a construct is taggable before applying a tag\. \ No newline at end of file From 15b1a17f61d67a7e967b5d1f25f3260715d913cd Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 15 Sep 2022 15:12:08 +0000 Subject: [PATCH 582/655] improve new single-resource tagging content --- v1/tagging.md | 24 ++++++++++++------------ v2/tagging.md | 6 +++--- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/v1/tagging.md b/v1/tagging.md index 7e491f34..8f65f54f 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -416,45 +416,45 @@ Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps { ## Tagging single constructs -`Tags.of(scope).add(key, value)` is the standard way to add tags to constructs in the AWS CDK\. Its tree\-walking behavior, which recursively tags all taggable resources under the given scope, is almost always what you want\. Sometimes, however, you may want to tag only some constructs, even just one\. +`Tags.of(scope).add(key, value)` is the standard way to add tags to constructs in the AWS CDK\. Its tree\-walking behavior, which recursively tags all taggable resources under the given scope, is almost always what you want\. Sometimes, however, you need to tag a specific, arbitrary construct \(or constructs\)\. One such case involves applying tags whose value is derived from some property of the construct being tagged\. The standard tagging approach recursively applies the same key and value to all matching resources in the scope, but here, the value could be different for each tagged construct\. -Tags are implemented using [aspects](aspects.md), and the CDK calls the tag's `visit()` method for each construct under the scope you specified using `Tags.of(scope)`\. We can call `visit()` directly to apply the tag to a single construct\. +Tags are implemented using [aspects](aspects.md), and the CDK calls the tag's `visit()` method for each construct under the scope you specified using `Tags.of(scope)`\. We can call `Tag.visit()` directly to apply a tag to a single construct\. ------ #### [ TypeScript ] ``` -new cdk.Tag(key, value).visit(scope); +new cdk.Tag(key, value).visit(construct); ``` ------ #### [ JavaScript ] ``` -new cdk.Tag(key, value).visit(scope); +new cdk.Tag(key, value).visit(construct); ``` ------ #### [ Python ] ``` -cdk.Tag(key, value).visit(scope) +cdk.Tag(key, value).visit(construct) ``` ------ #### [ Java ] ``` -Tag.Builder.create(key, value).build().visit(scope); +Tag.Builder.create(key, value).build().visit(construct); ``` ------ #### [ C\# ] ``` -new Tag(key, value).Visit(scope); +new Tag(key, value).Visit(construct); ``` ------ @@ -469,7 +469,7 @@ The example below applies a tag to each resource in a stack containing the resou ``` class PathTagger implements cdk.IAspect { visit(node: IConstruct) { - new cdk.Tag("aws-cdk-path", node.node.path).visit(scope); + new cdk.Tag("aws-cdk-path", node.node.path).visit(node); } } @@ -483,7 +483,7 @@ cdk.Aspects.of(stack).add(new PathTagger()) ``` class PathTagger { visit(node) { - new cdk.Tag("aws-cdk-path", node.node.path).visit(scope); + new cdk.Tag("aws-cdk-path", node.node.path).visit(node); } } @@ -498,7 +498,7 @@ cdk.Aspects.of(stack).add(new PathTagger()) @jsii.implements(cdk.IAspect) class PathTagger: def visit(self, node: IConstruct): - cdk.Tag("aws-cdk-path", node.node.path).visit(scope) + cdk.Tag("aws-cdk-path", node.node.path).visit(node) stack = MyStack(app) cdk.Aspects.of(stack).add(PathTagger()) @@ -531,10 +531,10 @@ public class PathTagger : IAspect } var stack = new MyStack(app); -Aspects.Of(stack).Add(new PathTagger); +Aspects.Of(stack).Add(new PathTagger()); ``` ------ **Tip** -The logic of what constructs should be tagged, including priorities, resource types, and so on, are built into the `Tag` class, so you don't need to test whether a construct is taggable before applying a tag\. \ No newline at end of file +The logic of conditional tagging, including priorities, resource types, and so on, is built into the `Tag` class, so you can use these features when applying tags to arbitrary resources\. Also, the `Tag` class only tags taggble resources, so you don't need to test whether a construct is taggable before applying a tag\. \ No newline at end of file diff --git a/v2/tagging.md b/v2/tagging.md index 923cfdf9..4177a82c 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -416,11 +416,11 @@ Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps { ## Tagging single constructs -`Tags.of(scope).add(key, value)` is the standard way to add tags to constructs in the AWS CDK\. Its tree\-walking behavior, which recursively tags all taggable resources under the given scope, is almost always what you want\. Sometimes, however, you may want to tag only some constructs, even just one\. +`Tags.of(scope).add(key, value)` is the standard way to add tags to constructs in the AWS CDK\. Its tree\-walking behavior, which recursively tags all taggable resources under the given scope, is almost always what you want\. Sometimes, however, you need to tag a specific, arbitrary construct \(or constructs\)\. One such case involves applying tags whose value is derived from some property of the construct being tagged\. The standard tagging approach recursively applies the same key and value to all matching resources in the scope, but here, the value could be different for each tagged construct\. -Tags are implemented using [aspects](aspects.md), and the CDK calls the tag's `visit()` method for each construct under the scope you specified using `Tags.of(scope)`\. We can call `visit()` directly to apply the tag to a single construct\. +Tags are implemented using [aspects](aspects.md), and the CDK calls the tag's `visit()` method for each construct under the scope you specified using `Tags.of(scope)`\. We can call `Tag.visit()` directly to apply a tag to a single construct\. ------ #### [ TypeScript ] @@ -537,4 +537,4 @@ Aspects.Of(stack).Add(new PathTagger); ------ **Tip** -The logic of what constructs should be tagged, including priorities, resource types, and so on, are built into the `Tag` class, so you don't need to test whether a construct is taggable before applying a tag\. \ No newline at end of file +The logic of conditional tagging, including priorities, resource types, and so on, is built into the `Tag` class, so you can use these features when applying tags to arbitrary resources\. Also, the `Tag` class only tags taggble resources, so you don't need to test whether a construct is taggable before applying a tag\. \ No newline at end of file From 9b7689f90d3f416513f6c4033810c9c879dac6dd Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 15 Sep 2022 22:55:50 +0000 Subject: [PATCH 583/655] fix typo --- v2/migrating-v2.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index f72f9a28..594ed983 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -24,7 +24,7 @@ The main changes from AWS CDK v1 to CDK v2 are as follows\. + The `Construct` class has been extracted from the AWS CDK into a separate library, along with related types, to support efforts to apply the Construct Programming Model to other domains\. If you are writing your own constructs or using related APIs, you must declare the `constructs` module as a dependency and make minor changes to your imports\. If you are using advanced features, such as hooking into the CDK app lifecycle, more changes may be needed\. [See the RFC](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0192-remove-constructs-compat.md#release-notes) for full details\. + Deprecated properties, methods, and types in AWS CDK v1\.x and its Construct Library have been removed completely from the CDK v2 API\. In most supported languages, these APIs produce warnings under v1\.x, so you may have already migrated to the replacement APIs\. A complete [list of deprecated APIs](https://github.com/aws/aws-cdk/blob/master/DEPRECATED_APIs.md) in CDK v1\.x is available on GitHub\. + Behavior that was gated by feature flags in AWS CDK v1\.x is enabled by default in CDK v2, and the old feature flags are no longer needed or, in most cases, supported\. A handful are still available to let you to revert to CDK v1 behavior in very specific circumstances; see [Updating feature flags](#migrating-v2-v1-upgrade-cdk-json)\. -+ CDK v2 requires that the environments you deploy into be boostrapped using the modern bootstrap stack; the legacy bootstrap stack \(the default under v1\) is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. Simply re\-bootstrap your existing environments to upgrade them\. It is no longer necessary to set any feature flags or environment variables to specify the modern bootstrap stack\. ++ CDK v2 requires that the environments you deploy into be bootstrapped using the modern bootstrap stack; the legacy bootstrap stack \(the default under v1\) is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. Simply re\-bootstrap your existing environments to upgrade them\. It is no longer necessary to set any feature flags or environment variables to specify the modern bootstrap stack\. **Important** The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. From 48ed9a2fc5254b71942e37daab2687cda982cf1f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 16 Sep 2022 22:34:59 +0000 Subject: [PATCH 584/655] make snapshot test actually a snapshot test --- v1/testing.md | 72 ++++++++----------------------------------- v2/testing.md | 84 +++++++++++---------------------------------------- 2 files changed, 30 insertions(+), 126 deletions(-) diff --git a/v1/testing.md b/v1/testing.md index 2becebfe..269f0c7d 100644 --- a/v1/testing.md +++ b/v1/testing.md @@ -1474,21 +1474,12 @@ import * as cdk from "@aws-cdk/core"; import { DeadLetterQueue } from "../lib/dead-letter-queue"; describe("DeadLetterQueue", () => { - test("creates an alarm", () => { + test("matches the snapshot", () => { const stack = new cdk.Stack(); new DeadLetterQueue(stack, "DeadLetterQueue"); const template = Template.fromStack(stack); - template.hasResourceProperties("AWS::CloudWatch::Alarm", { - Namespace: "AWS/SQS", - MetricName: "ApproximateNumberOfMessagesVisible", - Dimensions: [ - { - Name: "QueueName", - Value: Match.anyValue(), - }, - ], - }); + expect(template.toJSON()).toMatchSnapshot(); }); }); ``` @@ -1502,21 +1493,12 @@ const cdk = require("@aws-cdk/core"); const { DeadLetterQueue } = require("../lib/dead-letter-queue"); describe("DeadLetterQueue", () => { - test("creates an alarm", () => { + test("matches the snapshot", () => { const stack = new cdk.Stack(); new DeadLetterQueue(stack, "DeadLetterQueue"); const template = Template.fromStack(stack); - template.hasResourceProperties("AWS::CloudWatch::Alarm", { - Namespace: "AWS/SQS", - MetricName: "ApproximateNumberOfMessagesVisible", - Dimensions: [ - { - Name: "QueueName", - Value: Match.anyValue(), - }, - ], - }); + expect(template.toJSON()).toMatchSnapshot(); }); }); ``` @@ -1530,24 +1512,12 @@ from aws_cdk.assertions import Match, Template from app.dead_letter_queue import DeadLetterQueue -def test_creates_alarm(): +def snapshot_test(): stack = cdk.Stack() DeadLetterQueue(stack, "DeadLetterQueue") template = Template.from_stack(stack) - template.has_resource_properties( - "AWS::CloudWatch::Alarm", - { - "Namespace": "AWS/SQS", - "MetricName": "ApproximateNumberOfMessagesVisible", - "Dimensions": [ - { - "Name": "QueueName", - "Value": Match.any_value(), - }, - ], - }, - ) + assert template.to_json() == snapshot ``` ------ @@ -1557,6 +1527,7 @@ def test_creates_alarm(): package software.amazon.samples.awscdkassertionssamples; import org.junit.jupiter.api.Test; +import au.com.origin.snapshots.Expect; import software.amazon.awscdk.assertions.Match; import software.amazon.awscdk.assertions.Template; import software.amazon.awscdk.core.Stack; @@ -1566,19 +1537,12 @@ import java.util.Map; public class DeadLetterQueueTest { @Test - public void testCreatesAlarm() { + public void snapshotTest() { final Stack stack = new Stack(); new DeadLetterQueue(stack, "DeadLetterQueue"); final Template template = Template.fromStack(stack); - template.hasResourceProperties("AWS::CloudWatch::Alarm", Map.of( - "Namespace", "AWS/SQS", - "MetricName", "ApproximateNumberOfMessagesVisible", - "Dimensions", Collections.singletonList(Map.of( - "Name", "QueueName", - "Value", Match.anyValue() - )) - )); + expect.toMatchSnapshot(template.toJSON()); } } ``` @@ -1605,26 +1569,14 @@ namespace TestProject1 public class DeadLetterQueueTest { [TestMethod] - public void TestCreatesAlarm() + public void SnapshotTest() { var stack = new Stack(); new DeadLetterQueue(stack, "DeadLetterQueue"); var template = Template.FromStack(stack); - template.HasResourceProperties("AWS::CloudWatch::Alarm", new ObjectDict - { - { "Namespace", "AWS/SQS" }, - { "MetricName", "ApproximateNumberOfMessagesVisible" }, - { "Dimensions", new object[] - { - new ObjectDict - { - { "Name", "QueueName" }, - { "Value", Match.AnyValue() } - } - } - } - }); + + return Verifier.Verify(template.ToJSON()); } } } diff --git a/v2/testing.md b/v2/testing.md index 4b8f6d8a..66b7b107 100644 --- a/v2/testing.md +++ b/v2/testing.md @@ -1375,26 +1375,17 @@ We can test it like this: #### [ TypeScript ] ``` -import { Match, Template } from "aws-cdk-lib/assertions"; -import * as cdk from "aws-cdk-lib"; +import { Match, Template } from "@aws-cdk/assertions"; +import * as cdk from "@aws-cdk/core"; import { DeadLetterQueue } from "../lib/dead-letter-queue"; describe("DeadLetterQueue", () => { - test("creates an alarm", () => { + test("matches the snapshot", () => { const stack = new cdk.Stack(); new DeadLetterQueue(stack, "DeadLetterQueue"); const template = Template.fromStack(stack); - template.hasResourceProperties("AWS::CloudWatch::Alarm", { - Namespace: "AWS/SQS", - MetricName: "ApproximateNumberOfMessagesVisible", - Dimensions: [ - { - Name: "QueueName", - Value: Match.anyValue(), - }, - ], - }); + expect(template.toJSON()).toMatchSnapshot(); }); }); ``` @@ -1403,26 +1394,17 @@ describe("DeadLetterQueue", () => { #### [ JavaScript ] ``` -const { Match, Template } = require("aws-cdk-lib/assertions"); -const cdk = require("aws-cdk-lib"); +const { Match, Template } = require("@aws-cdk/assertions"); +const cdk = require("@aws-cdk/core"); const { DeadLetterQueue } = require("../lib/dead-letter-queue"); describe("DeadLetterQueue", () => { - test("creates an alarm", () => { + test("matches the snapshot", () => { const stack = new cdk.Stack(); new DeadLetterQueue(stack, "DeadLetterQueue"); const template = Template.fromStack(stack); - template.hasResourceProperties("AWS::CloudWatch::Alarm", { - Namespace: "AWS/SQS", - MetricName: "ApproximateNumberOfMessagesVisible", - Dimensions: [ - { - Name: "QueueName", - Value: Match.anyValue(), - }, - ], - }); + expect(template.toJSON()).toMatchSnapshot(); }); }); ``` @@ -1431,29 +1413,17 @@ describe("DeadLetterQueue", () => { #### [ Python ] ``` -import aws_cdk as cdk +from aws_cdk import core as cdk from aws_cdk.assertions import Match, Template from app.dead_letter_queue import DeadLetterQueue -def test_creates_alarm(): +def snapshot_test(): stack = cdk.Stack() DeadLetterQueue(stack, "DeadLetterQueue") template = Template.from_stack(stack) - template.has_resource_properties( - "AWS::CloudWatch::Alarm", - { - "Namespace": "AWS/SQS", - "MetricName": "ApproximateNumberOfMessagesVisible", - "Dimensions": [ - { - "Name": "QueueName", - "Value": Match.any_value(), - }, - ], - }, - ) + assert template.to_json() == snapshot ``` ------ @@ -1463,28 +1433,22 @@ def test_creates_alarm(): package software.amazon.samples.awscdkassertionssamples; import org.junit.jupiter.api.Test; +import au.com.origin.snapshots.Expect; import software.amazon.awscdk.assertions.Match; import software.amazon.awscdk.assertions.Template; -import software.amazon.awscdk.Stack; +import software.amazon.awscdk.core.Stack; import java.util.Collections; import java.util.Map; public class DeadLetterQueueTest { @Test - public void testCreatesAlarm() { + public void snapshotTest() { final Stack stack = new Stack(); new DeadLetterQueue(stack, "DeadLetterQueue"); final Template template = Template.fromStack(stack); - template.hasResourceProperties("AWS::CloudWatch::Alarm", Map.of( - "Namespace", "AWS/SQS", - "MetricName", "ApproximateNumberOfMessagesVisible", - "Dimensions", Collections.singletonList(Map.of( - "Name", "QueueName", - "Value", Match.anyValue() - )) - )); + expect.toMatchSnapshot(template.toJSON()); } } ``` @@ -1511,26 +1475,14 @@ namespace TestProject1 public class DeadLetterQueueTest { [TestMethod] - public void TestCreatesAlarm() + public void SnapshotTest() { var stack = new Stack(); new DeadLetterQueue(stack, "DeadLetterQueue"); var template = Template.FromStack(stack); - template.HasResourceProperties("AWS::CloudWatch::Alarm", new ObjectDict - { - { "Namespace", "AWS/SQS" }, - { "MetricName", "ApproximateNumberOfMessagesVisible" }, - { "Dimensions", new object[] - { - new ObjectDict - { - { "Name", "QueueName" }, - { "Value", Match.AnyValue() } - } - } - } - }); + + return Verifier.Verify(template.ToJSON()); } } } From 5f5af9e785e458a36865ee1e33efbed85a96b030 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 17 Sep 2022 00:53:27 +0000 Subject: [PATCH 585/655] clarify CDK's use of 'principal' --- v1/permissions.md | 10 +++++++--- v2/permissions.md | 8 ++++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/v1/permissions.md b/v1/permissions.md index 863a766d..e6cfc213 100644 --- a/v1/permissions.md +++ b/v1/permissions.md @@ -4,9 +4,13 @@ The AWS Construct Library uses a few common, widely\-implemented idioms to manag ## Principals -An IAM principal is an entity that can be authenticated in order to access AWS resources, such as a user, a service, or an application\. The AWS Construct Library supports many types of principals, including: +An IAM principal is an authenticated AWS entity representing a user, service, or application that can call AWS APIs\. The AWS Construct Library supports specifying principals in several flexible ways to grant them access your AWS resources\. -1. IAM resources such as `[Role](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Group.html)` +In security contexts, the term "principal" refers specifically to authenticated entities such as users\. Objects like groups and roles do not *represent* users \(and other authenticated entities\) but rather *identify* them indirectly for the purpose of granting permissions\. For example, if you create an IAM group, you can grant the group \(i\.e\. its members\) write access to a Amazon RDS table, but the group itself is not a principal since it does not represent a single entity \(also, you cannot log in to a group\)\. + +In the CDK's IAM library, classes that directly or indirectly identify principals implement the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.IPrincipal.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.IPrincipal.html) interface, allowing these objects to be used interchangeably in access policies\. However, not all of them are principals in the security sense\. These objects include: + +1. Traditional IAM resources such as `[Role](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Group.html)` 1. Service principals \(`new iam.[ServicePrincipal](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ServicePrincipal.html)('service.amazonaws.com')`\) @@ -28,7 +32,7 @@ Every construct that represents a resource that can be accessed, such as an Amaz The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.Group.html)`\. -Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other entities that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. +Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly instead of granting access to their role\. For example, if `bucket` is an Amazon S3 bucket, and `function` is a Lambda function, the code below grants the function read access to the bucket\. diff --git a/v2/permissions.md b/v2/permissions.md index a0662fae..6a2cd197 100644 --- a/v2/permissions.md +++ b/v2/permissions.md @@ -4,7 +4,11 @@ The AWS Construct Library uses a few common, widely\-implemented idioms to manag ## Principals -An IAM principal is an entity that can be authenticated in order to access AWS resources, such as a user, a service, or an application\. The AWS Construct Library supports many types of principals, including: +An IAM principal is an authenticated AWS entity representing a user, service, or application that can call AWS APIs\. The AWS Construct Library supports specifying principals in several flexible ways to grant them access your AWS resources\. + +In security contexts, the term "principal" refers specifically to authenticated entities such as users\. Objects like groups and roles do not *represent* users \(and other authenticated entities\) but rather *identify* them indirectly for the purpose of granting permissions\. For example, if you create an IAM group, you can grant the group \(i\.e\. its members\) write access to a Amazon RDS table, but the group itself is not a principal since it does not represent a single entity \(also, you cannot log in to a group\)\. + +In the CDK's IAM library, classes that directly or indirectly identify principals implement the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IPrincipal.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IPrincipal.html) interface, allowing these objects to be used interchangeably in access policies\. However, not all of them are principals in the security sense\. These objects include: 1. IAM resources such as `[Role](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Group.html)` @@ -28,7 +32,7 @@ Every construct that represents a resource that can be accessed, such as an Amaz The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html)`\. -Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Other entities that can be granted permissions are Amazon EC2 instances and CodeBuild projects\. +Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly instead of granting access to their role\. For example, if `bucket` is an Amazon S3 bucket, and `function` is a Lambda function, the code below grants the function read access to the bucket\. From ec23b2866711a47eb693ae0b96991f67b64fdf71 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 17 Sep 2022 00:54:37 +0000 Subject: [PATCH 586/655] fix transposed words --- v1/constructs.md | 2 +- v2/constructs.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/constructs.md b/v1/constructs.md index d481a0e2..dac22dc5 100644 --- a/v1/constructs.md +++ b/v1/constructs.md @@ -5,7 +5,7 @@ Constructs are the basic building blocks of AWS CDK apps\. A construct represent **Note** Constructs are part of the Construct Programming Model \(CPM\) and are also used by other tools such as CDK for Terraform \(CDKtf\), CDK for Kubernetes \(CDK8s\), and Projen\. -A construct can represent a single AWS resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can be a higher\-level abstraction consisting of multiple AWS related resources\. Examples of such components include a worker queue with its associated compute capacity, or a scheduled job with monitoring resources and a dashboard\. +A construct can represent a single AWS resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can be a higher\-level abstraction consisting of multiple related AWS resources\. Examples of such components include a worker queue with its associated compute capacity, or a scheduled job with monitoring resources and a dashboard\. The AWS CDK includes a collection of constructs called the AWS Construct Library, containing constructs for every AWS service\. [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=1&sort=downloadsDesc&offset=0) is a resource to help you discover additional constructs from AWS, third parties, and the open\-source CDK community\. diff --git a/v2/constructs.md b/v2/constructs.md index 44e5ada4..48de7dff 100644 --- a/v2/constructs.md +++ b/v2/constructs.md @@ -5,7 +5,7 @@ Constructs are the basic building blocks of AWS CDK apps\. A construct represent **Note** Constructs are part of the Construct Programming Model \(CPM\) and are also used by other tools such as CDK for Terraform \(CDKtf\), CDK for Kubernetes \(CDK8s\), and Projen\. -A construct can represent a single AWS resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can be a higher\-level abstraction consisting of multiple AWS related resources\. Examples of such components include a worker queue with its associated compute capacity, or a scheduled job with monitoring resources and a dashboard\. +A construct can represent a single AWS resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can be a higher\-level abstraction consisting of multiple related AWS resources\. Examples of such components include a worker queue with its associated compute capacity, or a scheduled job with monitoring resources and a dashboard\. The AWS CDK includes a collection of constructs called the AWS Construct Library, containing constructs for every AWS service\. [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) is a resource to help you discover additional constructs from AWS, third parties, and the open\-source CDK community\. From fb999c4e75cba8abc447b339287437f7eda89eab Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Sat, 17 Sep 2022 00:54:49 +0000 Subject: [PATCH 587/655] autogenerated ID churn --- v1/cli.md | 26 +++++++++++++------------- v1/manage-dependencies.md | 10 +++++----- v1/tagging.md | 2 +- v1/use_cfn_template.md | 2 +- v2/cli.md | 26 +++++++++++++------------- v2/manage-dependencies.md | 10 +++++----- v2/tagging.md | 2 +- v2/use_cfn_template.md | 2 +- 8 files changed, 40 insertions(+), 40 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index 376ef849..36857527 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -351,7 +351,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -370,7 +370,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -378,7 +378,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -454,7 +454,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -476,7 +476,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -733,7 +733,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -746,7 +746,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -767,7 +767,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -847,7 +847,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -925,7 +925,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -944,7 +944,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -970,7 +970,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -992,7 +992,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/manage-dependencies.md b/v1/manage-dependencies.md index 7ce395a8..cfef9502 100644 --- a/v1/manage-dependencies.md +++ b/v1/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -72,7 +72,7 @@ All AWS CDK dependencies must have the same version\. Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -99,7 +99,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -145,7 +145,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -169,7 +169,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v1/tagging.md b/v1/tagging.md index 8f65f54f..e251286e 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index cd8d1dfe..0bcd9aed 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/cli.md b/v2/cli.md index 31cdb8b6..c9943aaf 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -343,7 +343,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -362,7 +362,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -370,7 +370,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -446,7 +446,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -468,7 +468,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -725,7 +725,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -738,7 +738,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -759,7 +759,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -839,7 +839,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -917,7 +917,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -936,7 +936,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -962,7 +962,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -984,7 +984,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index d74ad6ff..db04da05 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -71,7 +71,7 @@ Specify exact versions for alpha construct library modules, which have APIs that Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -101,7 +101,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -147,7 +147,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -167,7 +167,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v2/tagging.md b/v2/tagging.md index 4177a82c..a8e50584 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 02b148e5..7bf0397c 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 43e6ce59a647ecde7bc4ddc89b0304e801d66391 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Sep 2022 17:42:45 +0000 Subject: [PATCH 588/655] shorten template output, fix Map.of call --- v1/serverless_example.md | 6 +++--- v2/serverless_example.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/v1/serverless_example.md b/v1/serverless_example.md index c1d06ca2..553a686f 100644 --- a/v1/serverless_example.md +++ b/v1/serverless_example.md @@ -126,7 +126,7 @@ Resources: CDKMetadata: Type: AWS::CDK::Metadata Properties: - Modules: "..." + ..." ``` ## Create a Lambda function to list all widgets @@ -198,7 +198,7 @@ Save it and be sure the project still results in an empty stack\. We haven't yet cdk synth ``` -## Creating a widget service +## Create a widget service Add the API Gateway, Lambda, and Amazon S3 packages to the app\. @@ -421,7 +421,7 @@ public class WidgetService extends Construct { .runtime(Runtime.NODEJS_14_X) .code(Code.fromAsset("resources")) .handler("widgets.main") - .environment(java.util.Map.of // Java 9 or later + .environment(java.util.Map.of( // Java 9 or later "BUCKET", bucket.getBucketName()) .build(); diff --git a/v2/serverless_example.md b/v2/serverless_example.md index 2dda3780..2cc1247d 100644 --- a/v2/serverless_example.md +++ b/v2/serverless_example.md @@ -126,7 +126,7 @@ Resources: CDKMetadata: Type: AWS::CDK::Metadata Properties: - Modules: "..." + ... ``` ## Create a Lambda function to list all widgets @@ -198,7 +198,7 @@ Save it and be sure the project still results in an empty stack\. We haven't yet cdk synth ``` -## Creating a widget service +## Create a widget service Create a new source file to define the widget service with the source code shown below\. @@ -359,7 +359,7 @@ public class WidgetService extends Construct { .runtime(Runtime.NODEJS_14_X) .code(Code.fromAsset("resources")) .handler("widgets.main") - .environment(java.util.Map.of // Java 9 or later + .environment(java.util.Map.of( // Java 9 or later "BUCKET", bucket.getBucketName()) .build(); From 0617b335ca676e8942344fccc8ca399513fed5dd Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Sep 2022 18:23:40 +0000 Subject: [PATCH 589/655] fix import in TypeScript example --- v2/stack_how_to_create_multiple_stacks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/stack_how_to_create_multiple_stacks.md b/v2/stack_how_to_create_multiple_stacks.md index e2963465..5a8c9c18 100644 --- a/v2/stack_how_to_create_multiple_stacks.md +++ b/v2/stack_how_to_create_multiple_stacks.md @@ -213,7 +213,7 @@ File: `lib/multistack-stack.ts` ``` import * as cdk from 'aws-cdk-lib'; -import Construct from constructs; +import { Construct } from constructs; import * as s3 from 'aws-cdk-lib/aws-s3'; interface MultistackProps extends cdk.StackProps { From 3e92d8b0ef115ea7c32eaf2868a678ae7bfcf22b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Sep 2022 18:37:50 +0000 Subject: [PATCH 590/655] add info about bootstrapping template v14 --- v2/bootstrapping.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index a0e4a804..55327b40 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -575,4 +575,5 @@ The bootstrap template is versioned and evolves over time with the AWS CDK itsel | 10 | 2\.4\.0 | ECR ScanOnPush is now enabled by default\. | | 11 | 2\.18\.0 | Adds policy allowing Lambda to pull from Amazon ECR repos so it survives rebootstrapping\. | | 12 | 2\.20\.0 | Adds support for experimental cdk import\. | -| 13 | 2\.25\.0 | Makes container images in bootstrap\-created Amazon ECR repositories immutable\. | \ No newline at end of file +| 13 | 2\.25\.0 | Makes container images in bootstrap\-created Amazon ECR repositories immutable\. | +| 14 | 2\.34\.0 | Turns off Amazon ECR image scanning at the repository level by default to allow bootstrapping regions that do not support image scanning\. | \ No newline at end of file From f05bc66ff476a52decc0422491a6a6e71e347f5f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Sep 2022 18:40:56 +0000 Subject: [PATCH 591/655] use archived tagging white paper link --- v1/tagging.md | 2 +- v2/tagging.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/tagging.md b/v1/tagging.md index e251286e..93dc8a15 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -3,7 +3,7 @@ Tags are informational key\-value elements that you can add to constructs in your AWS CDK app\. A tag applied to a given construct also applies to all of its taggable children\. Tags are included in the AWS CloudFormation template synthesized from your app and are applied to the AWS resources it deploys\. You can use tags to identify and categorize resources to simplify management, in cost allocation, and for access control, as well as for any other purposes you devise\. **Tip** -For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/tagging-best-practices.html)\. +For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf) \(PDF\)\. The [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. + [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html#addkey-value-props](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_core.Tags.html#addkey-value-props) applies a new tag to the given construct and all of its children\. diff --git a/v2/tagging.md b/v2/tagging.md index a8e50584..2804be5a 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -3,7 +3,7 @@ Tags are informational key\-value elements that you can add to constructs in your AWS CDK app\. A tag applied to a given construct also applies to all of its taggable children\. Tags are included in the AWS CloudFormation template synthesized from your app and are applied to the AWS resources it deploys\. You can use tags to identify and categorize resources to simplify management, in cost allocation, and for access control, as well as for any other purposes you devise\. **Tip** -For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/tagging-best-practices.html)\. +For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf) \(PDF\)\. The [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. + [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#addkey-value-props](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#addkey-value-props) applies a new tag to the given construct and all of its children\. From dbd0ede7a162f3a699f67c7fbb4e00656e6eb00b Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Sep 2022 18:52:45 +0000 Subject: [PATCH 592/655] add missing app.synth() calls --- v1/stack_how_to_create_multiple_stacks.md | 6 ++++++ v2/stack_how_to_create_multiple_stacks.md | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/v1/stack_how_to_create_multiple_stacks.md b/v1/stack_how_to_create_multiple_stacks.md index 7ab0aabb..9c291a45 100644 --- a/v1/stack_how_to_create_multiple_stacks.md +++ b/v1/stack_how_to_create_multiple_stacks.md @@ -465,6 +465,8 @@ new MultistackStack(app, "MyEastCdkStack", { env: {region: "us-east-1"}, encryptBucket: true }); + +app.synth(); ``` ------ @@ -488,6 +490,8 @@ new MultistackStack(app, "MyEastCdkStack", { env: {region: "us-east-1"}, encryptBucket: true }); + +app.synth(); ``` ------ @@ -510,6 +514,8 @@ MultistackStack(app, "MyWestCdkStack", MultistackStack(app, "MyEastCdkStack", env=core.Environment(region="us-east-1"), encrypt_bucket=True) + +app.synth() ``` ------ diff --git a/v2/stack_how_to_create_multiple_stacks.md b/v2/stack_how_to_create_multiple_stacks.md index 5a8c9c18..9ce296b9 100644 --- a/v2/stack_how_to_create_multiple_stacks.md +++ b/v2/stack_how_to_create_multiple_stacks.md @@ -420,6 +420,8 @@ new MultistackStack(app, "MyEastCdkStack", { env: {region: "us-east-1"}, encryptBucket: true }); + +app.synth(); ``` ------ @@ -443,6 +445,8 @@ new MultistackStack(app, "MyEastCdkStack", { env: {region: "us-east-1"}, encryptBucket: true }); + +app.synth(); ``` ------ @@ -465,6 +469,8 @@ MultistackStack(app, "MyWestCdkStack", MultistackStack(app, "MyEastCdkStack", env=cdk.Environment(region="us-east-1"), encrypt_bucket=True) + +app.synth() ``` ------ From de5b8031f9a053cae32fc2e8b76e0a6e909fefd7 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Sep 2022 19:27:54 +0000 Subject: [PATCH 593/655] add link to region codes --- v1/environments.md | 2 +- v2/environments.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/environments.md b/v1/environments.md index 16a54b2d..60ccb67f 100644 --- a/v1/environments.md +++ b/v1/environments.md @@ -1,6 +1,6 @@ # Environments -Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and region into which the stack is intended to be deployed\. +Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and region into which the stack is intended to be deployed\. The region is specified using a region code; see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints) for a list\. **Note** For all but the simplest deployments, you will need to [bootstrap](bootstrapping.md) each environment you will deploy into\. Deployment requires certain AWS resources to be available, and these resources are provisioned by bootstrapping\. diff --git a/v2/environments.md b/v2/environments.md index 4421d5d6..5606fc3c 100644 --- a/v2/environments.md +++ b/v2/environments.md @@ -1,6 +1,6 @@ # Environments -Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and region into which the stack is intended to be deployed\. +Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and region into which the stack is intended to be deployed\. The region is specified using a region code; see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints) for a list\. **Note** You must [bootstrap](bootstrapping.md) each environment you will deploy CDK stacks into\. Bootstrapping provisions certain AWS resources that are used during deployment\. From 23120392feb0dc2233f0178fd6ed074935340f28 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Sep 2022 19:28:43 +0000 Subject: [PATCH 594/655] add guidance about naming project folders --- v1/work-with-cdk-csharp.md | 2 +- v1/work-with-cdk-go.md | 2 +- v1/work-with-cdk-java.md | 2 +- v1/work-with-cdk-javascript.md | 2 +- v1/work-with-cdk-python.md | 2 +- v1/work-with-cdk-typescript.md | 2 +- v2/work-with-cdk-csharp.md | 2 +- v2/work-with-cdk-go.md | 2 +- v2/work-with-cdk-java.md | 2 +- v2/work-with-cdk-javascript.md | 2 +- v2/work-with-cdk-python.md | 2 +- v2/work-with-cdk-typescript.md | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/v1/work-with-cdk-csharp.md b/v1/work-with-cdk-csharp.md index 53824b88..fff79cf0 100644 --- a/v1/work-with-cdk-csharp.md +++ b/v1/work-with-cdk-csharp.md @@ -27,7 +27,7 @@ cd my-project cdk init app --language csharp ``` -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a C\# identifier; for example, it should not start with a number or contain spaces\. The resulting project includes a reference to the `Amazon.CDK` NuGet package\. It and its dependencies are installed automatically by NuGet\. diff --git a/v1/work-with-cdk-go.md b/v1/work-with-cdk-go.md index c934358b..c508148b 100644 --- a/v1/work-with-cdk-go.md +++ b/v1/work-with-cdk-go.md @@ -25,7 +25,7 @@ cd my-project cdk init app --language go ``` -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a Go identifier; for example, it should not start with a number or contain spaces\. The resulting project includes a reference to the AWS CDK Go module, `github.com/aws/aws-cdk-go/awscdk`, in `go.mod`\. The CDK and its dependencies are automatically installed when you build your app\. diff --git a/v1/work-with-cdk-java.md b/v1/work-with-cdk-java.md index 5c0be3a5..0d20ba46 100644 --- a/v1/work-with-cdk-java.md +++ b/v1/work-with-cdk-java.md @@ -30,7 +30,7 @@ cd my-project cdk init app --language java ``` -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a Java identifier; for example, it should not start with a number or contain spaces\. The resulting project includes a reference to the `software.amazon.awscdk.core` Maven package\. It and its dependencies are automatically installed by Maven\. diff --git a/v1/work-with-cdk-javascript.md b/v1/work-with-cdk-javascript.md index 7a918fee..f7b3183a 100644 --- a/v1/work-with-cdk-javascript.md +++ b/v1/work-with-cdk-javascript.md @@ -25,7 +25,7 @@ cdk init app --language javascript Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/v1/docs/core-readme.html](https://docs.aws.amazon.com/cdk/api/v1/docs/core-readme.html) module and its dependencies\. -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a JavaScript identifier; for example, it should not start with a number or contain spaces\. ## Using local `cdk` diff --git a/v1/work-with-cdk-python.md b/v1/work-with-cdk-python.md index c11aeb4e..3864a54b 100644 --- a/v1/work-with-cdk-python.md +++ b/v1/work-with-cdk-python.md @@ -40,7 +40,7 @@ cd my-project cdk init app --language python ``` -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a Python identifier; for example, it should not start with a number or contain spaces\. After initializing the project, activate the project's virtual environment\. This allows the project's dependencies to be installed locally in the project folder, instead of globally\. diff --git a/v1/work-with-cdk-typescript.md b/v1/work-with-cdk-typescript.md index f4772f52..52aa3746 100644 --- a/v1/work-with-cdk-typescript.md +++ b/v1/work-with-cdk-typescript.md @@ -34,7 +34,7 @@ cdk init app --language typescript Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/v1/docs/core-readme.html](https://docs.aws.amazon.com/cdk/api/v1/docs/core-readme.html) module and its dependencies\. -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a TypeScript identifier; for example, it should not start with a number or contain spaces\. ## Using local `tsc` and `cdk` diff --git a/v2/work-with-cdk-csharp.md b/v2/work-with-cdk-csharp.md index a3b29eb1..1e9b19e5 100644 --- a/v2/work-with-cdk-csharp.md +++ b/v2/work-with-cdk-csharp.md @@ -27,7 +27,7 @@ cd my-project cdk init app --language csharp ``` -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a C\# identifier; for example, it should not start with a number or contain spaces\. The resulting project includes a reference to the `Amazon.CDK.Lib` NuGet package\. It and its dependencies are installed automatically by NuGet\. diff --git a/v2/work-with-cdk-go.md b/v2/work-with-cdk-go.md index 1221680f..1545e80e 100644 --- a/v2/work-with-cdk-go.md +++ b/v2/work-with-cdk-go.md @@ -25,7 +25,7 @@ cd my-project cdk init app --language go ``` -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a Go identifier; for example, it should not start with a number or contain spaces\. The resulting project includes a reference to the AWS CDK Go module, `github.com/aws/aws-cdk-go/awscdk/v2`, in `go.mod`\. The CDK and its dependencies are automatically installed when you build your app\. diff --git a/v2/work-with-cdk-java.md b/v2/work-with-cdk-java.md index d0ee5b8c..83f7a9ce 100644 --- a/v2/work-with-cdk-java.md +++ b/v2/work-with-cdk-java.md @@ -30,7 +30,7 @@ cd my-project cdk init app --language java ``` -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a Java identifier; for example, it should not start with a number or contain spaces\. The resulting project includes a reference to the `software.amazon.awscdk` Maven package\. It and its dependencies are automatically installed by Maven\. diff --git a/v2/work-with-cdk-javascript.md b/v2/work-with-cdk-javascript.md index c1d945cc..442d2676 100644 --- a/v2/work-with-cdk-javascript.md +++ b/v2/work-with-cdk-javascript.md @@ -25,7 +25,7 @@ cdk init app --language javascript Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html) module and its dependencies\. -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a JavaScript identifier; for example, it should not start with a number or contain spaces\. ## Using local `cdk` diff --git a/v2/work-with-cdk-python.md b/v2/work-with-cdk-python.md index 4eaafc7b..c115d018 100644 --- a/v2/work-with-cdk-python.md +++ b/v2/work-with-cdk-python.md @@ -40,7 +40,7 @@ cd my-project cdk init app --language python ``` -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a Python identifier; for example, it should not start with a number or contain spaces\. To work with the new project, activate its virtual environment\. This allows the project's dependencies to be installed locally in the project folder, instead of globally\. diff --git a/v2/work-with-cdk-typescript.md b/v2/work-with-cdk-typescript.md index ddce401e..3aad420b 100644 --- a/v2/work-with-cdk-typescript.md +++ b/v2/work-with-cdk-typescript.md @@ -34,7 +34,7 @@ cdk init app --language typescript Creating a project also installs the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html) module and its dependencies\. -`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. +`cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a TypeScript identifier; for example, it should not start with a number or contain spaces\. ## Using local `tsc` and `cdk` From 51ecf605b449882cfa2b5aca1625878eeb544445 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Sep 2022 19:29:05 +0000 Subject: [PATCH 595/655] auto-generated id churn --- v1/cli.md | 26 +++++++++++++------------- v1/manage-dependencies.md | 10 +++++----- v1/tagging.md | 2 +- v1/use_cfn_template.md | 2 +- v2/cli.md | 26 +++++++++++++------------- v2/manage-dependencies.md | 10 +++++----- v2/tagging.md | 2 +- v2/use_cfn_template.md | 2 +- 8 files changed, 40 insertions(+), 40 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index 36857527..4d5af513 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -351,7 +351,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -370,7 +370,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -378,7 +378,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -454,7 +454,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -476,7 +476,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -733,7 +733,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -746,7 +746,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -767,7 +767,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -847,7 +847,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -925,7 +925,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -944,7 +944,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -970,7 +970,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -992,7 +992,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/manage-dependencies.md b/v1/manage-dependencies.md index cfef9502..bb65af42 100644 --- a/v1/manage-dependencies.md +++ b/v1/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -72,7 +72,7 @@ All AWS CDK dependencies must have the same version\. Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -99,7 +99,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -145,7 +145,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -169,7 +169,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v1/tagging.md b/v1/tagging.md index 93dc8a15..5b8ab603 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index 0bcd9aed..51d7210b 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/cli.md b/v2/cli.md index c9943aaf..cefbd1da 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -343,7 +343,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -362,7 +362,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -370,7 +370,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -446,7 +446,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -468,7 +468,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -725,7 +725,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -738,7 +738,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -759,7 +759,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -839,7 +839,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -917,7 +917,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -936,7 +936,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -962,7 +962,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -984,7 +984,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index db04da05..e6a98ac9 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -71,7 +71,7 @@ Specify exact versions for alpha construct library modules, which have APIs that Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -101,7 +101,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -147,7 +147,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -167,7 +167,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v2/tagging.md b/v2/tagging.md index 2804be5a..84713884 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 7bf0397c..973ffcfa 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 253537ef20cc2099a20e22286e3c7c17cbf892a3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Sep 2022 23:15:33 +0000 Subject: [PATCH 596/655] fix garbled sentence --- v1/cfn_layer.md | 2 +- v2/cfn_layer.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/cfn_layer.md b/v1/cfn_layer.md index 6c1c17d8..165660dd 100644 --- a/v1/cfn_layer.md +++ b/v1/cfn_layer.md @@ -2,7 +2,7 @@ The AWS CDK lets you describe AWS resources using constructs that operate at varying levels of abstraction\. + *Layer 1 \(L1\)* constructs directly represent AWS CloudFormation resources as defined by the CloudFormation specification\. These constructs can be identified via a name beginning with "Cfn," so they are also referred to as "Cfn constructs\." If a resource exists in AWS CloudFormation, it exists in the CDK as a L1 construct\. -+ *Layer 2 \(L2\)* or "curated" constructs are thoughtfully developed to provide a more ergonomic developer experience compared to the L1 construct they're built upon\. In a typical CDK app, L2 constructs are usually the most widely used type\. Often, L2 constructs define additional supporting resources, such as IAM policies, Amazon SNS topics, or AWS KMS keys\. L1 constructs sensible defaults, best\-practice security policies, and\. ++ *Layer 2 \(L2\)* or "curated" constructs are thoughtfully developed to provide a more ergonomic developer experience compared to the L1 construct they're built upon\. In a typical CDK app, L2 constructs are usually the most widely used type\. Often, L2 constructs define additional supporting resources, such as IAM policies, Amazon SNS topics, or AWS KMS keys\. L2 constructs provide sensible defaults, best\-practice security policies, and a more ergonomic developer experience\. + *Layer 3 \(L3\)* constructs or *patterns* define entire collections of AWS resources for specific use cases, making it easy to stand up a build pipeline, an Amazon ECS application, or one of many other types of common deployment scenarios\. Because they can constitute complete system designs, or substantial parts of a larger system, L3 constructs are often "opinionated"—they are built around a very particular approach toward solving the problem at hand, and things work out best when you follow their lead\. **Tip** diff --git a/v2/cfn_layer.md b/v2/cfn_layer.md index bec4a45b..8ccceef8 100644 --- a/v2/cfn_layer.md +++ b/v2/cfn_layer.md @@ -2,7 +2,7 @@ The AWS CDK lets you describe AWS resources using constructs that operate at varying levels of abstraction\. + *Layer 1 \(L1\)* constructs directly represent AWS CloudFormation resources as defined by the CloudFormation specification\. These constructs can be identified via a name beginning with "Cfn," so they are also referred to as "Cfn constructs\." If a resource exists in AWS CloudFormation, it exists in the CDK as a L1 construct\. -+ *Layer 2 \(L2\)* or "curated" constructs are thoughtfully developed to provide a more ergonomic developer experience compared to the L1 construct they're built upon\. In a typical CDK app, L2 constructs are usually the most widely used type\. Often, L2 constructs define additional supporting resources, such as IAM policies, Amazon SNS topics, or AWS KMS keys\. L1 constructs sensible defaults, best\-practice security policies, and\. ++ *Layer 2 \(L2\)* or "curated" constructs are thoughtfully developed to provide a more ergonomic developer experience compared to the L1 construct they're built upon\. In a typical CDK app, L2 constructs are usually the most widely used type\. Often, L2 constructs define additional supporting resources, such as IAM policies, Amazon SNS topics, or AWS KMS keys\. L2 constructs provide sensible defaults, best\-practice security policies, and a more ergonomic developer experience\. + *Layer 3 \(L3\)* constructs or *patterns* define entire collections of AWS resources for specific use cases, making it easy to stand up a build pipeline, an Amazon ECS application, or one of many other types of common deployment scenarios\. Because they can constitute complete system designs, or substantial parts of a larger system, L3 constructs are often "opinionated"—they are built around a very particular approach toward solving the problem at hand, and things work out best when you follow their lead\. **Tip** From f63b014865a571f9d66effa93f7ff3ee65c3ead0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 19 Sep 2022 23:34:45 +0000 Subject: [PATCH 597/655] fix aws configure command --- v1/getting_started.md | 2 +- v2/getting_started.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/getting_started.md b/v1/getting_started.md index 4ff585b1..d504d7aa 100644 --- a/v1/getting_started.md +++ b/v1/getting_started.md @@ -147,7 +147,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials **Note** Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. -The AWS CDK natively AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, first create a profile using aws config sso\. Then log in using aws sso login\. Finally, specify this profile when issuing cdk commands using the \-\-profile option or the `AWS_PROFILE` environment variable\. +The AWS CDK natively AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, first create a profile using aws configure sso\. Then log in using aws sso login\. Finally, specify this profile when issuing cdk commands using the \-\-profile option or the `AWS_PROFILE` environment variable\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. diff --git a/v2/getting_started.md b/v2/getting_started.md index b286f8de..8345bc8c 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -197,7 +197,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials **Note** Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. -The AWS CDK natively AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, first create a profile using aws config sso\. Then log in using aws sso login\. Finally, specify this profile when issuing cdk commands using the \-\-profile option or the `AWS_PROFILE` environment variable\. +The AWS CDK natively AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, first create a profile using aws configure sso\. Then log in using aws sso login\. Finally, specify this profile when issuing cdk commands using the \-\-profile option or the `AWS_PROFILE` environment variable\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. From 947532b601c6b764e769611d375dbaa9755758e6 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 20 Sep 2022 00:53:28 +0000 Subject: [PATCH 598/655] remove untrue statement about aspects only being used for tags --- v1/aspects.md | 2 +- v2/aspects.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/aspects.md b/v1/aspects.md index bce46526..202cda09 100644 --- a/v1/aspects.md +++ b/v1/aspects.md @@ -41,7 +41,7 @@ Aspects.Of(myConstruct).add(new SomeAspect(...)); ------ -The AWS CDK currently uses aspects only to [tag resources](tagging.md), but the framework is extensible and can also be used for other purposes\. For example, you can use it to validate or change the AWS CloudFormation resources that are defined for you by higher\-level constructs\. +The AWS CDK uses aspects to [tag resources](tagging.md), but the framework can also be used for other purposes\. For example, you can use it to validate or change the AWS CloudFormation resources that are defined for you by higher\-level constructs\. ## Aspects in detail diff --git a/v2/aspects.md b/v2/aspects.md index b3b28d1c..6b2860f2 100644 --- a/v2/aspects.md +++ b/v2/aspects.md @@ -41,7 +41,7 @@ Aspects.Of(myConstruct).add(new SomeAspect(...)); ------ -The AWS CDK currently uses aspects only to [tag resources](tagging.md), but the framework is extensible and can also be used for other purposes\. For example, you can use it to validate or change the AWS CloudFormation resources that are defined for you by higher\-level constructs\. +The AWS CDK uses aspects to [tag resources](tagging.md), but the framework can also be used for other purposes\. For example, you can use it to validate or change the AWS CloudFormation resources that are defined for you by higher\-level constructs\. ## Aspects in detail From 2f7261ab8ce253143be1e35dc4ca4522205e8646 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 20 Sep 2022 00:53:59 +0000 Subject: [PATCH 599/655] update v2 feature flags --- v2/featureflags.md | 52 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/v2/featureflags.md b/v2/featureflags.md index 57838038..49ae72eb 100644 --- a/v2/featureflags.md +++ b/v2/featureflags.md @@ -2,12 +2,53 @@ The AWS CDK uses *feature flags* to enable potentially breaking behaviors in a release\. Flags are stored as [Runtime context](context.md) values in `cdk.json` \(or `~/.cdk.json`\)\. They are not removed by the cdk context \-\-reset or cdk context \-\-clear commands\. -Feature flags are disabled by default, so existing projects that do not specify the flag will continue to work as expected with later AWS CDK releases\. New projects created using cdk init include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the old behavior, or to add flags to enable new behaviors after upgrading the AWS CDK\. +Feature flags are disabled by default, so existing projects that do not specify the flag will continue to work as before with later AWS CDK releases\. New projects created using cdk init include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the old behavior, or to add flags to enable new behaviors after upgrading the AWS CDK\. -**Note** -Currently, CDK v2 does not have any feature flags to enable new behaviors\. +See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. The AWS CDK source file [https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts) provides a complete list of all current feature flags\. -In CDK v2, feature flags are also used to revert certain behaviors to their v1 defaults\. The flags listed below, set to `false`, revert to specific v1 AWS CDK v1 behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. +## Enabling features with flags + +The following feature flags may be set to `true` to enable the described behavior\. + +`@aws-cdk/core:checkSecretUsage` +Makes it impossible to use Secrets Manager values in unsafe locations\. + +`@aws-cdk/aws-lambda:recognizeLayerVersion` +Ensure that updating a layer associated with a Lambda function creates a new version of the function\. + +`@aws-cdk/core:target-partitions` +Ensure that Amazon EC2 Systems Manager service principals are generated correctly\. + +`@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver` +Enables logging in service extensions containers by default\. + +`@aws-cdk/aws-ec2:uniqueImdsv2TemplateName` +Causes [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.InstanceRequireImdsv2Aspect.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.InstanceRequireImdsv2Aspect.html) to ensure that the generated name is unique\. + +`@aws-cdk/aws-iam:minimizePolicies` +Minimize the creation of IAM policies when possible\. + +`@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption` +In an Amazon SQS queue subscribed to an Amazon SNS topic, restrict decryption permissions to just the topic instead of all of SNS\. + +`@aws-cdk/aws-s3:createDefaultLoggingPolicy` +When using an S3 bucket with a service that will automatically create a bucket policy at deployment, have the AWS CDK configure the necessary policy\. + +`@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName` +Make sure cross\-account key alias is unique in pipelines\. + +`@aws-cdk/core:validateSnapshotRemovalPolicy` +The AWS CDK fails at synthesis time if the `SNAPSHOT` removal policy is not supported for a given resource\. + +`@aws-cdk/aws-ecs:arnFormatIncludesClusterName` +Use the new ARN format when importing an Amazon EC2 or Fargate cluster\. + +`@aws-cdk/aws-ecs:arnFormatIncludesClusterName` +Use the new ARN format when importing an Amazon EC2 or Fargate cluster\. + +## Disabling features with flags + +In CDK v2, a few feature flags are supported to revert certain behaviors to their v1 defaults\. The flags listed below, set to `false`, revert to specific AWS CDK v1 behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. `@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId` If your application uses multiple Amazon API Gateway API keys and associates them to usage plans @@ -21,6 +62,9 @@ If your application uses Amazon RDS database instance or database clusters, and `@aws-cdk/core:stackRelativeExports` If your application uses multiple stacks and you refer to resources from one stack in another, this determines whether absolute or relative path is used to construct AWS CloudFormation exports +`@aws-cdk/aws-lambda:recognizeVersionProps` +If set to `false`, the CDK includes metadata when detecting whether a Lambda function has changed\. This can cause deployment failures when only the metadata has changed, since duplicate versions are not allowed\. + The syntax for reverting these flags in `cdk.json` is shown here\. ``` From ff0fa52cd9644ae3822132acd4558ed0f941fa3d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 20 Sep 2022 00:54:28 +0000 Subject: [PATCH 600/655] autogenerated ID churn --- v2/cli.md | 26 +++++++++++++------------- v2/manage-dependencies.md | 10 +++++----- v2/tagging.md | 2 +- v2/use_cfn_template.md | 2 +- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/v2/cli.md b/v2/cli.md index cefbd1da..96f66905 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -343,7 +343,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -362,7 +362,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -370,7 +370,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -446,7 +446,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -468,7 +468,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -725,7 +725,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -738,7 +738,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -759,7 +759,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -839,7 +839,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -917,7 +917,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -936,7 +936,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -962,7 +962,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -984,7 +984,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index e6a98ac9..4f50782a 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -71,7 +71,7 @@ Specify exact versions for alpha construct library modules, which have APIs that Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -101,7 +101,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -147,7 +147,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -167,7 +167,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v2/tagging.md b/v2/tagging.md index 84713884..7b94fdce 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 973ffcfa..0cdcf380 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. From 2bba76e86fc3906ded85adc2d9625a526b2addfa Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 20 Sep 2022 18:36:09 +0000 Subject: [PATCH 601/655] fix spurious Constructs that should be L1 or L2 --- v1/cfn_layer.md | 16 ++++++++-------- v2/cfn_layer.md | 16 ++++++++-------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/v1/cfn_layer.md b/v1/cfn_layer.md index 165660dd..32063e5a 100644 --- a/v1/cfn_layer.md +++ b/v1/cfn_layer.md @@ -15,17 +15,17 @@ Abstractions are powerful tools for designing and implementing cloud application No abstraction is perfect, and even good abstractions cannot cover every possible use case\. While the value of the AWS CDK's model is plain, sometimes you'll come upon a construct that's perfect for your needs—if only you could make a small \(or large\) tweak\. For this reason, the AWS CDK provides ways to "break out" of the construct model, moving to a lower level of abstraction or to a different model entirely\. As their name implies, the CDK's *escape hatches* let you "escape" the AWS CDK paradigm and extend it in ways the AWS CDK designers never anticipated\. Then you can wrap all that in a new construct to hide the underlying complexity and provide a clean API for developers\. Some situations in which you'll reach for escape hatches include: -+ An AWS service feature is available through AWS CloudFormation, but there are no Construct constructs for it\. -+ An AWS service feature is available through AWS CloudFormation, and there are Construct constructs for the service, but these don't yet expose the feature\. Because Construct constructs are developed "by hand," they may sometimes lag behind the CFN Resource constructs\. ++ An AWS service feature is available through AWS CloudFormation, but there are no L2 constructs for it\. ++ An AWS service feature is available through AWS CloudFormation, and there are L2 constructs for the service, but these don't yet expose the feature\. Because L2 constructs are developed "by hand," they may sometimes lag behind the L1 constructs\. + The feature is not yet available through AWS CloudFormation at all\. To determine whether a feature is available through AWS CloudFormation, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. ## Using AWS CloudFormation constructs directly -If there are no Construct classes available for the service, you can fall back to the automatically generated CFN Resources, which map 1:1 onto all available AWS CloudFormation resources and properties\. These resources can be recognized by their name starting with `Cfn`, such as `CfnBucket` or `CfnRole`\. You instantiate them exactly as you would use the equivalent AWS CloudFormation resource\. For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. +If there are no L23 classes available for the service, you can fall back to the automatically generated L1 constructs, which map 1:1 onto all available AWS CloudFormation resources and properties\. These resources can be recognized by their name starting with `Cfn`, such as `CfnBucket` or `CfnRole`\. You instantiate them exactly as you would use the equivalent AWS CloudFormation resource\. For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. -For example, to instantiate a low\-level Amazon S3 bucket CFN Resource with analytics enabled, you would write something like the following\. +For example, to instantiate a low\-level Amazon S3 bucket L1 with analytics enabled, you would write something like the following\. ------ #### [ TypeScript ] @@ -188,11 +188,11 @@ For more information, see [AWS Resource and Property Types Reference](https://do ## Modifying the AWS CloudFormation resource behind AWS constructs -If a Construct is missing a feature or you are trying to work around an issue, you can modify the CFN Resource that is encapsulated by the Construct\. +If a L2 construct is missing a feature or you are trying to work around an issue, you can modify the L1 construct that is encapsulated by the L2 construct\. -All Constructs contain within them the corresponding CFN Resource\. For example, the high\-level `Bucket` construct wraps the low\-level `CfnBucket` construct\. Because the `CfnBucket` corresponds directly to the AWS CloudFormation resource, it exposes all features that are available through AWS CloudFormation\. +All L2 constructs contain within them the corresponding L1 construct\. For example, the high\-level `Bucket` construct wraps the low\-level `CfnBucket` construct\. Because the `CfnBucket` corresponds directly to the AWS CloudFormation resource, it exposes all features that are available through AWS CloudFormation\. -The basic approach to get access to the CFN Resource class is to use `construct.node.defaultChild` \(Python: `default_child`\), cast it to the right type \(if necessary\), and modify its properties\. Again, let's take the example of a `Bucket`\. +The basic approach to get access to the L1 class is to use `construct.node.defaultChild` \(Python: `default_child`\), cast it to the right type \(if necessary\), and modify its properties\. Again, let's take the example of a `Bucket`\. ------ #### [ TypeScript ] @@ -324,7 +324,7 @@ cfnBucket.CfnOptions.Metadata = new Dictionary ## Raw overrides -If there are properties that are missing from the CFN Resource, you can bypass all typing using raw overrides\. This also makes it possible to delete synthesized properties\. +If there are properties that are missing from the L1 construct, you can bypass all typing using raw overrides\. This also makes it possible to delete synthesized properties\. Use one of the `addOverride` methods \(Python: `add_override`\) methods, as shown in the following example\. diff --git a/v2/cfn_layer.md b/v2/cfn_layer.md index 8ccceef8..3d583e5a 100644 --- a/v2/cfn_layer.md +++ b/v2/cfn_layer.md @@ -15,17 +15,17 @@ Abstractions are powerful tools for designing and implementing cloud application No abstraction is perfect, and even good abstractions cannot cover every possible use case\. While the value of the AWS CDK's model is plain, sometimes you'll come upon a construct that's perfect for your needs—if only you could make a small \(or large\) tweak\. For this reason, the AWS CDK provides ways to "break out" of the construct model, moving to a lower level of abstraction or to a different model entirely\. As their name implies, the CDK's *escape hatches* let you "escape" the AWS CDK paradigm and extend it in ways the AWS CDK designers never anticipated\. Then you can wrap all that in a new construct to hide the underlying complexity and provide a clean API for developers\. Some situations in which you'll reach for escape hatches include: -+ An AWS service feature is available through AWS CloudFormation, but there are no Construct constructs for it\. -+ An AWS service feature is available through AWS CloudFormation, and there are Construct constructs for the service, but these don't yet expose the feature\. Because Construct constructs are developed "by hand," they may sometimes lag behind the CFN Resource constructs\. ++ An AWS service feature is available through AWS CloudFormation, but there are no L2 constructs for it\. ++ An AWS service feature is available through AWS CloudFormation, and there are L2 constructs for the service, but these don't yet expose the feature\. Because L2 constructs are developed "by hand," they may sometimes lag behind the L1 constructs\. + The feature is not yet available through AWS CloudFormation at all\. To determine whether a feature is available through AWS CloudFormation, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. ## Using AWS CloudFormation constructs directly -If there are no Construct classes available for the service, you can fall back to the automatically generated CFN Resources, which map 1:1 onto all available AWS CloudFormation resources and properties\. These resources can be recognized by their name starting with `Cfn`, such as `CfnBucket` or `CfnRole`\. You instantiate them exactly as you would use the equivalent AWS CloudFormation resource\. For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. +If there are no L2 classes available for the service, you can fall back to the automatically generated L1 constructss, which map 1:1 onto all available AWS CloudFormation resources and properties\. These resources can be recognized by their name starting with `Cfn`, such as `CfnBucket` or `CfnRole`\. You instantiate them exactly as you would use the equivalent AWS CloudFormation resource\. For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. -For example, to instantiate a low\-level Amazon S3 bucket CFN Resource with analytics enabled, you would write something like the following\. +For example, to instantiate a low\-level Amazon S3 bucket L1 with analytics enabled, you would write something like the following\. ------ #### [ TypeScript ] @@ -188,11 +188,11 @@ For more information, see [AWS Resource and Property Types Reference](https://do ## Modifying the AWS CloudFormation resource behind AWS constructs -If a Construct is missing a feature or you are trying to work around an issue, you can modify the CFN Resource that is encapsulated by the Construct\. +If a L2 construct is missing a feature or you are trying to work around an issue, you can modify the L1 construct that is encapsulated by the L2 construct\. -All Constructs contain within them the corresponding CFN Resource\. For example, the high\-level `Bucket` construct wraps the low\-level `CfnBucket` construct\. Because the `CfnBucket` corresponds directly to the AWS CloudFormation resource, it exposes all features that are available through AWS CloudFormation\. +All L2 constructs contain within them the corresponding L1 construct\. For example, the high\-level `Bucket` construct wraps the low\-level `CfnBucket` construct\. Because the `CfnBucket` corresponds directly to the AWS CloudFormation resource, it exposes all features that are available through AWS CloudFormation\. -The basic approach to get access to the CFN Resource class is to use `construct.node.defaultChild` \(Python: `default_child`\), cast it to the right type \(if necessary\), and modify its properties\. Again, let's take the example of a `Bucket`\. +The basic approach to get access to the L1 class is to use `construct.node.defaultChild` \(Python: `default_child`\), cast it to the right type \(if necessary\), and modify its properties\. Again, let's take the example of a `Bucket`\. ------ #### [ TypeScript ] @@ -378,7 +378,7 @@ To avoid confusion, do not create multiple L2 constructs that refer to the same ## Raw overrides -If there are properties that are missing from the CFN Resource, you can bypass all typing using raw overrides\. This also makes it possible to delete synthesized properties\. +If there are properties that are missing from the L1 construct, you can bypass all typing using raw overrides\. This also makes it possible to delete synthesized properties\. Use one of the `addOverride` methods \(Python: `add_override`\) methods, as shown in the following example\. From fd6ea34cd73d220509d71118e1386ffa9c2f2f96 Mon Sep 17 00:00:00 2001 From: Kyle Laker Date: Wed, 21 Sep 2022 15:12:22 -0400 Subject: [PATCH 602/655] Remove incorrect statement that CDK v2 does not have new feature flags (#424) CDK v2 _does_ now have feature flags (quite a lot of them actually). There is probably a mountain more to say on feature flags in v2, but this at least removes the blatantly incorrect statement and copies the v1 docs' wording about how to view the list of all feature flags and what they do. Co-authored-by: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> --- v2/featureflags.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/v2/featureflags.md b/v2/featureflags.md index 49ae72eb..421f8a30 100644 --- a/v2/featureflags.md +++ b/v2/featureflags.md @@ -76,4 +76,5 @@ The syntax for reverting these flags in `cdk.json` is shown here\. "@aws-cdk/core:stackRelativeExports": false, } } -``` \ No newline at end of file +``` + From a765023557adf1127bf74b9bcda6a75b2c46075d Mon Sep 17 00:00:00 2001 From: Thomas Steinbach Date: Wed, 21 Sep 2022 21:20:39 +0200 Subject: [PATCH 603/655] docs: Replace 'isToken' function by actual 'isUnresolved' (#409) In change a12fcfa of the aws-cdk-lib the function `Token.isToken` was replaced by `Token.isUnresolved`. This change in the documentation reflects that change in code. Co-authored-by: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> --- v2/apps.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/v2/apps.md b/v2/apps.md index 482a56a7..8f85ded2 100644 --- a/v2/apps.md +++ b/v2/apps.md @@ -153,8 +153,8 @@ This is the final stage of the execution of your AWS CDK app\. It's triggered by In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: -+ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you may inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. -+ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)` \(Python: `is_token`\)\. See [Tokens](tokens.md) for details\. ++ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you must inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. ++ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `Token.isUnresolved(value)` \(Python: `is_unresolved`\)\. See [Tokens](tokens.md) for details\. ## Cloud assemblies @@ -225,4 +225,4 @@ The CLI can also interact directly with an already\-synthesized cloud assembly\. ``` cdk --app ./my-cloud-assembly ls -``` \ No newline at end of file +``` From 7621a3a1f731e0bd55d95d8c9b3d8fd5ef51556d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Sep 2022 19:34:12 +0000 Subject: [PATCH 604/655] round-tripping PRs --- v1/apps.md | 4 ++-- v2/apps.md | 4 ++-- v2/featureflags.md | 3 +-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/v1/apps.md b/v1/apps.md index 5280e2ff..6001dcf4 100644 --- a/v1/apps.md +++ b/v1/apps.md @@ -153,8 +153,8 @@ This is the final stage of the execution of your AWS CDK app\. It's triggered by In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: -+ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you may inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1/typescript/custom-resource/) example\. -+ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isToken(value)` \(Python: `is_token`\)\. See [Tokens](tokens.md) for details\. ++ The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you must inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/CDKv1/typescript/custom-resource/) example\. ++ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isUnresloved(value)` \(Python: `is_unresolved`\)\. See [Tokens](tokens.md) for details\. ## Cloud assemblies diff --git a/v2/apps.md b/v2/apps.md index 8f85ded2..aa51fa32 100644 --- a/v2/apps.md +++ b/v2/apps.md @@ -154,7 +154,7 @@ In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: + The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you must inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. -+ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `Token.isUnresolved(value)` \(Python: `is_unresolved`\)\. See [Tokens](tokens.md) for details\. ++ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isUnresolved(value)` \(Python: `is_unreslovde`\)\. See [Tokens](tokens.md) for details\. ## Cloud assemblies @@ -225,4 +225,4 @@ The CLI can also interact directly with an already\-synthesized cloud assembly\. ``` cdk --app ./my-cloud-assembly ls -``` +``` \ No newline at end of file diff --git a/v2/featureflags.md b/v2/featureflags.md index 421f8a30..49ae72eb 100644 --- a/v2/featureflags.md +++ b/v2/featureflags.md @@ -76,5 +76,4 @@ The syntax for reverting these flags in `cdk.json` is shown here\. "@aws-cdk/core:stackRelativeExports": false, } } -``` - +``` \ No newline at end of file From a95b099ea93ea8f108525ea51201b2058c0d251e Mon Sep 17 00:00:00 2001 From: Mark Beacom <7315957+mbeacom@users.noreply.github.com> Date: Wed, 21 Sep 2022 15:36:48 -0400 Subject: [PATCH 605/655] Fix #406 - Correct boostrap typo in migration and troubleshooting guides (#407) --- v2/troubleshooting.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/v2/troubleshooting.md b/v2/troubleshooting.md index 985bf0f2..ecc10c2c 100644 --- a/v2/troubleshooting.md +++ b/v2/troubleshooting.md @@ -59,9 +59,9 @@ Your AWS environment has not been bootstrapped, and so does not have an Amazon S cdk bootstrap aws://ACCOUNT-NUMBER/REGION ``` -To avoid generating unexpected AWS charges, the AWS CDK does not automatically boostrap any environment\. You must bootstrap each environment into which you will deploy explicitly\. +To avoid generating unexpected AWS charges, the AWS CDK does not automatically bootstrap any environment\. You must bootstrap each environment into which you will deploy explicitly\. -By default, the boostrap resources are created in the region\(s\) used by stacks in the current AWS CDK application, or the region specified in your local AWS profile \(set by `aws configure`\), using that profile's account\. You can specify a different account and region on the command line as follows\. \(You must specify the account and region if you are not in an app's directory\.\) +By default, the bootstrap resources are created in the region\(s\) used by stacks in the current AWS CDK application, or the region specified in your local AWS profile \(set by `aws configure`\), using that profile's account\. You can specify a different account and region on the command line as follows\. \(You must specify the account and region if you are not in an app's directory\.\) ``` cdk bootstrap aws://ACCOUNT-NUMBER/REGION @@ -72,7 +72,7 @@ For more information, see [Bootstrapping](bootstrapping.md) \([back to list](#troubleshooting_top)\) **When deploying my AWS CDK stack, I receive a `forbidden: null` message** -You are deploying a stack that requires boostrap resources, but are using an IAM role or account that lacks permission to write to it\. \(The staging bucket is used when deploying stacks that contain assets or that synthesize an AWS CloudFormation template larger than 50K\.\) Use an account or role that has permission to perform the action `s3:*` against the bucket mentioned in the error message\. +You are deploying a stack that requires bootstrap resources, but are using an IAM role or account that lacks permission to write to it\. \(The staging bucket is used when deploying stacks that contain assets or that synthesize an AWS CloudFormation template larger than 50K\.\) Use an account or role that has permission to perform the action `s3:*` against the bucket mentioned in the error message\. \([back to list](#troubleshooting_top)\) From 58e9a99f24836d7462e58a27e5c10e2b89c802d8 Mon Sep 17 00:00:00 2001 From: Jerome Covington Date: Wed, 21 Sep 2022 15:50:15 -0400 Subject: [PATCH 606/655] Use a single widgetIntegration instance (#397) In the cdk v1 serverless examples, it seems to me that the separate instances of the lambda integration are not really necessary. Handling each request method is done via logic in the handler, which is identical for all integrations. --- v1/serverless_example.md | 77 +++++++++++----------------------------- 1 file changed, 21 insertions(+), 56 deletions(-) diff --git a/v1/serverless_example.md b/v1/serverless_example.md index 553a686f..9993fa20 100644 --- a/v1/serverless_example.md +++ b/v1/serverless_example.md @@ -769,18 +769,11 @@ File: `lib/widget_service.ts` ``` const widget = api.root.addResource("{id}"); - // Add new widget to bucket with: POST /{id} - const postWidgetIntegration = new apigateway.LambdaIntegration(handler); + const widgetIntegration = new apigateway.LambdaIntegration(handler); - // Get a specific widget from bucket with: GET /{id} - const getWidgetIntegration = new apigateway.LambdaIntegration(handler); - - // Remove a specific widget from the bucket with: DELETE /{id} - const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); - - widget.addMethod("POST", postWidgetIntegration); // POST /{id} - widget.addMethod("GET", getWidgetIntegration); // GET /{id} - widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} + widget.addMethod("POST", widgetIntegration); // POST /{id} + widget.addMethod("GET", widgetIntegration); // GET /{id} + widget.addMethod("DELETE", widgetIntegration); // DELETE /{id} ``` ------ @@ -791,18 +784,11 @@ File: `lib/widget_service.js` ``` const widget = api.root.addResource("{id}"); - // Add new widget to bucket with: POST /{id} - const postWidgetIntegration = new apigateway.LambdaIntegration(handler); - - // Get a specific widget from bucket with: GET /{id} - const getWidgetIntegration = new apigateway.LambdaIntegration(handler); + const widgetIntegration = new apigateway.LambdaIntegration(handler); - // Remove a specific widget from the bucket with: DELETE /{id} - const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); - - widget.addMethod("POST", postWidgetIntegration); // POST /{id} - widget.addMethod("GET", getWidgetIntegration); // GET /{id} - widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} + widget.addMethod("POST", widgetIntegration); // POST /{id} + widget.addMethod("GET", widgetIntegration); // GET /{id} + widget.addMethod("DELETE", widgetIntegration); // DELETE /{id} ``` ------ @@ -813,18 +799,11 @@ File: `my_widget_service/widget_service.py` ``` widget = api.root.add_resource("{id}") - # Add new widget to bucket with: POST /{id} - post_widget_integration = apigateway.LambdaIntegration(handler) - - # Get a specific widget from bucket with: GET /{id} - get_widget_integration = apigateway.LambdaIntegration(handler) - - # Remove a specific widget from the bucket with: DELETE /{id} - delete_widget_integration = apigateway.LambdaIntegration(handler) + widget_integration = apigateway.LambdaIntegration(handler) - widget.add_method("POST", post_widget_integration); # POST /{id} - widget.add_method("GET", get_widget_integration); # GET /{id} - widget.add_method("DELETE", delete_widget_integration); # DELETE /{id} + widget.add_method("POST", widget_integration); # POST /{id} + widget.add_method("GET", widget_integration); # GET /{id} + widget.add_method("DELETE", widget_integration); # DELETE /{id} ``` ------ @@ -835,18 +814,11 @@ File: `src/src/main/java/com/myorg/WidgetService.java` ``` Resource widget = api.getRoot().addResource("{id}"); - // Add new widget to bucket with: POST /{id} - LambdaIntegration postWidgetIntegration = new LambdaIntegration(handler); + LambdaIntegration widgetIntegration = new LambdaIntegration(handler); - // Get a specific widget from bucket with: GET /{id} - LambdaIntegration getWidgetIntegration = new LambdaIntegration(handler); - - // Remove a specific widget from the bucket with: DELETE /{id} - LambdaIntegration deleteWidgetIntegration = new LambdaIntegration(handler); - - widget.addMethod("POST", postWidgetIntegration); // POST /{id} - widget.addMethod("GET", getWidgetIntegration); // GET /{id} - widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} + widget.addMethod("POST", widgetIntegration); // POST /{id} + widget.addMethod("GET", widgetIntegration); // GET /{id} + widget.addMethod("DELETE", widgetIntegration); // DELETE /{id} ``` ------ @@ -857,18 +829,11 @@ File: `src/MyWidgetService/WidgetService.cs` ``` var widget = api.Root.AddResource("{id}"); - // Add new widget to bucket with: POST /{id} - var postWidgetIntegration = new LambdaIntegration(handler); - - // Get a specific widget from bucket with: GET /{id} - var getWidgetIntegration = new LambdaIntegration(handler); + var widgetIntegration = new LambdaIntegration(handler); - // Remove a specific widget from the bucket with: DELETE /{id} - var deleteWidgetIntegration = new LambdaIntegration(handler); - - widget.AddMethod("POST", postWidgetIntegration); // POST /{id} - widget.AddMethod("GET", getWidgetIntegration); // GET /{id} - widget.AdMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} + widget.AddMethod("POST", widgetIntegration); // POST /{id} + widget.AddMethod("GET", widgetIntegration); // GET /{id} + widget.AdMethod("DELETE", widgetIntegration); // DELETE /{id} ``` ------ @@ -898,4 +863,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` \ No newline at end of file +``` From dcf6dd3e97b5f91d25c203da87a72d313746085f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Sep 2022 19:58:44 +0000 Subject: [PATCH 607/655] round-tripping a PR --- v1/serverless_example.md | 10 +++--- v2/serverless_example.md | 75 +++++++++++----------------------------- 2 files changed, 25 insertions(+), 60 deletions(-) diff --git a/v1/serverless_example.md b/v1/serverless_example.md index 9993fa20..0a536f1b 100644 --- a/v1/serverless_example.md +++ b/v1/serverless_example.md @@ -771,8 +771,8 @@ File: `lib/widget_service.ts` const widgetIntegration = new apigateway.LambdaIntegration(handler); - widget.addMethod("POST", widgetIntegration); // POST /{id} - widget.addMethod("GET", widgetIntegration); // GET /{id} + widget.addMethod("POST", widgetIntegration); // POST /{id} + widget.addMethod("GET", widgetIntegration); // GET /{id} widget.addMethod("DELETE", widgetIntegration); // DELETE /{id} ``` @@ -786,8 +786,8 @@ File: `lib/widget_service.js` const widgetIntegration = new apigateway.LambdaIntegration(handler); - widget.addMethod("POST", widgetIntegration); // POST /{id} - widget.addMethod("GET", widgetIntegration); // GET /{id} + widget.addMethod("POST", widgetIntegration); // POST /{id} + widget.addMethod("GET", widgetIntegration); // GET /{id} widget.addMethod("DELETE", widgetIntegration); // DELETE /{id} ``` @@ -863,4 +863,4 @@ To avoid unexpected AWS charges, destroy your AWS CDK stack after you're done wi ``` cdk destroy -``` +``` \ No newline at end of file diff --git a/v2/serverless_example.md b/v2/serverless_example.md index 2cc1247d..e8b7fdc7 100644 --- a/v2/serverless_example.md +++ b/v2/serverless_example.md @@ -708,18 +708,11 @@ File: `lib/widget_service.ts` ``` const widget = api.root.addResource("{id}"); - // Add new widget to bucket with: POST /{id} - const postWidgetIntegration = new apigateway.LambdaIntegration(handler); + const widgetIntegration = new apigateway.LambdaIntegration(handler); - // Get a specific widget from bucket with: GET /{id} - const getWidgetIntegration = new apigateway.LambdaIntegration(handler); - - // Remove a specific widget from the bucket with: DELETE /{id} - const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); - - widget.addMethod("POST", postWidgetIntegration); // POST /{id} - widget.addMethod("GET", getWidgetIntegration); // GET /{id} - widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} + widget.addMethod("POST", widgetIntegration); // POST /{id} + widget.addMethod("GET", widgetIntegration); // GET /{id} + widget.addMethod("DELETE", widgetIntegration); // DELETE /{id} ``` ------ @@ -730,18 +723,11 @@ File: `lib/widget_service.js` ``` const widget = api.root.addResource("{id}"); - // Add new widget to bucket with: POST /{id} - const postWidgetIntegration = new apigateway.LambdaIntegration(handler); - - // Get a specific widget from bucket with: GET /{id} - const getWidgetIntegration = new apigateway.LambdaIntegration(handler); + const widgetIntegration = new apigateway.LambdaIntegration(handler); - // Remove a specific widget from the bucket with: DELETE /{id} - const deleteWidgetIntegration = new apigateway.LambdaIntegration(handler); - - widget.addMethod("POST", postWidgetIntegration); // POST /{id} - widget.addMethod("GET", getWidgetIntegration); // GET /{id} - widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} + widget.addMethod("POST", widgetIntegration); // POST /{id} + widget.addMethod("GET", widgetIntegration); // GET /{id} + widget.addMethod("DELETE", widgetIntegration); // DELETE /{id} ``` ------ @@ -752,18 +738,11 @@ File: `my_widget_service/widget_service.py` ``` widget = api.root.add_resource("{id}") - # Add new widget to bucket with: POST /{id} - post_widget_integration = apigateway.LambdaIntegration(handler) - - # Get a specific widget from bucket with: GET /{id} - get_widget_integration = apigateway.LambdaIntegration(handler) + widget_integration = apigateway.LambdaIntegration(handler) - # Remove a specific widget from the bucket with: DELETE /{id} - delete_widget_integration = apigateway.LambdaIntegration(handler) - - widget.add_method("POST", post_widget_integration); # POST /{id} - widget.add_method("GET", get_widget_integration); # GET /{id} - widget.add_method("DELETE", delete_widget_integration); # DELETE /{id} + widget.add_method("POST", widget_integration); # POST /{id} + widget.add_method("GET", widget_integration); # GET /{id} + widget.add_method("DELETE", widget_integration); # DELETE /{id} ``` ------ @@ -774,18 +753,11 @@ File: `src/src/main/java/com/myorg/WidgetService.java` ``` Resource widget = api.getRoot().addResource("{id}"); - // Add new widget to bucket with: POST /{id} - LambdaIntegration postWidgetIntegration = new LambdaIntegration(handler); - - // Get a specific widget from bucket with: GET /{id} - LambdaIntegration getWidgetIntegration = new LambdaIntegration(handler); - - // Remove a specific widget from the bucket with: DELETE /{id} - LambdaIntegration deleteWidgetIntegration = new LambdaIntegration(handler); + LambdaIntegration widgetIntegration = new LambdaIntegration(handler); - widget.addMethod("POST", postWidgetIntegration); // POST /{id} - widget.addMethod("GET", getWidgetIntegration); // GET /{id} - widget.addMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} + widget.addMethod("POST", widgetIntegration); // POST /{id} + widget.addMethod("GET", widgetIntegration); // GET /{id} + widget.addMethod("DELETE", widgetIntegration); // DELETE /{id} ``` ------ @@ -796,18 +768,11 @@ File: `src/MyWidgetService/WidgetService.cs` ``` var widget = api.Root.AddResource("{id}"); - // Add new widget to bucket with: POST /{id} - var postWidgetIntegration = new LambdaIntegration(handler); - - // Get a specific widget from bucket with: GET /{id} - var getWidgetIntegration = new LambdaIntegration(handler); - - // Remove a specific widget from the bucket with: DELETE /{id} - var deleteWidgetIntegration = new LambdaIntegration(handler); + var widgetIntegration = new LambdaIntegration(handler); - widget.AddMethod("POST", postWidgetIntegration); // POST /{id} - widget.AddMethod("GET", getWidgetIntegration); // GET /{id} - widget.AdMethod("DELETE", deleteWidgetIntegration); // DELETE /{id} + widget.AddMethod("POST", widgetIntegration); // POST /{id} + widget.AddMethod("GET", widgetIntegration); // GET /{id} + widget.AdMethod("DELETE", widgetIntegration); // DELETE /{id} ``` ------ From b60a6ec9790f715b11ecb70e90336f9f4407fa16 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Sep 2022 20:08:10 +0000 Subject: [PATCH 608/655] make it clear that diff includes dependencies --- v1/cli.md | 4 ++-- v2/cli.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index 4d5af513..dae12068 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -30,7 +30,7 @@ All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(` | `cdk bootstrap` | Deploys the CDK Toolkit staging stack; see [Bootstrapping](bootstrapping.md) | | `cdk deploy` | Deploys the specified stack\(s\) | | `cdk destroy` | Destroys the specified stack\(s\) | -| `cdk diff` | Compares the specified stack with the deployed stack or a local CloudFormation template | +| `cdk diff` | Compares the specified stack and its dependencies with the deployed stack\(s\) or a local CloudFormation template | | `cdk metadata` | Displays metadata about the specified stack | | `cdk init` | Creates a new CDK project in the current directory from a specified template | | `cdk context` | Manages cached context values | @@ -512,7 +512,7 @@ The setting can also be configured in the `cdk.json` file\. ## Comparing stacks -The `cdk diff` command compares the current version of a stack defined in your app with the already\-deployed version, or with a saved AWS CloudFormation template, and displays a list of changes \. +The `cdk diff` command compares the current version of a stack \(and its dependencies\) defined in your app with the already\-deployed version\(s\), or with a saved AWS CloudFormation template, and displays a list of changes\. ``` Stack HelloCdkStack diff --git a/v2/cli.md b/v2/cli.md index 96f66905..43d15172 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -24,7 +24,7 @@ All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(` | `cdk bootstrap` | Deploys the CDK Toolkit staging stack; see [Bootstrapping](bootstrapping.md) | | `cdk deploy` | Deploys the specified stack\(s\) | | `cdk destroy` | Destroys the specified stack\(s\) | -| `cdk diff` | Compares the specified stack with the deployed stack or a local CloudFormation template | +| `cdk diff` | Compares the specified stack and its dependencies with the deployed stack\(s\) or a local CloudFormation template | | `cdk metadata` | Displays metadata about the specified stack | | `cdk init` | Creates a new CDK project in the current directory from a specified template | | `cdk context` | Manages cached context values | @@ -504,7 +504,7 @@ The setting can also be configured in the `cdk.json` file\. ## Comparing stacks -The `cdk diff` command compares the current version of a stack defined in your app with the already\-deployed version, or with a saved AWS CloudFormation template, and displays a list of changes \. +The `cdk diff` command compares the current version of a stack \(and its dependencies\) defined in your app with the already\-deployed version\(s\), or with a saved AWS CloudFormation template, and displays a list of changes\. ``` Stack HelloCdkStack From 0ca8755ec1516ed1164992252a090fae32ad65e7 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Wed, 21 Sep 2022 13:09:15 -0700 Subject: [PATCH 609/655] Minor clarification (#412) --- v2/home.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v2/home.md b/v2/home.md index 4eaaf7bd..cff5e023 100644 --- a/v2/home.md +++ b/v2/home.md @@ -3,7 +3,7 @@ Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. **Note** -The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v2\. CDK v1 entered maintenance on June 1, 2022\. +The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v2\. The older, CDK v1 entered maintenance on June 1, 2022\. The AWS CDK lets you build reliable, scalable, cost\-effective applications in the cloud with the considerable expressive power of a programming language\. This approach yields many benefits, including: + Build with high\-level constructs that automatically provide sensible, secure defaults for your AWS resources, defining more infrastructure with less code\. @@ -261,4 +261,4 @@ Amazon Web Services \(AWS\) is a collection of digital infrastructure services t AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. -To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file +To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. From c2f6bc2bcae84613ad27600a8d30a45f38c6593c Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Sep 2022 20:33:08 +0000 Subject: [PATCH 610/655] update v1 notices --- v1/home.md | 2 +- v2/home.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/v1/home.md b/v1/home.md index 33eebd68..080098c5 100644 --- a/v1/home.md +++ b/v1/home.md @@ -3,7 +3,7 @@ Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. **Important** -The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v1\. +The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for the older AWS CDK v1\. CDK v1 entered maintenance on June 1, 2022\. During the maintenance phase, CDK v1 will receive critical bug fixes and security patches only\. New features will be developed exclusively for CDK v2 during the v1 maintenance phase\. On June 1, 2023, support will end for AWS CDK v1\. For more details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. The AWS CDK lets you build reliable, scalable, cost\-effective applications in the cloud with the considerable expressive power of a programming language\. This approach yields many benefits, including: diff --git a/v2/home.md b/v2/home.md index cff5e023..fb04e031 100644 --- a/v2/home.md +++ b/v2/home.md @@ -3,7 +3,7 @@ Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. **Note** -The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v2\. The older, CDK v1 entered maintenance on June 1, 2022\. +The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v2\. The older CDK v1 entered maintenance on June 1, 2022\. Support for CDK v1 will end on June 1, 2023\. The AWS CDK lets you build reliable, scalable, cost\-effective applications in the cloud with the considerable expressive power of a programming language\. This approach yields many benefits, including: + Build with high\-level constructs that automatically provide sensible, secure defaults for your AWS resources, defining more infrastructure with less code\. @@ -261,4 +261,4 @@ Amazon Web Services \(AWS\) is a collection of digital infrastructure services t AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. -To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. +To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file From 42563bed7062bde6329cf8c531b131ab54df117a Mon Sep 17 00:00:00 2001 From: WillTwait Date: Wed, 21 Sep 2022 16:39:06 -0400 Subject: [PATCH 611/655] Added mission period (#413) --- v2/best-practices.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/best-practices.md b/v2/best-practices.md index ffa6e4e8..5c22517f 100644 --- a/v2/best-practices.md +++ b/v2/best-practices.md @@ -182,4 +182,4 @@ When you synthesize your application, the cloud assembly created in the `cdk.out ### Measure everything -Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_dynamodb.Table.html) class\. \ No newline at end of file +Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_dynamodb.Table.html) class\. From 099f01a55dc542509393e1dd0b99d6ac317377b3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Sep 2022 20:40:46 +0000 Subject: [PATCH 612/655] newline --- v2/best-practices.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/best-practices.md b/v2/best-practices.md index 5c22517f..ffa6e4e8 100644 --- a/v2/best-practices.md +++ b/v2/best-practices.md @@ -182,4 +182,4 @@ When you synthesize your application, the cloud assembly created in the `cdk.out ### Measure everything -Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_dynamodb.Table.html) class\. +Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_dynamodb.Table.html) class\. \ No newline at end of file From 696348cda71bfda7c4e7478a817c05382cb92651 Mon Sep 17 00:00:00 2001 From: n-vo Date: Wed, 21 Sep 2022 15:43:14 -0500 Subject: [PATCH 613/655] Highlight syntax for --no-previous-parameters (#418) --- v2/parameters.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/parameters.md b/v2/parameters.md index fc7af332..eb7151cd 100644 --- a/v2/parameters.md +++ b/v2/parameters.md @@ -205,4 +205,4 @@ If you are deploying multiple stacks, you can specify a different value of each cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=uploadbucket --parameters YourStack:uploadBucketName=upbucket ``` -By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the `--no-previous-parameters flag` to require all parameters to be specified\. \ No newline at end of file +By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. From 155a1a0a57b6baebe388d86248b931e546f2a4ea Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Sep 2022 20:46:26 +0000 Subject: [PATCH 614/655] fix formatting of cli flag --- v1/parameters.md | 2 +- v2/parameters.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/parameters.md b/v1/parameters.md index b6e3bd0e..19d7b76c 100644 --- a/v1/parameters.md +++ b/v1/parameters.md @@ -205,4 +205,4 @@ If you are deploying multiple stacks, you can specify a different value of each cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=uploadbucket --parameters YourStack:uploadBucketName=upbucket ``` -By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the `--no-previous-parameters flag` to require all parameters to be specified\. \ No newline at end of file +By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. \ No newline at end of file diff --git a/v2/parameters.md b/v2/parameters.md index eb7151cd..effda5b2 100644 --- a/v2/parameters.md +++ b/v2/parameters.md @@ -205,4 +205,4 @@ If you are deploying multiple stacks, you can specify a different value of each cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=uploadbucket --parameters YourStack:uploadBucketName=upbucket ``` -By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. +By default, the AWS CDK retains values of parameters from previous deployments and uses them in subsequent deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. \ No newline at end of file From 2d73623bf023114c08f08c05f17ea6ee194e0eac Mon Sep 17 00:00:00 2001 From: Haakon-Lotveit Date: Wed, 21 Sep 2022 22:49:29 +0200 Subject: [PATCH 615/655] Clarifies the Arrays.asList method (#421) The list returned by Arrays.asList is Arrays$ArrayList, not ArrayList. Since one is unmodifiable and one is not, this can trip up people. It should also be noted that Java 8's docs says Arrays.asList returns List, not ArrayList[1]. So to make sure that the docs always smell of freshly baked quality, I propose this modest change. [1] https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html --- v2/work-with-cdk-java.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/v2/work-with-cdk-java.md b/v2/work-with-cdk-java.md index 83f7a9ce..cc1c3c8e 100644 --- a/v2/work-with-cdk-java.md +++ b/v2/work-with-cdk-java.md @@ -107,10 +107,10 @@ To create maps with more than ten entries, use [https://docs.oracle.com/javase/9 If you are using Java 8, you could provide your own methods similar to to these\. -JavaScript arrays are represented as `List` or `List` in Java\. The method `java.util.Arrays.asList` is convenient for defining short `ArrayList`s\. +JavaScript arrays are represented as `List` or `List` in Java\. The method `java.util.Arrays.asList` is convenient for defining short `List`s\. ``` -String[] cmds = Arrays.asList("cd lambda", "npm install", "npm install typescript") +List cmds = Arrays.asList("cd lambda", "npm install", "npm install typescript") ``` ### Missing values @@ -144,4 +144,4 @@ cdk deploy "*Stack" # PipeStack, LambdaStack, etc. **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. From f3e6bb9030d3925b4f579147691f62c25bc5846f Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Wed, 21 Sep 2022 20:51:42 +0000 Subject: [PATCH 616/655] correct Java Arrays.asList info --- v1/work-with-cdk-java.md | 4 ++-- v2/work-with-cdk-java.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/v1/work-with-cdk-java.md b/v1/work-with-cdk-java.md index 0d20ba46..883e3647 100644 --- a/v1/work-with-cdk-java.md +++ b/v1/work-with-cdk-java.md @@ -118,10 +118,10 @@ To create maps with more than ten entries, use [https://docs.oracle.com/javase/9 If you are using Java 8, you could provide your own methods similar to to these\. -JavaScript arrays are represented as `List` or `List` in Java\. The method `java.util.Arrays.asList` is convenient for defining short `ArrayList`s\. +JavaScript arrays are represented as `List` or `List` in Java\. The method `java.util.Arrays.asList` is convenient for defining short `List`s\. ``` -String[] cmds = Arrays.asList("cd lambda", "npm install", "npm install typescript") +List cmds = Arrays.asList("cd lambda", "npm install", "npm install typescript") ``` ### Missing values diff --git a/v2/work-with-cdk-java.md b/v2/work-with-cdk-java.md index cc1c3c8e..bddb3650 100644 --- a/v2/work-with-cdk-java.md +++ b/v2/work-with-cdk-java.md @@ -144,4 +144,4 @@ cdk deploy "*Stack" # PipeStack, LambdaStack, etc. **Tip** You don't need to explicitly synthesize stacks before deploying them; `cdk deploy` performs this step for you to make sure your latest code gets deployed\. -For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. +For full documentation of the `cdk` command, see [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. \ No newline at end of file From 69a064888ac79fd4a012dd5dba5f95630bf51738 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20Fern=C3=A1ndez=20Anzardo?= Date: Fri, 23 Sep 2022 13:01:03 -0700 Subject: [PATCH 617/655] Fixing typo: "is_unreslovde" -> "is_unresolved" (#425) Fixing typo: "is_unreslovde" -> "is_unresolved" --- v2/apps.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v2/apps.md b/v2/apps.md index aa51fa32..596fd550 100644 --- a/v2/apps.md +++ b/v2/apps.md @@ -154,7 +154,7 @@ In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: + The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you must inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. -+ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isUnresolved(value)` \(Python: `is_unreslovde`\)\. See [Tokens](tokens.md) for details\. ++ The AWS CDK app might have to work with values that can't be known at the time it runs\. For example, if the AWS CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` \(Python: `bucket_name`\) attribute, that value is not the name of the deployed bucket\. Instead, you get a `Token` value\. To determine whether a particular value is available, call `cdk.isUnresolved(value)` \(Python: `is_unresolved`\)\. See [Tokens](tokens.md) for details\. ## Cloud assemblies @@ -225,4 +225,4 @@ The CLI can also interact directly with an already\-synthesized cloud assembly\. ``` cdk --app ./my-cloud-assembly ls -``` \ No newline at end of file +``` From c9c4a45e6f136693280357d2ce76461fe9a6f5e2 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 29 Sep 2022 18:38:32 +0000 Subject: [PATCH 618/655] link to canonical list of disableable feature flags --- v2/apps.md | 2 +- v2/migrating-v2.md | 27 ++------------------------- 2 files changed, 3 insertions(+), 26 deletions(-) diff --git a/v2/apps.md b/v2/apps.md index 596fd550..16d52e35 100644 --- a/v2/apps.md +++ b/v2/apps.md @@ -225,4 +225,4 @@ The CLI can also interact directly with an already\-synthesized cloud assembly\. ``` cdk --app ./my-cloud-assembly ls -``` +``` \ No newline at end of file diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 594ed983..3506ac1c 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -80,32 +80,9 @@ To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\ ### Updating feature flags -Remove all feature flags from `cdk.json`\. You can add one or more of the flags listed below, set to `false`, if your app relies on these specific AWS CDK v1 behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. +Remove all v1 feature flags from `cdk.json`, as these are all active by default in AWS CDK v2\. -`@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId` -If your application uses multiple Amazon API Gateway API keys and associates them to usage plans - -`@aws-cdk/aws-rds:lowercaseDbIdentifier` -If your application uses Amazon RDS database instance or database clusters, and explicitly specifies the identifier for these - -`@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021` - If your application uses the TLS\_V1\_2\_2019 security policy with Amazon CloudFront distributions\. CDK v2 uses security policy TLSv1\.2\_2021 by default\. - -`@aws-cdk/core:stackRelativeExports` -If your application uses multiple stacks and you refer to resources from one stack in another, this determines whether absolute or relative path is used to construct AWS CloudFormation exports - -The syntax for reverting these flags in `cdk.json` is shown here\. - -``` -{ - "context": { - "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": false, - "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": false, - "@aws-cdk/aws-rds:lowercaseDbIdentifier": false, - "@aws-cdk/core:stackRelativeExports": false - } -} -``` +A handful of v1 feature flags can be set to `false` in order to revert to specific AWS CDK v1 behaviors; see [Disabling features with flags](featureflags.md#featureflags_disabling) for a complete list\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. ### CDK Toolkit compatibility From 7cd0a502f82c62fcd5f92b34545ee8c5398bb14a Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 29 Sep 2022 18:41:31 +0000 Subject: [PATCH 619/655] add "only" to version of CDK projects that CDK Toolkit v2 creates --- v1/work-with-cdk-v2.md | 2 +- v2/migrating-v2.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/work-with-cdk-v2.md b/v1/work-with-cdk-v2.md index 03f02e00..f93d3762 100644 --- a/v1/work-with-cdk-v2.md +++ b/v1/work-with-cdk-v2.md @@ -11,7 +11,7 @@ To identify stacks deployed with AWS CDK v1, use the [awscdk\-v1\-stack\-finder] ## CDK Toolkit v2 compatibility -CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compatible with CDK v1 apps, so you can use a single globally\-installed version of CDK Toolkit with all your AWS CDK projects, whether they use v1 or v2\. An exception is that CDK Toolkit v2 creates CDK v2 projects\. +CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compatible with CDK v1 apps, so you can use a single globally\-installed version of CDK Toolkit with all your AWS CDK projects, whether they use v1 or v2\. An exception is that CDK Toolkit v2 only creates CDK v2 projects\. If you need to create both v1 and v2 CDK projects, **do not install CDK Toolkit v2 globally\.** \(Remove it if you already have it installed: `npm remove -g aws-cdk`\.\) To invoke the CDK Toolkit, use npx to run v1 or v2 of the CDK Toolkit as desired\. diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 3506ac1c..a184ddfb 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -86,7 +86,7 @@ A handful of v1 feature flags can be set to `false` in order to revert to specif ### CDK Toolkit compatibility -CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compatible with CDK v1 apps, so you can use a single globally\-installed version of CDK Toolkit with all your AWS CDK projects, whether they use v1 or v2\. An exception is that CDK Toolkit v2 creates CDK v2 projects\. +CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compatible with CDK v1 apps, so you can use a single globally\-installed version of CDK Toolkit with all your AWS CDK projects, whether they use v1 or v2\. An exception is that CDK Toolkit v2 only creates CDK v2 projects\. If you need to create both v1 and v2 CDK projects, **do not install CDK Toolkit v2 globally\.** \(Remove it if you already have it installed: `npm remove -g aws-cdk`\.\) To invoke the CDK Toolkit, use npx to run v1 or v2 of the CDK Toolkit as desired\. From 92e599f0a55863e62869c1ad2b4de7d57d1cab63 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 30 Sep 2022 21:13:32 +0000 Subject: [PATCH 620/655] add Go examples and related content --- v1/work-with-cdk-go.md | 15 +++++- v2/cdk_pipeline.md | 13 +++++ v2/getting_started.md | 43 ++++++++++++++-- v2/hello_world.md | 100 +++++++++++++++++++++++++++++++++++++- v2/home.md | 39 +++++++++++++++ v2/manage-dependencies.md | 6 +-- v2/migrating-v2.md | 12 +++++ v2/multiple_languages.md | 83 +++++++++++++++++++++++++++++-- v2/work-with-cdk-go.md | 2 +- 9 files changed, 297 insertions(+), 16 deletions(-) diff --git a/v1/work-with-cdk-go.md b/v1/work-with-cdk-go.md index c508148b..68efe058 100644 --- a/v1/work-with-cdk-go.md +++ b/v1/work-with-cdk-go.md @@ -39,12 +39,23 @@ The AWS CDK's core package, which you'll need in most AWS CDK apps, is imported ``` import ( - "github.com/aws/aws-cdk-go/awscdk/awss3" + "github.com/aws/aws-cdk-go/awscdk/awss3" 2.16.0 // ... ) ``` -Once you have imported the Construct Library modules \(Go packages\) for the services you want to use in your app, you access constructs in that module using, for example, `awss3.Bucket`\. +The contents of the Amazon S3 Go package are then available in the `awss3` namespace\. For example, to instantiate a bucket, you would call `awss3.NewBucket()`\. + +You may specify an alias when importing if you prefer more concise names: + +``` +import ( + s3 "github.com/aws/aws-cdk-go/awscdk/awss3" // use s3.NewBucket etc. + // ... +) +``` + +The code examples in this guide use the actual Go package names, so it is clear which Go packages \(AWS Construct Library modules\) are needed\. ## AWS CDK idioms in Go diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index b9871571..a5ceefb9 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -131,6 +131,19 @@ cdk init app --language csharp If you are using Visual Studio, open the solution file in the `src` directory\. +------ +#### [ Go ] + +``` +cdk init app --language go +``` + +After the app has been created, also enter the following command to instll the AWS Construct Library modules required by the app\. + +``` +go get +``` + ------ **Important** diff --git a/v2/getting_started.md b/v2/getting_started.md index 8345bc8c..ed6b3197 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -45,7 +45,7 @@ The actual package name of the main CDK package varies by language\. ------ #### [ Python ] -| Install | `python -m pip install aws-cdk-lib` | +| Install | python \-m pip install aws\-cdk\-lib | | --- |--- | | Import | `import aws_cdk as cdk` | | --- |--- | @@ -61,12 +61,29 @@ The actual package name of the main CDK package varies by language\. ------ #### [ C\# ] -| Install | `dotnet add package Amazon.CDK.Lib` | +| Install | dotnet add package Amazon\.CDK\.Lib | | --- |--- | | Import | `using Amazon.CDK;` | | --- |--- | ------ +#### [ Go ] + +| Install | go get github\.com/aws/aws\-cdk\-go/awscdk/v2 | +| --- |--- | +| Import | + +``` +import ( + "github.com/aws/aws-cdk-go/awscdk/v2" +) +``` | +| --- |--- | + +------ + +**Note** +If you created a CDK project using cdk init, you won't need to manually install `aws-cdk-lib`\. Constructs come in three fundamental flavors: + **AWS CloudFormation\-only** or L1 \(short for "layer 1"\)\. These constructs correspond directly to resource types defined by AWS CloudFormation\. In fact, these constructs are automatically generated from the AWS CloudFormation specification, so when a new AWS service is launched, the AWS CDK supports it a short time after AWS CloudFormation does\. @@ -147,6 +164,19 @@ var bucket = new Bucket(this, "MyBucket", new BucketProps { }}); ``` +------ +#### [ Go ] + +``` +bucket := awss3.NewBucket(scope, jsii.String("MyBucket"), &awss3.BucketProps { + BucketName: jsii.String("my-bucket"), + Versioned: jsii.Bool(true), + WebsiteRedirect: &awss3.RedirectTarget { + HostName: jsii.String("aws.amazon.com"), + }, +}) +``` + ------ **Note** @@ -208,7 +238,7 @@ Other prerequisites depend on the language in which you develop AWS CDK applicat ------ #### [ TypeScript ] -+ TypeScript 2\.7 or later \(`npm -g install typescript`\) ++ TypeScript 3\.8 or later \(`npm -g install typescript`\) ------ #### [ JavaScript ] @@ -233,10 +263,15 @@ Java IDE recommended \(we use Eclipse in some examples in this Developer Guide\) Visual Studio 2019 \(any edition\) or Visual Studio Code recommended\. +------ +#### [ Go ] + +Go 1\.1\.6 or later\. + ------ **Note** -Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. +Third\-party Language Deprecation: each language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. ## Install the AWS CDK diff --git a/v2/hello_world.md b/v2/hello_world.md index eb5c2516..496e757e 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -85,6 +85,19 @@ cdk init app --language csharp If you are using Visual Studio, open the solution file in the `src` directory\. +------ +#### [ Go ] + +``` +cdk init app --language go +``` + +After the app has been created, also enter the following command to instll the AWS Construct Library modules required by the app\. + +``` +go get +``` + ------ **Tip** @@ -134,9 +147,13 @@ dotnet build src Or press F6 in Visual Studio ------ +#### [ Go ] -**Note** -If your project was created with an older version of the AWS CDK Toolkit, it may not automatically build when you run it\. If changes you make in your code fail to be reflected in the synthesized template, try a manual build\. Make sure you are using the latest available version of the AWS CDK for this tutorial\. +``` +go build +``` + +------ ## List the stacks in the app @@ -262,6 +279,58 @@ namespace HelloCdk } ``` +------ +#### [ Go ] + +In `hello-cdk.go`: + +``` +package main + +import ( + "github.com/aws/aws-cdk-go/awscdk/v2" + "github.com/aws/aws-cdk-go/awscdk/v2/awss3" + "github.com/aws/constructs-go/constructs/v10" + "github.com/aws/jsii-runtime-go" +) + +type HelloCdkStackProps struct { + awscdk.StackProps +} + +func NewHelloCdkStack(scope constructs.Construct, id string, props *HelloCdkStackProps) awscdk.Stack { + var sprops awscdk.StackProps + if props != nil { + sprops = props.StackProps + } + stack := awscdk.NewStack(scope, &id, &sprops) + + awss3.NewBucket(stack, jsii.String("MyFirstBucket"), &awss3.BucketProps{ + Versioned: jsii.Bool(true), + }) + + return stack +} + +func main() { + defer jsii.Close() + + app := awscdk.NewApp(nil) + + NewHelloCdkStack(app, "HelloCdkStack", &HelloCdkStackProps{ + awscdk.StackProps{ + Env: env(), + }, + }) + + app.Synth(nil) +} + +func env() *awscdk.Environment { + return nil +} +``` + ------ `Bucket` is the first construct we've seen, so let's take a closer look\. Like all constructs, the `Bucket` class takes three parameters\. @@ -401,6 +470,33 @@ new Bucket(this, "MyFirstBucket", new BucketProps }); ``` +------ +#### [ Go ] + +Update `hello-cdk.go`\. + +``` + awss3.NewBucket(stack, jsii.String("MyFirstBucket"), &awss3.BucketProps{ + Versioned: jsii.Bool(true), + RemovalPolicy: awscdk.RemovalPolicy_DESTROY, + AutoDeleteObjects: jsii.Bool(true), + }) +``` + +------ +#### [ C\# ] + +Update `src/HelloCdk/HelloCdkStack.cs`\. + +``` +new Bucket(this, "MyFirstBucket", new BucketProps +{ + Versioned = true, + RemovalPolicy = RemovalPolicy.DESTROY, + AutoDeleteObjects = true +}); +``` + ------ Here, we haven't written any code that, in itself, changes our Amazon S3 bucket\. Instead, our code defines the desired state of the bucket\. The AWS CDK synthesizes that state to a new AWS CloudFormation template and deploys a changeset that makes only the changes necessary to reach that state\. diff --git a/v2/home.md b/v2/home.md index fb04e031..8f0f71fc 100644 --- a/v2/home.md +++ b/v2/home.md @@ -174,6 +174,45 @@ public class MyEcsConstructStack : Stack } ``` +------ +#### [ Go ] + +``` +func NewMyEcsConstructStack(scope constructs.Construct, id string, props *MyEcsConstructStackProps) awscdk.Stack { + + var sprops awscdk.StackProps + + if props != nil { + sprops = props.StackProps + } + + stack := awscdk.NewStack(scope, &id, &sprops) + + vpc := awsec2.NewVpc(stack, jsii.String("MyVpc"), &awsec2.VpcProps{ + MaxAzs: jsii.Number(3), // Default is all AZs in region + }) + + cluster := awsecs.NewCluster(stack, jsii.String("MyCluster"), &awsecs.ClusterProps{ + Vpc: vpc, + }) + + awsecspatterns.NewApplicationLoadBalancedFargateService(stack, jsii.String("MyFargateService"), + &awsecspatterns.ApplicationLoadBalancedFargateServiceProps{ + Cluster: cluster, // required + Cpu: jsii.Number(512), // default is 256 + DesiredCount: jsii.Number(5), // default is 1 + MemoryLimitMiB: jsii.Number(2048), // Default is 512 + TaskImageOptions: &awsecspatterns.ApplicationLoadBalancedTaskImageOptions{ + Image: awsecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample"), nil), + }, + PublicLoadBalancer: jsii.Bool(true), // Default is false + }) + + return stack + +} +``` + ------ This class produces an AWS CloudFormation [template of more than 500 lines](https://github.com/awsdocs/aws-cdk-guide/blob/main/doc_source/my_ecs_construct-stack.yaml); deploying the AWS CDK app produces more than 50 resources of the following types\. diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index 4f50782a..95c50782 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -298,8 +298,6 @@ require ( ) ``` -Package names \(modules, in Go parlance\) are specified by URL with the version number appended\. Go's module system does not support version ranges, so all dependencies must be pinned to a specfic version\. +Package names \(modules, in Go parlance\) are specified by URL with the required version number appended\. Go's module system does not support version ranges\. -Go automatically downloads dependencies whenever you build\. The CDK does this for you automatically whenever you run your app, so there is no need to do it manually\. - -You may use the go get command to install a module and update `go.mod`\. To see a list of available updates for your dependencies, issue go list \-m \-u all\. \ No newline at end of file +Issue the go get command to install all modules and update `go.mod`\. To see a list of available updates for your dependencies, issue go list \-m \-u all\. \ No newline at end of file diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index a184ddfb..44326741 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -70,6 +70,13 @@ mvn package dotnet restore ``` +------ +#### [ Go ] + +``` +go get +``` + ------ After updating your dependencies, issue `npm update -g aws-cdk` to update the CDK Toolkit to the release version\. @@ -292,6 +299,11 @@ using Amazon.CDK.AWS.S3; // for stable constructs like Bucket using Amazon.CDK.Codestar.Alpha; // for experimental constructs ``` +------ +#### [ Go ] + +Issue go get to update your dependencies to the latest version and update your project's `.mod` file\. + ------ ## Testing your migrated app before deploying diff --git a/v2/multiple_languages.md b/v2/multiple_languages.md index 3da9f293..83950647 100644 --- a/v2/multiple_languages.md +++ b/v2/multiple_languages.md @@ -8,6 +8,7 @@ For more details on working with the AWS CDK in its supported programming langua + [Working with the AWS CDK in Python](work-with-cdk-python.md) + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) ++ [Working with the AWS CDK in Go](work-with-cdk-go.md) ## Importing a module @@ -133,11 +134,34 @@ var bucket = new s3.Bucket(...); var bucket = new Amazon.CDK.AWS.S3.Bucket(...) ``` +------ +#### [ Go ] + +Each AWS Construct Library module is provided as a Go package\. + +``` +import ( + "github.com/aws/aws-cdk-go/awscdk/v2" // CDK core package + "github.com/aws/aws-cdk-go/awscdk/v2/awss3" // AWS S3 construct library module +) + +// now instantiate a bucket +bucket := awss3.NewBucket(...) + +// use alias cdk for brevity/clarity +import ( + cdk "github.com/aws/aws-cdk-go/awscdk/v2" // CDK core package + s3 "github.com/aws/aws-cdk-go/awscdk/v2/awss3" // AWS S3 construct library module +) + +bucket := s3.NewBucket(...) +``` + ------ ## Instantiating a construct -AWS CDK construct classes have the same name in all supported languages\. Most languages use the `new` keyword to instantiate a class \(Python is the only one that doesn't\)\. Also, in most languages, the keyword `this` refers to the current instance\. Python, again, is the exception \(it uses `self` by convention\)\. You should pass a reference to the current instance as the `scope` parameter to every construct you create\. +AWS CDK construct classes have the same name in all supported languages\. Most languages use the `new` keyword to instantiate a class \(Python and Go do not\)\. Also, in most languages, the keyword `this` refers to the current instance\. \(Python uses `self` by convention\.\) You should pass a reference to the current instance as the `scope` parameter to every construct you create\. The third argument to a AWS CDK construct is `props`, an object containing attributes needed to build the construct\. This argument may be optional, but when it is required, the supported languages handle it in idiomatic ways\. The names of the attributes are also adapted to the language's standard naming patterns\. @@ -220,7 +244,7 @@ It is convenient to use the `var` keyword when instantiating a construct, so you // Instantiate default Bucket var bucket = Bucket(self, "MyBucket"); -// Instantiate Bucket with BucketName and versioned properties +// Instantiate Bucket with BucketName and Versioned properties var bucket = Bucket(self, "MyBucket", new BucketProps { BucketName = "my-bucket", Versioned = true}); @@ -232,6 +256,30 @@ var bucket = Bucket(self, "MyBucket", new BucketProps { }}); ``` +------ +#### [ Go ] + +To create a construct in Go, call the function `NewXxxxxx` where `Xxxxxxx` is the name of the construct\. The constructs' properties are defined as a struct\. + +In Go, all construct parameters are pointers, including values like numbers, Booleans, and strings\. Use the convenience functions like `jsii.String` to create these pointers\. + +``` + // Instantiate default Bucket + bucket := awss3.NewBucket(stack, jsii.String("MyBucket"), nil) + + // Instantiate Bucket with BucketName and Versioned properties + bucket1 := awss3.NewBucket(stack, jsii.String("MyBucket"), &awss3.BucketProps{ + BucketName: jsii.String("my-bucket"), + Versioned: jsii.Bool(true), + }) + + // Instantiate Bucket with WebsiteRedirect, which has its own sub-properties + bucket2 := awss3.NewBucket(stack, jsii.String("MyBucket"), &awss3.BucketProps{ + WebsiteRedirect: &awss3.RedirectTarget{ + HostName: jsii.String("aws.amazon.com"), + }}) +``` + ------ ## Accessing members @@ -276,16 +324,31 @@ Names are `PascalCase`\. bucket.BucketArn ``` +------ +#### [ Go ] + +Names are `PascalCase`\. + +``` +bucket.BucketArn +``` + ------ ## Enum constants -Enum constants are scoped to a class, and have uppercase names with underscores in all languages \(sometimes referred to as `SCREAMING_SNAKE_CASE`\)\. Since class names also use the same casing in all supported languages, qualified enum names are also the same\. +Enum constants are scoped to a class, and have uppercase names with underscores in all languages \(sometimes referred to as `SCREAMING_SNAKE_CASE`\)\. Since class names also use the same casing in all supported languages except Go, qualified enum names are also the same in these languages\. ``` s3.BucketEncryption.KMS_MANAGED ``` +In Go, enum constants are attributes of the module namespace and are written as follows\. + +``` +awss3.BucketEncryption_KMS_MANAGED +``` + ## Object interfaces The AWS CDK uses TypeScript object interfaces to indicate that a class implements an expected set of methods and properties\. You can recognize an object interface because its name starts with `I`\. A concrete class indicates the interface\(s\) it implements using the `implements` keyword\. @@ -352,4 +415,18 @@ public class MyAspect : IAspect } ``` +------ +#### [ Go ] + +Go structs do not need to explicitly declare which interfaces they implement\. The Go compiler determines implementation based on the methods and properties available on the structure\. For example, in the following code, `MyAspect` implements the `IAspect` interface because it provides a `Visit` method that takes a construct\. + +``` +type MyAspect struct { +} + +func (a MyAspect) Visit(node constructs.IConstruct) { + fmt.Println("Visited", *node.Node().Path()) +} +``` + ------ \ No newline at end of file diff --git a/v2/work-with-cdk-go.md b/v2/work-with-cdk-go.md index 1545e80e..c5780661 100644 --- a/v2/work-with-cdk-go.md +++ b/v2/work-with-cdk-go.md @@ -27,7 +27,7 @@ cdk init app --language go `cdk init` uses the name of the project folder to name various elements of the project, including classes, subfolders, and files\. Hyphens in the folder name are converted to underscores\. However, the name should otherwise follow the form of a Go identifier; for example, it should not start with a number or contain spaces\. -The resulting project includes a reference to the AWS CDK Go module, `github.com/aws/aws-cdk-go/awscdk/v2`, in `go.mod`\. The CDK and its dependencies are automatically installed when you build your app\. +The resulting project includes a reference to the core AWS CDK Go module, `github.com/aws/aws-cdk-go/awscdk/v2`, in `go.mod`\. Issue go get to install this and other required modules\. ## Managing AWS Construct Library modules From cf81771dfb7f4edb0561fe00a8403c3578f864d6 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 4 Oct 2022 20:43:59 +0000 Subject: [PATCH 621/655] update Go instructions and some versions --- v2/getting_started.md | 7 ++++--- v2/hello_world.md | 2 +- v2/home.md | 2 +- v2/multiple_languages.md | 2 +- v2/work-with-cdk-go.md | 10 +++++++++- 5 files changed, 16 insertions(+), 7 deletions(-) diff --git a/v2/getting_started.md b/v2/getting_started.md index ed6b3197..a91d5c5e 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -190,6 +190,7 @@ To help you use the AWS CDK in your favorite language, this Guide includes topic + [Working with the AWS CDK in Python](work-with-cdk-python.md) + [Working with the AWS CDK in Java](work-with-cdk-java.md) + [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) ++ [Working with the AWS CDK in Go](work-with-cdk-go.md) TypeScript was the first language supported by the AWS CDK, and much AWS CDK example code is written in TypeScript\. This Guide includes a topic specifically to show how to adapt TypeScript AWS CDK code for use with the other supported languages\. See [Translating TypeScript AWS CDK code to other languages](multiple_languages.md)\. @@ -247,7 +248,7 @@ No additional requirements ------ #### [ Python ] -+ Python 3\.6 or later including `pip` and `virtualenv` ++ Python 3\.7 or later including `pip` and `virtualenv` ------ #### [ Java ] @@ -259,14 +260,14 @@ Java IDE recommended \(we use Eclipse in some examples in this Developer Guide\) ------ #### [ C\# ] -\.NET Core 3\.1 or later\. +\.NET Core 3\.1 or later, or \.NET 6\.0 or later\. Visual Studio 2019 \(any edition\) or Visual Studio Code recommended\. ------ #### [ Go ] -Go 1\.1\.6 or later\. +Go 1\.1\.8 or later\. ------ diff --git a/v2/hello_world.md b/v2/hello_world.md index 496e757e..5445bf2b 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -303,7 +303,7 @@ func NewHelloCdkStack(scope constructs.Construct, id string, props *HelloCdkStac if props != nil { sprops = props.StackProps } - stack := awscdk.NewStack(scope, &id, &sprops) + stack := awscdk.NewStack(scope, &id, sprops) awss3.NewBucket(stack, jsii.String("MyFirstBucket"), &awss3.BucketProps{ Versioned: jsii.Bool(true), diff --git a/v2/home.md b/v2/home.md index 8f0f71fc..f870557f 100644 --- a/v2/home.md +++ b/v2/home.md @@ -186,7 +186,7 @@ func NewMyEcsConstructStack(scope constructs.Construct, id string, props *MyEcsC sprops = props.StackProps } - stack := awscdk.NewStack(scope, &id, &sprops) + stack := awscdk.NewStack(scope, &id, sprops) vpc := awsec2.NewVpc(stack, jsii.String("MyVpc"), &awsec2.VpcProps{ MaxAzs: jsii.Number(3), // Default is all AZs in region diff --git a/v2/multiple_languages.md b/v2/multiple_languages.md index 83950647..fbacf64d 100644 --- a/v2/multiple_languages.md +++ b/v2/multiple_languages.md @@ -148,7 +148,7 @@ import ( // now instantiate a bucket bucket := awss3.NewBucket(...) -// use alias cdk for brevity/clarity +// use aliases for brevity/clarity import ( cdk "github.com/aws/aws-cdk-go/awscdk/v2" // CDK core package s3 "github.com/aws/aws-cdk-go/awscdk/v2/awss3" // AWS S3 construct library module diff --git a/v2/work-with-cdk-go.md b/v2/work-with-cdk-go.md index c5780661..2c97e0f3 100644 --- a/v2/work-with-cdk-go.md +++ b/v2/work-with-cdk-go.md @@ -10,7 +10,7 @@ This topic explains the ins and outs of working with the AWS CDK in Go\. See the To work with the AWS CDK, you must have an AWS account and credentials and have installed Node\.js and the AWS CDK Toolkit\. See [AWS CDK Prerequisites](work-with.md#work-with-prerequisites)\. -The Go bindings for the AWS CDK use the standard [Go toolchain](https://golang.org/dl/), v1\.16 or later\. You can use the editor of your choice\. +The Go bindings for the AWS CDK use the standard [Go toolchain](https://golang.org/dl/), v1\.18 or later\. You can use the editor of your choice\. **Note** Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. @@ -52,6 +52,14 @@ Once you have imported the Construct Library modules \(Go packages\) for the ser Field and method names use camel casing \(`likeThis`\) in TypeScript, the CDK's language of origin\. In Go, these follow Go conventions, so are Pascal\-cased \(`LikeThis`\)\. +### Cleaning up + +In your `main` method, use `defer jsii.Close()` to make sure your CDK app cleans up after itself\. + +### Field and method names + +Field and method names use camel casing \(`likeThis`\) in TypeScript, the CDK's language of origin\. In Go, these follow Go conventions, so are Pascal\-cased \(`LikeThis`\)\. + ### Missing values and pointer conversion In Go, missing values in AWS CDK objects such as property bundles are represented by `nil`\. Go doesn't have nullable types; the only type that can contain `nil` is a pointer\. To allow values to be optional, then, all CDK properties, arguments, and return values are pointers, even for primitive types\. This applies to required values as well as optional ones, so if a required value later becomes optional, no breaking change in type is needed\. From 1499a7b6edf927b294406a8a425e0bcb761cb8b0 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 13 Oct 2022 00:30:18 +0000 Subject: [PATCH 622/655] update shared content --- v1/index.md | 14 +++++++------- v2/index.md | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/v1/index.md b/v1/index.md index 548eb7cc..d25dbf17 100644 --- a/v1/index.md +++ b/v1/index.md @@ -4,13 +4,13 @@ *****Copyright © 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. +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 diff --git a/v2/index.md b/v2/index.md index 5dda212f..fc00a714 100644 --- a/v2/index.md +++ b/v2/index.md @@ -4,13 +4,13 @@ *****Copyright © 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. +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 From a68e5cd4a063af345de7b0dda7a70f141d84ce92 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 13 Oct 2022 00:30:26 +0000 Subject: [PATCH 623/655] fix Python code example --- v1/getting_started.md | 2 +- v2/getting_started.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/getting_started.md b/v1/getting_started.md index d504d7aa..7480dc60 100644 --- a/v1/getting_started.md +++ b/v1/getting_started.md @@ -69,7 +69,7 @@ const bucket = new s3.Bucket(this, 'MyBucket', { #### [ Python ] ``` -bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=True, +bucket = s3.Bucket("MyBucket", bucket_name="my-bucket", versioned=True, website_redirect=s3.RedirectTarget(host_name="aws.amazon.com")) ``` diff --git a/v2/getting_started.md b/v2/getting_started.md index a91d5c5e..6c7d1bcb 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -136,7 +136,7 @@ const bucket = new s3.Bucket(this, 'MyBucket', { #### [ Python ] ``` -bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=True, +bucket = s3.Bucket("MyBucket", bucket_name="my-bucket", versioned=True, website_redirect=s3.RedirectTarget(host_name="aws.amazon.com")) ``` From 557302f8cca64bdf3da0dccefe60ca2b707873b8 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 13 Oct 2022 00:37:12 +0000 Subject: [PATCH 624/655] remove duplicate feature flag entry --- v2/featureflags.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/v2/featureflags.md b/v2/featureflags.md index 49ae72eb..bc981d68 100644 --- a/v2/featureflags.md +++ b/v2/featureflags.md @@ -43,9 +43,6 @@ The AWS CDK fails at synthesis time if the `SNAPSHOT` removal policy is not supp `@aws-cdk/aws-ecs:arnFormatIncludesClusterName` Use the new ARN format when importing an Amazon EC2 or Fargate cluster\. -`@aws-cdk/aws-ecs:arnFormatIncludesClusterName` -Use the new ARN format when importing an Amazon EC2 or Fargate cluster\. - ## Disabling features with flags In CDK v2, a few feature flags are supported to revert certain behaviors to their v1 defaults\. The flags listed below, set to `false`, revert to specific AWS CDK v1 behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. From 367e90b17aa7cbfb916fda14e1532875934efe28 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 14 Oct 2022 22:42:02 +0000 Subject: [PATCH 625/655] add missing word --- v1/getting_started.md | 2 +- v2/getting_started.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v1/getting_started.md b/v1/getting_started.md index 7480dc60..a6839166 100644 --- a/v1/getting_started.md +++ b/v1/getting_started.md @@ -147,7 +147,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials **Note** Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. -The AWS CDK natively AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, first create a profile using aws configure sso\. Then log in using aws sso login\. Finally, specify this profile when issuing cdk commands using the \-\-profile option or the `AWS_PROFILE` environment variable\. +The AWS CDK natively supports AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, first create a profile using aws configure sso\. Then log in using aws sso login\. Finally, specify this profile when issuing cdk commands using the \-\-profile option or the `AWS_PROFILE` environment variable\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. diff --git a/v2/getting_started.md b/v2/getting_started.md index 6c7d1bcb..e577fd90 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -228,7 +228,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials **Note** Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. -The AWS CDK natively AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, first create a profile using aws configure sso\. Then log in using aws sso login\. Finally, specify this profile when issuing cdk commands using the \-\-profile option or the `AWS_PROFILE` environment variable\. +The AWS CDK natively supports AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, first create a profile using aws configure sso\. Then log in using aws sso login\. Finally, specify this profile when issuing cdk commands using the \-\-profile option or the `AWS_PROFILE` environment variable\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. From 28cd4f76f32b50defb9072bd8d3e9dc5c4d8e185 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 18 Oct 2022 15:58:11 +0000 Subject: [PATCH 626/655] correct typo --- v2/featureflags.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/featureflags.md b/v2/featureflags.md index bc981d68..654c51dc 100644 --- a/v2/featureflags.md +++ b/v2/featureflags.md @@ -28,7 +28,7 @@ Causes [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.InstanceReq `@aws-cdk/aws-iam:minimizePolicies` Minimize the creation of IAM policies when possible\. -`@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption` +`@aws-cdk/aws-sns-subscriptions:restrictSqsDecryption` In an Amazon SQS queue subscribed to an Amazon SNS topic, restrict decryption permissions to just the topic instead of all of SNS\. `@aws-cdk/aws-s3:createDefaultLoggingPolicy` From 21b7cc68107a6ddfbc31cd57a76d2ea982953865 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 18 Oct 2022 15:58:21 +0000 Subject: [PATCH 627/655] fix GitHub links --- v2/home.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v2/home.md b/v2/home.md index f870557f..952580d8 100644 --- a/v2/home.md +++ b/v2/home.md @@ -276,7 +276,7 @@ In addition to this guide, the following other resources are available to AWS CD + [Issues](https://github.com/awslabs/aws-cdk/issues) + [Examples](https://github.com/aws-samples/aws-cdk-examples) + [Documentation Source](https://github.com/awsdocs/aws-cdk-guide) - + [License](https://github.com/awslabs/aws-cdk/blob/master/LICENSE) + + [License](https://github.com/awslabs/aws-cdk/blob/main/LICENSE) + [Releases](https://github.com/awslabs/aws-cdk/releases) + [AWS CDK OpenPGP key](pgp-keys.md#cdk_pgp_key) + [jsii OpenPGP key](pgp-keys.md#jsii_pgp_key) @@ -292,7 +292,7 @@ These tools can work with the AWS CDK to simplify serverless application develop ## Contributing to the AWS CDK -Because the AWS CDK is open source, the team encourages you to contribute to make it an even better tool\. For details, see [Contributing](https://github.com/awslabs/aws-cdk/blob/master/CONTRIBUTING.md)\. +Because the AWS CDK is open source, the team encourages you to contribute to make it an even better tool\. For details, see [Contributing](https://github.com/awslabs/aws-cdk/blob/main/CONTRIBUTING.md)\. ## About Amazon Web Services From 2646ea9ac0b4f36737ec35ae287e7ab56c0193ad Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 20 Oct 2022 04:44:37 +0000 Subject: [PATCH 628/655] edits for reading score --- v1/testing.md | 2 +- v2/apps.md | 20 +-- v2/aspects.md | 10 +- v2/assets.md | 30 ++--- v2/best-practices.md | 125 ++++++++++--------- v2/bootstrapping.md | 96 +++++++++------ v2/cdk_pipeline.md | 79 +++++++----- v2/cfn_layer.md | 28 +++-- v2/cli.md | 142 +++++++++++----------- v2/constructs.md | 63 ++++++---- v2/context.md | 32 ++--- v2/environments.md | 20 +-- v2/featureflags.md | 20 +-- v2/get_context_var.md | 2 +- v2/get_secrets_manager_value.md | 6 +- v2/get_ssm_value.md | 8 +- v2/getting_started.md | 56 +++++---- v2/hello_world.md | 71 +++++------ v2/home.md | 8 +- v2/how_to_set_cw_alarm.md | 4 +- v2/identifiers.md | 20 +-- v2/manage-dependencies.md | 50 ++++---- v2/migrating-v2.md | 95 +++++++++------ v2/multiple_languages.md | 18 +-- v2/parameters.md | 24 ++-- v2/permissions.md | 36 ++++-- v2/reference.md | 16 +-- v2/resources.md | 61 ++++++---- v2/serverless_example.md | 14 +-- v2/stack_how_to_create_multiple_stacks.md | 25 ++-- v2/stacks.md | 28 +++-- v2/tagging.md | 24 ++-- v2/testing.md | 48 ++++---- v2/tokens.md | 12 +- v2/troubleshooting.md | 34 +++--- v2/use_cfn_public_registry.md | 30 ++--- v2/use_cfn_template.md | 32 ++--- v2/vscode.md | 2 +- v2/work-with-cdk-csharp.md | 2 +- v2/work-with-cdk-go.md | 2 +- v2/work-with-cdk-java.md | 2 +- v2/work-with-cdk-javascript.md | 4 +- v2/work-with-cdk-python.md | 2 +- v2/work-with-cdk-typescript.md | 4 +- v2/work-with.md | 2 +- 45 files changed, 772 insertions(+), 637 deletions(-) diff --git a/v1/testing.md b/v1/testing.md index 269f0c7d..2f389906 100644 --- a/v1/testing.md +++ b/v1/testing.md @@ -4,7 +4,7 @@ With the AWS CDK, your infrastructure can be as testable as any other code you w There are two categories of tests you can write for AWS CDK apps\. + **Fine\-grained assertions** test specific aspects of the generated AWS CloudFormation template, such as "this resource has this property with this value\." These tests can detect regressions, and are also useful when you're developing new features using test\-driven development \(write a test first, then make it pass by writing a correct implementation\)\. Fine\-grained assertions are the tests you'll write the most of\. -+ **Snapshot tests** test the synthesized AWS CloudFormation template against a previously\-stored baseline template or "master\." Snapshot tests let you refactor freely, since you can be sure that the refactored code works exactly the same way as the original\. If the changes were intentional, you can accept a new baseline for future tests\. However, CDK upgrades can also cause synthesized templates to change, so you can't rely only on snapshots to make sure your implementation is correct\. ++ **Snapshot tests** test the synthesized AWS CloudFormation template against a previously\-stored baseline template\. Snapshot tests let you refactor freely, since you can be sure that the refactored code works exactly the same way as the original\. If the changes were intentional, you can accept a new baseline for future tests\. However, CDK upgrades can also cause synthesized templates to change, so you can't rely only on snapshots to make sure your implementation is correct\. **Note** Complete versions of the TypeScript, Python, and Java apps used as examples in this topic are [available on GitHub](https://github.com/cdklabs/aws-cdk-testing-examples/)\. diff --git a/v2/apps.md b/v2/apps.md index 16d52e35..b7938985 100644 --- a/v2/apps.md +++ b/v2/apps.md @@ -74,7 +74,7 @@ public class MyFirstStack : Stack ------ -However, this code has only *declared* a stack\. For the stack to actually be synthesized into a AWS CloudFormation template and deployed, it needs to be instantiated\. And, like all CDK constructs, it must be instantiated in some context\. The `App` is that context\. +However, this code has only *declared* a stack\. For the stack to actually be synthesized into an AWS CloudFormation template and deployed, it must be instantiated\. And, like all CDK constructs, it must be instantiated in some context\. The `App` is that context\. ## The app construct @@ -141,16 +141,16 @@ An AWS CDK app goes through the following phases in its lifecycle\. Your code instantiates all of the defined constructs and then links them together\. In this stage, all of the constructs \(app, stacks, and their child constructs\) are instantiated and the constructor chain is executed\. Most of your app code is executed in this stage\. 2\. Preparation -All constructs that have implemented the `prepare` method participate in a final round of modifications, to set up their final state\. The preparation phase happens automatically\. As a user, you don't see any feedback from this phase\. It's rare to need to use the "prepare" hook, and generally not recommended\. You should be very careful when mutating the construct tree during this phase, because the order of operations could impact behavior\. +All constructs that have implemented the `prepare` method participate in a final round of modifications, to set up their final state\. The preparation phase happens automatically\. As a user, you don't see any feedback from this phase\. It's rare to need to use the "prepare" hook, and generally not recommended\. Be very careful when mutating the construct tree during this phase, because the order of operations could impact behavior\. 3\. Validation -All constructs that have implemented the `validate` method can validate themselves to ensure that they're in a state that will correctly deploy\. You will get notified of any validation failures that happen during this phase\. Generally, we recommend that you perform validation as soon as possible \(usually as soon as you get some input\) and throw exceptions as early as possible\. Performing validation early improves diagnosability as stack traces will be more accurate, and ensures that your code can continue to execute safely\. +All constructs that have implemented the `validate` method can validate themselves to ensure that they're in a state that will correctly deploy\. You will get notified of any validation failures that happen during this phase\. Generally, we recommend performing validation as soon as possible \(usually as soon as you get some input\) and throwing exceptions as early as possible\. Performing validation early improves diagnosability as stack traces will be more accurate, and ensures that your code can continue to execute safely\. 4\. Synthesis -This is the final stage of the execution of your AWS CDK app\. It's triggered by a call to `app.synth()`, and it traverses the construct tree and invokes the `synthesize` method on all constructs\. Constructs that implement `synthesize` can participate in synthesis and emit deployment artifacts to the resulting cloud assembly\. These artifacts include AWS CloudFormation templates, AWS Lambda application bundles, file and Docker image assets, and other deployment artifacts\. [Cloud assemblies](#apps_cloud_assembly) describes the output of this phase\. In most cases, you won't need to implement the `synthesize` method +This is the final stage of the execution of your AWS CDK app\. It's triggered by a call to `app.synth()`, and it traverses the construct tree and invokes the `synthesize` method on all constructs\. Constructs that implement `synthesize` can participate in synthesis and emit deployment artifacts to the resulting cloud assembly\. These artifacts include AWS CloudFormation templates, AWS Lambda application bundles, file and Docker image assets, and other deployment artifacts\. [Cloud assemblies](#apps_cloud_assembly) describes the output of this phase\. In most cases, you won't need to implement the `synthesize` method\. 5\. Deployment -In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go, and then starts an AWS CloudFormation deployment to deploy the application and create the resources\. +In this phase, the AWS CDK Toolkit takes the deployment artifacts cloud assembly produced by the synthesis phase and deploys it to an AWS environment\. It uploads assets to Amazon S3 and Amazon ECR, or wherever they need to go\. Then, it starts an AWS CloudFormation deployment to deploy the application and create the resources\. By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS CDK app has already finished and exited\. This has the following implications: + The AWS CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing\. To run code during the deployment phase, you must inject it into the AWS CloudFormation template as a [custom resource](cfn_layer.md#cfn_layer_custom)\. For more information about adding a custom resource to your app, see the [AWS CloudFormation module](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudformation-readme.html), or the [custom\-resource](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) example\. @@ -158,13 +158,13 @@ By the time the AWS CloudFormation deployment phase \(step 5\) starts, your AWS ## Cloud assemblies -The call to `app.synth()` is what tells the AWS CDK to synthesize a cloud assembly from an app\. Typically you don't interact directly with cloud assemblies\. They are files that include everything needed to deploy your app to a cloud environment\. For example, it includes an AWS CloudFormation template for each stack in your app, and a copy of any file assets or Docker images that you reference in your app\. +The call to `app.synth()` is what tells the AWS CDK to synthesize a cloud assembly from an app\. Typically you don't interact directly with cloud assemblies\. They are files that include everything needed to deploy your app to a cloud environment\. For example, it includes an AWS CloudFormation template for each stack in your app\. It also includes a copy of any file assets or Docker images that you reference in your app\. See the [cloud assembly specification](https://github.com/aws/aws-cdk/blob/master/design/cloud-assembly.md) for details on how cloud assemblies are formatted\. -To interact with the cloud assembly that your AWS CDK app creates, you typically use the AWS CDK Toolkit, a command\-line tool\. But any tool that can read the cloud assembly format can be used to deploy your app\. +To interact with the cloud assembly that your AWS CDK app creates, you typically use the AWS CDK Toolkit, a command line tool\. But any tool that can read the cloud assembly format can be used to deploy your app\. -The CDK Toolkit needs to know how to execute your AWS CDK app\. If you created the project from a template using the `cdk init` command, your app's `cdk.json` file includes an `app` key that specifies the necessary command for the language the app is written in\. If your language requires compilation, the command line performs this step before running the app, so you can't forget to do it\. +The CDK Toolkit needs to know how to execute your AWS CDK app\. If you created the project from a template using the `cdk init` command, your app's `cdk.json` file includes an `app` key\. This key specifies the necessary command for the language that the app is written in\. If your language requires compilation, the command line performs this step before running the app, so you can't forget to do it\. ------ #### [ TypeScript ] @@ -213,7 +213,7 @@ The CDK Toolkit needs to know how to execute your AWS CDK app\. If you created t ------ -If you did not create your project using the CDK Toolkit, or wish to override the command line given in `cdk.json`, you can use the \-\-app option when issuing the `cdk` command\. +If you didn't create your project using the CDK Toolkit, or if you want to override the command line given in `cdk.json`, you can use the \-\-app option when issuing the `cdk` command\. ``` cdk --app 'executable' cdk-command ... @@ -221,7 +221,7 @@ cdk --app 'executable' cdk-command ... The *executable* part of the command indicates the command that should be run to execute your CDK application\. Use quotation marks as shown, since such commands contain spaces\. The *cdk\-command* is a subcommand like synth or deploy that tells the CDK Toolkit what you want to do with your app\. Follow this with any additional options needed for that subcommand\. -The CLI can also interact directly with an already\-synthesized cloud assembly\. To do that, just pass the directory in which the cloud assembly is stored in \-\-app\. The following example lists the stacks defined in the cloud assembly stored under `./my-cloud-assembly`\. +The CLI can also interact directly with an already\-synthesized cloud assembly\. To do that, pass the directory in which the cloud assembly is stored in \-\-app\. The following example lists the stacks defined in the cloud assembly stored under `./my-cloud-assembly`\. ``` cdk --app ./my-cloud-assembly ls diff --git a/v2/aspects.md b/v2/aspects.md index 6b2860f2..5d2accfa 100644 --- a/v2/aspects.md +++ b/v2/aspects.md @@ -1,6 +1,6 @@ # Aspects -Aspects are a way to apply an operation to all constructs in a given scope\. The aspect could modify the constructs, such as by adding tags, or it could verify something about the state of the constructs, such as ensuring that all buckets are encrypted\. +Aspects are a way to apply an operation to all constructs in a given scope\. The aspect could modify the constructs, such as by adding tags\. Or it could verify something about the state of the constructs, such as making sure that all buckets are encrypted\. To apply an aspect to a construct and all constructs in the same scope, call [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Aspects.html#static-ofscope](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Aspects.html#static-ofscope)`.of(SCOPE).add()` with a new aspect, as shown in the following example\. @@ -58,12 +58,12 @@ interface IAspect { ------ #### [ JavaScript ] -JavaScript doesn't have interfaces as a language feature, so an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. +JavaScript doesn't have interfaces as a language feature\. Therefore, an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. ------ #### [ Python ] -Python doesn't have interfaces as a language feature, so an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. +Python doesn't have interfaces as a language feature\. Therefore, an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on\. ------ #### [ Java ] @@ -90,13 +90,13 @@ When you call `Aspects.of(SCOPE).add(...)`, the construct adds the aspect to an During the [prepare phase](apps.md#lifecycle), the AWS CDK calls the `visit` method of the object for the construct and each of its children in top\-down order\. -The `visit` method is free to change anything in the construct\. In strongly\-typed languages, cast the received construct to a more specific type before accessing construct\-specific properties or methods\. +The `visit` method is free to change anything in the construct\. In strongly typed languages, cast the received construct to a more specific type before accessing construct\-specific properties or methods\. Aspects don't propagate across `Stage` construct boundaries, because `Stages` are self\-contained and immutable after definition\. Apply aspects on the `Stage` construct itself \(or lower\) if you want them to visit constructs inside the `Stage`\. ## Example -The following example validates that all buckets created in the stack have versioning enabled\. The aspect adds an error annotation to the constructs that fail the validation, which results in the synth operation failing and prevents deploying the resulting cloud assembly\. +The following example validates that all buckets created in the stack have versioning enabled\. The aspect adds an error annotation to the constructs that fail the validation\. This results in the synth operation failing and prevents deploying the resulting cloud assembly\. ------ #### [ TypeScript ] diff --git a/v2/assets.md b/v2/assets.md index 53bda1cc..51635955 100644 --- a/v2/assets.md +++ b/v2/assets.md @@ -1,18 +1,18 @@ # Assets -Assets are local files, directories, or Docker images that can be bundled into AWS CDK libraries and apps; for example, a directory that contains the handler code for an AWS Lambda function\. Assets can represent any artifact that the app needs to operate\. +Assets are local files, directories, or Docker images that can be bundled into AWS CDK libraries and apps\. For example, an asset might be a directory that contains the handler code for an AWS Lambda function\. Assets can represent any artifact that the app needs to operate\. You add assets through APIs that are exposed by specific AWS constructs\. For example, when you define a [lambda\.Function](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html) construct, the [code](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html#code) property lets you pass an [asset](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Code.html#static-fromwbrassetpath-options) \(directory\)\. `Function` uses assets to bundle the contents of the directory and use it for the function's code\. Similarly, [ecs\.ContainerImage\.fromAsset](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ContainerImage.html#static-fromwbrassetdirectory-props) uses a Docker image built from a local directory when defining an Amazon ECS task definition\. ## Assets in detail -When you refer to an asset in your app, the [cloud assembly](apps.md#apps_cloud_assembly) synthesized from your application includes metadata information with instructions for the AWS CDK CLI on where to find the asset on the local disk, and what type of bundling to perform based on the type of asset, such as a directory to compress \(zip\) or a Docker image to build\. +When you refer to an asset in your app, the [cloud assembly](apps.md#apps_cloud_assembly) that's synthesized from your application includes metadata information with instructions for the AWS CDK CLI\. The instructions include where to find the asset on the local disk and what type of bundling to perform based on the asset type, such as a directory to compress \(zip\) or a Docker image to build\. -The AWS CDK generates a source hash for assets, which can be used at construction time to determine whether the contents of an asset have changed\. +The AWS CDK generates a source hash for assets\. This can be used at construction time to determine whether the contents of an asset have changed\. By default, the AWS CDK creates a copy of the asset in the cloud assembly directory, which defaults to `cdk.out`, under the source hash\. This way, the cloud assembly is self\-contained, so if it moved over to a different host for deployment, it can still be deployed\. See [Cloud assemblies](apps.md#apps_cloud_assembly) for details\. -When the AWS CDK deploys an app that references assets \(either directly by the app code or through a library\), the AWS CDK CLI first prepares and publishes the assets to an Amazon S3 bucket or Amazon ECR repository, which was created during bootstrapping\. Only then are the resources defined in the stack deployed\. +When the AWS CDK deploys an app that references assets \(either directly by the app code or through a library\), the AWS CDK CLI first prepares and publishes the assets to an Amazon S3 bucket or Amazon ECR repository\. \(The S3 bucket or repository is created during bootstrapping\.\) Only then are the resources defined in the stack deployed\. This section describes the low\-level APIs available in the framework\. @@ -20,7 +20,7 @@ This section describes the low\-level APIs available in the framework\. The AWS CDK supports the following types of assets: -Amazon S3 Assets +Amazon S3 assets These are local files and directories that the AWS CDK uploads to Amazon S3\. Docker Image @@ -130,13 +130,13 @@ var fileAsset = new Asset(this, "SampleSingleFileAsset", new AssetProps ------ -In most cases, you don't need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods that enable you to use assets\. For Lambda functions, the [fromAsset\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Code.html#static-fromwbrassetpath-options) static method enables you to specify a directory or a \.zip file in the local file system\. +In most cases, you don't need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods so that you can use assets\. For Lambda functions, the [fromAsset\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Code.html#static-fromwbrassetpath-options) static method enables you to specify a directory or a \.zip file in the local file system\. #### Lambda function example -A common use case is to create AWS Lambda functions with the handler code, which is the entry point for the function, as an Amazon S3 asset\. +A common use case is creating Lambda functions with the handler code as an Amazon S3 asset\. -The following example uses an Amazon S3 asset to define a Python handler in the local directory `handler` and creates a Lambda function with the local directory asset as the `code` property\. Below is the Python code for the handler\. +The following example uses an Amazon S3 asset to define a Python handler in the local directory `handler`\. It also creates a Lambda function with the local directory asset as the `code` property\. Following is the Python code for the handler\. ``` def lambda_handler(event, context): @@ -271,13 +271,13 @@ public class HelloAssetStack : Stack The `Function` method uses assets to bundle the contents of the directory and use it for the function's code\. **Tip** -Java `.jar` files are ZIP files with a different extension\. These will be uploaded as\-is to Amazon S3, but when they are deployed as a Lambda function, the files they contain will be extracted, which probably isn't what you want\. To avoid this, place the `.jar` file in a directory and specify that directory as the asset\. +Java `.jar` files are ZIP files with a different extension\. These are uploaded as\-is to Amazon S3, but when deployed as a Lambda function, the files they contain are extracted, which you might not want\. To avoid this, place the `.jar` file in a directory and specify that directory as the asset\. #### Deploy\-time attributes example Amazon S3 asset types also expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. -The following example uses deploy\-time attributes to pass the location of an image asset into a Lambda function as environment variables\. \(The kind of file doesn't matter; the PNG image used here is just an example\.\) +The following example uses deploy\-time attributes to pass the location of an image asset into a Lambda function as environment variables\. \(The kind of file doesn't matter; the PNG image used here is only an example\.\) ------ #### [ TypeScript ] @@ -416,7 +416,7 @@ new Function(this, "myLambdaFunction", new FunctionProps #### Permissions -If you use Amazon S3 assets directly through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets-readme.html) module, IAM roles, users, or groups, and need to read assets in runtime, grant those assets IAM permissions through the [asset\.grantRead](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets.Asset.html#grantwbrreadgrantee) method\. +If you use Amazon S3 assets directly through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets-readme.html) module, IAM roles, users, or groups, and you need to read assets in runtime, then grant those assets IAM permissions through the [asset\.grantRead](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets.Asset.html#grantwbrreadgrantee) method\. The following example grants an IAM group read permissions on a file asset\. @@ -515,7 +515,7 @@ asset.GrantRead(group); The AWS CDK supports bundling local Docker images as assets through the [aws\-ecr\-assets](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr_assets-readme.html) module\. -The following example defines a docker image that is built locally and pushed to Amazon ECR\. Images are built from a local Docker context directory \(with a Dockerfile\) and uploaded to Amazon ECR by the AWS CDK CLI or your app's CI/CD pipeline, and can be naturally referenced in your AWS CDK app\. +The following example defines a Docker image that is built locally and pushed to Amazon ECR\. Images are built from a local Docker context directory \(with a Dockerfile\) and uploaded to Amazon ECR by the AWS CDK CLI or your app's CI/CD pipeline\. The images can be naturally referenced in your AWS CDK app\. ------ #### [ TypeScript ] @@ -583,7 +583,7 @@ The `my-image` directory must include a Dockerfile\. The AWS CDK CLI builds a Do #### Amazon ECS task definition example -A common use case is to create an Amazon ECS [TaskDefinition](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.TaskDefinition.html) to run docker containers\. The following example specifies the location of a Docker image asset that the AWS CDK builds locally and pushes to Amazon ECR\. +A common use case is to create an Amazon ECS [TaskDefinition](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.TaskDefinition.html) to run Docker containers\. The following example specifies the location of a Docker image asset that the AWS CDK builds locally and pushes to Amazon ECR\. ------ #### [ TypeScript ] @@ -868,9 +868,9 @@ var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps #### Permissions -If you use a module that supports Docker image assets, such as [aws\-ecs](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs-readme.html), the AWS CDK manages permissions for you when you use assets directly or through [ContainerImage\.fromEcrRepository](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ContainerImage.html#static-fromwbrecrwbrrepositoryrepository-tag) \(Python: `from_ecr_repository`\)\. If you use Docker image assets directly, you need to ensure that the consuming principal has permissions to pull the image\. +If you use a module that supports Docker image assets, such as [aws\-ecs](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs-readme.html), the AWS CDK manages permissions for you when you use assets directly or through [ContainerImage\.fromEcrRepository](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ContainerImage.html#static-fromwbrecrwbrrepositoryrepository-tag) \(Python: `from_ecr_repository`\)\. If you use Docker image assets directly, make sure that the consuming principal has permissions to pull the image\. -In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr.Repository.html#grantwbrpullgrantee) method \(Python: `grant_pull`\. This modifies the IAM policy of the principal to enable it to pull images from this repository\. If the principal that is pulling the image is not in the same account or is an AWS service, such as AWS CodeBuild, that does not assume a role in your account, you must grant pull permissions on the resource policy and not on the principal's policy\. Use the [asset\.repository\.addToResourcePolicy](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr.Repository.html#addwbrtowbrresourcewbrpolicystatement) method \(Python: `add_to_resource_policy`\) to grant the appropriate principal permissions\. +In most cases, you should use [asset\.repository\.grantPull](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr.Repository.html#grantwbrpullgrantee) method \(Python: `grant_pull`\. This modifies the IAM policy of the principal to enable it to pull images from this repository\. If the principal that is pulling the image is not in the same account, or if it's an AWS service that doesn't assume a role in your account \(such as AWS CodeBuild\), you must grant pull permissions on the resource policy and not on the principal's policy\. Use the [asset\.repository\.addToResourcePolicy](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr.Repository.html#addwbrtowbrresourcewbrpolicystatement) method \(Python: `add_to_resource_policy`\) to grant the appropriate principal permissions\. ## AWS CloudFormation resource metadata diff --git a/v2/best-practices.md b/v2/best-practices.md index ffa6e4e8..249fbfc7 100644 --- a/v2/best-practices.md +++ b/v2/best-practices.md @@ -1,12 +1,21 @@ # Best practices for developing and deploying cloud infrastructure with the AWS CDK -The AWS CDK allows developers or administrators to define their cloud infrastructure using a supported programming language\. CDK applications should be organized into logical units, such as API, database, and monitoring resources, and optionally have a pipeline for automated deployments\. The logical units should be implemented as constructs including the infrastructure \(e\.g\. Amazon S3 buckets, Amazon RDS databases, Amazon VPC network\), runtime code \(e\.g\. AWS Lambda functions\), and configuration code\. Stacks define the deployment model of these logical units\. For a more detailed introduction to the concepts behind the CDK, see [Getting started with the AWS CDK](getting_started.md)\. +With the AWS CDK, developers or administrators can define their cloud infrastructure by using a supported programming language\. CDK applications should be organized into logical units, such as API, database, and monitoring resources, and optionally have a pipeline for automated deployments\. The logical units should be implemented as constructs including the following: ++ Infrastructure \(such as Amazon S3 buckets, Amazon RDS databases, or an Amazon VPC network\) ++ Runtime code \(such as AWS Lambda functions\) ++ Configuration code -The AWS CDK reflects careful consideration of the needs of our customers and internal teams and of the failure patterns that often arise during the deployment and ongoing maintenance of complex cloud applications\. We discovered that failures are often related to "out\-of\-band" changes to an application, such as configuration changes, that were not fully tested\. Therefore, we developed the AWS CDK around a model in which your entire application, not just business logic but also infrastructure and configuration, is defined in code\. That way, proposed changes can be carefully reviewed, comprehensively tested in environments resembling production to varying degrees, and fully rolled back if something goes wrong\. +Stacks define the deployment model of these logical units\. For a more detailed introduction to the concepts behind the CDK, see [Getting started with the AWS CDK](getting_started.md)\. + +The AWS CDK reflects careful consideration of the needs of our customers and internal teams and of the failure patterns that often arise during the deployment and ongoing maintenance of complex cloud applications\. We discovered that failures are often related to "out\-of\-band" changes to an application that aren't fully tested, such as configuration changes\. Therefore, we developed the AWS CDK around a model in which your entire application is defined in code, not only business logic but also infrastructure and configuration\. That way, proposed changes can be carefully reviewed, comprehensively tested in environments resembling production to varying degrees, and fully rolled back if something goes wrong\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/all-in-one.jpg) -At deployment time, the AWS CDK synthesizes a cloud assembly that contains not only AWS CloudFormation templates describing your infrastructure in all target environments, but file assets containing your runtime code and their supporting files\. With the CDK, every commit in your application's main version control branch can represent a complete, consistent, deployable version of your application\. Your application can then be deployed automatically whenever a change is made\. +At deployment time, the AWS CDK synthesizes a cloud assembly that contains the following: ++ AWS CloudFormation templates that describe your infrastructure in all target environments ++ File assets that contain your runtime code and their supporting files + +With the CDK, every commit in your application's main version control branch can represent a complete, consistent, deployable version of your application\. Your application can then be deployed automatically whenever a change is made\. The philosophy behind the AWS CDK leads to our recommended best practices, which we have divided into four broad categories\. + [Organization best practices](#best-practices-organization) @@ -15,171 +24,171 @@ The philosophy behind the AWS CDK leads to our recommended best practices, which + [Application best practices](#best-practices-apps) **Tip** -In addition to the guidance in this document, you should also consider [best practices for AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html) as well as for the individual AWS services you use, where they are obviously applicable to CDK\-defined infrastructure\. +Also consider [best practices for AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html) and the individual AWS services that you use, where applicable to CDK\-defined infrastructure\. ## Organization best practices -In the beginning stages of AWS CDK adoption, it's important to consider how to set up your organization for success\. It's a best practice to have a team of experts responsible for training and guiding the rest of the company as they adopt the CDK\. The size of this team may vary, from one or two people at a small company to a full\-fledged Cloud Center of Excellence \(CCoE\) at a larger company\. This team is responsible for setting standards and policies for how cloud infrastructure will be done at your company, as well as for training and mentoring developers\. +In the beginning stages of AWS CDK adoption, it's important to consider how to set up your organization for success\. It's a best practice to have a team of experts responsible for training and guiding the rest of the company as they adopt the CDK\. The size of this team might vary, from one or two people at a small company to a full\-fledged Cloud Center of Excellence \(CCoE\) at a larger company\. This team is responsible for setting standards and policies for cloud infrastructure at your company, and also for training and mentoring developers\. -The CCoE may provide guidance on what programming languages should be used for cloud infrastructure\. The details will vary from one organization to the next, but a good policy helps make sure developers can easily understand and maintain all cloud infrastructure throughout the company\. +The CCoE might provide guidance on what programming languages should be used for cloud infrastructure\. Details will vary from one organization to the next, but a good policy helps make sure that developers can understand and maintain the company's cloud infrastructure\. -The CCoE also creates a "landing zone" that defines your organizational units within AWS\. A landing zone is a pre\-configured, secure, scalable, multi\-account AWS environment based on best practice blueprints\. You can tie together the services that make up your landing zone with [AWS Control Tower](https://aws.amazon.com/controltower/), a high\-level service configures and manages your entire multi\-account system from a single user interface\. +The CCoE also creates a "landing zone" that defines your organizational units within AWS\. A landing zone is a pre\-configured, secure, scalable, multi\-account AWS environment based on best practice blueprints\. To tie together the services that make up your landing zone, you can use [AWS Control Tower](https://aws.amazon.com/controltower/), which configures and manages your entire multi\-account system from a single user interface\. -Development teams should be able use their own accounts for testing and have the ability to deploy new resources in these accounts as needed\. Individual developers can treat these resources as extensions of their own development workstation\. Using [CDK Pipelines](cdk_pipeline.md), the AWS CDK applications can then be deployed via a CI/CD account to testing, integration, and production environments \(each isolated in its own AWS region and/or account\) by merging the developers' code into your organization's canonical repository\. +Development teams should be able to use their own accounts for testing and deploy new resources in these accounts as needed\. Individual developers can treat these resources as extensions of their own development workstation\. Using [CDK Pipelines](cdk_pipeline.md), the AWS CDK applications can then be deployed via a CI/CD account to testing, integration, and production environments \(each isolated in its own AWS Region or account\)\. This is done by merging the developers' code into your organization's canonical repository\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/best-practice-deploy-to-multiple-accounts.png) ## Coding best practices -This section presents best practices for organizing your AWS CDK code\. The diagram below shows the relationship between a team and that team's code repositories, packages, applications, and construct libraries\. +This section presents best practices for organizing your AWS CDK code\. The following diagram shows the relationship between a team and that team's code repositories, packages, applications, and construct libraries\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/code-organization.jpg) ### Start simple and add complexity only when you need it -The guiding principle for most of our best practices is to keep things simple as possible—but no simpler\. Add complexity only when your requirements dictate a more complicated solution\. With the AWS CDK, you can always refactor your code as necessary to support new requirements, so it doesn't make sense to architect for all possible scenarios up front\. +The guiding principle for most of our best practices is to keep things simple as possible—but no simpler\. Add complexity only when your requirements dictate a more complicated solution\. With the AWS CDK, you can refactor your code as necessary to support new requirements\. You don't have to architect for all possible scenarios upfront\. -### Align with the AWS Well\-Architected framework +### Align with the AWS Well\-Architected Framework -The [AWS Well\-Architected](http://aws.amazon.com/architecture/well-architected/) framework defines a *component* as the code, configuration, and AWS resources that together deliver against a requirement\. A component is often the unit of technical ownership, and is decoupled from other components\. The term *workload* is used to identify a set of components that together deliver business value\. A workload is usually the level of detail that business and technology leaders communicate about\. +The [AWS Well\-Architected](http://aws.amazon.com/architecture/well-architected/) Framework defines a *component* as the code, configuration, and AWS resources that together deliver against a requirement\. A component is often the unit of technical ownership, and is decoupled from other components\. The term *workload* is used to identify a set of components that together deliver business value\. A workload is usually the level of detail that business and technology leaders communicate about\. An AWS CDK application maps to a component as defined by the AWS Well\-Architected Framework\. AWS CDK apps are a mechanism to codify and deliver Well\-Architected cloud application best practices\. You can also create and share components as reusable code libraries through artifact repositories, such as AWS CodeArtifact\. ### Every application starts with a single package in a single repository -A single package is the entry point of your AWS CDK app\. This is where you define how and where the different logical units of your application are deployed, as well as the CI/CD pipeline to deploy the application\. The app's constructs define the logical units of your solution\. +A single package is the entry point of your AWS CDK app\. Here, you define how and where to deploy the different logical units of your application\. You also define the CI/CD pipeline to deploy the application\. The app's constructs define the logical units of your solution\. Use additional packages for constructs that you use in more than one application\. \(Shared constructs should also have their own lifecycle and testing strategy\.\) Dependencies between packages in the same repository are managed by your repo's build tooling\. -Though it is possible, it is not recommended to put multiple applications in the same repository, especially when using automated deployment pipelines, because this increases the "blast radius" of changes during deployment\. With multiple applications in a repository, not only do changes to one application trigger deployment of the others \(even if they have not changed\), but a break in one application prevents the other applications from being deployed\. +Although it's possible, we don't recommend putting multiple applications in the same repository, especially when using automated deployment pipelines\. Doing this increases the "blast radius" of changes during deployment\. When there are multiple applications in a repository, changes to one application trigger deployment of the others \(even if the others haven't changed\)\. Furthermore, a break in one application prevents the other applications from being deployed\. ### Move code into repositories based on code lifecycle or team ownership -When packages begin to be used in multiple applications, move them to their own repository, so they can be referenced by the build systems of the applications that use them, but updated on cadences independent of the lifecycles of those applications\. It may make sense to put all shared constructs in one repository at first\. +When packages begin to be used in multiple applications, move them to their own repository\. This way, the packages can be referenced by application build systems that use them, and they can also be updated on cadences independent of the application lifecycles\. However, at first it might make sense to put all shared constructs in one repository\. -Also move packages to their own repo when different teams are working on them, to help enforce access control\. +Also, move packages to their own repository when different teams are working on them\. This helps enforce access control\. -To consume packages across repository boundaries, you now need a private package repository—similar to NPM, PyPi, or Maven Central, but internal to your organization, and a release process that builds, tests, and publishes the package to the private package repository\. [CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/) can host packages for most popular programming languages\. +To consume packages across repository boundaries, you need a private package repository—similar to NPM, PyPi, or Maven Central, but internal to your organization\. You also need a release process that builds, tests, and publishes the package to the private package repository\. [CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/) can host packages for most popular programming languages\. -Dependencies on packages in the package repository are managed by your language's package manager, for example NPM for TypeScript or JavaScript applications\. Your package manager helps to make sure builds are repeatable by recording the specific versions of every package your application depends on and allows you to upgrade those dependencies in a controlled manner\. +Dependencies on packages in the package repository are managed by your language's package manager, such as NPM for TypeScript or JavaScript applications\. Your package manager helps to make sure that builds are repeatable\. It does this by recording the specific versions of every package that your application depends on\. It also lets you upgrade those dependencies in a controlled manner\. -Shared packages need a different testing strategy: although for a single application it might be good enough to deploy the application to a testing environment and confirm that it still works, shared packages need to be tested independently of the consuming application, as if they were being released to the public\. \(Your organization might in fact choose to actually release some shared packages to the public\.\) +Shared packages need a different testing strategy\. For a single application, it might be good enough to deploy the application to a testing environment and confirm that it still works\. But shared packages must be tested independently of the consuming application, as if they were being released to the public\. \(Your organization might choose to actually release some shared packages to the public\.\) Keep in mind that a construct can be arbitrarily simple or complex\. A `Bucket` is a construct, but `CameraShopWebsite` could be a construct, too\. ### Infrastructure and runtime code live in the same package -The AWS CDK not only generates AWS CloudFormation templates for deploying infrastructure, it also bundles runtime assets like Lambda functions and Docker images and deploys them alongside your infrastructure\. So it's not only possible to combine the code that defines your infrastructure and the code that implements your runtime logic into a single construct— it's a best practice\. These two kinds of code don't need to live in separate repositories or even in separate packages\. +In addition to generating AWS CloudFormation templates for deploying infrastructure, the AWS CDK also bundles runtime assets like Lambda functions and Docker images and deploys them alongside your infrastructure\. This makes it possible to combine the code that defines your infrastructure and the code that implements your runtime logic into a single construct\. It's a best practice to do this\. These two kinds of code don't need to live in separate repositories or even in separate packages\. -A construct that is self\-contained, in other words that completely describes a piece of functionality including its infrastructure and logic, makes it easy to evolve the two kinds of code together, test them in isolation, share and reuse the code across projects, and version all the code in sync\. +To evolve the two kinds of code together, you can use a self\-contained construct that completely describes a piece of functionality, including its infrastructure and logic\. With a self\-contained construct, you can test the two kinds of code in isolation, share and reuse the code across projects, and version all the code in sync\. ## Construct best practices -This section contains best practices for developing constructs\. Constructs are reusable, composable modules that encapsulate resources, and the building blocks of AWS CDK apps\. +This section contains best practices for developing constructs\. Constructs are reusable, composable modules that encapsulate resources\. They're the building blocks of AWS CDK apps\. ### Model with constructs, deploy with stacks Stacks are the unit of deployment: everything in a stack is deployed together\. So when building your application's higher\-level logical units from multiple AWS resources, represent each logical unit as a [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html), not as a [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html)\. Use stacks only to describe how your constructs should be composed and connected for your various deployment scenarios\. -If one of your logical units is a Web site, for example, the constructs that make it up \(Amazon S3 bucket, API Gateway, Lambda functions, Amazon RDS tables, etc\.\) should be composed into a single high\-level construct, and then that construct should be instantiated in one or more stacks for deployment\. +For example, if one of your logical units is a website, the constructs that make it up \(such as an Amazon S3 bucket, API Gateway, Lambda functions, or Amazon RDS tables\) should be composed into a single high\-level construct\. Then that construct should be instantiated in one or more stacks for deployment\. -By using constructs for building and stacks for deploying, you improve reuse potential of your infrastructure and give yourself more flexibility in how it is deployed\. +By using constructs for building and stacks for deploying, you improve reuse potential of your infrastructure and give yourself more flexibility in how it's deployed\. ### Configure with properties and methods, not environment variables -Environment variable lookups inside constructs and stacks are a common anti\-pattern\. Both constructs and stacks should accept a properties object to allow for full configurability completely in code\. To do otherwise is to introduce a dependency on the machine that the code will run on, which becomes another bit of configuration information you have to keep track of and manage\. +Environment variable lookups inside constructs and stacks are a common anti\-pattern\. Both constructs and stacks should accept a properties object to allow for full configurability completely in code\. Doing otherwise introduces a dependency on the machine that the code will run on, which creates yet more configuration information that you have to track and manage\. -In general, environment variable lookups should be limited to the top level of an AWS CDK app, and should be used to pass in information needed for running in a development environment; see [Environments](environments.md)\. +In general, environment variable lookups should be limited to the top level of an AWS CDK app\. They should also be used to pass in information that's needed for running in a development environment\. For more information, see [Environments](environments.md)\. ### Unit test your infrastructure -If you avoid network lookups during synthesis and model all your production stages in code \(best practices we cover later\), you can run a full suite of unit tests at build time, consistently, in all environments\. If any single commit always results in the same generated template, you can trust the unit tests that you write to confirm that the generated templates look how you expect them to\. See [Testing constructs](testing.md)\. +To consistently run a full suite of unit tests at build time in all environments, avoid network lookups during synthesis and model all your production stages in code\. \(These best practices are covered later\.\) If any single commit always results in the same generated template, you can trust the unit tests that you write to confirm that the generated templates look the way you expect\. For more information, see [Testing constructs](testing.md)\. ### Don't change the logical ID of stateful resources -Changing the logical ID of a resource results in the resource being replaced with a new one at the next deployment\. For stateful resources like databases and buckets, or persistent infrastructure like an Amazon VPC, this is almost never what you want\. Be careful about any refactor of your AWS CDK code that could cause the ID to change, and write unit tests that assert that the logical IDs of your stateful resources remain static\. The logical ID is derived from the `id` you specify when you instantiate the construct, and the construct's position in the construct tree; see [Logical IDs](identifiers.md#identifiers_logical_ids)\. +Changing the logical ID of a resource results in the resource being replaced with a new one at the next deployment\. For stateful resources like databases and S3 buckets, or persistent infrastructure like an Amazon VPC, this is seldom what you want\. Be careful about any refactoring of your AWS CDK code that could cause the ID to change\. Write unit tests that assert that the logical IDs of your stateful resources remain static\. The logical ID is derived from the `id` you specify when you instantiate the construct, and the construct's position in the construct tree\. For more information, see [Logical IDs](identifiers.md#identifiers_logical_ids)\. ### Constructs aren't enough for compliance -Many enterprise customers are writing their own wrappers for L2 constructs \(the "curated" constructs that represent individual AWS resources with built\-in sane defaults and best practices\) to enforce security best practices such as static encryption and specific IAM policies\. For example, you might create a `MyCompanyBucket` that you then use in your applications in place of the usual Amazon S3 `Bucket` construct\. This pattern is useful for surfacing security guidance early in the software development lifecycle, but it cannot be relied on as the sole means of enforcement\. +Many enterprise customers write their own wrappers for L2 constructs \(the "curated" constructs that represent individual AWS resources with built\-in sane defaults and best practices\)\. These wrappers enforce security best practices such as static encryption and specific IAM policies\. For example, you might create a `MyCompanyBucket` that you then use in your applications in place of the usual Amazon S3 `Bucket` construct\. This pattern is useful for surfacing security guidance early in the software development lifecycle, but don't rely on it as the sole means of enforcement\. Instead, use AWS features such as [service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) and [permission boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to enforce your security guardrails at the organization level\. Use [Aspects](aspects.md) or tools like [CloudFormation Guard](https://github.com/aws-cloudformation/cloudformation-guard) to make assertions about the security properties of infrastructure elements before deployment\. Use AWS CDK for what it does best\. -Finally, keep in mind that writing your own "L2\+" constructs like these may prevent your developers from taking advantage of the growing ecosystems of AWS CDK packages, such as [AWS Solutions Constructs](https://docs.aws.amazon.com/solutions/latest/constructs/welcome.html), as these are typically built upon standard AWS CDK constructs and won't be able to use your custom versions\. +Finally, keep in mind that writing your own "L2\+" constructs might prevent your developers from taking advantage of AWS CDK packages such as [AWS Solutions Constructs](https://docs.aws.amazon.com/solutions/latest/constructs/welcome.html) or third\-party constructs from Construct Hub\. These packages are typically built on standard AWS CDK constructs and won't be able to use your wrapper constructs\. ## Application best practices -In this section we discuss how best to write your AWS CDK applications, combining constructs to define how your AWS resources are connected\. +In this section we discuss how to write your AWS CDK applications, combining constructs to define how your AWS resources are connected\. ### Make decisions at synthesis time -Although AWS CloudFormation lets you make decisions at deployment time \(using `Conditions`, `{ Fn::If }`, and `Parameters`\), and the AWS CDK gives you some access to these mechanisms, we recommend against using them\. The types of values you can use, and the types of operations you can perform on them, are quite limited compared to those available in a general\-purpose programming language\. +Although AWS CloudFormation lets you make decisions at deployment time \(using `Conditions`, `{ Fn::If }`, and `Parameters`\), and the AWS CDK gives you some access to these mechanisms, we recommend against using them\. The types of values that you can use and the types of operations you can perform on them are limited compared to what's available in a general\-purpose programming language\. -Instead, try to make all decisions, such as which construct to instantiate, in your AWS CDK application, using your programming language's `if` statements and other features\. For example, a common CDK idiom, iterating over a list and instantiating a construct with values from each item in the list, simply isn't possible using AWS CloudFormation expressions\. +Instead, try to make all decisions, such as which construct to instantiate, in your AWS CDK application by using your programming language's `if` statements and other features\. For example, a common CDK idiom, iterating over a list and instantiating a construct with values from each item in the list, simply isn't possible using AWS CloudFormation expressions\. Treat AWS CloudFormation as an implementation detail that the AWS CDK uses for robust cloud deployments, not as a language target\. You're not writing AWS CloudFormation templates in TypeScript or Python, you're writing CDK code that happens to use CloudFormation for deployment\. ### Use generated resource names, not physical names -Names are a precious resource\. Every name can only be used once, so if you hard\-code a table name or bucket name into your infrastructure and application, you can't deploy that piece of infrastructure twice in the same account\. \(The name we're talking about here is the name specified by, for example, the `bucketName` property on an Amazon S3 bucket construct\.\) +Names are a precious resource\. Each name can only be used once\. Therefore, if you hardcode a table name or bucket name into your infrastructure and application, you can't deploy that piece of infrastructure twice in the same account\. \(The name we're talking about here is the name specified by, for example, the `bucketName` property on an Amazon S3 bucket construct\.\) -What's worse, you can't make changes to the resource that require it to be replaced\. If a property can only be set at resource creation, for example the `KeySchema` of an Amazon DynamoDB table, that property is immutable, and changing it requires a new resource\. But the new resource must have the same name in order to be a true replacement, and it can't while the existing resource is still using that name\. +What's worse, you can't make changes to the resource that require it to be replaced\. If a property can only be set at resource creation, such as the `KeySchema` of an Amazon DynamoDB table, then that property is immutable\. Changing this property requires a new resource\. However, the new resource must have the same name in order to be a true replacement\. But it can't have the same name while the existing resource is still using that name\. -A better approach is to specify as few names as possible\. If you leave out resource names, the AWS CDK will generate them for you, and it'll do so in a way that won't cause these problems\. You then, for example, pass the generated table name \(which you can reference as `table.tableName` in your AWS CDK application\) as an environment variable into your AWS Lambda function, or you generate a configuration file on your Amazon EC2 instance on startup, or you write the actual table name to AWS Systems Manager Parameter Store and your application reads it from there\. +A better approach is to specify as few names as possible\. If you omit resource names, the AWS CDK will generate them for you in a way that won't cause problems\. Suppose you have a table as a resource\. You can then pass the generated table name as an environment variable into your AWS Lambda function\. In your AWS CDK application, you can reference the table name as `table.tableName`\. Alternatively, you can generate a configuration file on your Amazon EC2 instance on startup, or write the actual table name to the AWS Systems Manager Parameter Store so your application can read it from there\. -If the place you need it is another AWS CDK stack, that's even easier\. Given one stack that defines the resource and another than needs to use it: -+ If the two stacks are in the same AWS CDK app, just pass a reference between the two stacks\. For example, save a reference to the resource's construct as an attribute of the defining stack \(`this.stack.uploadBucket = myBucket`\), then pass that attribute to the constructor of the stack that needs the resource\. -+ When the two stacks are in different AWS CDK apps, use a static `from` method to use an externally\-defined resource based on its ARN, name, or other attributes \(for example, `Table.fromArn()` for a DynamoDB table\)\. Use the `CfnOutput` construct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS console\. Or the second app can parse the CloudFormation template generated by the first app and retrieve that value from the Outputs section\. +If the place you need it is another AWS CDK stack, that's even more straightforward\. Supposing that one stack defines the resource and another stack needs to use it, the following applies: ++ If the two stacks are in the same AWS CDK app, pass a reference between the two stacks\. For example, save a reference to the resource's construct as an attribute of the defining stack \(`this.stack.uploadBucket = myBucket`\)\. Then, pass that attribute to the constructor of the stack that needs the resource\. ++ When the two stacks are in different AWS CDK apps, use a static `from` method to use an externally defined resource based on its ARN, name, or other attributes\. \(For example, use `Table.fromArn()` for a DynamoDB table\)\. Use the `CfnOutput` construct to print the ARN or other required value in the output of `cdk deploy`, or look in the AWS Management Console\. Alternatively, the second app can read the CloudFormation template generated by the first app and retrieve that value from the `Outputs` section\. ### Define removal policies and log retention -The AWS CDK does its best to keep you from losing data by defaulting to policies that retain everything you create\. For example, the default removal policy on resources that contain data \(such as Amazon S3 buckets and database tables\) is to never delete the resource when it is removed from the stack, but rather orphan the resource from the stack\. Similarly, the CDK's default is to retain all logs forever\. In production environments, these defaults can quickly result in the storage of large amounts of data you don't actually need, and a corresponding AWS bill\. +The AWS CDK attempts to keep you from losing data by defaulting to policies that retain everything you create\. For example, the default removal policy on resources that contain data \(such as Amazon S3 buckets and database tables\) is not to delete the resource when it is removed from the stack\. Instead, the resource is orphaned from the stack\. Similarly, the CDK's default is to retain all logs forever\. In production environments, these defaults can quickly result in the storage of large amounts of data that you don't actually need, and a corresponding AWS bill\. -Consider carefully what you want these policies to actually be for each production resource and specify them accordingly\. Use [Aspects](aspects.md) to validate the removal and logging policies in your stack\. +Consider carefully what you want these policies to be for each production resource and specify them accordingly\. Use [Aspects](aspects.md) to validate the removal and logging policies in your stack\. ### Separate your application into multiple stacks as dictated by deployment requirements There is no hard and fast rule to how many stacks your application needs\. You'll usually end up basing the decision on your deployment patterns\. Keep in mind the following guidelines: -+ It's typically easier to keep as many resources in the same stack as possible, so keep them together unless you know you want them separated\. -+ Consider keeping stateful resources \(like databases\) in a separate stack from stateless resources\. You can then turn on termination protection on the stateful stack, and can freely destroy or create multiple copies of the stateless stack without risk of data loss\. -+ Stateful resources are more sensitive to construct renaming—renaming leads to resource replacement—so it makes sense not to nest them inside constructs that are likely to be moved around or renamed \(unless the state can be rebuilt if lost, like a cache\)\. This is another good reason to put stateful resources in their own stack\. ++ It's typically more straightforward to keep as many resources in the same stack as possible, so keep them together unless you know you want them separated\. ++ Consider keeping stateful resources \(like databases\) in a separate stack from stateless resources\. You can then turn on termination protection on the stateful stack\. This way, you can freely destroy or create multiple copies of the stateless stack without risk of data loss\. ++ Stateful resources are more sensitive to construct renaming—renaming leads to resource replacement\. Therefore, don't nest stateful resources inside constructs that are likely to be moved around or renamed \(unless the state can be rebuilt if lost, like a cache\)\. This is another good reason to put stateful resources in their own stack\. ### Commit `cdk.context.json` to avoid non\-deterministic behavior -Determinism is key to successful AWS CDK deployments\. A AWS CDK app should have essentially the same result whenever it is deployed to a given environment\. +Determinism is key to successful AWS CDK deployments\. An AWS CDK app should have essentially the same result whenever it is deployed to a given environment\. Since your AWS CDK app is written in a general\-purpose programming language, it can execute arbitrary code, use arbitrary libraries, and make arbitrary network calls\. For example, you could use an AWS SDK to retrieve some information from your AWS account while synthesizing your app\. Recognize that doing so will result in additional credential setup requirements, increased latency, and a chance, however small, of failure every time you run `cdk synth`\. -You should never modify your AWS account or resources during synthesis; synthesizing an app should not have side effects\. Changes to your infrastructure should happen only in the deployment phase, after the AWS CloudFormation template has been generated\. This way, if there's a problem, AWS CloudFormation will automatically roll back the change\. To make changes that can't be easily made within the AWS CDK framework, use [custom resources](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.custom_resources-readme.html) to execute arbitrary code at deployment time\. +Never modify your AWS account or resources during synthesis\. Synthesizing an app should not have side effects\. Changes to your infrastructure should happen only in the deployment phase, after the AWS CloudFormation template has been generated\. This way, if there's a problem, AWS CloudFormation can automatically roll back the change\. To make changes that can't be easily made within the AWS CDK framework, use [custom resources](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.custom_resources-readme.html) to execute arbitrary code at deployment time\. -Even strictly read\-only calls are not necessarily safe\. Consider what happens if the value returned by a network call changes\. What part of your infrastructure will that impact? What will happen to already\-deployed resources? Here are just two of the situations in which a sudden change in values might cause a problem\. -+ If you provision an Amazon VPC to all available Availability Zones in a specified region, and the number of AZs is two on deployment day, your IP space gets split in half\. If AWS launches a new Availability Zone the next day, the next deployment after that tries to split your IP space into thirds, requiring all subnets to be recreated\. This probably won't be possible because your Amazon EC2 instances are still running, and you'll have to clean this up manually\. -+ If you query for the latest Amazon Linux machine image and deploy an Amazon EC2 instance, and the next day a new image is released, a subsequent deployment picks up the new AMI and replaces all your instances\. This may not be what you expected to happen\. +Even strictly read\-only calls are not necessarily safe\. Consider what happens if the value returned by a network call changes\. What part of your infrastructure will that impact? What will happen to already\-deployed resources? Following are two example situations in which a sudden change in values might cause a problem\. ++ If you provision an Amazon VPC to all available Availability Zones in a specified Region, and the number of AZs is two on deployment day, then your IP space gets split in half\. If AWS launches a new Availability Zone the next day, the next deployment after that tries to split your IP space into thirds, requiring all subnets to be recreated\. This probably won't be possible because your Amazon EC2 instances are still running, and you'll have to clean this up manually\. ++ If you query for the latest Amazon Linux machine image and deploy an Amazon EC2 instance, and the next day a new image is released, a subsequent deployment picks up the new AMI and replaces all your instances\. This might not be what you expected to happen\. -These situations can be particularly pernicious because the AWS\-side change may occur after months or years of successful deployments\. Suddenly your deployments are failing "for no reason" and you long ago forgot what you did and why\. +These situations can be pernicious because the AWS\-side change might occur after months or years of successful deployments\. Suddenly your deployments are failing "for no reason" and you long ago forgot what you did and why\. -Fortunately, the AWS CDK includes a mechanism called *context providers* to record a snapshot of non\-deterministic values, allowing future synthesis operations produce exactly the same template\. The only changes in the new template are the changes *you* made in your code\. When you use a construct's `.fromLookup()` method, the result of the call is cached in `cdk.context.json`, which you should commit to version control along with the rest of your code to ensure future executions of your CDK app use the same value\. The CDK Toolkit includes commands to manage the context cache, so you can refresh specific entries when you need to\. For more information, see [Runtime context](context.md)\. +Fortunately, the AWS CDK includes a mechanism called *context providers* to record a snapshot of non\-deterministic values\. This allows future synthesis operations to produce exactly the same template as they did when first deployed\. The only changes in the new template are the changes that *you* made in your code\. When you use a construct's `.fromLookup()` method, the result of the call is cached in `cdk.context.json`\. You should commit this to version control along with the rest of your code to make sure that future executions of your CDK app use the same value\. The CDK Toolkit includes commands to manage the context cache, so you can refresh specific entries when you need to\. For more information, see [Runtime context](context.md)\. -If you need some value \(from AWS or elsewhere\) for which there is no native CDK context provider, we recommend writing a separate script to retrieve the value and write it to a file, then read that file in your CDK app\. Run the script only when you want to refresh the stored value, not as part of your regular build process\. +If you need some value \(from AWS or elsewhere\) for which there is no native CDK context provider, we recommend writing a separate script\. The script should retrieve the value and write it to a file, then read that file in your CDK app\. Run the script only when you want to refresh the stored value, not as part of your regular build process\. ### Let the AWS CDK manage roles and security groups -One of the great features of the AWS CDK construct library is the `grant()` convenience methods that allow quick and simple creation of AWS Identity and Access Management roles granting access to one resource by another using minimally\-scoped permissions\. For example, consider a line like the following: +With the AWS CDK construct library's `grant()` convenience methods, you can create AWS Identity and Access Management roles that grant access to one resource by another using minimally scoped permissions\. For example, consider a line like the following: ``` myBucket.grantRead(myLambda) ``` -This single line results in a policy being added to the Lambda function's role \(which is also created for you\)\. That role and its policies are more than a dozen lines of CloudFormation that you don't have to write, and the AWS CDK grants only the minimal permissions required for the function to read from the bucket\. +This single line adds a policy to the Lambda function's role \(which is also created for you\)\. That role and its policies are more than a dozen lines of CloudFormation that you don't have to write\. The AWS CDK grants only the minimal permissions required for the function to read from the bucket\. -If you require developers to always use predefined roles that were created by a security team, AWS CDK coding becomes much more complicated, and your teams lose a lot of flexibility in how they design their applications\. A better alternative is to use [service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) and [permission boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to ensure that developers stay within the guardrails\. +If you require developers to always use predefined roles that were created by a security team, AWS CDK coding becomes much more complicated\. Your teams could lose a lot of flexibility in how they design their applications\. A better alternative is to use [service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) and [permission boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to make sure that developers stay within the guardrails\. ### Model all production stages in code -In traditional AWS CloudFormation scenarios, your goal is to produce a single artifact that is parameterized so that it can be deployed to various target environments after applying configuration values specific to those environments\. In the CDK, you can, and should, build that configuration right into your source code\. Create a stack for your production environment, and a separate one for each of your other stages, and put the configuration values for each right there in the code\. Use services like [Secrets Manager](https://aws.amazon.com/secrets-manager/) and [Systems Manager](https://aws.amazon.com/systems-manager/) Parameter Store for sensitive values that you don't want to check in to source control, using the names or ARNs of those resources\. +In traditional AWS CloudFormation scenarios, your goal is to produce a single artifact that is parameterized so that it can be deployed to various target environments after applying configuration values specific to those environments\. In the CDK, you can, and should, build that configuration into your source code\. Create a stack for your production environment, and create a separate stack for each of your other stages\. Then, put the configuration values for each stack in the code\. Use services like [Secrets Manager](https://aws.amazon.com/secrets-manager/) and [Systems Manager](https://aws.amazon.com/systems-manager/) Parameter Store for sensitive values that you don't want to check in to source control, using the names or ARNs of those resources\. -When you synthesize your application, the cloud assembly created in the `cdk.out` folder contains a separate template for each environment\. Your entire build is deterministic: there are no out\-of\-band changes to your application, and any given commit always yields the exact same AWS CloudFormation template and accompanying assets, which makes unit testing much more reliable\. +When you synthesize your application, the cloud assembly created in the `cdk.out` folder contains a separate template for each environment\. Your entire build is deterministic\. There are no out\-of\-band changes to your application, and any given commit always yields the exact same AWS CloudFormation template and accompanying assets\. This makes unit testing much more reliable\. ### Measure everything -Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation, and that automation isn't possible without extensive amounts of monitoring\. Create metrics, alarms, and dashboards to measure all aspects of your deployed resources\. And don't just measure simple things like CPU usage and disk space: also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_dynamodb.Table.html) class\. \ No newline at end of file +Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation\. That automation is only possible with extensive amounts of monitoring\. To measure all aspects of your deployed resources, create metrics, alarms, and dashboards\. Don't stop at measuring things like CPU usage and disk space\. Also record your business metrics, and use those measurements to automate deployment decisions like rollbacks\. Most of the L2 constructs in AWS CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the [dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_dynamodb.Table.html) class\. \ No newline at end of file diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index 55327b40..bb2cf023 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -1,21 +1,23 @@ # Bootstrapping -Deploying AWS CDK apps into an AWS [environment](environments.md) \(a combination of an AWS account and region\) requires that you provision resources the AWS CDK needs to perform the deployment\. These resources include an Amazon S3 bucket for storing files and IAM roles that grant permissions needed to perform deployments\. The process of provisioning these initial resources is called *bootstrapping*\. +*Bootstrapping* is the process of provisioning resources for the AWS CDK before you can deploy AWS CDK apps into an AWS [environment](environments.md)\. \(An AWS environment is a combination of an AWS account and Region\)\. -The required resources are defined in a AWS CloudFormation stack, called the *bootstrap stack*, which is usually named `CDKToolkit`\. Like any AWS CloudFormation stack, it appears in the AWS CloudFormation console once it has been deployed\. +These resources include an Amazon S3 bucket for storing files and IAM roles that grant permissions needed to perform deployments\. + +The required resources are defined in an AWS CloudFormation stack, called the *bootstrap stack*, which is usually named `CDKToolkit`\. Like any AWS CloudFormation stack, it appears in the AWS CloudFormation console once it has been deployed\. **Note** CDK v2 uses a bootstrap template dubbed the modern template\. The legacy template from CDK v1 is not supported in v2\. -Environments are independent, so if you want to deploy to multiple environments \(different AWS accounts or different regions in the same account\), each environment must be bootstrapped separately\. +Environments are independent\. If you want to deploy to multiple environments \(different AWS accounts or different Regions in the same account\), each environment must be bootstrapped separately\. **Important** You may incur AWS charges for data stored in the bootstrapped resources\. **Note** -Older versions of the bootstrap template created a Customer Master Key \(CMK\) in each bootstrapped environment by default\. To avoid charges for the CMK, re\-bootstrap these environments using `--no-bootstrap-customer-key`\. The current default is to not use a CMK to avoid these charges\. +Earlier versions of the bootstrap template created an AWS KMS key in each bootstrapped environment by default\. To avoid charges for the KMS key, re\-bootstrap these environments using `--no-bootstrap-customer-key`\. The current default is no KMS key, which helps avoid these charges\. -If you attempt to deploy an AWS CDK application into an environment that does not have the necessary resources, you receive an error message telling you that you need to bootstrap the environment\. +If you attempt to deploy an AWS CDK application into an environment that doesn't have the necessary resources, an error message reminds you to bootstrap the environment\. If you are using CDK Pipelines to deploy into another account's environment, and you receive a message like the following: @@ -23,18 +25,18 @@ If you are using CDK Pipelines to deploy into another account's environment, and Policy contains a statement with one or more invalid principals ``` -This error message means that the appropriate IAM roles do not exist in the other environment, which is most likely caused by a lack of bootstrapping\. +This error message means that the appropriate IAM roles do not exist in the other environment\. The most likely cause is a lack of bootstrapping\. **Note** Do not delete and recreate an account's bootstrap stack if you are using CDK Pipelines to deploy into that account\. The pipeline will stop working\. To update the bootstrap stack to a new version, instead re\-run `cdk bootstrap` to update the bootstrap stack in place\. ## How to bootstrap -Bootstrapping is the deployment of a AWS CloudFormation template to a specific AWS environment \(account and region\)\. The bootstrapping template accepts parameters that customize some aspects of the bootstrapped resources \(see [Customizing bootstrapping](#bootstrapping-customizing)\)\. Thus, you can bootstrap in one of two ways\. +Bootstrapping is the deployment of an AWS CloudFormation template to a specific AWS environment \(account and Region\)\. The bootstrapping template accepts parameters that customize some aspects of the bootstrapped resources \(see [Customizing bootstrapping](#bootstrapping-customizing)\)\. Thus, you can bootstrap in one of two ways\. + Use the AWS CDK Toolkit's cdk bootstrap command\. This is the simplest method and works well if you have only a few environments to bootstrap\. -+ Deploy the template provided by the AWS CDK Toolkit using another AWS CloudFormation deployment tool\. This lets you use AWS CloudFormation Stack Sets or AWS Control Tower as well as the AWS CloudFormation console or the AWS CLI\. You can even make small modifications to the template before deployment\. This approach is more flexible and is suitable for large\-scale deployments\. ++ Deploy the template provided by the AWS CDK Toolkit using another AWS CloudFormation deployment tool\. This lets you use AWS CloudFormation StackSets or AWS Control Tower and also the AWS CloudFormation console or the AWS CLI\. You can make small modifications to the template before deployment\. This approach is more flexible and is suitable for large\-scale deployments\. -It is not an error to bootstrap an environment more than once\. If an environment you bootstrap has already been bootstrapped, its bootstrap stack will be upgraded if necessary; otherwise, nothing happens\. +It is not an error to bootstrap an environment more than once\. If an environment you bootstrap has already been bootstrapped, its bootstrap stack will be upgraded if necessary\. Otherwise, nothing happens\. ### Bootstrapping with the AWS CDK Toolkit @@ -51,7 +53,9 @@ cdk bootstrap aws://123456789012/us-east-1 cdk bootstrap 123456789012/us-east-1 123456789012/us-west-1 ``` -The CDK Toolkit always synthesizes the AWS CDK app in the current directory\. If you do not specify at least one environment in the `cdk bootstrap` command, it bootstraps all the environments referenced in the app\. If a stack is environment\-agnostic \(that is, it does not have an `env` property\), the CDK's environment \(for example, the one specified using \-\-profile, or the default AWS environment otherwise\) is applied to make the stack environment\-specific, and that environment is then bootstrapped\. +The CDK Toolkit always synthesizes the AWS CDK app in the current directory\. If you do not specify at least one environment in the `cdk bootstrap` command, it bootstraps all the environments referenced in the app\. + +If a stack is environment\-agnostic \(meaning it doesn't have an `env` property\), then the CDK's environment is applied to make the stack environment\-specific\. The CDK's environment is the one specified using \-\-profile or environment variables, or the default AWS environment otherwise\. That environment is then bootstrapped\. For example, the following command synthesizes the current AWS CDK app using the `prod` AWS profile, then bootstraps its environments\. @@ -113,18 +117,18 @@ As previously mentioned, AWS CDK v1 supported two bootstrapping templates, legac \* *We will add additional resources to the bootstrap template as needed\.* -An environment that has been bootstrapped using the legacy template can \(and must\) be upgraded to use the modern template for use with CDK v2 by re\-bootstrapping\. Re\-deploy all AWS CDK applications in the environment at least once before deleting the legacy bucket\. +An environment that was bootstrapped using the legacy template must be upgraded to use the modern template for CDK v2 by re\-bootstrapping\. Re\-deploy all AWS CDK applications in the environment at least once before deleting the legacy bucket\. ## Customizing bootstrapping There are two ways to customize the bootstrapping resources\. -+ Use command\-line parameters with the `cdk bootstrap` command\. This lets you modify a few aspects of the template\. -+ Modify the default bootstrap template and deploy it yourself\. This gives you unlimited control over the bootstrap resources\. ++ Use command line parameters with the `cdk bootstrap` command\. This lets you modify a few aspects of the template\. ++ Modify the default bootstrap template and deploy it yourself\. This gives you more complete control over the bootstrap resources\. -The following command\-line options, when used with CDK Toolkit's cdk bootstrap, provide commonly\-needed adjustments to the bootstrapping template\. +The following command line options, when used with CDK Toolkit's cdk bootstrap, provide commonly needed adjustments to the bootstrapping template\. + \-\-bootstrap\-bucket\-name overrides the name of the Amazon S3 bucket\. May require changes to your CDK app \(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. + \-\-bootstrap\-kms\-key\-id overrides the AWS KMS key used to encrypt the S3 bucket\. -+ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. By default, stacks are deployed with full administrator privileges using the `AdministratorAccess` policy\. ++ \-\-cloudformation\-execution\-policies specifies the ARNs of managed policies that should be attached to the deployment role assumed by AWS CloudFormation during deployment of your stacks\. By default, stacks are deployed with full administrator permissions using the `AdministratorAccess` policy\. The policy ARNs must be passed as a single string argument, with the individual ARNs separated by commas\. For example: @@ -132,15 +136,21 @@ The following command\-line options, when used with CDK Toolkit's cdk bootstrap, --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess". ``` **Important** -To avoid deployment failures, be sure the policies you specify are sufficient for any deployments you will perform in the environment being bootstrapped\. -+ \-\-qualifier a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid resource name clashes when you provision multiple bootstrap stacks in the same environment using \-\-toolkit\-stack\-name\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier also requires that your CDK app pass the changed value to the stack synthesizer\(see [Stack synthesizers](#bootstrapping-synthesizers)\)\. +To avoid deployment failures, be sure the policies that you specify are sufficient for any deployments you will perform in the environment being bootstrapped\. ++ \-\-qualifier is a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid resource name clashes when you provision multiple bootstrap stacks in the same environment using \-\-toolkit\-stack\-name\. The default is `hnb659fds` \(this value has no significance\)\. + + Changing the qualifier also requires that your CDK app pass the changed value to the stack synthesizer\. For more information, see [Stack synthesizers](#bootstrapping-synthesizers)\. + \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. -+ \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. -+ \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. -+ \-\-termination\-protection prevents the bootstrap stack from being deleted \(see [Protecting a stack from being deleted](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html) in the AWS CloudFormation User Guide\) ++ \-\-trust lists the AWS accounts that may deploy into the environment being bootstrapped\. + + Use this flag when bootstrapping an environment that a CDK Pipeline in another environment will deploy into\. The account doing the bootstrapping is always trusted\. ++ \-\-trust\-for\-lookup lists the AWS accounts that may look up context information from the environment being bootstrapped\. + + Use this flag to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly\. ++ \-\-termination\-protection prevents the bootstrap stack from being deleted\. For more information, see [Protecting a stack from being deleted](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html) in the *AWS CloudFormation User Guide*\. **Important** -The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. +The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list\. By default, this extends permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](#bootstrapping-customizing) with policies and trusted accounts that you are comfortable with\. ### Customizing the template @@ -160,7 +170,7 @@ cdk bootstrap --template bootstrap-template.yaml ## Stack synthesizers -Your AWS CDK app needs to know about the bootstrapping resources available to it in order to successfully synthesize a stack that can be deployed\. The *stack synthesizer* is an AWS CDK class that controls how the stack's template is synthesized, including how it uses bootstrapping resources \(for example, how it refers to assets stored in the bootstrap bucket\)\. +Your AWS CDK app needs to know about the bootstrapping resources available to it in order to successfully synthesize a stack that can be deployed\. The *stack synthesizer* is an AWS CDK class that controls how the stack's template is synthesized\. This includes how it uses bootstrapping resources \(for example, how it refers to assets stored in the bootstrap bucket\)\. The AWS CDK's built\-in stack synthesizers is called `DefaultStackSynthesizer`\. It includes capabilities for cross\-account deployments and [CDK Pipelines](cdk_pipeline.md) deployments\. @@ -235,11 +245,15 @@ If you don't provide the `synthesizer` property, `DefaultStackSynthesizer` is us ## Customizing synthesis -Depending on the changes you made to the bootstrap template, you may also need to customize synthesis\. The `DefaultStackSynthesizer` can be customized using the properties described below\. If none of these properties provide the customizations you require, you can write your synthesizer as a class that implements `IStackSynthesizer` \(perhaps deriving from `DefaultStackSynthesizer`\)\. +Depending on the changes you made to the bootstrap template, you may also need to customize synthesis\. The `DefaultStackSynthesizer` can be customized using the properties described as follows\. + +If none of these properties provide the customizations you require, you can write your synthesizer as a class that implements `IStackSynthesizer` \(perhaps deriving from `DefaultStackSynthesizer`\)\. ### Changing the qualifier -The *qualifier* is added to the name of bootstrap resources to distinguish the resources in separate bootstrap stacks\. To deploy two different versions of the bootstrap stack in the same environment \(AWS account and region\), then, the stacks must have different qualifiers\. This feature is intended for name isolation between automated tests of the CDK itself\. Unless you can very precisely scope down the IAM permissions given to the AWS CloudFormation execution role, there are no privilege isolation benefits to having two different bootstrap stacks in a single account, so there is usually no need to change this value\. +The *qualifier* is added to the name of bootstrap resources to distinguish the resources in separate bootstrap stacks\. To deploy two different versions of the bootstrap stack in the same environment \(AWS account and Region\), the stacks must have different qualifiers\. + +This feature is intended for name isolation between automated tests of the CDK itself\. Unless you can very precisely scope down the IAM permissions given to the AWS CloudFormation execution role, there are no permission isolation benefits to having two different bootstrap stacks in a single account\. Therefore, there's usually no need to change this value\. To change the qualifier, configure the `DefaultStackSynthesizer` either by instantiating the synthesizer with the property: @@ -316,9 +330,9 @@ Or by configuring the qualifier as a context key in `cdk.json`\. All the other `DefaultStackSynthesizer` properties relate to the names of the resources in the bootstrapping template\. You only need to provide any of these properties if you modified the bootstrap template and changed the resource names or naming scheme\. -All properties accept the special placeholders `${Qualifier}`, `${AWS::Partition}`, `${AWS::AccountId}`, and `${AWS::Region}`\. These placeholders are replaced with the values of the `qualifier` parameter and with the values of the AWS partition, account ID, and region for the stack's environment, respectively\. +All properties accept the special placeholders `${Qualifier}`, `${AWS::Partition}`, `${AWS::AccountId}`, and `${AWS::Region}`\. These placeholders are replaced with the values of the `qualifier` parameter and the AWS partition, account ID, and Region values for the stack's environment, respectively\. -The following example shows the most commonly\-used properties for `DefaultStackSynthesizer` along with their default values, as if you were instantiating the synthesizer\. For a complete list, see [DefaultStackSynthesizerProps](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.DefaultStackSynthesizerProps.html#properties)\. +The following example shows the most commonly used properties for `DefaultStackSynthesizer` along with their default values, as if you were instantiating the synthesizer\. For a complete list, see [DefaultStackSynthesizerProps](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.DefaultStackSynthesizerProps.html#properties)\. ------ #### [ TypeScript ] @@ -519,7 +533,9 @@ new DefaultStackSynthesizer(new DefaultStackSynthesizerProps ## The bootstrapping template contract -The requirements of the bootstrapping stack depend on the stack synthesizer in use\. If you write your own stack synthesizer, you have complete control of the bootstrap resources that your synthesizer requires and how the synthesizer finds them\. This section describes the expectations that the `DefaultStackSynthesizer` has of the bootstrapping template\. +The requirements of the bootstrapping stack depend on the stack synthesizer in use\. If you write your own stack synthesizer, you have complete control of the bootstrap resources that your synthesizer requires and how the synthesizer finds them\. + +This section describes the expectations that the `DefaultStackSynthesizer` has of the bootstrapping template\. ### Versioning @@ -542,10 +558,12 @@ Outputs: ### Roles -The `DefaultStackSynthesizer` requires five IAM roles for five different purposes\. If you are not using the default roles, the synthesizer needs to be told the ARNs for the roles you want to use\. The roles are: -+ The *deployment role* is assumed by the AWS CDK Toolkit and by AWS CodePipeline to deploy into an environment\. Its `AssumeRolePolicy` controls who can deploy into the environment\. The permissions this role needs can be seen in the template\. +The `DefaultStackSynthesizer` requires five IAM roles for five different purposes\. If you are not using the default roles, you must tell the synthesizer the ARNs for the roles you want to use\. + +The roles are as follows: ++ The *deployment role* is assumed by the AWS CDK Toolkit and by AWS CodePipeline to deploy into an environment\. Its `AssumeRolePolicy` controls who can deploy into the environment\. In the template, you can see the permissions that this role needs\. + The *lookup role* is assumed by the AWS CDK Toolkit to perform context lookups in an environment\. Its `AssumeRolePolicy` controls who can deploy into the environment\. The permissions this role needs can be seen in the template\. -+ The *file publishing role* and the *image publishing role* are assumed by the AWS CDK Toolkit and by AWS CodeBuild projects to publish assets into an environment: that is, to write to the S3 bucket and the ECR repository, respectively\. These roles require write access to these resources\. ++ The *file publishing role* and the *image publishing role* are assumed by the AWS CDK Toolkit and by AWS CodeBuild projects to publish assets into an environment\. They're used to write to the S3 bucket and the ECR repository, respectively\. These roles require write access to these resources\. + *The AWS CloudFormation execution role* is passed to AWS CloudFormation to perform the actual deployment\. Its permissions are the permissions that the deployment will execute under\. The permissions are passed to the stack as a parameter that lists managed policy ARNs\. ### Outputs @@ -557,23 +575,25 @@ The AWS CDK Toolkit requires that the following CloudFormation outputs exist on ### Template history -The bootstrap template is versioned and evolves over time with the AWS CDK itself\. If you provide your own bootstrap template, keep it up\-to\-date with the canonical default template to ensure that yours continues to work with all CDK features\. This section contains a list of the changes made in each version\. +The bootstrap template is versioned and evolves over time with the AWS CDK itself\. If you provide your own bootstrap template, keep it up to date with the canonical default template\. You want to make sure that your template continues to work with all CDK features\. + +This section contains a list of the changes made in each version\. | Template version | AWS CDK version | Changes | | --- | --- | --- | -| 1 | 1\.40\.0 | Initial version of template with Bucket, Key, Repository and Roles\. | +| 1 | 1\.40\.0 | Initial version of template with Bucket, Key, Repository, and Roles\. | | 2 | 1\.45\.0 | Split asset publishing role into separate file and image publishing roles\. | | 3 | 1\.46\.0 | Add FileAssetKeyArn export to be able to add decrypt permissions to asset consumers\. | -| 4 | 1\.61\.0 | KMS permissions are now implicit via S3 and no longer require FileAsetKeyArn, Add CdkBootstrapVersion SSM parameter so the bootstrap stack version can be verified without knowing the stack name\. | +| 4 | 1\.61\.0 | AWS KMS permissions are now implicit via Amazon S3 and no longer require FileAsetKeyArn\. Add CdkBootstrapVersion SSM parameter so the bootstrap stack version can be verified without knowing the stack name\. | | 5 | 1\.87\.0 | Deployment role can read SSM parameter\. | | 6 | 1\.108\.0 | Add lookup role separate from deployment role\. | | 6 | 1\.109\.0 | Attach aws\-cdk:bootstrap\-role tag to deployment, file publishing, and image publishing roles\. | -| 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly \(however, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | +| 7 | 1\.110\.0 | Deployment role can no longer read Buckets in the target account directly\. \(However, this role is effectively an administrator, and could always use its AWS CloudFormation permissions to make the bucket readable anyway\)\. | | 8 | 1\.114\.0 | The lookup role has full read\-only permissions to the target environment, and has a aws\-cdk:bootstrap\-role tag as well\. | -| 9 | 2\.1\.0 | Fixes S3 asset uploads from being rejected by commonly referenced encryption SCP\. | -| 10 | 2\.4\.0 | ECR ScanOnPush is now enabled by default\. | -| 11 | 2\.18\.0 | Adds policy allowing Lambda to pull from Amazon ECR repos so it survives rebootstrapping\. | +| 9 | 2\.1\.0 | Fixes Amazon S3 asset uploads from being rejected by commonly referenced encryption SCP\. | +| 10 | 2\.4\.0 | Amazon ECR ScanOnPush is now enabled by default\. | +| 11 | 2\.18\.0 | Adds policy allowing Lambda to pull from Amazon ECR repos so it survives re\-bootstrapping\. | | 12 | 2\.20\.0 | Adds support for experimental cdk import\. | | 13 | 2\.25\.0 | Makes container images in bootstrap\-created Amazon ECR repositories immutable\. | -| 14 | 2\.34\.0 | Turns off Amazon ECR image scanning at the repository level by default to allow bootstrapping regions that do not support image scanning\. | \ No newline at end of file +| 14 | 2\.34\.0 | Turns off Amazon ECR image scanning at the repository level by default to allow bootstrapping Regions that do not support image scanning\. | \ No newline at end of file diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index a5ceefb9..82906305 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -1,28 +1,37 @@ # Continuous integration and delivery \(CI/CD\) using CDK Pipelines -[CDK Pipelines](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines-readme.html) is a construct library module for painless continuous delivery of AWS CDK applications\. Whenever you check your AWS CDK app's source code in to AWS CodeCommit, GitHub, or CodeStar, CDK Pipelines can automatically build, test, and deploy your new version\. +[CDK Pipelines](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines-readme.html) is a construct library module for painless continuous delivery of AWS CDK applications\. Whenever you check your AWS CDK app's source code in to AWS CodeCommit, GitHub, or AWS CodeStar, CDK Pipelines can automatically build, test, and deploy your new version\. -CDK Pipelines are self\-updating: if you add application stages or stacks, the pipeline automatically reconfigures itself to deploy those new stages and/or stacks\. +CDK Pipelines are self\-updating\. If you add application stages or stacks, the pipeline automatically reconfigures itself to deploy those new stages or stacks\. **Note** -CDK Pipelines supports two APIs: the original API that was made available in the Developer Preview, and a modern one that incorporates feedback from CDK customers received during the preview phase\. The examples in this topic use the modern API\. For details on the differences between the two supported APIs, see [CDK Pipelines original API](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/pipelines/ORIGINAL_API.md)\. +CDK Pipelines supports two APIs\. One is the original API that was made available in the CDK Pipelines Developer Preview\. The other is a modern API that incorporates feedback from CDK customers received during the preview phase\. The examples in this topic use the modern API\. For details on the differences between the two supported APIs, see [CDK Pipelines original API](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/pipelines/ORIGINAL_API.md)\. ## Bootstrap your AWS environments -Before you can use CDK Pipelines, you must bootstrap the AWS environment\(s\) to which you will deploy your stacks\. An [environment](environments.md) is an account/region pair to which you want to deploy a CDK stack\. A CDK Pipeline involves at least two environments: the environment where the pipeline is provisioned, and the environment where you want to deploy the application's stacks \(or its stages, which are groups of related stacks\)\. These environments can be the same, though best practices recommend you isolate stages from each other in different AWS accounts or regions\. +Before you can use CDK Pipelines, you must bootstrap the AWS environments to which you will deploy your stacks\. An [environment](environments.md) is an account/Region pair to which you want to deploy a CDK stack\. + +A CDK Pipeline involves at least two environments\. One environment is where the pipeline is provisioned\. The other environment is where you want to deploy the application's stacks \(or its stages, which are groups of related stacks\)\. These environments can be the same, though best practices recommend you isolate stages from each other in different AWS accounts or Regions\. **Note** See [Bootstrapping](bootstrapping.md) for more information on the kinds of resources created by bootstrapping and how to customize the bootstrap stack\. -Continuous deployment with CDK Pipelines requires that the CDK Toolkit stack include an Amazon S3 bucket, an Amazon ECR repository, and IAM roles to give the various parts of a pipeline the permissions they need\. The CDK Toolkit will upgrade your existing bootstrap stack or create a new one, as necessary\. +Continuous deployment with CDK Pipelines requires the following to be included in the CDK Toolkit stack: ++ An S3 bucket ++ An Amazon ECR repository ++ IAM roles to give the various parts of a pipeline the permissions they need + +The CDK Toolkit upgrades your existing bootstrap stack or creates a new one if necessary\. -To bootstrap an environment that can provision an AWS CDK pipeline, invoke `cdk bootstrap` as shown below\. Invoking the AWS CDK Toolkit via the `npx` command temporarily installs it if necessary, and will use the version of the Toolkit installed in the current project if one exists\. +To bootstrap an environment that can provision an AWS CDK pipeline, invoke `cdk bootstrap` as shown in the following example\. Invoking the AWS CDK Toolkit via the `npx` command temporarily installs it if necessary\. It will also use the version of the Toolkit installed in the current project, if one exists\. -\-\-cloudformation\-execution\-policies specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The default `AdministratorAccess` policy ensures that your pipeline can deploy every type of AWS resource\. If you use this policy, make sure you trust all the code and dependencies that make up your AWS CDK app\. +\-\-cloudformation\-execution\-policies specifies the ARN of a policy under which future CDK Pipelines deployments will execute\. The default `AdministratorAccess` policy makes sure that your pipeline can deploy every type of AWS resource\. If you use this policy, make sure you trust all the code and dependencies that make up your AWS CDK app\. Most organizations mandate stricter controls on what kinds of resources can be deployed by automation\. Check with the appropriate department within your organization to determine the policy your pipeline should use\. -You may omit the \-\-profile option if your default AWS profile contains the necessary credentials or to instead use the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to provide your AWS account credentials\. +You can omit the \-\-profile option in the following situations: ++ If your default AWS profile contains the necessary credentials ++ If you want to use the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to provide your AWS account credentials ------ #### [ macOS/Linux ] @@ -42,9 +51,11 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ ------ -To bootstrap additional environments into which AWS CDK applications will be deployed by the pipeline, use the commands below instead\. The \-\-trust option indicates which other account should have permissions to deploy AWS CDK applications into this environment; specify the pipeline's AWS account ID\. +To bootstrap additional environments into which AWS CDK applications will be deployed by the pipeline, use the following commandsinstead\. The \-\-trust option indicates which other account should have permissions to deploy AWS CDK applications into this environment\. For this option, specify the pipeline's AWS account ID\. -Again, you may omit the \-\-profile option if your default AWS profile contains the necessary credentials or if you are using the `AWS_*` environment variables to provide your AWS account credentials\. +Again, you can omit the \-\-profile option in the following situations: ++ If your default AWS profile contains the necessary credentials ++ If you're using the `AWS_*` environment variables to provide your AWS account credentials ------ #### [ macOS/Linux ] @@ -69,11 +80,11 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ **Tip** Use administrative credentials only to bootstrap and to provision the initial pipeline\. Afterward, use the pipeline itself, not your local machine, to deploy changes\. -If you are upgrading a legacy\-bootstrapped environment, the old Amazon S3 bucket is orphaned when the new bucket is created\. Delete it manually using the Amazon S3 console\. +If you are upgrading a legacy bootstrapped environment, the previous Amazon S3 bucket is orphaned when the new bucket is created\. Delete it manually by using the Amazon S3 console\. ## Initialize project -Create a new, empty GitHub project and clone it to your workstation in the `my-pipeline` directory\. \(Our code examples in this topic use GitHub; you can also use CodeStar or AWS CodeCommit\.\) +Create a new, empty GitHub project and clone it to your workstation in the `my-pipeline` directory\. \(Our code examples in this topic use GitHub\. You can also use AWS CodeStar or AWS CodeCommit\.\) ``` git clone GITHUB-CLONE-URL my-pipeline @@ -81,7 +92,7 @@ cd my-pipeline ``` **Note** -You may use a name other than `my-pipeline` for your app's main directory, but since the AWS CDK Toolkit bases some file and class names on the name of the main directory, you'll need to tweak these later in this topic\. +You can use a name other than `my-pipeline` for your app's main directory\. However, if you do so, you will have to tweak the file and class names later in this topic\. This is because the AWS CDK Toolkit bases some file and class names on the name of the main directory\. After cloning, initialize the project as usual\. @@ -106,7 +117,7 @@ cdk init app --language javascript cdk init app --language python ``` -After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install the AWS CDK core dependencies\. +After the app has been created, also enter the following two commands\. These activate the app's Python virtual environment and install the AWS CDK core dependencies\. ``` source .venv/bin/activate @@ -138,7 +149,7 @@ If you are using Visual Studio, open the solution file in the `src` directory\. cdk init app --language go ``` -After the app has been created, also enter the following command to instll the AWS Construct Library modules required by the app\. +After the app has been created, also enter the following command to install the AWS Construct Library modules that the app requires\. ``` go get @@ -153,12 +164,14 @@ Be sure to commit your `cdk.json` and `cdk.context.json` files to source control Your CDK Pipelines application will include at least two stacks: one that represents the pipeline itself, and one or more stacks that represent the application deployed through it\. Stacks can also be grouped into *stages*, which you can use to deploy copies of infrastructure stacks to different environments\. For now, we'll consider the pipeline, and later delve into the application it will deploy\. -The construct [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.CodePipeline.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.CodePipeline.html) is the construct that represents a CDK Pipeline that uses AWS CodePipeline as its deployment engine\. When you instantiate `CodePipeline` in a stack, you define the source location for the pipeline \(e\.g\. a GitHub repository\) and the commands to build the app\. For example, the following defines a pipeline whose source is stored in a GitHub repository, and includes a build step for a TypeScript CDK application\. Fill in the information about your GitHub repo where indicated\. +The construct [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.CodePipeline.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.CodePipeline.html) is the construct that represents a CDK Pipeline that uses AWS CodePipeline as its deployment engine\. When you instantiate `CodePipeline` in a stack, you define the source location for the pipeline \(such as a GitHub repository\)\. You also define the commands to build the app\. + +For example, the following defines a pipeline whose source is stored in a GitHub repository\. It also includes a build step for a TypeScript CDK application\. Fill in the information about your GitHub repo where indicated\. **Note** By default, the pipeline authenticates to GitHub using a personal access token stored in Secrets Manager under the name `github-token`\. -You'll also need to update the instantiation of the pipeline stack to specify the AWS account and region\. +You'll also need to update the instantiation of the pipeline stack to specify the AWS account and Region\. ------ #### [ TypeScript ] @@ -403,7 +416,7 @@ namespace MyPipeline ------ -You must deploy a pipeline manually once\. After that, the pipeline will keep itself up to date from the source code repository, so make sure the code in the repo is the code you want deployed\. Check in your changes and push to GitHub, then deploy: +You must deploy a pipeline manually once\. After that, the pipeline keeps itself up to date from the source code repository\. So be sure that the code in the repo is the code you want deployed\. Check in your changes and push to GitHub, then deploy: ``` git add --all @@ -413,17 +426,17 @@ cdk deploy ``` **Tip** -Now that you've done the initial deployment, your local AWS account no longer needs administrative access, because all changes to your app will be deployed via the pipeline\. All you need to be able to do is push to GitHub\. +Now that you've done the initial deployment, your local AWS account no longer needs administrative access\. This is because all changes to your app will be deployed via the pipeline\. All you need to be able to do is push to GitHub\. ## Application stages -To define a multi\-stack AWS application that can be added to the pipeline all at once, define a subclass of `[Stage](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stage.html)` \(not to be confused with `CdkStage` in the CDK Pipelines module\)\. +To define a multi\-stack AWS application that can be added to the pipeline all at once, define a subclass of `[Stage](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stage.html)`\. \(This is different from `CdkStage` in the CDK Pipelines module\.\) The stage contains the stacks that make up your application\. If there are dependencies between the stacks, the stacks are automatically added to the pipeline in the right order\. Stacks that don't depend on each other are deployed in parallel\. You can add a dependency relationship between stacks by calling `stack1.addDependency(stack2)`\. Stages accept a default `env` argument, which becomes the default environment for the stacks inside it\. \(Stacks can still have their own environment specified\.\)\. -An application is added to the pipeline by calling `[addStage](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.CodePipeline.html#addwbrstagestage-optionss)()` with instances of [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stage.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stage.html)\. A stage can be instantiated and added to the pipeline multiple times to define different stages of your DTAP or multi\-region application pipeline: +An application is added to the pipeline by calling `[addStage](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.CodePipeline.html#addwbrstagestage-optionss)()` with instances of [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stage.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stage.html)\. A stage can be instantiated and added to the pipeline multiple times to define different stages of your DTAP or multi\-Region application pipeline\. We will create a stack containing a simple Lambda function and place that stack in a stage\. Then we will add the stage to the pipeline so it can be deployed\. @@ -882,7 +895,7 @@ testingStage.AddPost(new ManualApprovalStep("approval")); ------ -You can add stages to a [Wave](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.Wave.html) to deploy them in parallel, for example when deploying a stage to multiple accounts or regions\. +You can add stages to a [Wave](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.Wave.html) to deploy them in parallel, for example when deploying a stage to multiple accounts or Regions\. ------ #### [ TypeScript ] @@ -966,7 +979,9 @@ wave.AddStage(new MyPipelineAppStage(this, "MyAppUS", new StageProps ## Testing deployments -You can add steps to a CDK Pipeline to validate the deployments you are performing\. Using the CDK Pipeline library's `[ShellStep](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.ShellStep.html)`, you can try to access a just\-deployed Amazon API Gateway backed by a Lambda function, for example, or issue an AWS CLI command to check some setting of a deployed resource\. +You can add steps to a CDK Pipeline to validate the deployments that you're performing\. For example, you can use the CDK Pipeline library's `[ShellStep](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.ShellStep.html)` to perform tasks such as the following: ++ Trying to access a newly deployed Amazon API Gateway backed by a Lambda function ++ Checking a setting of a deployed resource by issuing an AWS CLI command In its simplest form, adding validation actions looks like this: @@ -1028,9 +1043,9 @@ stage.AddPost(new ShellStep("validate", new ShellStepProps ------ -Because many AWS CloudFormation deployments result in the generation of resources with unpredictable names, CDK Pipelines provide a way to read AWS CloudFormation outputs after a deployment\. This makes it possible to pass \(for example\) the generated URL of a load balancer to a test action\. +Many AWS CloudFormation deployments result in the generation of resources with unpredictable names\. Because of this, CDK Pipelines provide a way to read AWS CloudFormation outputs after a deployment\. This makes it possible to pass \(for example\) the generated URL of a load balancer to a test action\. -To use outputs, expose the `CfnOutput` object you're interested in and pass it in a step's `envFromCfnOutputs` property to make it available as an environment variable within that step\. +To use outputs, expose the `CfnOutput` object you're interested in\. Then, pass it in a step's `envFromCfnOutputs` property to make it available as an environment variable within that step\. ------ #### [ TypeScript ] @@ -1119,7 +1134,7 @@ stage.AddPost(new ShellStep("lbaddr", new ShellStepProps You can write simple validation tests right in the `ShellStep`, but this approach becomes unwieldy when the test is more than a few lines\. For more complex tests, you can bring additional files \(such as complete shell scripts, or programs in other languages\) into the `ShellStep` via the `inputs` property\. The inputs can be any step that has an output, including a source \(such as a GitHub repo\) or another `ShellStep`\. -Bringing in files from the source repository is appropriate if the files are directly usable in the test \(for example, if they are themselves executable\)\. In this example, we declare our GitHub repo as `source` \(rather than instantiating it inline as part of the `CodePipeline`\), then pass this fileset to both the pipeline and the validation test\. +Bringing in files from the source repository is appropriate if the files are directly usable in the test \(for example, if they are themselves executable\)\. In this example, we declare our GitHub repo as `source` \(rather than instantiating it inline as part of the `CodePipeline`\)\. Then, we pass this fileset to both the pipeline and the validation test\. ------ #### [ TypeScript ] @@ -1391,12 +1406,14 @@ stage.AddPost(new ShellStep("validate", new ShellStepProps ## Security notes -Any form of continuous delivery has inherent security risks\. Under the AWS [Shared Responsibility Model](https://aws.amazon.com/compliance/shared-responsibility-model/), you are responsible for the security of your information in the AWS cloud\. The CDK Pipelines library gives you a head start by incorporating secure defaults and modeling best practices, but by its very nature a library that needs a high level of access to fulfill its intended purpose cannot assure complete security\. There are many attack vectors outside of AWS and your organization\. +Any form of continuous delivery has inherent security risks\. Under the AWS [Shared Responsibility Model](https://aws.amazon.com/compliance/shared-responsibility-model/), you are responsible for the security of your information in the AWS Cloud\. The CDK Pipelines library gives you a head start by incorporating secure defaults and modeling best practices\. + +However, by its very nature, a library that needs a high level of access to fulfill its intended purpose cannot assure complete security\. There are many attack vectors outside of AWS and your organization\. -In particular, keep in mind the following\. -+ Be mindful of the software you depend on\. Vet all third\-party software you run in your pipeline, as it has the ability to change the infrastructure that gets deployed\. -+ Use dependency locking to prevent accidental upgrades\. CDK Pipelines respects `package-lock.json` and `yarn.lock` to ensure your dependencies are the ones you expect\. -+ Credentials for production environments should be short\-lived\. After bootstrapping and initial provisioning, there is no need for developers to have account credentials at all; changes can be deployed through the pipeline\. Eliminate the possibility of credentials leaking by not needing them in the first place\! +In particular, keep in mind the following: ++ Be mindful of the software you depend on\. Vet all third\-party software you run in your pipeline, because it can change the infrastructure that gets deployed\. ++ Use dependency locking to prevent accidental upgrades\. CDK Pipelines respects `package-lock.json` and `yarn.lock` to make sure that your dependencies are the ones you expect\. ++ Credentials for production environments should be short\-lived\. After bootstrapping and initial provisioning, there is no need for developers to have account credentials at all\. Changes can be deployed through the pipeline\. Reduce the possibility of credentials leaking by not needing them in the first place\. ## Troubleshooting diff --git a/v2/cfn_layer.md b/v2/cfn_layer.md index 3d583e5a..f6fd6747 100644 --- a/v2/cfn_layer.md +++ b/v2/cfn_layer.md @@ -2,17 +2,19 @@ The AWS CDK lets you describe AWS resources using constructs that operate at varying levels of abstraction\. + *Layer 1 \(L1\)* constructs directly represent AWS CloudFormation resources as defined by the CloudFormation specification\. These constructs can be identified via a name beginning with "Cfn," so they are also referred to as "Cfn constructs\." If a resource exists in AWS CloudFormation, it exists in the CDK as a L1 construct\. -+ *Layer 2 \(L2\)* or "curated" constructs are thoughtfully developed to provide a more ergonomic developer experience compared to the L1 construct they're built upon\. In a typical CDK app, L2 constructs are usually the most widely used type\. Often, L2 constructs define additional supporting resources, such as IAM policies, Amazon SNS topics, or AWS KMS keys\. L2 constructs provide sensible defaults, best\-practice security policies, and a more ergonomic developer experience\. -+ *Layer 3 \(L3\)* constructs or *patterns* define entire collections of AWS resources for specific use cases, making it easy to stand up a build pipeline, an Amazon ECS application, or one of many other types of common deployment scenarios\. Because they can constitute complete system designs, or substantial parts of a larger system, L3 constructs are often "opinionated"—they are built around a very particular approach toward solving the problem at hand, and things work out best when you follow their lead\. ++ *Layer 2 \(L2\)* or "curated" constructs are thoughtfully developed to provide a more ergonomic developer experience compared to the L1 construct they're built upon\. In a typical CDK app, L2 constructs are usually the most widely used type\. Often, L2 constructs define additional supporting resources, such as IAM policies, Amazon SNS topics, or AWS KMS keys\. L2 constructs provide sensible defaults, best practice security policies, and a more ergonomic developer experience\. ++ *Layer 3 \(L3\)* constructs or *patterns* define entire collections of AWS resources for specific use cases\. L3 constructs help to stand up a build pipeline, an Amazon ECS application, or one of many other types of common deployment scenarios\. Because they can constitute complete system designs, or substantial parts of a larger system, L3 constructs are often "opinionated\." They are built around a particular approach toward solving the problem at hand, and things work out better when you follow their lead\. **Tip** -For more details on AWS CDK constructs, see [Constructs](constructs.md)\. +For more details about AWS CDK constructs, see [Constructs](constructs.md)\. -At the highest level, your AWS CDK application and the stacks in it are themselves abstractions of your entire cloud infrastructure, or significant chunks of it, and may be parameterized to deploy them in different environments or for different needs\. +At the highest level, your AWS CDK application and the stacks in it are themselves abstractions of your entire cloud infrastructure, or significant chunks of it\. They can be parameterized to deploy them in different environments or for different needs\. Abstractions are powerful tools for designing and implementing cloud applications\. The AWS CDK gives you the power not only to build with its abstractions, but also to create new abstractions\. Using the existing open\-source L2 and L3 constructs as guidance, you can build your own L2 and L3 constructs to reflect your own organization's best practices and opinions\. -No abstraction is perfect, and even good abstractions cannot cover every possible use case\. While the value of the AWS CDK's model is plain, sometimes you'll come upon a construct that's perfect for your needs—if only you could make a small \(or large\) tweak\. For this reason, the AWS CDK provides ways to "break out" of the construct model, moving to a lower level of abstraction or to a different model entirely\. As their name implies, the CDK's *escape hatches* let you "escape" the AWS CDK paradigm and extend it in ways the AWS CDK designers never anticipated\. Then you can wrap all that in a new construct to hide the underlying complexity and provide a clean API for developers\. +No abstraction is perfect, and even good abstractions cannot cover every possible use case\. Although the value of the AWS CDK's model is plain, you might sometimes find a construct that almost fits your needs, lacking only a small \(or large\) tweak\. + +For this reason, the AWS CDK provides ways to "break out" of the construct model\. This lets you move to a lower level of abstraction or to a different model entirely\. As their name implies, the CDK's *escape hatches* let you "escape" the AWS CDK paradigm and extend it in ways the AWS CDK designers didn't anticipate\. Then you can wrap all that in a new construct to hide the underlying complexity and provide a clean API for developers\. Some situations in which you'll reach for escape hatches include: + An AWS service feature is available through AWS CloudFormation, but there are no L2 constructs for it\. @@ -23,7 +25,7 @@ To determine whether a feature is available through AWS CloudFormation, see [AWS ## Using AWS CloudFormation constructs directly -If there are no L2 classes available for the service, you can fall back to the automatically generated L1 constructss, which map 1:1 onto all available AWS CloudFormation resources and properties\. These resources can be recognized by their name starting with `Cfn`, such as `CfnBucket` or `CfnRole`\. You instantiate them exactly as you would use the equivalent AWS CloudFormation resource\. For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. +If there are no L2 classes available for the service, you can fall back to the automatically generated L1 constructs\. These map 1:1 to all available AWS CloudFormation resources and properties\. These resources can be recognized by their name starting with `Cfn`, such as `CfnBucket` or `CfnRole`\. You instantiate them exactly as you would use the equivalent AWS CloudFormation resource\. For more information, see [AWS Resource and Property Types Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)\. For example, to instantiate a low\-level Amazon S3 bucket L1 with analytics enabled, you would write something like the following\. @@ -93,7 +95,7 @@ new CfnBucket(this, 'MyBucket', new CfnBucketProps { ------ -In the rare case where you want to define a resource that doesn't have a corresponding `CfnXxx` class, such as a new resource type that hasn't yet been published in the AWS CloudFormation resource specification, you can instantiate the `cdk.CfnResource` directly and specify the resource type and properties\. This is shown in the following example\. +There might be rare cases where you want to define a resource that doesn't have a corresponding `CfnXxx` class\. This could be a new resource type that hasn't yet been published in the AWS CloudFormation resource specification\. In cases like this, you can instantiate the `cdk.CfnResource` directly and specify the resource type and properties\. This is shown in the following example\. ------ #### [ TypeScript ] @@ -188,7 +190,7 @@ For more information, see [AWS Resource and Property Types Reference](https://do ## Modifying the AWS CloudFormation resource behind AWS constructs -If a L2 construct is missing a feature or you are trying to work around an issue, you can modify the L1 construct that is encapsulated by the L2 construct\. +If an L2 construct is missing a feature or you're trying to work around an issue, you can modify the L1 construct that's encapsulated by the L2 construct\. All L2 constructs contain within them the corresponding L1 construct\. For example, the high\-level `Bucket` construct wraps the low\-level `CfnBucket` construct\. Because the `CfnBucket` corresponds directly to the AWS CloudFormation resource, it exposes all features that are available through AWS CloudFormation\. @@ -324,7 +326,9 @@ cfnBucket.CfnOptions.Metadata = new Dictionary ## An unescape hatch -The AWS CDK also provides the capability to go *up* an abstraction level, which we might cheekily refer to as an "unescape" hatch\. If you have an L1 construct, such as `CfnBucket`, you can create a new L2 construct \(`Bucket` in this case\) to wrap the L1 construct\. This is convenient when you have created an L1 resource but want to use it with a construct that requires an L2 resource, or want to use convenience methods like `.grantXxxxx()` that aren't available on the L1 construct\. +The AWS CDK also provides the capability to go *up* an abstraction level, which we might cheekily refer to as an "unescape" hatch\. If you have an L1 construct, such as `CfnBucket`, you can create a new L2 construct \(`Bucket` in this case\) to wrap the L1 construct\. + +This is convenient when you create an L1 resource but want to use it with a construct that requires an L2 resource\. It's also helpful when you want to use convenience methods like `.grantXxxxx()` that aren't available on the L1 construct\. You move to the higher abstraction level using a static method on the L2 class called `.fromCfnXxxxx()`—for example, `Bucket.fromCfnBucket()` for Amazon S3 buckets\. The L1 resource is the only parameter\. @@ -496,11 +500,11 @@ cfnBucket.AddPropertyDeletionOverride("Tags.0"); ## Custom resources -If the feature isn't available through AWS CloudFormation, but only through a direct API call, the only solution is to write an AWS CloudFormation Custom Resource to make the API call you need\. Don't worry, the AWS CDK makes it easier to write these, and wrap them up into a regular construct interface, so from another user's perspective the feature feels native\. +If the feature isn't available through AWS CloudFormation, but only through a direct API call, there's only one solution\. You must write an AWS CloudFormation Custom Resource to make the API call you need\. Don't worry, the AWS CDK makes it easier to write these and wrap them up into a regular construct interface\. From the perspective of a consumer of your construct, the feature feels native\. -Building a custom resource involves writing a Lambda function that responds to a resource's CREATE, UPDATE and DELETE lifecycle events\. If your custom resource needs to make only a single API call, consider using the [AwsCustomResource](https://github.com/awslabs/aws-cdk/tree/master/packages/%40aws-cdk/custom-resources)\. This makes it possible to perform arbitrary SDK calls during an AWS CloudFormation deployment\. Otherwise, you should write your own Lambda function to perform the work you need to get done\. +Building a custom resource involves writing a Lambda function that responds to a resource's `CREATE`, `UPDATE`, and `DELETE` lifecycle events\. If your custom resource needs to make only a single API call, consider using the [AwsCustomResource](https://github.com/awslabs/aws-cdk/tree/master/packages/%40aws-cdk/custom-resources)\. This makes it possible to perform arbitrary SDK calls during an AWS CloudFormation deployment\. Otherwise, you should write your own Lambda function to perform the work you need to get done\. -The subject is too broad to completely cover here, but the following links should get you started: +The subject is too broad to cover completely here, but the following links should get you started: + [Custom Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) + [Custom\-Resource Example](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/) + For a more fully fledged example, see the [DnsValidatedCertificate](https://github.com/awslabs/aws-cdk/blob/master/packages/@aws-cdk/aws-certificatemanager/lib/dns-validated-certificate.ts) class in the CDK standard library\. This is implemented as a custom resource\. \ No newline at end of file diff --git a/v2/cli.md b/v2/cli.md index 43d15172..4ee77719 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -10,7 +10,7 @@ npm install -g aws-cdk@X.YY.Z # install specific version ``` **Tip** -If you regularly work with multiple versions of the AWS CDK, you may want to install a matching version of the AWS CDK Toolkit in individual CDK projects\. To do this, omit `-g` from the `npm install` command\. Then use `npx aws-cdk` to invoke it; this will run the local version if one exists, falling back to a global version if not\. +If you regularly work with multiple versions of the AWS CDK, consider installing a matching version of the AWS CDK Toolkit in individual CDK projects\. To do this, omit `-g` from the `npm install` command\. Then use `npx aws-cdk` to invoke it\. This runs the local version if one exists, falling back to a global version if not\. ## Toolkit commands @@ -20,24 +20,24 @@ All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(` | Command | Function | | --- | --- | | `cdk list` \(`ls`\) | Lists the stacks in the app | -| `cdk synthesize` \(`synth`\) | Synthesizes and prints the CloudFormation template for the specified stack\(s\) | +| `cdk synthesize` \(`synth`\) | Synthesizes and prints the CloudFormation template for one or more specified stacks | | `cdk bootstrap` | Deploys the CDK Toolkit staging stack; see [Bootstrapping](bootstrapping.md) | -| `cdk deploy` | Deploys the specified stack\(s\) | -| `cdk destroy` | Destroys the specified stack\(s\) | -| `cdk diff` | Compares the specified stack and its dependencies with the deployed stack\(s\) or a local CloudFormation template | +| `cdk deploy` | Deploys one or more specified stacks | +| `cdk destroy` | Destroys one or more specified stacks | +| `cdk diff` | Compares the specified stack and its dependencies with the deployed stacks or a local CloudFormation template | | `cdk metadata` | Displays metadata about the specified stack | | `cdk init` | Creates a new CDK project in the current directory from a specified template | | `cdk context` | Manages cached context values | -| `cdk docs` \(`doc`\) | Opens the CDK API reference in your browser | +| `cdk docs` \(`doc`\) | Opens the CDK API Reference in your browser | | `cdk doctor` | Checks your CDK project for potential problems | For the options available for each command, see [Toolkit reference](#cli-ref) or [Built\-in help](#cli-help)\. ## Specifying options and their values -Command line options begin with two hyphens \(`--`\)\. Some frequently\-used options have single\-letter synonyms that begin with a single hyphen \(for example, `--app` has a synonym `-a`\)\. The order of options in an AWS CDK Toolkit command is not important\. +Command line options begin with two hyphens \(`--`\)\. Some frequently used options have single\-letter synonyms that begin with a single hyphen \(for example, `--app` has a synonym `-a`\)\. The order of options in an AWS CDK Toolkit command is not important\. -All options accept a value, which must follow the option name\. The value may be separated from the name by whitespace or by an equals sign `=`\. The following two options are equivalent +All options accept a value, which must follow the option name\. The value may be separated from the name by white space or by an equals sign `=`\. The following two options are equivalent\. ``` --toolkit-stack-name MyBootstrapStack @@ -82,10 +82,10 @@ Issue `cdk version` to display the version of the AWS CDK Toolkit\. Provide this ## Version reporting -To gain insight into how the AWS CDK is used, the constructs used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used by AWS to identify stacks using a construct with known security or reliability issues, and to contact their users with important information\. +To gain insight into how the AWS CDK is used, the constructs used by AWS CDK applications are collected and reported by using a resource identified as `AWS::CDK::Metadata`\. This resource is added to AWS CloudFormation templates, and can easily be reviewed\. This information can also be used by AWS to identify stacks using a construct with known security or reliability issues\. It can also be used to contact their users with important information\. **Note** -Prior to version 1\.93\.0, the AWS CDK reported the names and versions of the modules loaded during synthesis, rather than the constructs used in the stack\. +Before version 1\.93\.0, the AWS CDK reported the names and versions of the modules loaded during synthesis, instead of the constructs used in the stack\. By default, the AWS CDK reports the use of constructs in the following NPM modules that are used in the stack: + AWS CDK core module @@ -102,7 +102,7 @@ CDKMetadata: Analytics: "v2:deflate64:H4sIAND9SGAAAzXKSw5AMBAA0L1b2PdzBYnEAdio3RglglY60zQi7u6TWL/XKmNUlxeQSOKwaPTBqrNhwEWU3hGHiCzK0dWWfAxoL/Fd8mvk+QkS/0X6BdjnCdgmOOQKWz+AqqLDt2Y3YMnLYWwAAAA=" ``` -The `Analytics` property is a gzipped, base64\-encoded, prefix\-encoded list of the constructs present in the stack\. +The `Analytics` property is a gzipped, base64\-encoded, prefix\-encoded list of the constructs in the stack\. To opt out of version reporting, use one of the following methods: + Use the cdk command with the \-\-no\-version\-reporting argument to opt out for a single command\. @@ -121,32 +121,32 @@ To opt out of version reporting, use one of the following methods: } ``` -## Specifying credentials and region +## Specifying credentials and Region -The CDK Toolkit needs to know your AWS account credentials and the AWS region into which you are deploying, not only for deployment operations but also to retrieve context values during synthesis\. Together, your account and region make up the *environment*\. +The CDK Toolkit needs to know your AWS account credentials and the AWS Region that you're deploying into\. This is needed for deployment operations and to retrieve context values during synthesis\. Together, your account and Region make up the *environment*\. **Important** We strongly recommend against using your main AWS account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. -Credentials and region may be specified using environment variables or in configuration files\. These are the same variables and files used by other AWS tools such as the AWS CLI and the various AWS SDKs\. The CDK Toolkit looks for this information in the following order\. -+ The `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` environment variables\. Always specify all three variables, not just one or two\. +Credentials and Region may be specified using environment variables or in configuration files\. These are the same variables and files used by other AWS tools such as the AWS CLI and the various AWS SDKs\. The CDK Toolkit looks for this information in the following order\. ++ The `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` environment variables\. Always specify all three variables, not only one or two\. + A specific profile defined in the standard AWS `config` and `credentials` files, and specified using the `--profile` option on `cdk` commands\. + The `[default]` section of the standard AWS `config` and `credentials` files\. **Note** The standard AWS `config` and `credentials` files are located at `~/.aws/config` and `~/.aws/credentials` \(macOS/Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\)\. -The environment specified in your AWS CDK app using the stack's `env` property is used during synthesis to generate an environment\-specific AWS CloudFormation template and during deployment to override the account or region specified by one of the above methods\. For more information, see [Environments](environments.md)\. +The environment that you specify in your AWS CDK app by using the stack's `env` property is used during synthesis\. It's used to generate an environment\-specific AWS CloudFormation template, and during deployment, it overrides the account or Region specified by one of the preceding methods\. For more information, see [Environments](environments.md)\. -If you have the AWS CLI installed, the easiest way to configure your account credentials and a default region is to issue the following command: +If you have the AWS CLI installed, the easiest way to configure your account credentials and a default Region is to issue the following command: ``` aws configure ``` -Provide your AWS access key ID, secret access key, and default region when prompted\. These values are written to the `[default]` section of the `config` and `credentials` files\. +Provide your AWS access key ID, secret access key, and default Region when prompted\. These values are written to the `[default]` section of the `config` and `credentials` files\. -If you don't have the AWS CLI installed, you can manually create or edit the `config` and `credentials` files to contain default credentials and a default region, in the following format\. +If you don't have the AWS CLI installed, you can manually create or edit the `config` and `credentials` files to contain default credentials and a default Region\. Use the following format\. + In `~/.aws/config` or `%USERPROFILE%\.aws\config` ``` @@ -161,7 +161,7 @@ If you don't have the AWS CLI installed, you can manually create or edit the `co aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY ``` -Besides specifying AWS credentials and a region in the `[default]` section, you can also add one or more `[profile NAME]` sections, where *NAME* is the name of the profile\. +Besides specifying AWS credentials and a Region in the `[default]` section, you can also add one or more `[profile NAME]` sections, where *NAME* is the name of the profile\. + In `~/.aws/config` or `%USERPROFILE%\.aws\config` ``` @@ -183,21 +183,21 @@ Besides specifying AWS credentials and a region in the `[default]` section, you aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY ``` -Always add named profiles to both the `config` and `credentials` files\. The AWS CDK Toolkit does not fall back to using the region in the `[default]` section when the specified named profile is not found in the `config` file, as some other AWS tools do\. +Always add named profiles to both the `config` and `credentials` files\. The AWS CDK Toolkit doesn't fall back to using the Region in the `[default]` section when the specified named profile is not found in the `config` file\. However, some other AWS tools do\. **Important** -Do not name a profile `default`: that is, do not use a `[profile default]` section in either `config` or `credentials`\. +Do not name a profile `default`\. That is, do not use a `[profile default]` section in either `config` or `credentials`\. **Note** -Although the AWS CDK uses credentials from the same sources files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. +The AWS CDK uses credentials from the same sources files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)\. However, the AWS CDK might behave somewhat differently from these tools\. It uses the AWS SDK for JavaScript under the hood\. For complete details on setting up credentials for the AWS SDK for JavaScript, see [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html)\. You may optionally use the `--role-arn` \(or `-r`\) option to specify the ARN of an IAM role that should be used for deployment\. This role must be assumable by the AWS account being used\. ## Specifying the app command -Many features of the CDK Toolkit require one or more AWS CloudFormation templates be synthesized, which in turn requires running your application\. Since the AWS CDK supports programs written in a variety of languages, it uses a configuration option to specify the exact command necessary to run your app\. This option can be specified in two ways\. +Many features of the CDK Toolkit require one or more AWS CloudFormation templates be synthesized, which in turn requires running your application\. The AWS CDK supports programs written in a variety of languages\. Therefore, it uses a configuration option to specify the exact command necessary to run your app\. This option can be specified in two ways\. -First, and most commonly, it can be specified using the `app` key inside the file `cdk.json`, which is in the main directory of your AWS CDK project\. The CDK Toolkit provides an appropriate command when creating a new project with `cdk init`\. Here is the `cdk.json` from a fresh TypeScript project, for instance\. +First, and most commonly, it can be specified using the `app` key inside the file `cdk.json`\. This is in the main directory of your AWS CDK project\. The CDK Toolkit provides an appropriate command when creating a new project with `cdk init`\. Here is the `cdk.json` from a fresh TypeScript project, for instance\. ``` { @@ -205,11 +205,11 @@ First, and most commonly, it can be specified using the `app` key inside the fil } ``` -The CDK Toolkit looks for `cdk.json` in the current working directory when attempting to run your app, so you might keep a shell open in your project's main directory for issuing CDK Toolkit commands\. +The CDK Toolkit looks for `cdk.json` in the current working directory when attempting to run your app\. Because of this, you might keep a shell open in your project's main directory for issuing CDK Toolkit commands\. The CDK Toolkit also looks for the app key in `~/.cdk.json` \(that is, in your home directory\) if it can't find it in `./cdk.json`\. Adding the app command here can be useful if you usually work with CDK code in the same language\. -If you are in some other directory, or if you want to run your app via a command other than the one in `cdk.json`, you can use the `--app` \(or `-a`\) option to specify it\. +If you are in some other directory, or to run your app using a command other than the one in `cdk.json`, use the `--app` \(or `-a`\) option to specify it\. ``` cdk --app "npx ts-node bin/hello-cdk.ts" ls @@ -234,7 +234,7 @@ You may also use wildcards to specify IDs that match a pattern\. You may also use the \-\-all option to specify all stacks\. -If your app uses [CDK Pipelines](cdk_pipeline.md), the CDK Toolkit understands your stacks and stages as a hierarchy, and the \-\-all option and the `*` wildcard only match top\-level stacks\. To match all the stacks, use `**`\. Also use `**` to indicate all the stacks under a particular hierarchy\. +If your app uses [CDK Pipelines](cdk_pipeline.md), the CDK Toolkit understands your stacks and stages as a hierarchy\. Also, the \-\-all option and the `*` wildcard only match top\-level stacks\. To match all the stacks, use `**`\. Also use `**` to indicate all the stacks under a particular hierarchy\. When using wildcards, enclose the pattern in quotes, or escape the wildcards with `\`\. If you don't, your shell may try to expand the pattern to the names of files in the current directory\. At best, this won't do what you expect; at worst, you could deploy stacks you didn't intend to\. This isn't strictly necessary on Windows because `cmd.exe` does not expand wildcards, but is good practice nonetheless\. @@ -247,7 +247,7 @@ cdk synth 'PipelineStack/Prod/**' # All stacks in Prod stage in a CDK Pipeline ``` **Note** -The order in which you specify the stacks is not necessarily the order in which they will be processed\. The AWS CDK Toolkit takes into account dependencies between stacks when deciding the order in which to process them\. For example, if one stack uses a value produced by another \(such as the ARN of a resource defined in the second stack\), the second stack is synthesized before the first one because of this dependency\. You can add dependencies between stacks manually using the stack's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#addwbrdependencytarget-reason](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#addwbrdependencytarget-reason) method\. +The order in which you specify the stacks is not necessarily the order in which they will be processed\. The AWS CDK Toolkit accounts for dependencies between stacks when deciding the order in which to process them\. For example, let's say that one stack uses a value produced by another \(such as the ARN of a resource defined in the second stack\)\. In this case, the second stack is synthesized before the first one because of this dependency\. You can add dependencies between stacks manually using the stack's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#addwbrdependencytarget-reason](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#addwbrdependencytarget-reason) method\. ## Bootstrapping your AWS environment @@ -257,9 +257,9 @@ Deploying stacks with the CDK requires special dedicated AWS CDK resources to be cdk bootstrap ``` -If issued with no arguments, as shown here, the `cdk bootstrap` command synthesizes the current app and bootstraps the environments its stacks will be deployed to\. If the app contains environment\-agnostic stacks, which do not explicitly specify an environment so they can be deployed anywhere, the default account and region are bootstrapped, or the environment specified using `--profile`\. +If issued with no arguments, as shown here, the `cdk bootstrap` command synthesizes the current app and bootstraps the environments its stacks will be deployed to\. If the app contains environment\-agnostic stacks, which don't explicitly specify an environment, the default account and Region are bootstrapped, or the environment specified using `--profile`\. -Outside of an app, you must explicitly specify the environment to be bootstrapped\. You may also do so to bootstrap an environment that's not specified in your app or local AWS profile\. Credentials must be configured \(e\.g\. in `~/.aws/credentials`\) for the specified account and region\. You may specify a profile that contains the required credentials\. +Outside of an app, you must explicitly specify the environment to be bootstrapped\. You may also do so to bootstrap an environment that's not specified in your app or local AWS profile\. Credentials must be configured \(e\.g\. in `~/.aws/credentials`\) for the specified account and Region\. You may specify a profile that contains the required credentials\. ``` cdk bootstrap ACCOUNT-NUMBER/REGION # e.g. @@ -270,16 +270,16 @@ cdk bootstrap --profile test 1111111111/us-east-1 **Important** Each environment \(account/region combination\) to which you deploy such a stack must be bootstrapped separately\. -You may incur AWS charges for what the AWS CDK stores in the bootstrapped resources\. Additionally, if you use `-bootstrap-customer-key`, a Customer Master Key \(CMK\) will be created, which also incurs charges per environment\. +You may incur AWS charges for what the AWS CDK stores in the bootstrapped resources\. Additionally, if you use `-bootstrap-customer-key`, an AWS KMS key will be created, which also incurs charges per environment\. **Note** -Older versions of the bootstrap template created a Customer Master Key by default\. To avoid charges, re\-bootstrap using `--no-bootstrap-customer-key`\. +Earlier versions of the bootstrap template created a KMS key by default\. To avoid charges, re\-bootstrap using `--no-bootstrap-customer-key`\. **Note** CDK Toolkit v2 does not support the original bootstrap template, dubbed the legacy template, used by default with CDK v1\. **Important** -The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. +The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list\. By default, this extends permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts that you are comfortable with\. ## Creating a new app @@ -321,11 +321,11 @@ cdk list cdk ls ``` -If your application contains [CDK Pipelines](cdk_pipeline.md) stacks, the CDK Toolkit displays stack names as paths according to their location in the pipeline hierarchy \(e\.g\., `PipelineStack`, `PipelineStack/Prod`, `PipelineStack/Prod/MyService`, etc\)\. +If your application contains [CDK Pipelines](cdk_pipeline.md) stacks, the CDK Toolkit displays stack names as paths according to their location in the pipeline hierarchy\. \(For example, `PipelineStack`, `PipelineStack/Prod`, and `PipelineStack/Prod/MyService`\.\) -If your app contains many stacks, you can specify full or partial stack IDs of the stacks to be listed; see [Specifying stacks](#cli-stacks)\. +If your app contains many stacks, you can specify full or partial stack IDs of the stacks to be listed\. For more information, see [Specifying stacks](#cli-stacks)\. -Add the `--long` flag to see more information about the stacks, including the stack names and their environments \(AWS account and region\)\. +Add the `--long` flag to see more information about the stacks, including the stack names and their environments \(AWS account and Region\)\. ## Synthesizing stacks @@ -339,11 +339,11 @@ cdk synth "*" # all stacks in app ``` **Note** -The CDK Toolkit actually runs your app and synthesizes fresh templates before most operations \(e\.g\. when deploying or comparing stacks\)\. These templates are stored by default in the `cdk.out` directory\. The `cdk synth` command simply prints the generated templates for the specified stack\(s\)\. +The CDK Toolkit actually runs your app and synthesizes fresh templates before most operations \(such as when deploying or comparing stacks\)\. These templates are stored by default in the `cdk.out` directory\. The `cdk synth` command simply prints the generated templates for one or more specified stacks\. -See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. +See `cdk synth --help` for all available options\. A few of the most frequently used options are covered in the following section\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -355,14 +355,14 @@ cdk synth --context key=value MyStack cdk synth --context key1=value1 --context key2=value2 MyStack ``` -When deploying multiple stacks, the specified context values are normally passed to all of them\. If you wish, you may specify different values for each stack by prefixing the stack name to the context value\. +When deploying multiple stacks, the specified context values are normally passed to all of them\. If you want, you can specify different values for each stack by prefixing the stack name to the context value\. ``` # different context values for each stack cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -370,7 +370,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -380,7 +380,7 @@ cdk synth --output=~/templates ## Deploying stacks -The `cdk deploy` subcommand deploys the specified stack\(s\) to your AWS account\. +The `cdk deploy` subcommand deploys one or more specified stacks to your AWS account\. ``` cdk deploy # if app contains only one stack @@ -392,11 +392,11 @@ cdk deploy "*" # all stacks in app **Note** The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates before deploying anything\. Therefore, most command line options you can use with `cdk synth` \(for example, `--context`\) can also be used with `cdk deploy`\. -See `cdk deploy --help` for all available options\. A few of the most useful options are covered below\. +See `cdk deploy --help` for all available options\. A few of the most useful options are covered in the following section\. ### Skipping synthesis -The cdk deploy command normally synthesizes your app's stacks before deploying to make sure the deployment reflects the latest version of your app\. If you know that you haven't made any changes to your code since your last cdk synth, you may suppress the redundant synthesis step when deploying\. Simply specify your project's `cdk.out` directory in the \-\-app option\. +The cdk deploy command normally synthesizes your app's stacks before deploying to make sure that the deployment reflects the latest version of your app\. If you know that you haven't changed your code since your last cdk synth, you can suppress the redundant synthesis step when deploying\. To do so, specify your project's `cdk.out` directory in the \-\-app option\. ``` cdk deploy --app cdk.out StackOne StackTwo @@ -404,15 +404,15 @@ cdk deploy --app cdk.out StackOne StackTwo ### Disabling rollback -One of AWS CloudFormation's marquee features is its ability to roll back changes so that deployments are atomic—they either succeed or fail as a whole\. The AWS CDK inherits this capability because it synthesizes and deploys AWS CloudFormation templates\. +AWS CloudFormation has the ability to roll back changes so that deployments are atomic\. This means that they either succeed or fail as a whole\. The AWS CDK inherits this capability because it synthesizes and deploys AWS CloudFormation templates\. -Rollback makes sure your resources are in a consistent state at all times, which is vital for production stacks\. However, while you're still developing your infrastructure, some failures are inevitable, and rolling back failed deployments just slows you down\. +Rollback makes sure that your resources are in a consistent state at all times, which is vital for production stacks\. However, while you're still developing your infrastructure, some failures are inevitable, and rolling back failed deployments can slow you down\. -For this reason, the CDK Toolkit allows you to disable rollback by adding `--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. +For this reason, the CDK Toolkit lets you disable rollback by adding `--no-rollback` to your `cdk deploy` command\. With this flag, failed deployments are not rolled back\. Instead, resources deployed before the failed resource remain in place, and the next deployment starts with the failed resource\. You'll spend a lot less time waiting for deployments and a lot more time developing your infrastructure\. ### Hot swapping -Use the `--hotswap` flag with `cdk deploy` to attempt to update your AWS resources directly instead of generating a AWS CloudFormation changeset and deploying it\. Deployment falls back to AWS CloudFormation deployment if hot swapping is not possible\. +Use the `--hotswap` flag with `cdk deploy` to attempt to update your AWS resources directly instead of generating an AWS CloudFormation changeset and deploying it\. Deployment falls back to AWS CloudFormation deployment if hot swapping is not possible\. Currently hot swapping supports Lambda functions, Step Functions state machines, and Amazon ECS container images\. The `--hotswap` flag also disables rollback \(i\.e\., implies `--no-rollback`\)\. @@ -421,11 +421,11 @@ Hot\-swapping is not recommended for production deployments\. ### Watch mode -The CDK Toolkit's watch mode \( cdk deploy \-\-watch, or cdk watch for short\) continuously monitors your CDK app's source files and assets for changes and immediately performs a deployment of the specified stacks when a change is detected\. +The CDK Toolkit's watch mode \( cdk deploy \-\-watch, or cdk watch for short\) continuously monitors your CDK app's source files and assets for changes\. It immediately performs a deployment of the specified stacks when a change is detected\. -By default, these deployments use the `--hotswap` flag, which fast\-tracks deployment of changes to Lambda functions, and falls back to deploying through AWS CloudFormation if you have changed infrastructure configuration\. To have `cdk watch` always perform full AWS CloudFormation deployments, add the `--no-hotswap` flag to `cdk watch`\. +By default, these deployments use the `--hotswap` flag, which fast\-tracks deployment of changes to Lambda functions\. It also falls back to deploying through AWS CloudFormation if you have changed infrastructure configuration\. To have `cdk watch` always perform full AWS CloudFormation deployments, add the `--no-hotswap` flag to `cdk watch`\. -Any changes made while `cdk watch` is already performing a deployment will be combined into a single deployment, which will begin as soon as the in\-progress deployment is complete\. +Any changes made while `cdk watch` is already performing a deployment are combined into a single deployment, which begins as soon as the in\-progress deployment is complete\. Watch mode uses the `"watch"` key in the project's `cdk.json` to determine which files to monitor\. By default, these files are your application files and assets, but this can be changed by modifying the `"include"` and `"exclude"` entries in the `"watch"` key\. The following `cdk.json` file shows an example of these entries\. @@ -439,14 +439,14 @@ Watch mode uses the `"watch"` key in the project's `cdk.json` to determine which } ``` -`cdk watch` executes the `"build"` command from `cdk.json` to build your app before synthesis\. If your deployment requires any commands to build or package your Lambda code \(or anything else that's not in your CDK app proper\), add it here\. +`cdk watch` executes the `"build"` command from `cdk.json` to build your app before synthesis\. If your deployment requires any commands to build or package your Lambda code \(or anything else that's not in your CDK app\), add it here\. Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"build"` keys\. Each path is interpreted relative to the parent directory of `cdk.json`\. The default value of `include` is `**/*`, meaning all files and directories in the project root directory\. `exclude` is optional\. **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -460,7 +460,7 @@ To define multiple parameters, use multiple `--parameters` flags\. cdk deploy MyStack --parameters uploadBucketName=UpBucket --parameters downloadBucketName=DownBucket ``` -If you are deploying multiple stacks, you can specify a different value of each parameter for each stack by prefixing the name of the parameter with the stack name and a colon\. Otherwise, the same value is passed to all stacks\. +If you are deploying multiple stacks, you can specify a different value of each parameter for each stack\. To do so, prefix the name of the parameter with the stack name and a colon\. Otherwise, the same value is passed to all stacks\. ``` cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket --parameters YourStack:uploadBucketName=UpBucket @@ -468,7 +468,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -504,7 +504,7 @@ The setting can also be configured in the `cdk.json` file\. ## Comparing stacks -The `cdk diff` command compares the current version of a stack \(and its dependencies\) defined in your app with the already\-deployed version\(s\), or with a saved AWS CloudFormation template, and displays a list of changes\. +The `cdk diff` command compares the current version of a stack \(and its dependencies\) defined in your app with the already\-deployed versions, or with a saved AWS CloudFormation template, and displays a list of changes\. ``` Stack HelloCdkStack @@ -549,13 +549,13 @@ Resources └─ [+] Delete ``` -To compare your app's stack\(s\) with the existing deployment: +To compare your app's stacks with the existing deployment: ``` cdk diff MyStack ``` -To compare your app's stack\(s\) with a saved CloudFormation template: +To compare your app's stacks with a saved CloudFormation template: ``` cdk diff --template ~/stacks/MyStack.old MyStack @@ -563,7 +563,7 @@ cdk diff --template ~/stacks/MyStack.old MyStack ## Configuration \(`cdk.json`\) -Default values for many CDK Toolkit command\-line flags may be stored in a project's `cdk.json` file or in the `.cdk.json` file in your user directory\. Below is an alphabetical reference to the supported configuration settings\. +Default values for many CDK Toolkit command line flags can be stored in a project's `cdk.json` file or in the `.cdk.json` file in your user directory\. Following is an alphabetical reference to the supported configuration settings\. | Key | Notes | CDK Toolkit option | @@ -582,7 +582,7 @@ Default values for many CDK Toolkit command\-line flags may be stored in a proje | outputsFile | The file to which AWS CloudFormation outputs from deployed stacks will be written \(in JSON format\)\. | \-\-outputs\-file | | pathMetadata | If false, CDK path metadata is not added to synthesized templates\. | \-\-no\-path\-metadata | | plugin | JSON array specifying the package names or local paths of packages that extend the CDK | \-\-plugin | -| profile | Name of the default AWS profile used for specifying region and account credentials\. | \-\-profile | +| profile | Name of the default AWS profile used for specifying Region and account credentials\. | \-\-profile | | progress | If set to "events", the CDK Toolkit displays all AWS CloudFormation events during deployment, rather than a progress bar\. | \-\-progress | | requireApproval | Default approval level for security changes\. See [Security\-related changes](#cli-security) | \-\-require\-approval | | rollback | If false, failed deployments are not rolled back\. | \-\-no\-rollback | @@ -595,7 +595,7 @@ Default values for many CDK Toolkit command\-line flags may be stored in a proje ## Toolkit reference -This section provides a reference for the AWS CDK Toolkit derived from its help, first a general reference with the options available with all commands, then \(in collapsible sections\) specific references with options available only with specific subcommands\. +This section provides a reference for the AWS CDK Toolkit derived from its help\. First there's a general reference with the options available with all commands\. Then \(in collapsible sections\), you can find specific references with options that are available only with specific subcommands\. ``` Usage: cdk -a COMMAND @@ -725,7 +725,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -738,7 +738,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -759,7 +759,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -839,7 +839,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -917,7 +917,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -936,7 +936,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -962,7 +962,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -984,7 +984,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/constructs.md b/v2/constructs.md index 48de7dff..b49c9bcb 100644 --- a/v2/constructs.md +++ b/v2/constructs.md @@ -3,9 +3,9 @@ Constructs are the basic building blocks of AWS CDK apps\. A construct represents a "cloud component" and encapsulates everything AWS CloudFormation needs to create the component\. **Note** -Constructs are part of the Construct Programming Model \(CPM\) and are also used by other tools such as CDK for Terraform \(CDKtf\), CDK for Kubernetes \(CDK8s\), and Projen\. +Constructs are part of the Construct Programming Model \(CPM\)\. They're also used by other tools such as CDK for Terraform \(CDKtf\), CDK for Kubernetes \(CDK8s\), and Projen\. -A construct can represent a single AWS resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket, or it can be a higher\-level abstraction consisting of multiple related AWS resources\. Examples of such components include a worker queue with its associated compute capacity, or a scheduled job with monitoring resources and a dashboard\. +A construct can represent a single AWS resource, such as an Amazon Simple Storage Service \(Amazon S3\) bucket\. A construct can also be a higher\-level abstraction consisting of multiple related AWS resources\. Examples of such components include a worker queue with its associated compute capacity, or a scheduled job with monitoring resources and a dashboard\. The AWS CDK includes a collection of constructs called the AWS Construct Library, containing constructs for every AWS service\. [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) is a resource to help you discover additional constructs from AWS, third parties, and the open\-source CDK community\. @@ -18,28 +18,35 @@ The AWS CDK includes the [AWS Construct Library](https://docs.aws.amazon.com/cdk This library includes constructs that represent all the resources available on AWS\. For example, the `[s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html)` class represents an Amazon S3 bucket, and the `[dynamodb\.Table](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_dynamodb.Table.html)` class represents an Amazon DynamoDB table\. -There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or **L1**, short for "layer 1"\)\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties, which requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. +**L1 constructs** +There are three different levels of constructs in this library, beginning with low\-level constructs, which we call *CFN Resources* \(or **L1**, short for "layer 1"\)\. These constructs directly represent all resources available in AWS CloudFormation\. CFN Resources are periodically generated from the [AWS CloudFormation Resource Specification](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)\. They are named **Cfn***Xyz*, where *Xyz* is name of the resource\. For example, [CfnBucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.CfnBucket.html) represents the [AWS::S3::Bucket](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html) AWS CloudFormation resource\. When you use Cfn resources, you must explicitly configure all resource properties\. This requires a complete understanding of the details of the underlying AWS CloudFormation resource model\. -The next level of constructs, **L2**, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but provide the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#addwbrlifecyclewbrrulerule), which adds a lifecycle rule to the bucket\. +**L2 constructs** +The next level of constructs, **L2**, also represent AWS resources, but with a higher\-level, intent\-based API\. They provide similar functionality, but incorporate the defaults, boilerplate, and glue logic you'd be writing yourself with a CFN Resource construct\. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent\. They also provide convenience methods that make it simpler to work with the resource\. For example, the [s3\.Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) class represents an Amazon S3 bucket with additional properties and methods, such as [bucket\.addLifeCycleRule\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#addwbrlifecyclewbrrulerule), which adds a lifecycle rule to the bucket\. -Finally, the AWS Construct Library includes **L3** constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer \(ALB\)\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. +**L3 constructs** +Finally, the AWS Construct Library includes **L3** constructs, which we call *patterns*\. These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources\. For example, the [aws\-ecs\-patterns\.ApplicationLoadBalancedFargateService](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns.ApplicationLoadBalancedFargateService.html) construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer\. The [aws\-apigateway\.LambdaRestApi](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.LambdaRestApi.html) construct represents an Amazon API Gateway API that's backed by an AWS Lambda function\. For more information about how to navigate the library and discover constructs that can help you build your apps, see the [API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html)\. ## Composition -*Composition* is the key pattern for defining higher\-level abstractions through constructs\. A high\-level construct can be composed from any number of lower\-level constructs, and in turn, those could be composed from even lower\-level constructs, which eventually are composed from AWS resources\. From a bottom\-up perspective, you use constructs to organize the individual AWS resources you want to deploy using whatever abstractions are convenient for your purpose, with as many layers as you need\. +*Composition* is the key pattern for defining higher\-level abstractions through constructs\. A high\-level construct can be composed from any number of lower\-level constructs\. In turn, those could be composed from even lower\-level constructs, which eventually are composed from AWS resources\. -Composition lets you define reusable components and share them like any other code\. For example, a team can define a construct that implements the company's best practice for a DynamoDB table with backup, global replication, auto\-scaling, and monitoring, and share it with other teams in their organization, or publicly\. Teams can now use this construct as they would any other library package in their preferred programming language to define their tables and comply with their team's best practices\. When the library is updated, developers will get access to the new version's bug fixes and improvements through the workflows they already have for their other types of code\. +From a bottom\-up perspective, you use constructs to organize the individual AWS resources that you want to deploy\. You use whatever abstractions are convenient for your purpose, with as many layers as you need\. + +Composition lets you define reusable components and share them like any other code\. For example, a team can define a construct that implements the company's best practice for a DynamoDB table with backup, global replication, automatic scaling, and monitoring\. The team can share the construct with other teams in their organization, or publicly\. + +Teams can use this construct in their preferred programming language like they would use any other library package to define their tables and comply with best practices\. When the library is updated, developers will get access to the new version's bug fixes and improvements through the workflows they already have for their other types of code\. ## Initialization Constructs are implemented in classes that extend the [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) base class\. You define a construct by instantiating the class\. All constructs take three parameters when they are initialized: + **scope** — The construct's parent or owner, either a stack or another construct, which determines its place in the [construct tree](#constructs_tree)\. You should usually pass `this` \(or `self` in Python\), which represents the current object, for the scope\. -+ **id** — An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct and is used to generate unique identifiers such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. -+ **props** — A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the **props** parameter completely\. ++ **id** — An [identifier](identifiers.md) that must be unique within this scope\. The identifier serves as a namespace for everything that's defined within the current construct\. It's used to generate unique identifiers such as [resource names](resources.md#resources_physical_names) and AWS CloudFormation logical IDs\. ++ **props** — A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration\. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can omit the **props** parameter completely\. -Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once, for example for [tagging](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tag.html) or for specifying where the constructs will be deployed\. +Identifiers need only be unique within a scope\. This lets you instantiate and reuse constructs without concern for the constructs and identifiers they might contain, and enables composing constructs into higher\-level abstractions\. In addition, scopes make it possible to refer to groups of constructs all at once\. Examples include for [tagging](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tag.html), or specifying where the constructs will be deployed\. ## Apps and stacks @@ -158,9 +165,9 @@ namespace HelloCdkApp ------ -As you can see, you need a scope within which to define your bucket\. Since resources eventually need to be deployed as part of a AWS CloudFormation stack into an *AWS [environment](environments.md)*, which covers a specific AWS account and AWS region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html)\. +As you can see, you need a scope within which to define your bucket\. Resources eventually need to be deployed as part of an AWS CloudFormation stack into an *AWS [environment](environments.md)*\. The environment covers a specific AWS account and AWS Region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html)\. -Stacks in AWS CDK apps extend the **Stack** base class, as shown in the previous example\. This is a common pattern when creating a stack within your AWS CDK app: extend the **Stack** class, define a constructor that accepts **scope**, **id**, and **props**, and invoke the base class constructor via `super` with the received **scope**, **id**, and **props**, as shown in the following example\. +Stacks in AWS CDK apps extend the **Stack** base class, as shown in the previous example\. The following example is a common pattern when creating a stack within your AWS CDK app\. It shows how to extend the **Stack** class, define a constructor that accepts **scope**, **id**, and **props**, and invoke the base class constructor via `super` with the received **scope**, **id**, and **props**\. ------ #### [ TypeScript ] @@ -367,7 +374,7 @@ var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps **Important** You can't use L2 property types with L1 constructs, or vice versa\. When working with L1 constructs, always use the types defined inside the L1 construct you're using\. Do not use types from other L1 constructs \(some may have the same name, but they are not the same type\)\. -Some of our language\-specific API references currently have errors in the paths to L1 property types, or don't document these classes at all\. We hope to fix this soon\. In the meantime, just remember that such types are always inner classes of the L1 construct they are used with\. +Some of our language\-specific API references currently have errors in the paths to L1 property types, or don't document these classes at all\. We hope to fix this soon\. In the meantime, remember that such types are always inner classes of the L1 construct they are used with\. ## Using L2 constructs @@ -505,9 +512,11 @@ new Bucket(this, "MyEncryptedBucket", new BucketProps ## Interacting with constructs -Constructs are classes that extend the base [Construct](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) class\. After you instantiate a construct, the construct object exposes a set of methods and properties that enable you to interact with the construct and pass it around as a reference to other parts of the system\. The AWS CDK framework doesn't put any restrictions on the APIs of constructs; authors can define any API they wish\. However, the AWS constructs that are included with the AWS Construct Library, such as `s3.Bucket`, follow guidelines and common patterns in order to provide a consistent experience across all AWS resources\. +Constructs are classes that extend the base [Construct](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) class\. After you instantiate a construct, the construct object exposes a set of methods and properties that let you interact with the construct and pass it around as a reference to other parts of the system\. + +The AWS CDK framework doesn't put any restrictions on the APIs of constructs\. Authors can define any API they want\. However, the AWS constructs that are included with the AWS Construct Library, such as `s3.Bucket`, follow guidelines and common patterns\. This provides a consistent experience across all AWS resources\. -For example, almost all AWS constructs have a set of [grant](permissions.md#permissions_grants) methods that you can use to grant AWS Identity and Access Management \(IAM\) permissions on that construct to a principal\. The following example grants the IAM group `data-science` permission to read from the Amazon S3 bucket `raw-data`\. +Most AWS constructs have a set of [grant](permissions.md#permissions_grants) methods that you can use to grant AWS Identity and Access Management \(IAM\) permissions on that construct to a principal\. The following example grants the IAM group `data-science` permission to read from the Amazon S3 bucket `raw-data`\. ------ #### [ TypeScript ] @@ -556,7 +565,9 @@ rawData.GrantRead(dataScience); ------ -Another common pattern is for AWS constructs to set one of the resource's attributes, such as its Amazon Resource Name \(ARN\), name, or URL from data supplied elsewhere\. For example, the following code defines an AWS Lambda function and associates it with an Amazon Simple Queue Service \(Amazon SQS\) queue through the queue's URL in an environment variable\. +Another common pattern is for AWS constructs to set one of the resource's attributes from data supplied elsewhere\. Attributes can include Amazon Resource Names \(ARNs\), names, or URLs\. + +The following code defines an AWS Lambda function and associates it with an Amazon Simple Queue Service \(Amazon SQS\) queue through the queue's URL in an environment variable\. ------ #### [ TypeScript ] @@ -639,11 +650,11 @@ For information about the most common API patterns in the AWS Construct Library, ## Writing your own constructs -In addition to using existing constructs like `s3.Bucket`, you can also write your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct such as `s3.Bucket` or `sns.Topic` behaves the same as a construct from a third\-party library that someone published via NPM or Maven or PyPI—or to your company's internal package repository\. +In addition to using existing constructs like `s3.Bucket`, you can also write your own constructs, and then anyone can use them in their apps\. All constructs are equal in the AWS CDK\. An AWS CDK construct \(such as `s3.Bucket` or `sns.Topic`\) behaves the same as a construct from a third\-party library published via NPM, Maven, or PyPI\. Constructs published to your company's internal package repository also behave the same way\. To declare a new construct, create a class that extends the [Construct](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) base class, in the `constructs` package, then follow the pattern for initializer arguments\. -For example, you could declare a construct that represents an Amazon S3 bucket which sends an Amazon Simple Notification Service \(Amazon SNS\) notification every time someone uploads a file into it: +The following example shows how to declare a construct that represents an Amazon S3 bucket\. The S3 bucket sends an Amazon Simple Notification Service \(Amazon SNS\) notification every time someone uploads a file into it\. ------ #### [ TypeScript ] @@ -834,7 +845,7 @@ new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketProps ------ -Typically, you would also want to expose some properties or methods on your constructs\. For example, it's not very useful to have a topic hidden behind your construct, because it wouldn't be possible for users of your construct to subscribe to it\. Adding a `topic` property allows consumers to access the inner topic, as shown in the following example: +Typically, you would also want to expose some properties or methods on your constructs\. It's not very useful to have a topic hidden behind your construct, because users of your construct aren't able to subscribe to it\. Adding a `topic` property lets consumers access the inner topic, as shown in the following example: ------ #### [ TypeScript ] @@ -994,16 +1005,16 @@ As we've already seen, in AWS CDK apps, you define constructs "inside" other con The root of this tree is your app—that is, an instance of the `App` class\. Within the app, you instantiate one or more stacks\. Within stacks, you instantiate either AWS CloudFormation resources or higher\-level constructs, which may themselves instantiate resources or other constructs, and so on down the tree\. -Constructs are *always* explicitly defined within the scope of another construct, so there is never any doubt about the relationships between constructs\. Almost always, you should pass `this` \(in Python, `self`\) as the scope, indicating that the new construct is a child of the current construct\. The intended pattern is that you derive your construct from [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html), then instantiate the constructs it uses in its constructor\. +Constructs are *always* explicitly defined within the scope of another construct, so there is no doubt about the relationships between constructs\. Almost always, you should pass `this` \(in Python, `self`\) as the scope, indicating that the new construct is a child of the current construct\. The intended pattern is that you derive your construct from [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html), then instantiate the constructs it uses in its constructor\. Passing the scope explicitly allows each construct to add itself to the tree, with this behavior entirely contained within the [`Construct` base class](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html)\. It works the same way in every language supported by the AWS CDK and does not require introspection or other "magic\." **Important** -Technically, it's possible to pass some scope other than `this` when instantiating a construct, which allows you to add constructs anywhere in the tree, or even in another stack in the same app\. For example, you could write a mixin\-style function that adds constructs to a scope passed in as an argument\. The practical difficulty here is that you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope\. The practice also makes your code more difficult to understand, maintain, and reuse\. It is virtually always better to find a way to express your intent without resorting to abusing the `scope` argument\. +Technically, it's possible to pass some scope other than `this` when instantiating a construct\. You can add constructs anywhere in the tree, or even in another stack in the same app\. For example, you could write a mixin\-style function that adds constructs to a scope passed in as an argument\. The practical difficulty here is that you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope\. The practice also makes your code more difficult to understand, maintain, and reuse\. It is almost always better to find a way to express your intent without resorting to abusing the `scope` argument\. -The AWS CDK uses the IDs of all constructs in the path from the tree's root to each child construct to generate the unique IDs required by AWS CloudFormation\. This approach means that construct IDs need be unique only within their scope, rather than within the entire stack as in native AWS CloudFormation\. It does, however, mean that if you move a construct to a different scope, its generated stack\-unique ID will change, and AWS CloudFormation will no longer consider it the same resource\. +The AWS CDK uses the IDs of all constructs in the path from the tree's root to each child construct to generate the unique IDs required by AWS CloudFormation\. This approach means that construct IDs only need to be unique within their scope, rather than within the entire stack as in native AWS CloudFormation\. However, if you move a construct to a different scope, its generated stack\-unique ID changes, and AWS CloudFormation won't consider it the same resource\. -The construct tree is separate from the constructs you define in your AWS CDK code, but it is accessible through any construct's `node` attribute, which is a reference to the node that represents that construct in the tree\. Each node is a [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Node.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Node.html) instance, the attributes of which provide access to the tree's root and to the node's parent scopes and children\. +The construct tree is separate from the constructs that you define in your AWS CDK code\. However, it's accessible through any construct's `node` attribute, which is a reference to the node that represents that construct in the tree\. Each node is a [https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Node.html](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Node.html) instance, the attributes of which provide access to the tree's root and to the node's parent scopes and children\. + `node.children` – The direct children of the construct\. + `node.id` – The identifier of the construct within its scope\. + `node.path` – The full path of the construct including the IDs of all of its parents\. @@ -1012,6 +1023,8 @@ The construct tree is separate from the constructs you define in your AWS CDK co + `node.scopes` – All parents of the construct, up to the root\. + `node.uniqueId` – The unique alphanumeric identifier for this construct within the tree \(by default, generated from `node.path` and a hash\)\. -The construct tree defines an implicit order in which constructs are synthesized to resources in the final AWS CloudFormation template\. Where one resource must be created before another, AWS CloudFormation or the AWS Construct Library will generally infer the dependency and make sure the resources are created in the right order\. You can also add an explicit dependency between two nodes using `node.addDependency()`; see [Dependencies](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html#dependencies) in the AWS CDK API Reference\. +The construct tree defines an implicit order in which constructs are synthesized to resources in the final AWS CloudFormation template\. Where one resource must be created before another, AWS CloudFormation or the AWS Construct Library generally infers the dependency\. They then make sure that the resources are created in the right order\. + +You can also add an explicit dependency between two nodes by using `node.addDependency()`\. For more information, see [Dependencies](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html#dependencies) in the *AWS CDK API Reference*\. -The AWS CDK provides a simple way to visit every node in the construct tree and perform an operation on each one\. See [Aspects](aspects.md)\. \ No newline at end of file +The AWS CDK provides a simple way to visit every node in the construct tree and perform an operation on each one\. For more information, see [Aspects](aspects.md)\. \ No newline at end of file diff --git a/v2/context.md b/v2/context.md index f8ab0e3a..8d96edd9 100644 --- a/v2/context.md +++ b/v2/context.md @@ -2,11 +2,11 @@ Context values are key\-value pairs that can be associated with an app, stack, or construct\. They may be supplied to your app from a file \(usually either `cdk.json` or `cdk.context.json` in your project directory\) or on the command line\. -The CDK Toolkit uses context to cache values retrieved from your AWS account during synthesis, such as the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs currently available for Amazon EC2 instances\. Because these values are provided by your AWS account, they can change between runs of your CDK application, which makes them a potential source of unintended change\. The CDK Toolkit's caching behavior "freezes" these values for your CDK app until you decide to accept the new values\. +The CDK Toolkit uses context to cache values retrieved from your AWS account during synthesis\. Values include the Availability Zones in your account or the Amazon Machine Image \(AMI\) IDs currently available for Amazon EC2 instances\. Because these values are provided by your AWS account, they can change between runs of your CDK application\. This makes them a potential source of unintended change\. The CDK Toolkit's caching behavior "freezes" these values for your CDK app until you decide to accept the new values\. -Without context caching, if you had specified "latest Amazon Linux" as the AMI for your Amazon EC2 instances, and a new version of this AMI were released, then the next time you deployed your CDK stack, your already\-deployed instances would be using the outdated \("wrong"\) AMI and would therefore need to be upgraded\. Upgrading would result in replacing all your existing instances with new ones, which would probably be unexpected and undesired\. +Imagine the following scenario without context caching\. Let's say you specified "latest Amazon Linux" as the AMI for your Amazon EC2 instances, and a new version of this AMI was released\. Then, the next time you deployed your CDK stack, your already\-deployed instances would be using the outdated \("wrong"\) AMI and would need to be upgraded\. Upgrading would result in replacing all your existing instances with new ones, which would probably be unexpected and undesired\. -Instead, the CDK records your account's available AMIs in your project's `cdk.context.json` file, and uses the stored value for future synthesis operations\. This way, the list of AMIs is no longer a potential source of change, and you can be sure that your stacks will always synthesize to the same AWS CloudFormation templates\. +Instead, the CDK records your account's available AMIs in your project's `cdk.context.json` file, and uses the stored value for future synthesis operations\. This way, the list of AMIs is no longer a potential source of change\. You can also be sure that your stacks will always synthesize to the same AWS CloudFormation templates\. Not all context values are cached values from your AWS environment\. [Feature flags](featureflags.md) are also context values\. You can also create your own context values for use by your apps or constructs\. @@ -15,16 +15,16 @@ Context keys are strings\. Values may be any type supported by JSON: numbers, st **Tip** If your constructs create their own context values, incorporate your library's package name in its keys so they won't conflict with other packages' context values\. -Many context values are associated with a particular AWS environment, and a given CDK app can be deployed in more than one environment\. The key for such values includes the AWS account and region so that values from different environments do not conflict\. +Many context values are associated with a particular AWS environment, and a given CDK app can be deployed in more than one environment\. The key for such values includes the AWS account and Region so that values from different environments do not conflict\. -The context key below illustrates the format used by the AWS CDK, including the account and region\. +The following context key illustrates the format used by the AWS CDK, including the account and Region\. ``` availability-zones:account=123456789012:region=eu-central-1 ``` **Important** -Cached context values are managed by the AWS CDK and its constructs, including constructs you may write\. Do not add or change cached context values by manually editing files\. It can be useful, however, to review `cdk.context.json` occasionally to see what values are being cached\. Context values that do not represent cached values should be stored under the `context` key of `cdk.json` so they won't be cleared when cached values are cleared\. +Cached context values are managed by the AWS CDK and its constructs, including constructs you may write\. Do not add or change cached context values by manually editing files\. It can be useful, however, to review `cdk.context.json` occasionally to see what values are being cached\. Context values that don't represent cached values should be stored under the `context` key of `cdk.json`\. This way, they won't be cleared when cached values are cleared\. ## Sources of context values @@ -39,15 +39,15 @@ Context values can be provided to your AWS CDK app in six different ways: The project file `cdk.context.json` is where the AWS CDK caches context values retrieved from your AWS account\. This practice avoids unexpected changes to your deployments when, for example, a new Availability Zone is introduced\. The AWS CDK does not write context data to any of the other files listed\. **Important** -Because they are part of your application's state, `cdk.json` and `cdk.context.json` must be committed to source control along with the rest of your app's source code\. Otherwise, deployments in other environments \(for example, a CI pipeline\) may produce inconsistent results\. +Because they're part of your application's state, `cdk.json` and `cdk.context.json` must be committed to source control along with the rest of your app's source code\. Otherwise, deployments in other environments \(for example, a CI pipeline\) might produce inconsistent results\. -Context values are scoped to the construct that created them; they are visible to child constructs, but not to parents or siblings\. Context values set by the AWS CDK Toolkit \(the cdk command\), whether automatically, from a file, or from the \-\-context option, are implicitly set on the `App` construct, and so are visible to every construct in every stack in the app\. +Context values are scoped to the construct that created them; they are visible to child constructs, but not to parents or siblings\. Context values that are set by the AWS CDK Toolkit \(the cdk command\) can be set automatically, from a file, or from the \-\-context option\. Context values from these sources are implicitly set on the `App` construct\. Therefore, they're visible to every construct in every stack in the app\. -Your app can read a context value using the `construct.node.tryGetContext` method\. If the requested entry is not found on the current construct or any of its parents, the result is `undefined` \(or your language's equivalent, such as `None` in Python\)\. +Your app can read a context value using the `construct.node.tryGetContext` method\. If the requested entry isn't found on the current construct or any of its parents, the result is `undefined`\. \(Alternatively, the result could be your language's equivalent, such as `None` in Python\.\) ## Context methods -The AWS CDK supports several context methods that enable AWS CDK apps to obtain contextual information from the AWS environment\. For example, you can get a list of Availability Zones that are available in a given AWS account and region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones) method\. +The AWS CDK supports several context methods that enable AWS CDK apps to obtain contextual information from the AWS environment\. For example, you can get a list of Availability Zones that are available in a given AWS account and Region, using the [stack\.availabilityZones](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones) method\. The following are the context methods: @@ -66,7 +66,7 @@ Gets the existing Amazon Virtual Private Clouds in your accounts\. [LookupMachineImage](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.LookupMachineImage.html) Looks up a machine image for use with a NAT instance in an Amazon Virtual Private Cloud\. -If a required context value isn't available, the AWS CDK app notifies the CDK Toolkit that the context information is missing\. The CLI then queries the current AWS account for the information, stores the resulting context information in the `cdk.context.json` file, and executes the AWS CDK app again with the context values\. +If a required context value isn't available, the AWS CDK app notifies the CDK Toolkit that the context information is missing\. Next, the CLI queries the current AWS account for the information and stores the resulting context information in the `cdk.context.json` file\. Then, it executes the AWS CDK app again with the context values\. ## Viewing and managing context @@ -86,7 +86,7 @@ Context found in cdk.json: Run cdk context --reset KEY_OR_NUMBER to remove a context key. If it is a cached value, it will be refreshed on the next cdk synth. ``` -To remove a context value, run cdk context \-\-reset, specifying the value's corresponding key or number\. The following example removes the value that corresponds to the second key in the preceding example, which is the list of availability zones in the Ireland region\. +To remove a context value, run cdk context \-\-reset, specifying the value's corresponding key or number\. The following example removes the value that corresponds to the second key in the preceding example\. This value represents the list of Availability Zones in the Europe \(Ireland\) Region\. ``` cdk context --reset 2 @@ -98,7 +98,7 @@ availability-zones:account=123456789012:region=eu-west-1 reset. It will be refreshed on the next SDK synthesis run. ``` -Therefore, if you want to update to the latest version of the Amazon Linux AMI, you can use the preceding example to do a controlled update of the context value and reset it, and then synthesize and deploy your app again\. +Therefore, if you want to update to the latest version of the Amazon Linux AMI, use the preceding example to do a controlled update of the context value and reset it\. Then, synthesize and deploy your app again\. ``` cdk synth @@ -110,7 +110,7 @@ To clear all of the stored context values for your app, run cdk context \-\-clea cdk context --clear ``` -Only context values stored in `cdk.context.json` can be reset or cleared\. The AWS CDK does not touch other context values\. To protect a context value from being reset using these commands, then, you might copy the value to `cdk.json`\. +Only context values stored in `cdk.context.json` can be reset or cleared\. The AWS CDK does not touch other context values\. Therefore, to protect a context value from being reset using these commands, you might copy the value to `cdk.json`\. ## AWS CDK Toolkit `--context` flag @@ -128,11 +128,11 @@ cdk synth --context key1=value1 --context key2=value2 MyStack When synthesizing multiple stacks, the specified context values are passed to all stacks\. To provide different context values to individual stacks, either use different keys for the values, or use multiple cdk synth or cdk deploy commands\. -Context values passed from the command line are always strings\. If a value is usually of some other type, your code must be prepared to convert or parse the value\. To allow non\-string context values provided in other ways \(for example, in `cdk.context.json`\) to work as expected, make sure the value is a string before converting it\. +Context values passed from the command line are always strings\. If a value is usually of some other type, your code must be prepared to convert or parse the value\. You might have non\-string context values provided in other ways \(for example, in `cdk.context.json`\)\. To make sure this kind of value works as expected, confirm that the value is a string before converting it\. ## Example -Below is an example of using an existing Amazon VPC using AWS CDK context\. +Following is an example of using an existing Amazon VPC using AWS CDK context\. ------ #### [ TypeScript ] diff --git a/v2/environments.md b/v2/environments.md index 5606fc3c..8e2b0b9c 100644 --- a/v2/environments.md +++ b/v2/environments.md @@ -1,6 +1,6 @@ # Environments -Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and region into which the stack is intended to be deployed\. The region is specified using a region code; see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints) for a list\. +Each `Stack` instance in your AWS CDK app is explicitly or implicitly associated with an environment \(`env`\)\. An environment is the target AWS account and Region into which the stack is intended to be deployed\. The Region is specified using a Region code\. For a list, see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints)\. **Note** You must [bootstrap](bootstrapping.md) each environment you will deploy CDK stacks into\. Bootstrapping provisions certain AWS resources that are used during deployment\. @@ -15,9 +15,9 @@ The file `app.py` in your project's main directory\. The file named `ProjectNameApp.java`, for example `HelloCdkApp.java`, nested deep under the `src/main` directory\. The file named `Program.cs` under `src\ProjectName`, for example `src\HelloCdk\Program.cs`\. -In an environment\-agnostic stack, any constructs that use availability zones will see two AZs, allowing the stack to be deployed to any region\. +In an environment\-agnostic stack, any constructs that use Availability Zones will see two AZs, allowing the stack to be deployed to any Region\. -When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile \(or the default profile, if none is specified\) to determine where to deploy\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations in your AWS account\. See [AWS CDK Toolkit \(`cdk` command\)](cli.md) for details\. +When using cdk deploy to deploy environment\-agnostic stacks, the AWS CDK CLI uses the specified AWS CLI profile to determine where to deploy\. If no profile is specified, the default profile is used\. The AWS CDK CLI follows a protocol similar to the AWS CLI to determine which AWS credentials to use when performing operations in your AWS account\. See [AWS CDK Toolkit \(`cdk` command\)](cli.md) for details\. For production stacks, we recommend that you explicitly specify the environment for each stack in your app using the `env` property\. The following example specifies different environments for its two different stacks\. @@ -106,9 +106,9 @@ new MyFirstStack(app, "first-stack-eu", new StackProps { Env=envEU }); ------ -When you hard\-code the target account and region as above, the stack will always be deployed to that specific account and region\. To make the stack deployable to a different target, but to determine the target at synthesis time, your stack can use two environment variables provided by the AWS CDK CLI: `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. These variables are set based on the AWS profile specified using the \-\-profile option, or the default AWS profile if you don't specify one\. +When you hardcode the target account and Region as shown in the preceding example, the stack is always deployed to that specific account and Region\. To make the stack deployable to a different target, but to determine the target at synthesis time, your stack can use two environment variables provided by the AWS CDK CLI: `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. These variables are set based on the AWS profile specified using the \-\-profile option, or the default AWS profile if you don't specify one\. -The following code fragment shows how to access the account and region passed from the AWS CDK CLI in your stack\. +The following code fragment shows how to access the account and Region passed from the AWS CDK CLI in your stack\. ------ #### [ TypeScript ] @@ -116,7 +116,7 @@ The following code fragment shows how to access the account and region passed fr Access environment variables via Node's `process` object\. **Note** - You need the DefinitelyTyped module to use `process` in TypeScript\. `cdk init` installs this module for you, but if you are working with a project created before it was added, or didn't set up your project using `cdk init`, install it manually\. + You need the `DefinitelyTyped` module to use `process` in TypeScript\. `cdk init` installs this module for you\. However, you should install this module manually if you are working with a project created before it was added, or if you didn't set up your project using `cdk init`\. ``` npm install @types/node @@ -210,11 +210,11 @@ new MyDevStack(app, "dev", new StackProps { Env = makeEnv() }); ------ -The AWS CDK distinguishes between not specifying the `env` property at all and specifying it using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. Constructs that are defined in such a stack cannot use any information about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html#static-fromwbrlookupscope-id-options) \(Python: `from_lookup`\), which need to query your AWS account\. These features do not work at all without an explicit environment specified; to use them, you must specify `env`\. +The AWS CDK distinguishes between not specifying the `env` property at all and specifying it using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`\. The former implies that the stack should synthesize an environment\-agnostic template\. Constructs that are defined in such a stack cannot use any information about their environment\. For example, you can't write code like `if (stack.region === 'us-east-1')` or use framework facilities like [Vpc\.fromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html#static-fromwbrlookupscope-id-options) \(Python: `from_lookup`\), which need to query your AWS account\. These features don't work at all until you specify an explicit environment; to use them, you must specify `env`\. -When you pass in your environment using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, the stack will be deployed in the account and Region determined by the AWS CDK CLI at the time of synthesis\. This allows environment\-dependent code to work, but it also means that the synthesized template could be different based on the machine, user, or session under which it is synthesized\. This behavior is often acceptable or even desirable during development, but it would probably be an anti\-pattern for production use\. +When you pass in your environment using `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION`, the stack will be deployed in the account and Region determined by the AWS CDK CLI at the time of synthesis\. This lets environment\-dependent code work, but it also means that the synthesized template could be different based on the machine, user, or session that it's synthesized under\. This behavior is often acceptable or even desirable during development, but it would probably be an anti\-pattern for production use\. -You can set `env` however you like, using any valid expression\. For example, you might write your stack to support two additional environment variables to let you override the account and region at synthesis time\. We'll call these `CDK_DEPLOY_ACCOUNT` and `CDK_DEPLOY_REGION` here, but you could name them anything you like, as they are not set by the AWS CDK\. In the following stack's environment, we use our alternative environment variables if they're set, falling back to the default environment provided by the AWS CDK if they are not\. +You can set `env` however you like, using any valid expression\. For example, you might write your stack to support two additional environment variables to let you override the account and Region at synthesis time\. We'll call these `CDK_DEPLOY_ACCOUNT` and `CDK_DEPLOY_REGION` here, but you could name them anything you like, as they are not set by the AWS CDK\. In the following stack's environment, alternative environment variables are used if they're set\. If they're not set, they fall back to the default environment provided by the AWS CDK\. ------ #### [ TypeScript ] @@ -304,7 +304,7 @@ new MyDevStack(app, "dev", new StackProps { Env = makeEnv() }); ------ -With your stack's environment declared this way, you can now write a short script or batch file like the following to set the variables from command line arguments, then call `cdk deploy`\. Any arguments beyond the first two are passed through to `cdk deploy` and can be used to specify command\-line options or stacks\. +With your stack's environment declared this way, you can write a short script or batch file like the following to set the variables from command line arguments, then call `cdk deploy`\. Any arguments beyond the first two are passed through to `cdk deploy` and can be used to specify command line options or stacks\. ------ #### [ macOS/Linux ] diff --git a/v2/featureflags.md b/v2/featureflags.md index 654c51dc..bc9a0d20 100644 --- a/v2/featureflags.md +++ b/v2/featureflags.md @@ -2,11 +2,11 @@ The AWS CDK uses *feature flags* to enable potentially breaking behaviors in a release\. Flags are stored as [Runtime context](context.md) values in `cdk.json` \(or `~/.cdk.json`\)\. They are not removed by the cdk context \-\-reset or cdk context \-\-clear commands\. -Feature flags are disabled by default, so existing projects that do not specify the flag will continue to work as before with later AWS CDK releases\. New projects created using cdk init include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the old behavior, or to add flags to enable new behaviors after upgrading the AWS CDK\. +Feature flags are disabled by default\. Existing projects that do not specify the flag will continue to work as before with later AWS CDK releases\. New projects created using cdk init include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the earlier behavior\. You can also add flags to enable new behaviors after upgrading the AWS CDK\. See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. The AWS CDK source file [https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts) provides a complete list of all current feature flags\. -## Enabling features with flags +## Enabling features with flags The following feature flags may be set to `true` to enable the described behavior\. @@ -14,22 +14,22 @@ The following feature flags may be set to `true` to enable the described behavio Makes it impossible to use Secrets Manager values in unsafe locations\. `@aws-cdk/aws-lambda:recognizeLayerVersion` -Ensure that updating a layer associated with a Lambda function creates a new version of the function\. +Verify that updating a layer associated with a Lambda function creates a new version of the function\. `@aws-cdk/core:target-partitions` -Ensure that Amazon EC2 Systems Manager service principals are generated correctly\. +Verify that Amazon EC2 Systems Manager service principals are generated correctly\. `@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver` Enables logging in service extensions containers by default\. `@aws-cdk/aws-ec2:uniqueImdsv2TemplateName` -Causes [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.InstanceRequireImdsv2Aspect.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.InstanceRequireImdsv2Aspect.html) to ensure that the generated name is unique\. +Causes [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.InstanceRequireImdsv2Aspect.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.InstanceRequireImdsv2Aspect.html) to verify that the generated name is unique\. `@aws-cdk/aws-iam:minimizePolicies` Minimize the creation of IAM policies when possible\. `@aws-cdk/aws-sns-subscriptions:restrictSqsDecryption` -In an Amazon SQS queue subscribed to an Amazon SNS topic, restrict decryption permissions to just the topic instead of all of SNS\. +In an Amazon SQS queue subscribed to an Amazon SNS topic, restrict decryption permissions to only the topic instead of all of Amazon SNS\. `@aws-cdk/aws-s3:createDefaultLoggingPolicy` When using an S3 bucket with a service that will automatically create a bucket policy at deployment, have the AWS CDK configure the necessary policy\. @@ -45,19 +45,19 @@ Use the new ARN format when importing an Amazon EC2 or Fargate cluster\. ## Disabling features with flags -In CDK v2, a few feature flags are supported to revert certain behaviors to their v1 defaults\. The flags listed below, set to `false`, revert to specific AWS CDK v1 behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. +In CDK v2, a few feature flags are supported to revert certain behaviors to their v1 defaults\. The following flags, set to `false`, revert to specific AWS CDK v1 behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. `@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId` -If your application uses multiple Amazon API Gateway API keys and associates them to usage plans +If your application uses multiple Amazon API Gateway API keys and associates them to usage plans\. `@aws-cdk/aws-rds:lowercaseDbIdentifier` -If your application uses Amazon RDS database instance or database clusters, and explicitly specifies the identifier for these +If your application uses Amazon RDS database instance or database clusters, and explicitly specifies the identifier for these\. `@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021` If your application uses the TLS\_V1\_2\_2019 security policy with Amazon CloudFront distributions\. CDK v2 uses security policy TLSv1\.2\_2021 by default\. `@aws-cdk/core:stackRelativeExports` -If your application uses multiple stacks and you refer to resources from one stack in another, this determines whether absolute or relative path is used to construct AWS CloudFormation exports +If your application uses multiple stacks and you refer to resources from one stack in another, this determines whether absolute or relative path is used to construct AWS CloudFormation exports\. `@aws-cdk/aws-lambda:recognizeVersionProps` If set to `false`, the CDK includes metadata when detecting whether a Lambda function has changed\. This can cause deployment failures when only the metadata has changed, since duplicate versions are not allowed\. diff --git a/v2/get_context_var.md b/v2/get_context_var.md index 33a839cf..94faa194 100644 --- a/v2/get_context_var.md +++ b/v2/get_context_var.md @@ -18,7 +18,7 @@ To specify the same context variable and value in the `cdk.json` file, use the f } ``` -To get the value of a context variable in your app, use the `TryGetContext` method in the context of a construct \(that is, when `this`, or `self` in Python, is an instance of some construct\)\. The example gets the context value **bucket\_name**\. If the requested value is not defined, `TryGetContext` returns `undefined` \(`None` in Python; `null` in Java and C\#; `nil` in Go\) rather than raising an exception\. +To get the value of a context variable in your app, use the `TryGetContext` method in the context of a construct\. \(That is, when `this`, or `self` in Python, is an instance of some construct\.\) The example gets the context value **bucket\_name**\. If the requested value is not defined, `TryGetContext` returns `undefined` \(`None` in Python; `null` in Java and C\#; `nil` in Go\) rather than raising an exception\. ------ #### [ TypeScript ] diff --git a/v2/get_secrets_manager_value.md b/v2/get_secrets_manager_value.md index b7735f00..2a6ba746 100644 --- a/v2/get_secrets_manager_value.md +++ b/v2/get_secrets_manager_value.md @@ -104,11 +104,11 @@ public class SecretsManagerStack : Stack ------ **Tip** -Use the [create\-secret](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_secretsmanager.Secret.html) CLI command to create a secret from the command\-line, such as when testing: +Use the [create\-secret](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_secretsmanager.Secret.html) CLI command to create a secret from the command line, such as when testing: ``` aws secretsmanager create-secret --name ImportedSecret --secret-string mygroovybucket ``` -The command returns an ARN you can use with the above example\. +The command returns an ARN that you can use with the preceding example\. -Once you have created a `Secret` instance, you can get the secret's value from the instance's `secretValue` attribute\. The value is represented by a `[SecretValue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.SecretValue.html)` instance, a special type of [Tokens](tokens.md)\. As it is a token, it has meaning only after resolution; your CDK app does not need to access its actual value, but can instead pass the `SecretValue` instance \(or its string or numeric representation\) to whatever CDK method needs the value\. \ No newline at end of file +Once you have created a `Secret` instance, you can get the secret's value from the instance's `secretValue` attribute\. The value is represented by a `[SecretValue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.SecretValue.html)` instance, a special type of [Tokens](tokens.md)\. Because it's a token, it has meaning only after resolution\. Your CDK app does not need to access its actual value\. Instead, the app can pass the `SecretValue` instance \(or its string or numeric representation\) to whatever CDK method needs the value\. \ No newline at end of file diff --git a/v2/get_ssm_value.md b/v2/get_ssm_value.md index 62ae2999..c7acc715 100644 --- a/v2/get_ssm_value.md +++ b/v2/get_ssm_value.md @@ -9,7 +9,7 @@ This topic shows how to read attributes from the AWS Systems Manager Parameter S ## Reading Systems Manager values at deployment time -To read values from the Systems Manager Parameter Store, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrforwbrstringwbrparameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrforwbrsecurewbrstringwbrparameterscope-parametername-version) methods, depending on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md), not the actual value\. The value is resolved by AWS CloudFormation during deployment\. +To read values from the Systems Manager Parameter Store, use the [valueForStringParameter](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrforwbrstringwbrparameterscope-parametername-version) and [valueForSecureStringParameter](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrforwbrsecurewbrstringwbrparameterscope-parametername-version) methods\. Choose a method based on whether the attribute you want is a plain string or a secure string value\. These methods return [tokens](tokens.md), not the actual value\. The value is resolved by AWS CloudFormation during deployment\. A [limited number of AWS services](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#template-parameters-dynamic-patterns-resources) currently support this feature\. @@ -102,14 +102,14 @@ var secureStringToken = StringParameter.ValueForSecureStringParameter( ## Reading Systems Manager values at synthesis time -It is sometimes useful to "bake in" a parameter at synthesis time, so that the resulting AWS CloudFormation template always uses the same value, rather than resolving the value during deployment\. +It is sometimes useful to "bake in" a parameter at synthesis time\. This way, the resulting AWS CloudFormation template always uses the same value, instead of resolving the value during deployment\. -To read a value from the Systems Manager parameter store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrfromwbrlookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it will be retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and region information\. +To read a value from the Systems Manager Parameter Store at synthesis time, use the [valueFromLookup](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm.StringParameter.html#static-valuewbrfromwbrlookupscope-parametername) method \(Python: `value_from_lookup`\)\. This method returns the actual value of the parameter as a [Runtime context](context.md) value\. If the value is not already cached in `cdk.json` or passed on the command line, it is retrieved from the current AWS account\. For this reason, the stack *must* be synthesized with explicit account and Region information\. Only plain Systems Manager strings may be retrieved, not secure strings\. It is not possible to request a specific version; the latest version is always returned\. **Important** -The retrieved value will end up in your synthesized AWS CloudFormation template, which may be a security risk depending on who has access to your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. +The retrieved value will end up in your synthesized AWS CloudFormation template\. This might be a security risk, depending on who has access to your AWS CloudFormation templates and what kind of value it is\. Generally, don't use this feature for passwords, keys, or other values you want to keep private\. ------ #### [ TypeScript ] diff --git a/v2/getting_started.md b/v2/getting_started.md index e577fd90..21340b3a 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -6,9 +6,9 @@ This topic introduces you to important AWS CDK concepts and describes how to ins The AWS Cloud Development Kit \(AWS CDK\) lets you define your cloud infrastructure as code in one of its supported programming languages\. It is intended for moderately to highly experienced AWS users\. -Ideally, you already have experience with popular AWS services, particularly [AWS Identity and Access Management](https://aws.amazon.com/iam/) \(IAM\)\. You might already have AWS credentials on your workstation for use with an AWS SDK or the AWS CLI and experience working with AWS resources programmatically\. +Ideally, you already have experience with popular AWS services, particularly [AWS Identity and Access Management](https://aws.amazon.com/iam/) \(IAM\)\. You might already have AWS credentials on your workstation for use with an AWS SDK or the AWS CLI\. You might also have experience working with AWS resources programmatically\. -Familiarity with [AWS CloudFormation](https://aws.amazon.com/cloudformation/) is also useful, as the output of an AWS CDK program is an AWS CloudFormation template\. +Familiarity with [AWS CloudFormation](https://aws.amazon.com/cloudformation/) is also useful, because the output of an AWS CDK program is an AWS CloudFormation template\. Finally, you should be proficient in the programming language you intend to use with the AWS CDK\. @@ -16,13 +16,15 @@ Finally, you should be proficient in the programming language you intend to use The AWS CDK is designed around a handful of important concepts\. We will introduce a few of these here briefly\. Follow the links to learn more, or see the Concepts topics in this guide's Table of Contents\. -An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, Python, Java, C\# or Go that uses the AWS CDK to define AWS infrastructure\. An app defines one or more [stacks](stacks.md)\. Stacks \(equivalent to AWS CloudFormation stacks\) contain [constructs](constructs.md), each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on\. +An AWS CDK [app](apps.md) is an application written in TypeScript, JavaScript, Python, Java, C\# or Go that uses the AWS CDK to define AWS infrastructure\. An app defines one or more [stacks](stacks.md)\. Stacks \(equivalent to AWS CloudFormation stacks\) contain [constructs](constructs.md)\. Each construct defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, or Amazon DynamoDB tables\. -Constructs \(as well as stacks and apps\) are represented as classes \(types\) in your programming language of choice\. You instantiate constructs within a stack to declare them to AWS, and connect them to each other using well\-defined interfaces\. +Constructs \(and also stacks and apps\) are represented as classes \(types\) in your programming language of choice\. You instantiate constructs within a stack to declare them to AWS, and connect them to each other using well\-defined interfaces\. -The AWS CDK includes the CDK Toolkit \(also called the CLI\), a command\-line tool for working with your AWS CDK apps and stacks\. Among other functions, the Toolkit provides the ability to convert one or more AWS CDK stacks to AWS CloudFormation templates and related assets \(a process called *synthesis*\) and to deploy your stacks to an AWS account\. +The AWS CDK includes the CDK Toolkit \(also called the CLI\), a command line tool for working with your AWS CDK apps and stacks\. Among other functions, the Toolkit provides the ability to do the following: ++ Convert one or more AWS CDK stacks to AWS CloudFormation templates and related assets \(a process called *synthesis*\) ++ Deploy your stacks to an AWS account -The AWS CDK includes a library of AWS constructs called the AWS Construct Library, organized into various modules\. The library contains constructs for each AWS service\. The main CDK package is called `aws-cdk-lib`, and it contains the majority of the AWS Construct Library, along with base classes like `Stack` and `App` used in most CDK applications\. +The AWS CDK includes a library of AWS constructs called the AWS Construct Library, organized into various modules\. The library contains constructs for each AWS service\. The main CDK package is called `aws-cdk-lib`, and it contains the majority of the AWS Construct Library\. It also contains base classes like `Stack` and `App` that are used in most CDK applications\. The actual package name of the main CDK package varies by language\. @@ -83,15 +85,15 @@ import ( ------ **Note** -If you created a CDK project using cdk init, you won't need to manually install `aws-cdk-lib`\. +If you created a CDK project using cdk init, you don't need to manually install `aws-cdk-lib`\. Constructs come in three fundamental flavors: -+ **AWS CloudFormation\-only** or L1 \(short for "layer 1"\)\. These constructs correspond directly to resource types defined by AWS CloudFormation\. In fact, these constructs are automatically generated from the AWS CloudFormation specification, so when a new AWS service is launched, the AWS CDK supports it a short time after AWS CloudFormation does\. ++ **AWS CloudFormation\-only** or L1 \(short for "layer 1"\)\. These constructs correspond directly to resource types defined by AWS CloudFormation\. In fact, these constructs are automatically generated from the AWS CloudFormation specification\. Therefore, when a new AWS service is launched, the AWS CDK supports it a short time after AWS CloudFormation does\. AWS CloudFormation resources always have names that begin with `Cfn`\. For example, for the Amazon S3 service, `CfnBucket` is the L1 construct for an Amazon S3 bucket\. All L1 resources are in `aws-cdk-lib`\. -+ **Curated** or L2\. These constructs are carefully developed by the AWS CDK team to address specific use cases and simplify infrastructure development\. For the most part, they encapsulate L1 resources, providing sensible defaults and best\-practice security policies\. For example, `Bucket` is the L2 construct for an Amazon S3 bucket\. ++ **Curated** or L2\. These constructs are carefully developed by the AWS CDK team to address specific use cases and simplify infrastructure development\. For the most part, they encapsulate L1 resources, providing sensible defaults and best practice security policies\. For example, `Bucket` is the L2 construct for an Amazon S3 bucket\. Libraries may also define supporting resources needed by the primary L2 resource\. Some services have more than one L2 namespace in the Construct Library for organizational purposes\. @@ -100,17 +102,17 @@ Constructs come in three fundamental flavors: As with L2 constructs, L3 constructs that are ready for production use \(stable\) are included in `aws-cdk-lib`, while those still under development are in separate modules\. -Finally, the `constructs` package contains the `Construct` base class\. It's in its own package because it is used not only by the AWS CDK but also by other construct\-based tools, including CDK for Terraform and CDK for Kubernetes\. +Finally, the `constructs` package contains the `Construct` base class\. It's in its own package because it's used by other construct\-based tools in addition to the AWS CDK, including CDK for Terraform and CDK for Kubernetes\. -Numerous third parties have also published constructs compatible with the AWS CDK\. Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&offset=0) to explore the AWS CDK construct ecosystem\. +Numerous third parties have also published constructs compatible with the AWS CDK\. Visit [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&offset=0) to explore the AWS CDK construct partner ecosystem\. ## Supported programming languages -The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, C\#, and Go\. Other JVM and \.NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time\. +The AWS CDK has first\-class support for TypeScript, JavaScript, Python, Java, C\#, and Go\. Other JVM and \.NET CLR languages may also be used, at least in theory\. However, we are unable to offer support for them at this time\. -To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\) and language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. +To facilitate supporting so many languages, the AWS CDK is developed in one language \(TypeScript\)\. Language bindings are generated for the other languages through the use of a tool called [JSII](https://github.com/aws/jsii)\. -We have taken pains to make AWS CDK app development in each language follow that language's usual conventions, so writing AWS CDK apps feels natural, not like writing TypeScript in Python \(for example\)\. Take a look: +We have taken pains to make AWS CDK app development in each language follow that language's usual conventions\. This way, writing AWS CDK apps feels natural, not like writing TypeScript in Python, for example\. Take a look at the following examples: ------ #### [ TypeScript ] @@ -184,7 +186,7 @@ These code snippets are intended for illustration only\. They are incomplete and The AWS Construct Library is distributed using each language's standard package management tools, including NPM, PyPi, Maven, and NuGet\. There's even a version of the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) for each language\. -To help you use the AWS CDK in your favorite language, this Guide includes topics that explain how to use the AWS CDK in all supported languages\. +To help you use the AWS CDK in your favorite language, this guide includes the following topics for supported languages: + [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) + [Working with the AWS CDK in JavaScript](work-with-cdk-javascript.md) + [Working with the AWS CDK in Python](work-with-cdk-python.md) @@ -192,26 +194,26 @@ To help you use the AWS CDK in your favorite language, this Guide includes topic + [Working with the AWS CDK in C\#](work-with-cdk-csharp.md) + [Working with the AWS CDK in Go](work-with-cdk-go.md) -TypeScript was the first language supported by the AWS CDK, and much AWS CDK example code is written in TypeScript\. This Guide includes a topic specifically to show how to adapt TypeScript AWS CDK code for use with the other supported languages\. See [Translating TypeScript AWS CDK code to other languages](multiple_languages.md)\. +TypeScript was the first language supported by the AWS CDK, and much AWS CDK example code is written in TypeScript\. This guide includes a topic specifically to show how to adapt TypeScript AWS CDK code for use with the other supported languages\. For more information, see [Translating TypeScript AWS CDK code to other languages](multiple_languages.md)\. ## Prerequisites Here's what you need to install to use the AWS CDK\. -All AWS CDK developers, even those working in Python, Java, or C\#, need [Node\.js](https://nodejs.org/en/download/) 10\.13\.0 or later\. All supported languages use the same back end, which runs on Node\.js\. We recommend a version in [active long\-term support](https://nodejs.org/en/about/releases/), which, at this writing, is the latest 16\.x release\. Your organization may have a different recommendation\. +All AWS CDK developers, even those working in Python, Java, or C\#, need [Node\.js](https://nodejs.org/en/download/) 10\.13\.0 or later\. All supported languages use the same backend, which runs on Node\.js\. We recommend a version in [active long\-term support](https://nodejs.org/en/about/releases/), which, at this writing, is the latest 16\.x release\. Your organization may have a different recommendation\. **Important** Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. -You must configure your workstation with your credentials and an AWS region, if you have not already done so\. If you have the AWS CLI installed, the easiest way to satisfy this requirement is issue the following command: +You must configure your workstation with your credentials and an AWS Region, if you have not already done so\. If you have the AWS CLI installed, we recommend running the following command: ``` aws configure ``` -Provide your AWS access key ID, secret access key, and default region when prompted\. +Provide your AWS access key ID, secret access key, and default Region when prompted\. -You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(macOS/Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default region, in the following format\. +You can also manually create or edit the `~/.aws/config` and `~/.aws/credentials` \(macOS/Linux\) or `%USERPROFILE%\.aws\config` and `%USERPROFILE%\.aws\credentials` \(Windows\) files to contain credentials and a default Region\. Use the following format\. + In `~/.aws/config` or `%USERPROFILE%\.aws\config` ``` @@ -227,7 +229,7 @@ You may also manually create or edit the `~/.aws/config` and `~/.aws/credentials ``` **Note** -Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it may behave slightly differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the region\. The AWS CDK does not fall back to reading the region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. +Although the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), it might behave somewhat differently from these tools\. In particular, if you use a named profile from the `credentials` file, the `config` must have a profile of the same name specifying the Region\. The AWS CDK does not fall back to reading the Region from the `[default]` section in `config`\. Also, do not use a profile named "default" \(e\.g\. `[profile default]`\)\. See [Setting credentials](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html) for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood\. The AWS CDK natively supports AWS IAM Identity Center \(successor to AWS Single Sign\-On\)\. To use IAM Identity Center with the CDK, first create a profile using aws configure sso\. Then log in using aws sso login\. Finally, specify this profile when issuing cdk commands using the \-\-profile option or the `AWS_PROFILE` environment variable\. Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. @@ -255,7 +257,7 @@ No additional requirements + Java Development Kit \(JDK\) 8 \(a\.k\.a\. 1\.8\) or later + Apache Maven 3\.5 or later -Java IDE recommended \(we use Eclipse in some examples in this Developer Guide\)\. IDE must be able to import Maven projects\. Check to make sure your project is set to use Java 1\.8\. Set the JAVA\_HOME environment variable to the path where you have installed the JDK\. +Java IDE recommended \(we use Eclipse in some examples in this guide\)\. IDE must be able to import Maven projects\. Check to make sure that your project is set to use Java 1\.8\. Set the JAVA\_HOME environment variable to the path where you have installed the JDK\. ------ #### [ C\# ] @@ -272,7 +274,7 @@ Go 1\.1\.8 or later\. ------ **Note** -Third\-party Language Deprecation: each language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. +Third\-party language deprecation: each language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. ## Install the AWS CDK @@ -305,12 +307,12 @@ If you don't have your AWS account number handy, you can get it from the AWS Man ``` aws sts get-caller-identity ``` -If you have created named profiles in your local AWS configuration, you can use the `--profile` option to display the account information for a specific profile's account, such as the *prod* profile as shown here\. +If you created named profiles in your local AWS configuration, you can use the `--profile` option to display the account information for a specific profile\. The following example shows how to display account information for the *prod* profile\. ``` aws sts get-caller-identity --profile prod ``` -To display the default region, use `aws configure get`\. +To display the default Region, use `aws configure get`\. ``` aws configure get region @@ -321,7 +323,7 @@ aws configure get region --profile prod The AWS CDK Toolkit, also known as the Command Line Interface \(CLI\), is the main tool you use to interact with your AWS CDK app\. It executes your code and produces and deploys the AWS CloudFormation templates it generates\. It also has deployment, diff, deletion, and troubleshooting capabilities\. For more information, see cdk \-\-help or [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. -The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open\-source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the plug\-in](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. +The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plug\-in for Visual Studio Code that helps you create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications\. It includes the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the plug\-in](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. ## Next steps @@ -329,7 +331,7 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Come on in; the water's fine\! Build [your first AWS CDK app](hello_world.md)\. + Try the [CDK Workshop](https://cdkworkshop.com/) for a more in\-depth tour involving a more complex project\. + See the [API reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) to begin exploring the provided constructs available for your favorite AWS services\. -+ Visit the [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) to find constructs from the CDK community as well as from AWS\. ++ Visit the [Construct Hub](https://constructs.dev/search?q=&cdk=aws-cdk&cdkver=2&sort=downloadsDesc&offset=0) to find constructs from the CDK community and also from AWS\. + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Abstractions and escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. diff --git a/v2/hello_world.md b/v2/hello_world.md index 5445bf2b..14e8bcc7 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -2,26 +2,29 @@ You've read [Getting started with the AWS CDK](getting_started.md) and set up your development environment for writing AWS CDK apps? Great\! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app\. -In this tutorial, you'll learn about the structure of a AWS CDK project, how to use the AWS Construct Library to define AWS resources using code, and how to synthesize, diff, and deploy collections of resources using the AWS CDK Toolkit command\-line tool\. +In this tutorial, you'll learn about the following: ++ The structure of an AWS CDK project ++ How to use the AWS Construct Library to define AWS resources using code ++ How to synthesize, diff, and deploy collections of resources using the AWS CDK Toolkit command line tool -The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps\. +The standard AWS CDK development workflow is similar to what you're already familiar with as a developer, with only a few extra steps\. -1. Create the app from a template provided by the AWS CDK +1. Create the app from a template provided by the AWS CDK\. -1. Add code to the app to create resources within stacks +1. Add code to the app to create resources within stacks\. -1. Build the app \(optional; the AWS CDK Toolkit will do it for you if you forget\) +1. \(Optional\) Build the app\. \(The AWS CDK Toolkit does this for you if you forget\.\) -1. Synthesize one or more stacks in the app to create an AWS CloudFormation template +1. Synthesize one or more stacks in the app to create an AWS CloudFormation template\. -1. Deploy one or more stacks to your AWS account +1. Deploy one or more stacks to your AWS account\. -The build step catches syntax and type errors\. The synthesis step catches logical errors in defining your AWS resources\. The deployment may find permission issues\. As always, you go back to the code, find the problem, fix it, then build, synthesize and deploy again\. +The build step catches syntax and type errors\. The synthesis step catches logical errors in defining your AWS resources\. The deployment may find permission issues\. As always, you go back to the code, find the problem, fix it, then build, synthesize, and deploy again\. **Tip** Don't forget to keep your AWS CDK code under version control\! -This tutorial walks you through creating and deploying a simple AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. The app contains one stack, which contains one resource: an Amazon S3 bucket\. +This tutorial walks you through creating and deploying a simple AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template\. The app contains one stack, which contains one resource, an Amazon S3 bucket\. We'll also show what happens when you make a change and re\-deploy, and how to clean up when you're done\. @@ -30,14 +33,14 @@ We'll also show what happens when you make a change and re\-deploy, and how to c Each AWS CDK app should be in its own directory, with its own local module dependencies\. Create a new directory for your app\. Starting in your home directory, or another directory if you prefer, issue the following commands\. **Important** -Be sure to name your project directory `hello-cdk`, *exactly as shown here\.* The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, the code in this tutorial won't work\. +Be sure to name your project directory `hello-cdk`, *exactly as shown here\.* The AWS CDK project template uses the directory name to name things in the generated code\. If you use a different name, the code in this tutorial won't work\. ``` mkdir hello-cdk cd hello-cdk ``` -Now initialize the app using the cdk init command, specifying the desired template \("app"\) and programming language\. That is: +Now initialize the app by using the cdk init command\. Specify the desired template \("app"\) and programming language as shown in the following examples: ------ #### [ TypeScript ] @@ -60,7 +63,7 @@ cdk init app --language javascript cdk init app --language python ``` -After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install the AWS CDK core dependencies\. +After the app has been created, also enter the following two commands\. These activate the app's Python virtual environment and install the AWS CDK core dependencies\. ``` source .venv/bin/activate @@ -92,7 +95,7 @@ If you are using Visual Studio, open the solution file in the `src` directory\. cdk init app --language go ``` -After the app has been created, also enter the following command to instll the AWS Construct Library modules required by the app\. +After the app has been created, also enter the following command to install the AWS Construct Library modules that the app requires\. ``` go get @@ -101,7 +104,7 @@ go get ------ **Tip** -If you don't specify a template, the default is "app," which is the one we wanted anyway, so technically you can leave it out and save four keystrokes\. +If you don't specify a template, the default is "app," which is the one we wanted anyway\. Technically, you can omit it and save four keystrokes\. The cdk init command creates a number of files and folders inside the `hello-cdk` directory to help you organize the source code for your AWS CDK app\. Take a moment to explore\. The structure of a basic app is all there; you'll fill in the details in this tutorial\. @@ -109,7 +112,7 @@ If you have Git installed, each project you create using cdk init is also initia ## Build the app -In most programming environments, after making changes to your code, you'd build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you so you can't forget\. But you can still build manually whenever you want to catch syntax and type errors\. For reference, here's how\. +In most programming environments, after changing your code, you build \(compile\) it\. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you so that you can't forget\. But you can still build manually whenever you want to catch syntax and type errors\. For reference, here's how\. ------ #### [ TypeScript ] @@ -157,7 +160,7 @@ go build ## List the stacks in the app -Just to verify everything is working correctly, list the stacks in your app\. +To verify that everything is working correctly, list the stacks in your app\. ``` cdk ls @@ -169,7 +172,7 @@ If you don't see `HelloCdkStack`, make sure you named your app's directory `hell At this point, your app doesn't do anything because the stack it contains doesn't define any resources\. Let's add an Amazon S3 bucket\. -The CDK's Amazon S3 support is part of its main library, `aws-cdk-lib`, so we don't need to install another library\. We can just define an Amazon S3 bucket in the stack using the [Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) construct\. +The CDK's Amazon S3 support is part of its main library, `aws-cdk-lib`, so we don't need to install another library\. We can define an Amazon S3 bucket in the stack using the [Bucket](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html) construct\. ------ #### [ TypeScript ] @@ -333,12 +336,12 @@ func env() *awscdk.Environment { ------ -`Bucket` is the first construct we've seen, so let's take a closer look\. Like all constructs, the `Bucket` class takes three parameters\. +`Bucket` is the first construct that we've seen, so let's take a closer look\. Like all constructs, the `Bucket` class takes three parameters\. + **scope:** Tells the bucket that the stack is its parent: it is defined within the scope of the stack\. You can define constructs inside of constructs, creating a hierarchy \(tree\)\. Here, and in most cases, the scope is `this` \(`self` in Python\), meaning the construct that contains the bucket: the stack\. -+ **Id:** The logical ID of the Bucket within your AWS CDK app\. This \(plus a hash based on the bucket's location within the stack\) uniquely identifies the bucket across deployments so the AWS CDK can update it if you change how it's defined in your app\. Here it is "MyFirstBucket\." Buckets can also have a name, which is separate from this ID \(it's the `bucketName` property\)\. ++ **Id:** The logical ID of the Bucket within your AWS CDK app\. This \(plus a hash based on the bucket's location within the stack\) uniquely identifies the bucket across deployments\. This way, the AWS CDK can update it if you change how it's defined in your app\. Here, it's "MyFirstBucket\." Buckets can also have a name, which is separate from this ID \(it's the `bucketName` property\)\. + **props:** A bundle of values that define properties of the bucket\. Here we've defined only one property: `versioned`, which enables versioning for the files in the bucket\. -All constructs take these same three arguments, so it's easy to stay oriented as you learn about new ones\. And as you might expect, you can subclass any construct to extend it to suit your needs, or just to change its defaults\. +All constructs take these same three arguments, so it's easy to stay oriented as you learn about new ones\. And as you might expect, you can subclass any construct to extend it to suit your needs, or if you want to change its defaults\. **Tip** If a construct's props are all optional, you can omit the `props` parameter entirely\. @@ -346,7 +349,7 @@ If a construct's props are all optional, you can omit the `props` parameter enti Props are represented differently in the languages supported by the AWS CDK\. + In TypeScript and JavaScript, `props` is a single argument and you pass in an object containing the desired properties\. + In Python, props are passed as keyword arguments\. -+ In Java, a Builder is provided to pass the props\. Two, actually; one for `BucketProps`, and a second for `Bucket` to let you build the construct and its props object in one step\. This code uses the latter\. ++ In Java, a Builder is provided to pass the props\. There are two: one for `BucketProps`, and a second for `Bucket` to let you build the construct and its props object in one step\. This code uses the latter\. + In C\#, you instantiate a `BucketProps` object using an object initializer and pass it as the third parameter\. ## Synthesize an AWS CloudFormation template @@ -357,12 +360,12 @@ Synthesize an AWS CloudFormation template for the app, as follows\. cdk synth ``` -If your app contained more than one stack, you'd need to specify which stack\(s\) to synthesize\. But since it only contains one, the CDK Toolkit knows you must mean that one\. +If your app contained more than one stack, you'd need to specify which stack or stacks to synthesize\. But since it only contains one, the CDK Toolkit knows you must mean that one\. **Tip** If you received an error like `--app is required...`, it's probably because you are running the command from a subdirectory\. Navigate to the main app directory and try again\. -The `cdk synth` command executes your app, which causes the resources defined in it to be translated into an AWS CloudFormation template\. The displayed output of `cdk synth` is a YAML\-format template; the beginning of our app's output is shown below\. The template is also saved in the `cdk.out` directory in JSON format\. +The `cdk synth` command executes your app, which causes the resources defined in it to be translated into an AWS CloudFormation template\. The displayed output of `cdk synth` is a YAML\-format template\. Following, you can see the beginning of our app's output\. The template is also saved in the `cdk.out` directory in JSON format\. ``` Resources: @@ -376,10 +379,10 @@ Resources: Metadata:... ``` -Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for the bucket and see how the `versioned` property was translated\. +Even if you aren't familiar with AWS CloudFormation, you can find the bucket definition and see how the `versioned` property was translated\. **Note** -Every generated template contains a `AWS::CDK::Metadata` resource by default\. \(We haven't shown it here\.\) The AWS CDK team uses this metadata to gain insight into how the AWS CDK is used, so we can continue to improve it\. For details, including how to opt out of version reporting, see [Version reporting](cli.md#version_reporting)\. +Every generated template contains a `AWS::CDK::Metadata` resource by default\. \(We haven't shown it here\.\) The AWS CDK team uses this metadata to gain insight into how the AWS CDK is used, so that we can continue to improve it\. For details, including how to opt out of version reporting, see [Version reporting](cli.md#version_reporting)\. The `cdk synth` generates a perfectly valid AWS CloudFormation template\. You could take it and deploy it using the AWS CloudFormation console or another tool\. But the AWS CDK Toolkit can also do that\. @@ -403,7 +406,7 @@ You've deployed your first stack using the AWS CDK—congratulations\! But that' ## Modifying the app -The AWS CDK can update your deployed resources after you modify your app\. Let's change our bucket so it can be automatically deleted when we delete the stack, which involves changing its `RemovalPolicy`\. Also, because AWS CloudFormation won't delete Amazon S3 buckets that contain any objects, we'll ask the AWS CDK to delete the objects from our bucket before destroying the bucket, via the `autoDeleteObjects` property\. +The AWS CDK can update your deployed resources after you modify your app\. Let's change the bucket so it can be automatically deleted when deleting the stack\. This involves changing the bucket's `RemovalPolicy`\. Also, use the `autoDeleteObjects` property to ask the AWS CDK to delete the objects from the bucket before destroying it\. \(AWS CloudFormation doesn't delete S3 buckets that contain any objects\.\) ------ #### [ TypeScript ] @@ -499,15 +502,15 @@ new Bucket(this, "MyFirstBucket", new BucketProps ------ -Here, we haven't written any code that, in itself, changes our Amazon S3 bucket\. Instead, our code defines the desired state of the bucket\. The AWS CDK synthesizes that state to a new AWS CloudFormation template and deploys a changeset that makes only the changes necessary to reach that state\. +Here, we haven't written any code that, in itself, changes our Amazon S3 bucket\. Instead, our code defines the desired state of the bucket\. The AWS CDK synthesizes that state to a new AWS CloudFormation template\. Then, it deploys a changeset that makes only the changes necessary to reach that state\. -To see these changes, we'll use the `cdk diff` command \. +To see these changes, we'll use the `cdk diff` command\. ``` cdk diff ``` -The AWS CDK Toolkit queries your AWS account for the last\-deployed AWS CloudFormation template for the `HelloCdkStack` and compares it with the template it just synthesized from your app\. The output should look like the following\. +The AWS CDK Toolkit queries your AWS account for the last\-deployed AWS CloudFormation template for the `HelloCdkStack`\. Then, it compares the last\-deployed template with the template it just synthesized from your app\. The output should look like the following\. ``` Stack HelloCdkStack @@ -555,14 +558,14 @@ Resources This diff has four sections\. + **IAM Statement Changes** and **IAM Policy Changes** \- These permission changes are there because we set the `AutoDeleteObjects` property on our Amazon S3 bucket\. The auto\-delete feature uses a custom resource to delete the objects in the bucket before the bucket itself is deleted\. The IAM objects grant the custom resource's code access to the bucket\. + **Parameters** \- The AWS CDK uses these entries to locate the Lambda function asset for the custom resource\. -+ **Resources** \- The new and changed resources in this stack\. We can see the aforementioned IAM objects, the custom resource, and its associated Lambda function being added\. We can also see that the bucket's `DeletionPolicy` and `UpdateReplacePolicy` attributes are being updated\. These allow the bucket to be deleted along with the stack, and to be replaced with a new one\. ++ **Resources** \- The new and changed resources in this stack\. We can see the previously mentioned IAM objects, the custom resource, and its associated Lambda function being added\. We can also see that the bucket's `DeletionPolicy` and `UpdateReplacePolicy` attributes are being updated\. These allow the bucket to be deleted along with the stack, and to be replaced with a new one\. -You may be curious about why we specified `RemovalPolicy` in our AWS CDK app but got a `DeletionPolicy` property in the resulting AWS CloudFormation template\. The AWS CDK uses a different name for the property because the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it\. See [Removal policies](resources.md#resources_removal) for further details\. +You may be curious about why we specified `RemovalPolicy` in our AWS CDK app but got a `DeletionPolicy` property in the resulting AWS CloudFormation template\. The AWS CDK uses a different name for the property\. This is because the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it\. For more information, see [Removal policies](resources.md#resources_removal)\. -It's informative to compare the output of cdk synth here with the previous output and see the many additional lines of AWS CloudFormation template that the AWS CDK generated for us based on these relatively small changes\. +It's informative to compare the output of cdk synth here with the previous output\. You can see the many additional lines of AWS CloudFormation template that the AWS CDK generated for us based on these relatively small changes\. **Important** -All AWS CDK v2 deployments use dedicated AWS resources to hold data during deployment, so your AWS account and region must be [bootstrapped](bootstrapping.md) to create these resources before you can deploy\. If you haven't already bootstrapped, issue: +All AWS CDK v2 deployments use dedicated AWS resources to hold data during deployment\. Therefore, your AWS account and Region must be [bootstrapped](bootstrapping.md) to create these resources before you can deploy\. If you haven't already bootstrapped, issue the following command: ``` cdk bootstrap aws://ACCOUNT-NUMBER/REGION @@ -615,7 +618,7 @@ cdk destroy Enter y to approve the changes and delete any stack resources\. **Note** -If we hadn't changed the bucket's `RemovalPolicy`, the stack deletion would complete successfully, but the bucket would become orphaned \(no longer associated with the stack\)\. +If we didn't change the bucket's `RemovalPolicy`, the stack deletion would complete successfully, but the bucket would become orphaned \(no longer associated with the stack\)\. ## Next steps diff --git a/v2/home.md b/v2/home.md index 952580d8..9364957c 100644 --- a/v2/home.md +++ b/v2/home.md @@ -3,7 +3,7 @@ Welcome to the *AWS Cloud Development Kit \(AWS CDK\) Developer Guide*\. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation\. **Note** -The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v2\. The older CDK v1 entered maintenance on June 1, 2022\. Support for CDK v1 will end on June 1, 2023\. +The CDK has been released in two major versions, v1 and v2\. This is the Developer Guide for AWS CDK v2\. The earlier CDK v1 entered maintenance on June 1, 2022\. Support for CDK v1 will end on June 1, 2023\. The AWS CDK lets you build reliable, scalable, cost\-effective applications in the cloud with the considerable expressive power of a programming language\. This approach yields many benefits, including: + Build with high\-level constructs that automatically provide sensible, secure defaults for your AWS resources, defining more infrastructure with less code\. @@ -244,12 +244,12 @@ And let's not forget\.\.\. code completion within your IDE or editor\! It's easy to [get set up](getting_started.md) and [write your first CDK app](hello_world.md)\. Short code examples are available throughout this Guide in the AWS CDK's supported programming languages: TypeScript, JavaScript, Python, Java, and C\#\. Longer examples are available [in our GitHub repository](https://github.com/aws-samples/aws-cdk-examples)\. -The [AWS CDK Toolkit](cli.md) is a command line tool for interacting with CDK apps\. It enables developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change\. +The [AWS CDK Toolkit](cli.md) is a command line tool for interacting with CDK apps\. Developers can use the AWS CDK Toolkit to synthesize artifacts such as AWS CloudFormation templates and to deploy stacks to development AWS accounts\. You can also diff against a deployed stack to understand the impact of a code change\. The [AWS Construct Library](constructs.md) offers constructs for each AWS service, many with "rich" APIs that provide high\-level abstractions\. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS\. **Note** -There is no charge for using the AWS CDK, but you might incur AWS charges for creating or using AWS [chargeable resources](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources), such as running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Pricing Calculator](https://calculator.aws/#/) to estimate charges for the use of various AWS resources\. +There is no charge for using the AWS CDK, but you might incur AWS charges for creating or using AWS [chargeable resources](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#chargeable-resources)\. These might include running Amazon EC2 instances or using Amazon S3 storage\. Use the [AWS Pricing Calculator](https://calculator.aws/#/) to estimate charges for the use of various AWS resources\. ## The Construct Programming Model @@ -298,6 +298,6 @@ Because the AWS CDK is open source, the team encourages you to contribute to mak Amazon Web Services \(AWS\) is a collection of digital infrastructure services that developers can use when developing their applications\. The services include computing, storage, database, and application synchronization \(messaging and queueing\)\. -AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. +AWS uses a pay\-as\-you\-go service model\. You are charged only for the services that you — or your applications — use\. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier\. In the tier, services are free below a certain level of usage\. For more information about AWS costs and the free usage tier, see [Test\-Driving AWS in the Free Usage Tier](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html)\. To obtain an AWS account, go to [aws\.amazon\.com](https://aws.amazon.com), and then choose **Create an AWS Account**\. \ No newline at end of file diff --git a/v2/how_to_set_cw_alarm.md b/v2/how_to_set_cw_alarm.md index fe2304ea..30509f4c 100644 --- a/v2/how_to_set_cw_alarm.md +++ b/v2/how_to_set_cw_alarm.md @@ -111,7 +111,7 @@ var metric = new Metric(this, "Metric", new MetricProps ## Creating the alarm -Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three evaluation periods\. You can use comparisons such as less\-than in your alarms via the `comparisonOperator` property; greater\-than\-or\-equal\-to is the AWS CDK default, so we don't need to specify it\. +Once you have a metric, either an existing one or one you defined, you can create an alarm\. In this example, the alarm is raised when there are more than 100 of your metric in two of the last three evaluation periods\. You can use comparisons such as less\-than in your alarms via the `comparisonOperator` property\. Greater\-than\-or\-equal\-to is the AWS CDK default, so we don't need to specify it\. ------ #### [ TypeScript ] @@ -178,7 +178,7 @@ var alarm = new Alarm(this, "Alarm", new AlarmProps ------ -An alternative way to create an alarm is using the metric's [createAlarm\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html#createwbralarmscope-id-props) method, which takes essentially the same properties as the `Alarm` constructor; you just don't need to pass in the metric, since it's already known\. +An alternative way to create an alarm is using the metric's [createAlarm\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html#createwbralarmscope-id-props) method, which takes essentially the same properties as the `Alarm` constructor\. You don't need to pass in the metric, because it's already known\. ------ #### [ TypeScript ] diff --git a/v2/identifiers.md b/v2/identifiers.md index 5715003d..42e30350 100644 --- a/v2/identifiers.md +++ b/v2/identifiers.md @@ -8,12 +8,12 @@ If you attempt to create an identifier with the same value within the same scope ## Construct IDs -The most common identifier, `id`, is the identifier passed as the second argument when instantiating a construct object\. This identifier, like all identifiers, need only be unique within the scope in which it is created, which is the first argument when instantiating a construct object\. +The most common identifier, `id`, is the identifier passed as the second argument when instantiating a construct object\. This identifier, like all identifiers, only needs to be unique within the scope in which it is created, which is the first argument when instantiating a construct object\. **Note** -The `id` of a stack is also the identifier you use to refer to it in the [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. +The `id` of a stack is also the identifier that you use to refer to it in the [AWS CDK Toolkit \(`cdk` command\)](cli.md)\. -Let's look at an example where we have two constructs with the identifier `MyBucket` in our app\. However, since they are defined in different scopes, the first in the scope of the stack with the identifier `Stack1`, and the second in the scope of a stack with the identifier `Stack2`, that doesn't cause any sort of conflict, and they can coexist in the same app without any issues\. +Let's look at an example where we have two constructs with the identifier `MyBucket` in our app\. The first is defined in the scope of the stack with the identifier `Stack1`\. The second is defined in the scope of a stack with the identifier `Stack2`\. Because they're defined in different scopes, this doesn't cause any conflict, and they can coexist in the same app without issues\. ------ #### [ TypeScript ] @@ -147,9 +147,9 @@ class Program The constructs in an AWS CDK application form a hierarchy rooted in the `App` class\. We refer to the collection of IDs from a given construct, its parent construct, its grandparent, and so on to the root of the construct tree, as a *path*\. -The AWS CDK typically displays paths in your templates as a string, with the IDs from the levels separated by slashes, starting at the node just below the root `App` instance, which is usually a stack\. For example, the paths of the two Amazon S3 bucket resources in the previous code example are `Stack1/MyBucket` and `Stack2/MyBucket`\. +The AWS CDK typically displays paths in your templates as a string\. The IDs from the levels are separated by slashes, starting at the node immediately under the root `App` instance, which is usually a stack\. For example, the paths of the two Amazon S3 bucket resources in the previous code example are `Stack1/MyBucket` and `Stack2/MyBucket`\. -You can access the path of any construct programmatically, as shown in the following example, which gets the path of `myConstruct` \(or `my_construct`, as Python developers would write it\)\. Since IDs must be unique within the scope they are created, their paths are always unique within a AWS CDK application\. +You can access the path of any construct programmatically, as shown in the following example\. This gets the path of `myConstruct` \(or `my_construct`, as Python developers would write it\)\. Since IDs must be unique within the scope they are created, their paths are always unique within an AWS CDK application\. ------ #### [ TypeScript ] @@ -190,7 +190,7 @@ string path = myConstruct.Node.Path; ## Unique IDs -Since AWS CloudFormation requires that all logical IDs in a template are unique, the AWS CDK must be able to generate a unique identifier for each construct in an application\. Resources have paths that are globally unique \(the names of all scopes from the stack to a specific resource\) so the AWS CDK generates the necessary unique identifiers by concatenating the elements of the path and adding an 8\-digit hash\. \(The hash is necessary to distinguish distinct paths, such as `A/B/C` and `A/BC`, that would result in the same AWS CloudFormation identifier, since AWS CloudFormation identifiers are alphanumeric and cannot contain slashes or other separator characters\.\) The AWS CDK calls this string the *unique ID* of the construct\. +AWS CloudFormation requires that all logical IDs in a template be unique\. Because of this, the AWS CDK must be able to generate a unique identifier for each construct in an application\. Resources have paths that are globally unique \(the names of all scopes from the stack to a specific resource\)\. Therefore, the AWS CDK generates the necessary unique identifiers by concatenating the elements of the path and adding an 8\-digit hash\. \(The hash is necessary to distinguish distinct paths, such as `A/B/C` and `A/BC`, that would result in the same AWS CloudFormation identifier\. AWS CloudFormation identifiers are alphanumeric and cannot contain slashes or other separator characters\.\) The AWS CDK calls this string the *unique ID* of the construct\. In general, your AWS CDK app should not need to know about unique IDs\. You can, however, access the unique ID of any construct programmatically, as shown in the following example\. @@ -231,7 +231,7 @@ string uid = Names.Uniqueid(myConstruct); ------ -The *address* is another kind of unique identifier that uniquely distinguishes CDK resources\. Derived from the SHA\-1 hash of the path, it is not human\-readable, but its constant, relatively short length \(always 42 hexadecimal characters\) makes it useful in situations where the "traditional" unique ID might be too long\. Some constructs may use the address in the synthesized AWS CloudFormation template instead of the unique ID\. Again, your app generally should not need to know about its constructs' addresses, but you can retrieve a construct's address as follows\. +The *address* is another kind of unique identifier that uniquely distinguishes CDK resources\. Derived from the SHA\-1 hash of the path, it is not human\-readable\. However, its constant, relatively short length \(always 42 hexadecimal characters\) makes it useful in situations where the "traditional" unique ID might be too long\. Some constructs may use the address in the synthesized AWS CloudFormation template instead of the unique ID\. Again, your app generally should not need to know about its constructs' addresses, but you can retrieve a construct's address as follows\. ------ #### [ TypeScript ] @@ -272,10 +272,10 @@ string addr = myConstruct.Node.Addr; ## Logical IDs -Unique IDs serve as the *logical identifiers*, which are sometimes called *logical names*, of resources in the generated AWS CloudFormation templates for those constructs that represent AWS resources\. +Unique IDs serve as the *logical identifiers* \(or *logical names*\) of resources in the generated AWS CloudFormation templates for constructs that represent AWS resources\. -For example, the Amazon S3 bucket in the previous example that is created within `Stack2` results in an `AWS::S3::Bucket` resource with the logical ID `Stack2MyBucket4DD88B4F` in the resulting AWS CloudFormation template\. +For example, the Amazon S3 bucket in the previous example that is created within `Stack2` results in an `AWS::S3::Bucket` resource\. The resource's logical ID is `Stack2MyBucket4DD88B4F` in the resulting AWS CloudFormation template\. ### Logical ID stability -Avoid changing the logical ID of a resource after it has been created\. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation creates a new resource with the new logical ID, then deletes the existing one\. Depending on the type of resource, this may cause service interruption or data loss, or both\. \ No newline at end of file +Avoid changing the logical ID of a resource after it has been created\. AWS CloudFormation identifies resources by their logical ID\. Therefore, if you change the logical ID of a resource, AWS CloudFormation creates a new resource with the new logical ID, then deletes the existing one\. Depending on the type of resource, this might cause service interruption, data loss, or both\. \ No newline at end of file diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index 95c50782..1d41115e 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -1,6 +1,8 @@ # Managing dependencies -Dependencies for your AWS CDK app or library are managed using package management tools commonly used with the programming language in which you develop your app\. Typically, the CDK supports the language's standard or official package management tool, if there is one, or its most popular or widely\-supported one if not\. You may also be able to use other tools, especially if they interoperate with the supported tools, although our ability to support alternatives is limited\. +Dependencies for your AWS CDK app or library are managed using package management tools\. These tools are commonly used with the programming language in which you develop your app\. + +Typically, the CDK supports the language's standard or official package management tool, if there is one, or its most popular or widely supported one if not\. You might also be able to use other tools, especially if they interoperate with the supported tools, although our ability to support alternatives is limited\. The CDK supports the following package managers\. @@ -25,15 +27,15 @@ In TypeScript and JavaScript CDK projects, dependencies are specified in `packag **Tip** When you install a package using npm install, NPM records it in `package.json` for you\. -If you prefer, you may use Yarn in place of NPM\. However, the CDK does not support Yarn's plug\-and\-play mode, which is default mode in Yarn 2\. Add the following to your project's `.yarnrc.yml` file to disable this feature\. +If you prefer, you may use Yarn in place of NPM\. However, the CDK does not support Yarn's plug\-and\-play mode, which is default mode in Yarn 2\. Add the following to your project's `.yarnrc.yml` file to turn off this feature\. ``` nodeLinker: node-modules ``` -### Applications +### Applications -The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. +The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, only without the TypeScript\-related entries\. ``` { @@ -65,13 +67,13 @@ The following is an example `package.json` generated by cdk init \-\-language ty } ``` -For deployable CDK apps, `aws-cdk-lib` must be specified in the `dependencies` section of `package.json`\. You may use a caret \(^\) version number specifier to indicate that you will accept later versions than the one specified as long as they are within the same major version\. +For deployable CDK apps, `aws-cdk-lib` must be specified in the `dependencies` section of `package.json`\. You can use a caret \(^\) version number specifier to indicate that you will accept later versions than the one specified as long as they are within the same major version\. Specify exact versions for alpha construct library modules, which have APIs that may change\. Do not use ^ or \~ since later versions of these modules may bring API changes that can break your app\. Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -94,14 +96,14 @@ If you're developing a construct library, specify its dependencies via a combina } ``` -In `peerDependencies`, use a caret \(^\) to specify the lowest version of `aws-cdk-lib` that your library works with, to maximize the compatibility of your library with a range of CDK versions\. Specify exact versions for alpha construct library modules, which have APIs that may change\. Using `peerDependencies` makes sure there is only one copy of all CDK libraries in the `node_modules` tree\. +In `peerDependencies`, use a caret \(^\) to specify the lowest version of `aws-cdk-lib` that your library works with\. This maximizes the compatibility of your library with a range of CDK versions\. Specify exact versions for alpha construct library modules, which have APIs that may change\. Using `peerDependencies` makes sure that there is only one copy of all CDK libraries in the `node_modules` tree\. -In `devDependencies`, specify the tools and libraries you need for testing, optionally with ^ to indicate that later compatible versions are acceptable\. Specify exactly \(without ^ or \~\) the lowest versions of `aws-cdk-lib` and other CDK packages that you advertise your library be compatible with\. This practice ensures that your tests run against those versions, so that if you inadvertently use a feature found only in newer versions, your tests can catch it\. +In `devDependencies`, specify the tools and libraries you need for testing, optionally with ^ to indicate that later compatible versions are acceptable\. Specify exactly \(without ^ or \~\) the lowest versions of `aws-cdk-lib` and other CDK packages that you advertise your library be compatible with\. This practice makes sure that your tests run against those versions\. This way, if you inadvertently use a feature found only in newer versions, your tests can catch it\. **Warning** -`peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies +`peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`\. Otherwise, they won't be installed, and you will receive a warning about unresolved peer dependencies\. -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -129,7 +131,7 @@ yarn install --frozen-lockfile ------ -To update the installed modules, the npm install and yarn upgrade commands given above can be used\. Either command updates the packages in `node_modules` to the latest versions that satisfy the rules in `package.json`, but they do not update `package.json` itself, which you might want to do to set a new minimum version\. If you host your package on GitHub, you can configure [Dependabot version updates](https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuring-dependabot-version-updates) to automatically update `package.json`\. Alternatively, use [npm\-check\-updates](https://www.npmjs.com/package/npm-check-updates)\. +To update the installed modules, the preceding npm install and yarn upgrade commands can be used\. Either command updates the packages in `node_modules` to the latest versions that satisfy the rules in `package.json`\. However, they do not update `package.json` itself, which you might want to do to set a new minimum version\. If you host your package on GitHub, you can configure [Dependabot version updates](https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuring-dependabot-version-updates) to automatically update `package.json`\. Alternatively, use [npm\-check\-updates](https://www.npmjs.com/package/npm-check-updates)\. **Important** By design, when you install or update dependencies, NPM and Yarn choose the latest version of every package that satisfies the requirements specified in `package.json`\. There is always a risk that these versions may be broken \(either accidentally or intentionally\)\. Test thoroughly after updating your project's dependencies\. @@ -145,9 +147,9 @@ python -m pip command options The python \-m pip invocation works on most systems; pip requires that PIP's executable be on the system path\. If pip doesn't work, try replacing it with python \-m pip\. -cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. +cdk init \-\-language python creates a virtual environment for your new project\. This lets each project have its own versions of dependencies, and also a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -165,9 +167,9 @@ python -m pip install -r requirements.txt ``` **Tip** -The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. +The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file\. This can be used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(including transitive ones\) to the exact versions that you tested with\. To avoid problems when upgrading packages later, use a separate file for this, such as `freeze.txt` \(not `requirements.txt`\)\. Then, regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. @@ -214,7 +216,7 @@ Many Java IDEs have integrated Maven support and visual `pom.xml` editors, which ``` -Maven does not support dependency locking, so while it is possible to specify version ranges in `pom.xml`, we recommend you always use exact versions to keep your builds repeatable\. +Maven does not support dependency locking\. Although it's possible to specify version ranges in `pom.xml`, we recommend you always use exact versions to keep your builds repeatable\. Maven automatically installs transitive dependencies, but there can only be one installed copy of each package\. The version that is specified highest in the POM tree is selected; applications always have the last word in what version of packages get installed\. @@ -222,9 +224,9 @@ Maven automatically installs or updates your dependencies whenever you build \(m ## C\# -In C\# AWS CDK apps, you manage dependencies using NuGet\. NuGet has four standard, mostly\-equivalent interfaces; you can use the one that suits your needs and working style\. You can also use compatible tools, such as [Paket](https://fsprojects.github.io/Paket/) or [MyGet](https://www.myget.org/) or even edit the `.csproj` file directly\. +In C\# AWS CDK apps, you manage dependencies using NuGet\. NuGet has four standard, mostly equivalent interfaces; you can use the one that suits your needs and working style\. You can also use compatible tools, such as [Paket](https://fsprojects.github.io/Paket/) or [MyGet](https://www.myget.org/) or even edit the `.csproj` file directly\. -NuGet does not allow you to specify version ranges for dependencies\. Every dependency is pinned to a specific version\. +NuGet does not let you specify version ranges for dependencies\. Every dependency is pinned to a specific version\. After updating your dependencies, Visual Studio will use NuGet to retrieve the specified versions of each package the next time you build\. If you are not using Visual Studio, use the dotnet restore command to update your dependencies\. @@ -241,10 +243,10 @@ Your project's `.csproj` file contains an `` container that lists you ### The Visual Studio NuGet GUI -Visual Studio's NuGet tools are accessible from **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution**\. Use the **Browse** tab to find the AWS Construct Library packages you want to install\. You can choose the desired version, including pre\-release versions of your modules and add them to any of the open projects\. +Visual Studio's NuGet tools are accessible from **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution**\. Use the **Browse** tab to find the AWS Construct Library packages you want to install\. You can choose the desired version, including prerelease versions of your modules, and add them to any of the open projects\. **Note** -All AWS Construct Library modules deemed "experimental" \(see [Versioning](reference.md#versioning)\) are flagged as pre\-release in NuGet and have an `alpha` name suffix\. +All AWS Construct Library modules deemed "experimental" \(see [Versioning](reference.md#versioning)\) are flagged as prerelease in NuGet and have an `alpha` name suffix\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/visual-studio-nuget.png) @@ -256,15 +258,15 @@ The NuGet console is a PowerShell\-based interface to NuGet that works in the co ### The `dotnet` command -The `dotnet` command is the primary command\-line tool for working with Visual Studio C\# projects\. You can invoke it from any Windows command prompt\. Among its many capabilities, `dotnet` can add NuGet dependencies to a Visual Studio project\. +The `dotnet` command is the primary command line tool for working with Visual Studio C\# projects\. You can invoke it from any Windows command prompt\. Among its many capabilities, `dotnet` can add NuGet dependencies to a Visual Studio project\. -Assuming you're in the same directory as the Visual Studio project \(`.csproj`\) file, issue a command like the following to install a package\. Note that since the main CDK library is included when you create a project, you should ever only need to explictly install experimental modules\. Experimental modules require you to specify an explicit version number\. +Assuming you're in the same directory as the Visual Studio project \(`.csproj`\) file, issue a command like the following to install a package\. Because the main CDK library is included when you create a project, you only need to explicitly install experimental modules\. Experimental modules require you to specify an explicit version number\. ``` dotnet add package Amazon.CDK.AWS.IoT.Alpha -v VERSION-NUMBER ``` -You may issue the command from another directory by including the path to the project file, or to the directory that contains it, after the `add` keyword\. The following example assumes that you are in your AWS CDK project's main directory\. +You can issue the command from another directory\. To do so, include the path to the project file, or to the directory that contains it, after the `add` keyword\. The following example assumes that you are in your AWS CDK project's main directory\. ``` dotnet add src/PROJECT-DIR package Amazon.CDK.AWS.IoT.Alpha -v VERSION-NUMBER @@ -300,4 +302,4 @@ require ( Package names \(modules, in Go parlance\) are specified by URL with the required version number appended\. Go's module system does not support version ranges\. -Issue the go get command to install all modules and update `go.mod`\. To see a list of available updates for your dependencies, issue go list \-m \-u all\. \ No newline at end of file +Issue the go get command to install all required modules and update `go.mod`\. To see a list of available updates for your dependencies, issue go list \-m \-u all\. \ No newline at end of file diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index 44326741..f4fe5854 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -1,43 +1,43 @@ # Migrating to AWS CDK v2 -Version 2 of the AWS Cloud Development Kit \(AWS CDK\) is designed to make writing infrastructure as code in your preferred programming language even easier\. This topic describes the changes between v1 and v2 of the AWS CDK\. +Version 2 of the AWS Cloud Development Kit \(AWS CDK\) is designed to make writing infrastructure as code in your preferred programming language easier\. This topic describes the changes between v1 and v2 of the AWS CDK\. **Tip** To identify stacks deployed with AWS CDK v1, use the [awscdk\-v1\-stack\-finder](https://www.npmjs.com/package/awscdk-v1-stack-finder) utility\. The main changes from AWS CDK v1 to CDK v2 are as follows\. -+ AWS CDK v2 consolidates the stable parts of the AWS Construct Library, including the core library, into a single package, `aws-cdk-lib`\. Developers no longer need to install additional packages for the individual AWS services they use\. This single\-package approach also eliminates the need to synchronize the versions of the various CDK library packages\. ++ AWS CDK v2 consolidates the stable parts of the AWS Construct Library, including the core library, into a single package, `aws-cdk-lib`\. Developers no longer need to install additional packages for the individual AWS services they use\. This single\-package approach also means that you don't have to synchronize the versions of the various CDK library packages\. L1 \(CfnXXXX\) constructs, which represent the exact resources available in AWS CloudFormation, are always considered stable and so are included in `aws-cdk-lib`\. -+ Experimental modules, where we're still working with the community to develop new [L2 or L3 constructs](constructs.md#constructs_lib), are not included in `aws-cdk-lib`; they are instead distributed as individual packages\. Experimental packages are named with an `alpha` suffix and a semantic version number that matches the first version of the AWS Construct Library with which they are compatible, also with an `alpha` suffix\. Constructs move into `aws-cdk-lib` after being designated stable, permitting the main Construct Library to adhere to strict semantic versioning\. ++ Experimental modules, where we're still working with the community to develop new [L2 or L3 constructs](constructs.md#constructs_lib), are not included in `aws-cdk-lib`\. Instead, they're distributed as individual packages\. Experimental packages are named with an `alpha` suffix and a semantic version number\. The semantic version number matches the first version of the AWS Construct Library that they're compatible with, also with an `alpha` suffix\. Constructs move into `aws-cdk-lib` after being designated stable, permitting the main Construct Library to adhere to strict semantic versioning\. - Stability is specified at the service level\. For example, if we begin creating one or more [L2 constructs](constructs.md#constructs_lib) for Amazon AppFlow, which at this writing has only L1 constructs, they would first appear in a module named `@aws-cdk/aws-appflow-alpha`, then move to `aws-cdk-lib` when we feel the new constructs meet the fundamental needs of customers\. + Stability is specified at the service level\. For example, if we begin creating one or more [L2 constructs](constructs.md#constructs_lib) for Amazon AppFlow, which at this writing has only L1 constructs, they first appear in a module named `@aws-cdk/aws-appflow-alpha`\. Then, they move to `aws-cdk-lib` when we feel that the new constructs meet the fundamental needs of customers\. Once a module has been designated stable and incorporated into `aws-cdk-lib`, new APIs are added using the "BetaN" convention described in the next bullet\. - A new version of each experimental module is released with every release of the AWS CDK, but for the most part, they needn't be kept in sync\. You can upgrade `aws-cdk-lib` or the experimental module whenever you want\. The exception is that when two or more related experimental modules depend on each other, they must be the same version\. -+ For stable modules to which new functionality is being added, new APIs \(whether entirely new constructs or new methods or properties on an existing construct\) receive a `Beta1` suffix \(and then `Beta2`, `Beta3`, etc\. when breaking changes are needed\) while work is in progress\. A version of the API without the suffix is added when the API is designated stable\. All methods except the latest \(whether beta or final\) are then deprecated\. + A new version of each experimental module is released with every release of the AWS CDK\. For the most part, however, they needn't be kept in sync\. You can upgrade `aws-cdk-lib` or the experimental module whenever you want\. The exception is that when two or more related experimental modules depend on each other, they must be the same version\. ++ For stable modules to which new functionality is being added, new APIs \(whether entirely new constructs or new methods or properties on an existing construct\) receive a `Beta1` suffix while work is in progress\. \(Followed by `Beta2`, `Beta3`, and so on when breaking changes are needed\.\) A version of the API without the suffix is added when the API is designated stable\. All methods except the latest \(whether beta or final\) are then deprecated\. - For example, if we add a new method `grantPower()` to a construct, it initially appears as `grantPowerBeta1().` If breaking changes are needed \(for example, a new required parameter or property\), the next version of the method would be named `grantPowerBeta2()`, and so on\. When work is complete and the API is finalized, the method `grantPower()` \(with no suffix\) is added, and the BetaN methods are deprecated\. + For example, if we add a new method `grantPower()` to a construct, it initially appears as `grantPowerBeta1()`\. If breaking changes are needed \(for example, a new required parameter or property\), the next version of the method would be named `grantPowerBeta2()`, and so on\. When work is complete and the API is finalized, the method `grantPower()` \(with no suffix\) is added, and the BetaN methods are deprecated\. - All the beta APIs remain in the Construct Library until the next major version \(3\.0\) release, and their signatures will not change\. You'll see deprecation warnings if you use them, so you should move to the final version of the API at your earliest convenience, but a future AWS CDK 2\.x release will not break your application\. -+ The `Construct` class has been extracted from the AWS CDK into a separate library, along with related types, to support efforts to apply the Construct Programming Model to other domains\. If you are writing your own constructs or using related APIs, you must declare the `constructs` module as a dependency and make minor changes to your imports\. If you are using advanced features, such as hooking into the CDK app lifecycle, more changes may be needed\. [See the RFC](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0192-remove-constructs-compat.md#release-notes) for full details\. + All the beta APIs remain in the Construct Library until the next major version \(3\.0\) release, and their signatures will not change\. You'll see deprecation warnings if you use them, so you should move to the final version of the API at your earliest convenience\. However, no future AWS CDK 2\.x releases will break your application\. ++ The `Construct` class has been extracted from the AWS CDK into a separate library, along with related types\. This is done to support efforts to apply the Construct Programming Model to other domains\. If you are writing your own constructs or using related APIs, you must declare the `constructs` module as a dependency and make minor changes to your imports\. If you are using advanced features, such as hooking into the CDK app lifecycle, more changes may be needed\. For full details, [see the RFC](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0192-remove-constructs-compat.md#release-notes)\. + Deprecated properties, methods, and types in AWS CDK v1\.x and its Construct Library have been removed completely from the CDK v2 API\. In most supported languages, these APIs produce warnings under v1\.x, so you may have already migrated to the replacement APIs\. A complete [list of deprecated APIs](https://github.com/aws/aws-cdk/blob/master/DEPRECATED_APIs.md) in CDK v1\.x is available on GitHub\. -+ Behavior that was gated by feature flags in AWS CDK v1\.x is enabled by default in CDK v2, and the old feature flags are no longer needed or, in most cases, supported\. A handful are still available to let you to revert to CDK v1 behavior in very specific circumstances; see [Updating feature flags](#migrating-v2-v1-upgrade-cdk-json)\. -+ CDK v2 requires that the environments you deploy into be bootstrapped using the modern bootstrap stack; the legacy bootstrap stack \(the default under v1\) is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. Simply re\-bootstrap your existing environments to upgrade them\. It is no longer necessary to set any feature flags or environment variables to specify the modern bootstrap stack\. ++ Behavior that was gated by feature flags in AWS CDK v1\.x is enabled by default in CDK v2\. The earlier feature flags are no longer needed, and in most cases they're not supported\. A few are still available to let you revert to CDK v1 behavior in very specific circumstances\. For more information, see [Updating feature flags](#migrating-v2-v1-upgrade-cdk-json)\. ++ With CDK v2, the environments you deploy into must be bootstrapped using the modern bootstrap stack\. The legacy bootstrap stack \(the default under v1\) is no longer supported\. CDK v2 furthermore requires a new version of the modern stack\. To upgrade your existing environments, re\-bootstrap them\. It is no longer necessary to set any feature flags or environment variables to use the modern bootstrap stack\. **Important** -The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list, which by default will extend permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts you are comfortable with\. +The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any AWS account in the `--trust` list\. By default, this extends permissions to read and write to any resource in the bootstrapped account\. Make sure to [configure the bootstrapping stack](bootstrapping.md#bootstrapping-customizing) with policies and trusted accounts that you are comfortable with\. ## New prerequisites Most requirements for AWS CDK v2 are the same as for AWS CDK v1\.x\. Additional requirements are listed here\. + For TypeScript developers, TypeScript 3\.8 or later is required\. -+ A new version of the CDK Toolkit is required for use with CDK v2\. Now that CDK v2 is Generally Available, v2 is the default version when installing the CDK Toolkit\. It is backward\-compatible with CDK v1 projects, so you do not need to keep the old version installed unless you want to create CDK v1 projects\. To upgrade, issue `npm install -g aws-cdk`\. ++ A new version of the CDK Toolkit is required for use with CDK v2\. Now that CDK v2 is generally available, v2 is the default version when installing the CDK Toolkit\. It is backward\-compatible with CDK v1 projects, so you don't need to keep the earlier version installed unless you want to create CDK v1 projects\. To upgrade, issue `npm install -g aws-cdk`\. ## Upgrading from AWS CDK v2 Developer Preview -If you have been using the CDK v2 Developer Preview, you have dependencies in your project on a Release Candidate version of the AWS CDK, such as `2.0.0-rc1`\. Update these to `2.0.0`, then update the modules installed in your project\. +If you're using the CDK v2 Developer Preview, you have dependencies in your project on a Release Candidate version of the AWS CDK, such as `2.0.0-rc1`\. Update these to `2.0.0`, then update the modules installed in your project\. ------ #### [ TypeScript ] @@ -83,7 +83,7 @@ After updating your dependencies, issue `npm update -g aws-cdk` to update the CD ## Migrating from AWS CDK v1 to CDK v2 -To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language it is written in\. +To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\. Then update your app's dependencies and imports as necessary for the programming language that it's written in\. ### Updating feature flags @@ -93,7 +93,7 @@ A handful of v1 feature flags can be set to `false` in order to revert to specif ### CDK Toolkit compatibility -CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compatible with CDK v1 apps, so you can use a single globally\-installed version of CDK Toolkit with all your AWS CDK projects, whether they use v1 or v2\. An exception is that CDK Toolkit v2 only creates CDK v2 projects\. +CDK v2 requires v2 or later of the CDK Toolkit\. This version is backward\-compatible with CDK v1 apps\. Therefore, you can use a single globally installed version of CDK Toolkit with all your AWS CDK projects, whether they use v1 or v2\. An exception is that CDK Toolkit v2 only creates CDK v2 projects\. If you need to create both v1 and v2 CDK projects, **do not install CDK Toolkit v2 globally\.** \(Remove it if you already have it installed: `npm remove -g aws-cdk`\.\) To invoke the CDK Toolkit, use npx to run v1 or v2 of the CDK Toolkit as desired\. @@ -125,7 +125,7 @@ Update your app's dependencies, then install the new packages\. Finally, update **Applications** For CDK apps, update `package.json` as follows\. Remove dependencies on v1\-style individual stable modules and establish the lowest version of `aws-cdk-lib` you require for your application \(2\.0\.0 here\)\. -Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` with which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. +Experimental constructs are provided in separate, independently versioned packages with names that end in `alpha` and an alpha version number\. The alpha version number corresponds to the first release of `aws-cdk-lib` with which they're compatible\. Here, we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. ``` { @@ -157,8 +157,8 @@ Note that `aws-cdk-lib` appears both as a peer dependency and a dev dependency\. ``` **Note** -You should perform a major version bump on your library's version number when releasing a v2\-compatible library, as this will be a breaking change for consumers of the library\. It is not possible to support both CDK v1 and v2 with a single library\. To continue to support customers who are still using v1, you could maintain the older release in parallel, or create a new package for v2\. -It's up to you how long you want to continue supporting AWS CDK v1 customers, but you could take your cue from the lifecycle of CDK v1 itself, which entered maintenance on June 1, 2022 and will reach end\-of\-life on June 1, 2023\. For full details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy) +You should perform a major version bump on your library's version number when releasing a v2\-compatible library, because this is a breaking change for library consumers\. It is not possible to support both CDK v1 and v2 with a single library\. To continue to support customers who are still using v1, you could maintain the earlier release in parallel, or create a new package for v2\. +It's up to you how long you want to continue supporting AWS CDK v1 customers\. You might take your cue from the lifecycle of CDK v1 itself, which entered maintenance on June 1, 2022 and will reach end\-of\-life on June 1, 2023\. For full details, see [AWS CDK Maintenance Policy](https://github.com/aws/aws-cdk-rfcs/blob/master/text/0079-cdk-2.0.md#aws-cdk-maintenance-policy)\. **Both libraries and apps** Install the new dependencies by running `npm install` or `yarn install`\. @@ -177,7 +177,7 @@ import * as codestar from '@aws-cdk/aws-codestar-alpha'; // experimental module Update `package.json` as follows\. Remove dependencies on v1\-style individual stable modules and establish the lowest version of `aws-cdk-lib` you require for your application \(2\.0\.0 here\)\. -Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` with which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. +Experimental constructs are provided in separate, independently versioned packages with names that end in `alpha` and an alpha version number\. The alpha version number corresponds to the first release of `aws-cdk-lib` with which they're compatible\. Here, we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. ``` { @@ -191,7 +191,10 @@ Experimental constructs are provided in separate, independently\-versioned packa Install the new dependencies by running `npm install` or `yarn install`\. -Change your app's imports to import `Construct` from the new `constructs` module, core types such as `App` and `Stack` from the top level of `aws-cdk-lib`, and AWS Construct Library modules from namespaces under `aws-cdk-lib`\. +Change your app's imports to do the following: ++ Import `Construct` from the new `constructs` module ++ Import core types, such as `App` and `Stack`, from the top level of `aws-cdk-lib` ++ Import AWS Construct Library modules from namespaces under `aws-cdk-lib` ``` const { Construct } = require('constructs'); @@ -205,7 +208,7 @@ const codestar = require('@aws-cdk/aws-codestar-alpha'); // experimental modu Update `requirements.txt` or the `install_requires` definition in `setup.py` as follows\. Remove dependencies on v1\-style individual stable modules\. -Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0alpha1\. +Experimental constructs are provided in separate, independently versioned packages with names that end in `alpha` and an alpha version number\. The alpha version number corresponds to the first release of `aws-cdk-lib` with which they're compatible\. Here, we have pinned `aws-codestar` to v2\.0\.0alpha1\. ``` install_requires=[ @@ -219,7 +222,10 @@ install_requires=[ **Tip** Uninstall any other versions of AWS CDK modules already installed in your app's virtual environment using `pip uninstall`\. Then Install the new dependencies with `python -m pip install -r requirements.txt`\. -Change your app's imports to import `Construct` from the new `constructs` module, core types such as `App` and `Stack` from the top level of `aws_cdk`, and AWS Construct Library modules from namespaces under `aws_cdk`\. +Change your app's imports to do the following: ++ Import `Construct` from the new `constructs` module ++ Import core types, such as `App` and `Stack`, from the top level of `aws_cdk` ++ Import AWS Construct Library modules from namespaces under `aws_cdk` ``` from constructs import Construct @@ -243,7 +249,7 @@ s3.Bucket(...) In `pom.xml`, remove all `software.amazon.awscdk` dependencies for stable modules and replace them with dependencies on `software.constructs` \(for `Construct`\) and `software.amazon.awscdk`\. -Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` wit which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. +Experimental constructs are provided in separate, independently versioned packages with names that end in `alpha` and an alpha version number\. The alpha version number corresponds to the first release of `aws-cdk-lib` with which they're compatible\. Here, we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. ``` @@ -264,7 +270,10 @@ Experimental constructs are provided in separate, independently\-versioned packa Install the new dependencies by running `mvn package`\. -Change your code to import `Construct` from the new `software.constructs` library, core classes like `Stack` and `App` from `software.amazon.awscdk`, and service constructs from `software.amazon.awscdk.services`\. +Change your code to do the following: ++ Import `Construct` from the new `software.constructs` library ++ Import core classes, like `Stack` and `App`, from `software.amazon.awscdk` ++ Import service constructs from `software.amazon.awscdk.services` ``` import software.constructs.Construct; @@ -280,7 +289,7 @@ import software.amazon.awscdk.services.codestar.alpha.GitHubRepository; The most straightforward way to upgrade the dependencies of a C\# CDK application is to edit the `.csproj` file manually\. Remove all stable `Amazon.CDK.*` package references and replace them with references to the `Amazon.CDK.Lib` and `Constructs` packages\. -Experimental constructs are provided in separate, independently\-versioned packages with names that end in `alpha` and an alpha version number that corresponds to the first release of `aws-cdk-lib` with which they are compatible\. Here we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. +Experimental constructs are provided in separate, independently versioned packages with names that end in `alpha` and an alpha version number\. The alpha version number corresponds to the first release of `aws-cdk-lib` with which they're compatible\. Here, we have pinned `aws-codestar` to v2\.0\.0\-alpha\.1\. ``` @@ -311,25 +320,35 @@ Issue go get to update your dependencies to the latest version and update your p Before deploying your stacks, use `cdk diff` to check for unexpected changes to the resources\. Changes to logical IDs \(causing replacement of resources\) are **not** expected\. Expected changes include but are not limited to: -+ Changes to the `CDKMetadata` resource -+ Updated asset hashes -+ Changes related to the new\-style stack synthesis, if your app used the legacy stack synthesizer in v1 \(CDK v2 does not support the legacy stack synthesizer\) -+ The addition of a `CheckBootstrapVersion` rule ++ Changes to the `CDKMetadata` resource\. ++ Updated asset hashes\. ++ Changes related to the new\-style stack synthesis\. Applies if your app used the legacy stack synthesizer in v1\. \(CDK v2 does not support the legacy stack synthesizer\.\) ++ The addition of a `CheckBootstrapVersion` rule\. -Unexpected changes are typically not caused by upgrading to AWS CDK v2 in itself, but are usually the result of deprecated behavior that was previously changed by feature flags\. This is a symptom of upgrading from a version of CDK older than about 1\.85\.x; you'd see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by upgrading your app to the latest v1\.x release, removing feature flags, revising your code as necessary, deploying, and then upgrading to v2\. +Unexpected changes are typically not caused by upgrading to AWS CDK v2 in itself\. Usually, they're the result of deprecated behavior that was previously changed by feature flags\. This is a symptom of upgrading from a version of CDK earlier than about 1\.85\.x\. You would see the same changes upgrading to the latest v1\.x release\. You can usually resolve this by doing the following: + +1. Upgrade your app to the latest v1\.x release + +1. Remove feature flags + +1. Revise your code as necessary + +1. Deploy + +1. Upgrade to v2 **Note** -If your upgraded app ends up undeployable after the two\-stage upgrade, please [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. +If your upgraded app is undeployable after the two\-stage upgrade, [report the issue](https://github.com/aws/aws-cdk/issues/new/choose)\. -When you are ready to deploy the stacks in your app, consider deploying a copy first so you can test it\. The easiest way to do this is to deploy it into a different region\. However, you can also simply change the IDs of your stack\(s\)\. After testing, be sure to destroy the testing copy with cdk destroy\. +When you are ready to deploy the stacks in your app, consider deploying a copy first so you can test it\. The easiest way to do this is to deploy it into a different Region\. However, you can also change the IDs of your stacks\. After testing, be sure to destroy the testing copy with cdk destroy\. ## Troubleshooting -**Typescript `'from' expected` or `';' expected` error in imports** +**TypeScript `'from' expected` or `';' expected` error in imports** Upgrade to TypeScript 3\.8 or later\. -**Please run 'cdk bootstrap'** -If you see an error like this one: +**Run 'cdk bootstrap'** +If you see an error like the following: ``` ❌ MyStack failed: Error: MyStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) @@ -338,7 +357,7 @@ If you see an error like this one: MyStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) ``` -AWS CDK v2 requires an updated bootstrap stack, and furthermore, all v2 deployments require bootstrap resources \(v1 allowed you to deploy simple stacks without having bootstrapped\)\. See [Bootstrapping](bootstrapping.md) for complete details\. +AWS CDK v2 requires an updated bootstrap stack, and furthermore, all v2 deployments require bootstrap resources\. \(With v1, you could deploy simple stacks without bootstrapping\.\) For complete details, see [Bootstrapping](bootstrapping.md)\. ## Finding v1 stacks @@ -348,4 +367,4 @@ When migrating your CDK application from v1 to v2, you might want to identify th npx awscdk-v1-stack-finder ``` -See the awscdk\-v1\-stack\-finder [README](https://github.com/cdklabs/awscdk-v1-stack-finder/blob/main/README.md) for usage details\. \ No newline at end of file +For usage details, see the awscdk\-v1\-stack\-finder [README](https://github.com/cdklabs/awscdk-v1-stack-finder/blob/main/README.md)\. \ No newline at end of file diff --git a/v2/multiple_languages.md b/v2/multiple_languages.md index fbacf64d..9633fc8b 100644 --- a/v2/multiple_languages.md +++ b/v2/multiple_languages.md @@ -1,6 +1,6 @@ # Translating TypeScript AWS CDK code to other languages -TypeScript was the first language supported for developing AWS CDK applications, and for that reason, there is a substantial amount of example CDK code written in TypeScript\. If you are developing in another language, it may be useful to compare how AWS CDK code is implemented in TypeScript and your language of choice, so you can, with a little effort, make use of these examples\. +TypeScript was the first language supported for developing AWS CDK applications\. Therefore, a substantial amount of example CDK code is written in TypeScript\. If you are developing in another language, it might be useful to compare how AWS CDK code is implemented in TypeScript and your language of choice\. This can help you use these examples\. For more details on working with the AWS CDK in its supported programming languages, see: + [Working with the AWS CDK in TypeScript](work-with-cdk-typescript.md) @@ -49,7 +49,7 @@ const bucket = Bucket(...); ------ #### [ Python ] -Like TypeScript, Python supports namespaced module imports and selective imports\. Namespaces in Python look like **aws\_cdk\.***xxx*, where *xxx* represents an AWS service name, such as **s3** for Amazon S3 \(we'll use Amazon S3 for our examples\)\. +Like TypeScript, Python supports namespaced module imports and selective imports\. Namespaces in Python look like **aws\_cdk\.***xxx*, where *xxx* represents an AWS service name, such as **s3** for Amazon S3\. \(Amazon S3 is used in these examples\)\. ``` # Import main CDK library as cdk @@ -109,9 +109,9 @@ var bucket = ------ #### [ C\# ] -In C\#, you import types with the `using` directive\. There are two styles, which give you access either all the types in the specified namespace using their plain names, or let you refer to the namespace itself using an alias\. +In C\#, you import types with the `using` directive\. There are two styles\. One gives you access to all the types in the specified namespace by using their plain names\. With the other, you can refer to the namespace itself by using an alias\. -Packages are named like `Amazon.CDK.AWS.xxx` for AWS Construct Library packages \(the core module is `Amazon.CDK`\)\. +Packages are named like `Amazon.CDK.AWS.xxx` for AWS Construct Library packages\. \(The core module is `Amazon.CDK`\.\) ``` // Make CDK base classes available under cdk @@ -163,7 +163,7 @@ bucket := s3.NewBucket(...) AWS CDK construct classes have the same name in all supported languages\. Most languages use the `new` keyword to instantiate a class \(Python and Go do not\)\. Also, in most languages, the keyword `this` refers to the current instance\. \(Python uses `self` by convention\.\) You should pass a reference to the current instance as the `scope` parameter to every construct you create\. - The third argument to a AWS CDK construct is `props`, an object containing attributes needed to build the construct\. This argument may be optional, but when it is required, the supported languages handle it in idiomatic ways\. The names of the attributes are also adapted to the language's standard naming patterns\. +The third argument to an AWS CDK construct is `props`, an object containing attributes needed to build the construct\. This argument may be optional, but when it is required, the supported languages handle it in idiomatic ways\. The names of the attributes are also adapted to the language's standard naming patterns\. ------ #### [ TypeScript/JavaScript ] @@ -190,7 +190,7 @@ const bucket = new s3.Bucket(this, 'MyBucket', { Python doesn't use a `new` keyword when instantiating a class\. The properties argument is represented using keyword arguments, and the arguments are named using `snake_case`\. -If a props value is itself a bundle of attributes, it is represented by a class named after the property, which accepts keyword arguments for the sub\-properties\. +If a props value is itself a bundle of attributes, it is represented by a class named after the property, which accepts keyword arguments for the subproperties\. In Python, the current instance is passed to methods as the first argument, which is named `self` by convention\. @@ -211,7 +211,7 @@ bucket = s3.Bucket(self, "MyBucket", website_redirect=s3.WebsiteRedirect( In Java, the props argument is represented by a class named `XxxxProps` \(for example, `BucketProps` for the `Bucket` construct's props\)\. You build the props argument using a builder pattern\. -Each `XxxxProps` class has a builder, and there is also a convenient builder for each construct that builds the props and the construct in one step, as shown here\. +Each `XxxxProps` class has a builder\. There is also a convenient builder for each construct that builds the props and the construct in one step, as shown in the following example\. Props are named the same as in TypeScript, using `camelCase`\. @@ -284,7 +284,7 @@ In Go, all construct parameters are pointers, including values like numbers, Boo ## Accessing members -It is common to refer to attributes or properties of constructs and other AWS CDK classes and use these values as, for examples, inputs to build other constructs\. The naming differences described above for methods apply\. Furthermore, in Java, it is not possible to access members directly; instead, a getter method is provided\. +It is common to refer to attributes or properties of constructs and other AWS CDK classes and use these values as, for example, inputs to build other constructs\. The naming differences described previously for methods apply here also\. Furthermore, in Java, it is not possible to access members directly\. Instead, a getter method is provided\. ------ #### [ TypeScript/JavaScript ] @@ -351,7 +351,7 @@ awss3.BucketEncryption_KMS_MANAGED ## Object interfaces -The AWS CDK uses TypeScript object interfaces to indicate that a class implements an expected set of methods and properties\. You can recognize an object interface because its name starts with `I`\. A concrete class indicates the interface\(s\) it implements using the `implements` keyword\. +The AWS CDK uses TypeScript object interfaces to indicate that a class implements an expected set of methods and properties\. You can recognize an object interface because its name starts with `I`\. A concrete class indicates the interfaces that it implements by using the `implements` keyword\. ------ #### [ TypeScript/JavaScript ] diff --git a/v2/parameters.md b/v2/parameters.md index effda5b2..65721b05 100644 --- a/v2/parameters.md +++ b/v2/parameters.md @@ -1,8 +1,8 @@ # Parameters -AWS CloudFormation templates can contain [parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html)—custom values that are supplied at deployment time and incorporated into the template\. Since the AWS CDK synthesizes AWS CloudFormation templates, it too offers support for deployment\-time parameters\. +AWS CloudFormation templates can contain [parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html)—custom values that are supplied at deployment time and incorporated into the template\. Because the AWS CDK synthesizes AWS CloudFormation templates, it also offers support for deployment\-time parameters\. -Using the AWS CDK, you can both define parameters, which can then be used in the properties of constructs you create, and you can also deploy stacks containing parameters\. +Using the AWS CDK, you can define parameters, which can then be used in the properties of constructs you create\. You can also deploy stacks that contain parameters\. When deploying the AWS CloudFormation template using the AWS CDK Toolkit, you provide the parameter values on the command line\. If you deploy the template through the AWS CloudFormation console, you are prompted for the parameter values\. @@ -11,18 +11,18 @@ In general, we recommend against using AWS CloudFormation parameters with the AW **Note** To do control flow with parameters, you can use [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnCondition.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnCondition.html) constructs, although this is awkward compared to native `if` statements\. -Using parameters requires you to be mindful of how the code you're writing behaves at deployment time, as well as at synthesis time\. This makes it harder to understand and reason about your AWS CDK application, in many cases for little benefit\. +Using parameters requires you to be mindful of how the code you're writing behaves at deployment time, and also at synthesis time\. This makes it harder to understand and reason about your AWS CDK application, in many cases for little benefit\. -It is better, again in general, to have your CDK app accept any necessary information in some well\-defined way and use it directly to declare constructs in your CDK app\. An ideal AWS CDK\-generated AWS CloudFormation template is concrete, with no values remaining to be specified at deployment time\. +Generally, it's better to have your CDK app accept necessary information in a well\-defined way and use it directly to declare constructs in your CDK app\. An ideal AWS CDK\-generated AWS CloudFormation template is concrete, with no values remaining to be specified at deployment time\. -There are, however, use cases to which AWS CloudFormation parameters are uniquely suited\. If you have separate teams defining and deploying infrastructure, for example, you can use parameters to make the generated templates more widely useful\. Additionally, the AWS CDK's support for AWS CloudFormation parameters lets you use the AWS CDK with AWS services that use AWS CloudFormation templates \(such as AWS Service Catalog\), which use parameters to configure the template being deployed\. +There are, however, use cases to which AWS CloudFormation parameters are uniquely suited\. If you have separate teams defining and deploying infrastructure, for example, you can use parameters to make the generated templates more widely useful\. Also, because the AWS CDK supports AWS CloudFormation parameters, you can use the AWS CDK with AWS services that use AWS CloudFormation templates \(such as AWS Service Catalog\)\. These AWS services use parameters to configure the template that's being deployed\. ## Defining parameters Use the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnParameter.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnParameter.html) class to define a parameter\. You'll want to specify at least a type and a description for most parameters, though both are technically optional\. The description appears when the user is prompted to enter the parameter's value in the AWS CloudFormation console\. For more information on the available types, see [Types](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html#parameters-section-structure-properties-type)\. **Note** -You can define parameters in any scope, but we recommend defining parameters at the stack level so that their logical ID does not change when you refactor your code\. +You can define parameters in any scope\. However, we recommend defining parameters at the stack level so that their logical ID doesn't change when you refactor your code\. ------ #### [ TypeScript ] @@ -75,9 +75,9 @@ var uploadBucketName = new CfnParameter(this, "uploadBucketName", new CfnParamet ## Using parameters -A `CfnParameter` instance exposes its value to your AWS CDK app via a [token](tokens.md)\. Like all tokens, the parameter's token is resolved at synthesis time, but it resolves to a reference to the parameter defined in the AWS CloudFormation template, which will be resolved at deploy time, rather than to a concrete value\. +A `CfnParameter` instance exposes its value to your AWS CDK app via a [token](tokens.md)\. Like all tokens, the parameter's token is resolved at synthesis time\. But it resolves to a reference to the parameter defined in the AWS CloudFormation template \(which will be resolved at deploy time\), rather than to a concrete value\. -You can retrieve the token as an instance of the `Token` class, or in string, string list, or numeric encoding, depending on the type of value required by the class or method you want to use the parameter with\. +You can retrieve the token as an instance of the `Token` class, or in string, string list, or numeric encoding\. Your choice depends on the kind of value required by the class or method that you want to use the parameter with\. ------ #### [ TypeScript ] @@ -136,7 +136,7 @@ You can retrieve the token as an instance of the `Token` class, or in string, st ------ -For example, to use a parameter in a Bucket definition: +For example, to use a parameter in a `Bucket` definition: ------ #### [ TypeScript ] @@ -185,9 +185,9 @@ var bucket = new Bucket(this, "myBucket") ## Deploying with parameters -A generated template containing parameters can be deployed in the usual way through the AWS CloudFormation console; you are prompted for the values of each parameter\. +A generated template containing parameters can be deployed in the usual way through the AWS CloudFormation console\. You are prompted for the values of each parameter\. -The AWS CDK Toolkit \(`cdk` command\-line tool\) also supports specifying parameters at deployment\. You may provide these on the command line following the `--parameters` flag\. You might deploy a stack that uses the `uploadBucketName` parameter like this\. +The AWS CDK Toolkit \(`cdk` command line tool\) also supports specifying parameters at deployment\. You provide these on the command line following the `--parameters` flag\. You might deploy a stack that uses the `uploadBucketName` parameter, like the following example\. ``` cdk deploy MyStack --parameters uploadBucketName=uploadbucket @@ -199,7 +199,7 @@ To define multiple parameters, use multiple `--parameters` flags\. cdk deploy MyStack --parameters uploadBucketName=upbucket --parameters downloadBucketName=downbucket ``` -If you are deploying multiple stacks, you can specify a different value of each parameter for each stack by prefixing the name of the parameter with the stack name and a colon\. +If you are deploying multiple stacks, you can specify a different value of each parameter for each stack\. To do so, prefix the name of the parameter with the stack name and a colon\. ``` cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=uploadbucket --parameters YourStack:uploadBucketName=upbucket diff --git a/v2/permissions.md b/v2/permissions.md index 6a2cd197..a5806904 100644 --- a/v2/permissions.md +++ b/v2/permissions.md @@ -1,12 +1,14 @@ # Permissions -The AWS Construct Library uses a few common, widely\-implemented idioms to manage access and permissions\. The IAM module provides you with the tools you need to use these idioms\. +The AWS Construct Library uses a few common, widely implemented idioms to manage access and permissions\. The IAM module provides you with the tools you need to use these idioms\. ## Principals An IAM principal is an authenticated AWS entity representing a user, service, or application that can call AWS APIs\. The AWS Construct Library supports specifying principals in several flexible ways to grant them access your AWS resources\. -In security contexts, the term "principal" refers specifically to authenticated entities such as users\. Objects like groups and roles do not *represent* users \(and other authenticated entities\) but rather *identify* them indirectly for the purpose of granting permissions\. For example, if you create an IAM group, you can grant the group \(i\.e\. its members\) write access to a Amazon RDS table, but the group itself is not a principal since it does not represent a single entity \(also, you cannot log in to a group\)\. +In security contexts, the term "principal" refers specifically to authenticated entities such as users\. Objects like groups and roles do not *represent* users \(and other authenticated entities\) but rather *identify* them indirectly for the purpose of granting permissions\. + +For example, if you create an IAM group, you can grant the group \(and thus its members\) write access to an Amazon RDS table\. However, the group itself is not a principal because it doesn't represent a single entity \(also, you cannot log in to a group\)\. In the CDK's IAM library, classes that directly or indirectly identify principals implement the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IPrincipal.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IPrincipal.html) interface, allowing these objects to be used interchangeably in access policies\. However, not all of them are principals in the security sense\. These objects include: @@ -20,7 +22,7 @@ In the CDK's IAM library, classes that directly or indirectly identify principal 1. Canonical user principals \(`new iam.[CanonicalUserPrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.CanonicalUserPrincipal.html)('79a59d[...]7ef2be')`\) -1. AWS organizations principals \(`new iam.[OrganizationPrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.OrganizationPrincipal.html)('org-id')`\) +1. AWS Organizations principals \(`new iam.[OrganizationPrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.OrganizationPrincipal.html)('org-id')`\) 1. Arbitrary ARN principals \(`new iam.[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ArnPrincipal.html)(res.arn)`\) @@ -28,13 +30,15 @@ In the CDK's IAM library, classes that directly or indirectly identify principal ## Grants -Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with **grant**\. For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrreadidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrreadwbrwriteidentity-objectskeypattern)` \(Python: `grant_read`, `grant_read_write`\) to enable read and read/write access, respectively, from an entity to the bucket without having to know exactly which Amazon S3 IAM permissions are required to perform these operations\. +Every construct that represents a resource that can be accessed, such as an Amazon S3 bucket or Amazon DynamoDB table, has methods that grant access to another entity\. All such methods have names starting with **grant**\. + +For example, Amazon S3 buckets have the methods `[grantRead](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrreadidentity-objectskeypattern)` and `[grantReadWrite](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrreadwbrwriteidentity-objectskeypattern)` \(Python: `grant_read`, `grant_read_write`\) to enable read and read/write access, respectively, from an entity to the bucket\. The entity doesn't have to know exactly which Amazon S3 IAM permissions are required to perform these operations\. -The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IGrantable.html)\. This interface represents entities that can be granted permissions—that is, resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html)`\. +The first argument of a **grant** method is always of type [IGrantable](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IGrantable.html)\. This interface represents entities that can be granted permissions\. That is, it represents resources with roles, such as the IAM objects `[Role](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html)`, `[User](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html)`, and `[Group](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html)`\. Other entities can also be granted permissions\. For example, later in this topic, we show how to grant a CodeBuild project access to an Amazon S3 bucket\. Generally, the associated role is obtained via a `role` property on the entity being granted access\. -Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly instead of granting access to their role\. For example, if `bucket` is an Amazon S3 bucket, and `function` is a Lambda function, the code below grants the function read access to the bucket\. +Resources that use execution roles, such as `[lambda\.Function](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html)`, also implement `IGrantable`, so you can grant them access directly instead of granting access to their role\. For example, if `bucket` is an Amazon S3 bucket, and `function` is a Lambda function, the following code grants the function read access to the bucket\. ------ #### [ TypeScript ] @@ -73,7 +77,9 @@ bucket.GrantRead(function); ------ - Sometimes permissions must be applied while your stack is being deployed\. One such case is when you grant a AWS CloudFormation custom resource access to some other resource\. The custom resource will be invoked during deployment, so it must have the specified permissions at deployment time\. Another case is when a service verifies that the role you pass to it has the right policies applied \(a number of AWS services do this to make sure you didn't forget to set the policies\)\. In those cases, the deployment may fail if the permissions are applied too late\. + Sometimes permissions must be applied while your stack is being deployed\. One such case is when you grant an AWS CloudFormation custom resource access to some other resource\. The custom resource will be invoked during deployment, so it must have the specified permissions at deployment time\. + +Another case is when a service verifies that the role you pass to it has the right policies applied\. \(A number of AWS services do this to make sure that you didn't forget to set the policies\.\) In those cases, the deployment might fail if the permissions are applied too late\. To force the grant's permissions to be applied before another resource is created, you can add a dependency on the grant itself, as shown here\. Though the return value of grant methods is commonly discarded, every grant method in fact returns an `iam.Grant` object\. @@ -263,9 +269,11 @@ role.AddToPolicy(new PolicyStatement(new PolicyStatementProps ------ - In our example above, we've created a new `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyStatement.html)` inline with the `[addToPolicy](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html#addwbrtowbrpolicystatement)` \(Python: `add_to_policy`\) call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. + In the preceding example, we've created a new `[PolicyStatement](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyStatement.html)` inline with the `[addToPolicy](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html#addwbrtowbrpolicystatement)` \(Python: `add_to_policy`\) call\. You can also pass in an existing policy statement or one you've modified\. The [PolicyStatement](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyStatement.html) object has [numerous methods](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.PolicyStatement.html#methods) for adding principals, resources, conditions, and actions\. -If you're using a construct that requires a role to function correctly, you can either pass in an existing role when instantiating the construct object, or let the construct create a new role for you, trusting the appropriate service principal\. The following example uses such a construct: a CodeBuild project\. +If you're using a construct that requires a role to function correctly, you can do one of the following: ++ Pass in an existing role when instantiating the construct object\. ++ Let the construct create a new role for you, trusting the appropriate service principal\. The following example uses such a construct: a CodeBuild project\. ------ #### [ TypeScript ] @@ -354,7 +362,11 @@ var project = new Project(this, "Project", new ProjectProps ------ -Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. This property is not available on external resources, however, so such constructs have an `addToRolePolicy` \(Python: `add_to_role_policy`\) method that does nothing if the construct is an external resource, and calls the `addToPolicy` \(Python: `add_to_policy`\) method of the `role` property otherwise, saving you the trouble of handling the undefined case explicitly\. The following example demonstrates: +Once the object is created, the role \(whether the role passed in or the default one created by the construct\) is available as the property `role`\. However, this property is not available on external resources\. Therefore, these constructs have an `addToRolePolicy` \(Python: `add_to_role_policy`\) method\. + +The method does nothing if the construct is an external resource, and it calls the `addToPolicy` \(Python: `add_to_policy`\) method of the `role` property otherwise\. This saves you the trouble of handling the undefined case explicitly\. + +The following example demonstrates: ------ #### [ TypeScript ] @@ -494,13 +506,13 @@ bucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps ## Using external IAM objects -If you have defined an IAM user, principal, group, or role outside your AWS CDK app, you can use that IAM object in your AWS CDK app by creating a reference to it using its ARN or \(for users, groups, and roles\) its name\. The returned reference can then be used to grant permissions or to construct policy statements as explained above\. +If you have defined an IAM user, principal, group, or role outside your AWS CDK app, you can use that IAM object in your AWS CDK app\. To do so, create a reference to it using its ARN or its name\. \(Use the name for users, groups, and roles\.\) The returned reference can then be used to grant permissions or to construct policy statements as explained previously\. + For users, call `[User\.fromUserArn\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html#static-fromwbruserwbrarnscope-id-userarn)` or `[User\.fromUserName\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.User.html#static-fromwbruserwbrnamescope-id-username)`\. `User.fromUserAttributes()` is also available, but currently provides the same functionality as `User.fromUserArn()`\. + For principals, instantiate an `[ArnPrincipal](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ArnPrincipal.html)` object\. + For groups, call `[Group\.fromGroupArn\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Group.html#static-fromwbrgroupwbrarnscope-id-grouparn)` or `[Group\.fromGroupName\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Group.html#static-fromwbrgroupwbrnamescope-id-groupname)`\. + For roles, call `[Role\.fromRoleArn\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html#static-fromwbrrolewbrarnscope-id-rolearn-options)` or `[Role\.fromRoleName\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Role.html#static-fromwbrrolewbrnamescope-id-rolename)`\. -Policies \(including managed policies\) can be used in similar fashion using the methods listed below\. You can use references to these objects anywhere an IAM policy is required\. +Policies \(including managed policies\) can be used in similar fashion using the following methods\. You can use references to these objects anywhere an IAM policy is required\. + `[Policy\.fromPolicyName](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.Policy.html#static-fromwbrpolicywbrnamescope-id-policyname)` + `[ManagedPolicy\.fromManagedPolicyArn](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ManagedPolicy.html#static-fromwbrmanagedwbrpolicywbrarnscope-id-managedpolicyarn)` + `[ManagedPolicy\.fromManagedPolicyName](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.ManagedPolicy.html#static-fromwbrmanagedwbrpolicywbrnamescope-id-managedpolicyname)` diff --git a/v2/reference.md b/v2/reference.md index aa23927e..42d41645 100644 --- a/v2/reference.md +++ b/v2/reference.md @@ -8,13 +8,15 @@ Separate versions of the API Reference are provided for TypeScript/JavaScript, P ## Versioning -Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and strictly adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs are limited to major releases\. Minor and patch releases are backward compatible, meaning that the code written in a previous version with the same major version can be upgraded to a newer version within the same major version, and will continue to build and run, producing the same output\. +Version numbers consist of three numeric version parts: *major*\.*minor*\.*patch*, and strictly adhere to the [semantic versioning](https://semver.org) model\. This means that breaking changes to stable APIs are limited to major releases\. + +Minor and patch releases are backward compatible\. The code written in a previous version with the same major version can be upgraded to a newer version within the same major version\. It will also continue to build and run, producing the same output\. ### AWS CDK Toolkit \(CLI\) compatibility The AWS CDK Toolkit \(that is, the `cdk` command line command\) is *always* compatible with construct libraries of a semantically *lower* or *equal* version number\. It is, therefore, always safe to upgrade the AWS CDK Toolkit within the same major version\. -The AWS CDK Toolkit may be, but is *not always*, compatible with construct libraries of a semantically *higher* version, depending on whether the same cloud assembly schema version is employed by the two components\. The AWS CDK framework generates a cloud assembly during synthesis; the AWS CDK Toolkit consumes it for deployment\. The schema that defines the format of the cloud assembly is strictly specified and versioned\. AWS construct libraries using a given cloud assembly schema version are compatible with AWS CDK toolkit versions using that schema version or later, which may include releases of the AWS CDK Toolkit *older than* a given construct library release\. +The AWS CDK Toolkit might be, but is *not always*, compatible with construct libraries of a semantically *higher* version\. This depends on whether the same cloud assembly schema version is employed by the two components\. The AWS CDK framework generates a cloud assembly during synthesis; the AWS CDK Toolkit consumes it for deployment\. The schema that defines the format of the cloud assembly is strictly specified and versioned\. AWS construct libraries using a given cloud assembly schema version are compatible with AWS CDK toolkit versions using that schema version or later\. This might include releases of the AWS CDK Toolkit that are *earlier than* a given construct library release\. When the cloud assembly version required by the construct library is not compatible with the version supported by the AWS CDK Toolkit, you receive an error message like this one\. @@ -23,7 +25,7 @@ Cloud assembly schema version mismatch: Maximum schema version supported is 3.0. Please upgrade your CLI in order to interact with this app. ``` -To resolve this error, update the AWS CDK Toolkit to a version compatible with the required cloud assembly version, or simply to the latest available version\. The alternative \(downgrading the construct library modules your app uses\) is generally not desirable\. +To resolve this error, update the AWS CDK Toolkit to a version compatible with the required cloud assembly version, or to the latest available version\. The alternative \(downgrading the construct library modules your app uses\) is generally not desirable\. **Note** For more details on the cloud assembly schema, see [Cloud Assembly Versioning](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/cloud-assembly-schema#versioning)\. @@ -32,15 +34,15 @@ For more details on the cloud assembly schema, see [Cloud Assembly Versioning](h The modules in the AWS Construct Library move through various stages as they are developed from concept to mature API\. Different stages imply different promises for API stability in subsequent versions of the AWS CDK\. -APIs in the main AWS CDK library, `aws-cdk-lib`, are stable, and the library is fully semantically\-versioned\. This package includes AWS CloudFormation \(L1\) constructs for all AWS services as well as all stable higher\-level \(L2/3\) modules\. \(It also includes the core CDK classes like `App` and `Construct`\.\) No APIs will be removed from this package \(though they may be deprecated\) until the next major release of the CDK\. No individual API will ever have breaking changes; if a breaking change is required, an entirely new API will be added\. +APIs in the main AWS CDK library, `aws-cdk-lib`, are stable, and the library is fully semantically versioned\. This package includes AWS CloudFormation \(L1\) constructs for all AWS services and all stable higher\-level \(L2 and L3\) modules\. \(It also includes the core CDK classes like `App` and `Stack`\.\) No APIs will be removed from this package \(though they may be deprecated\) until the next major release of the CDK\. No individual API will ever have breaking changes; if a breaking change is required, an entirely new API will be added\. New APIs under development for a service already incorporated in `aws-cdk-lib` are identified using a `BetaN` suffix, where `N` starts at 1 and is incremented with each breaking change to the new API\. `BetaN` APIs are never removed, only deprecated, so your existing app continues to work with newer versions of `aws-cdk-lib`\. When the API is deemed stable, a new API without the `BetaN` suffix is added\. -When higher\-level \(L2 or L3\) APIs begin to be developed for an AWS service which previously had only L1 APIs, those APIs are initially distributed in a separate package\. The name of such a package has an "Alpha" suffix, and its version matches the first version of `aws-cdk-lib` it is compatible with, with an `alpha` sub\-version\. When the module supports the intended use cases, its APIs are added to `aws-cdk-lib`\. +When higher\-level \(L2 or L3\) APIs begin to be developed for an AWS service that previously had only L1 APIs, those APIs are initially distributed in a separate package\. The name of such a package has an "Alpha" suffix, and its version matches the first version of `aws-cdk-lib` it is compatible with, with an `alpha` sub\-version\. When the module supports the intended use cases, its APIs are added to `aws-cdk-lib`\. ### Language binding stability -From time to time, we may add support to the AWS CDK for additional programming languages\. Although the API described in all the languages is the same, the way that API is expressed varies by language and may change as the language support evolves\. For this reason, language bindings are deemed experimental for a time until they are considered ready for production use\. +From time to time, we might add support to the AWS CDK for additional programming languages\. Although the API described in all the languages is the same, the way that API is expressed varies by language and might change as the language support evolves\. For this reason, language bindings are deemed experimental for a time until they are considered ready for production use\. | Language | Stability | @@ -50,4 +52,4 @@ From time to time, we may add support to the AWS CDK for additional programming | Python | Stable | | Java | Stable | | C\#/\.NET | Stable | -| Go | Experimental | \ No newline at end of file +| Go | Stable | \ No newline at end of file diff --git a/v2/resources.md b/v2/resources.md index e704f8a9..f244b77e 100644 --- a/v2/resources.md +++ b/v2/resources.md @@ -2,7 +2,7 @@ As described in [Constructs](constructs.md), the AWS CDK provides a rich class library of constructs, called *AWS constructs*, that represent all AWS resources\. -To create an instance of a resource using its corresponding construct, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here's how to create an Amazon SQS queue with KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. +To create an instance of a resource using its corresponding construct, pass in the scope as the first argument, the logical ID of the construct, and a set of configuration properties \(props\)\. For example, here's how to create an Amazon SQS queue with AWS KMS encryption using the [sqs\.Queue](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. ------ #### [ TypeScript ] @@ -117,7 +117,7 @@ See [Tokens](tokens.md) for information about how the AWS CDK encodes deploy\-ti ## Referencing resources -Many AWS CDK classes require properties that are AWS CDK resource objects \(resources\)\. For example, an Amazon ECS resource requires a reference to the cluster on which it runs; an Amazon CloudFront distribution requires a reference to the bucket containing source code\. To satisfy these requirements, you can refer to a resource in one of two ways: +Many AWS CDK classes require properties that are AWS CDK resource objects \(resources\)\. For example, an Amazon ECS resource requires a reference to the cluster on which it runs\. An Amazon CloudFront distribution requires a reference to the bucket containing the source code\. To satisfy these requirements, you can refer to a resource in one of two ways: + By passing a resource defined in your CDK app, either in the same stack or in a different one + By passing a proxy object referencing a resource defined in your AWS account, created from a unique identifier of the resource \(such as an ARN\) @@ -173,7 +173,7 @@ var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cl ## Referencing resources in a different stack -You can refer to resources in a different stack as long as they are defined in the same app and are in the same AWS account and region\. The pattern generally used is: +You can refer to resources in a different stack as long as they are defined in the same app and are in the same AWS account and Region\. The following pattern is generally used: + Store a reference to the construct as an attribute of the stack that produces the resource\. \(To get a reference to the current construct's stack, use `Stack.of(this)`\.\) + Pass this reference to the constructor of the stack that consumes the resource as a parameter or a property\. The consuming stack then passes it as a property to any construct that needs it\. @@ -263,21 +263,21 @@ var stack2 = new StackThatExpectsABucket(app, "Stack2", new StackProps { Env = p ------ -If the AWS CDK determines that the resource is in the same account and region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. +If the AWS CDK determines that the resource is in the same account and Region, but in a different stack, it automatically synthesizes AWS CloudFormation [exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html) in the producing stack and an [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html) in the consuming stack to transfer that information from one stack to the other\. ### Resolving dependency deadlocks -Referencing a resource from one stack in a different stack creates a dependency between the two stacks to ensure that they are deployed in the right order\. Once this dependency has been made concrete by deploying the stacks, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure\. This happens if there is another dependency between the two stacks that force them to be deployed in the same order, but it can also happen without a dependency if the producing stack is simply chosen by the CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it is no longer needed, but the exported resource is still being used in the consuming stack because its update has not yet been deployed, so deploying the producer stack fails\. +Referencing a resource from one stack in a different stack creates a dependency between the two stacks\. This makes sure that they're deployed in the right order\. After the stacks are deployed, this dependency is concrete\. After that, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure\. This happens if there is another dependency between the two stacks that force them to be deployed in the same order\. It can also happen without a dependency if the producing stack is simply chosen by the CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it's no longer needed, but the exported resource is still being used in the consuming stack because its update is not yet deployed\. Therefore, deploying the producer stack fails\. -To break this deadlock, remove the use of the shared resource from the consuming stack \(which will remove the automatic export from the producing stack\), then manually add the same export to the producing stack using exactly the same logical ID as the automatically\-generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then remove the manual export \(and the shared resource if it is no longer needed\), and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html#static-fromwbrlookupscope-id-options)` method is a convenient way to create the manual export for this purpose \(see the example in the linked method reference\)\. +To break this deadlock, remove the use of the shared resource from the consuming stack\. \(This removes the automatic export from the producing stack\.\) Next, manually add the same export to the producing stack using exactly the same logical ID as the automatically generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then, remove the manual export \(and the shared resource if it's no longer needed\) and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html#static-fromwbrlookupscope-id-options)` method is a convenient way to create the manual export for this purpose\. \(See the example in the linked method reference\.\) ## Referencing resources in your AWS account -Suppose you want to use a resource already available in your AWS account in your AWS CDK app: for example, a resource that was defined through the console, an AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into a proxy object that serves as a reference to the resource by calling a static factory method on the resource's class\. +Suppose you want to use a resource already available in your AWS account in your AWS CDK app\. This might be a resource that was defined through the console, an AWS SDK, directly with AWS CloudFormation, or in a different AWS CDK application\. You can turn the resource's ARN \(or another identifying attribute, or group of attributes\) into a proxy object\. The proxy object serves as a reference to the resource by calling a static factory method on the resource's class\. -When you create such a proxy, the external resource **does not** become a part of your AWS CDK app, and therefore, changes you make to the proxy in your AWS CDK app do not affect the deployed resource\. The proxy can, however, be passed to any AWS CDK method that requires a resource of that type\. +When you create such a proxy, the external resource **does not** become a part of your AWS CDK app\. Therefore, changes you make to the proxy in your AWS CDK app do not affect the deployed resource\. The proxy can, however, be passed to any AWS CDK method that requires a resource of that type\. -The following example shows how to reference a bucket based on an existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and a Amazon Virtual Private Cloud based on an existing VPC having a specific ID\. +The following example shows how to reference a bucket based on an existing bucket with the ARN **arn:aws:s3:::my\-bucket\-name**, and an Amazon Virtual Private Cloud based on an existing VPC having a specific ID\. ------ #### [ TypeScript ] @@ -362,11 +362,11 @@ Vpc.FromVpcAttributes(this, "MyVpc", new VpcAttributes Let's take a closer look at the [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.Vpc.html#static-fromwbrlookupscope-id-options](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.Vpc.html#static-fromwbrlookupscope-id-options) method\. Because the `ec2.Vpc` construct is complex, there are many ways you might want to select the VPC to be used with your CDK app\. To address this, the VPC construct has a `fromLookup` static method \(Python: `from_lookup`\) that lets you look up the desired Amazon VPC by querying your AWS account at synthesis time\. -To use `Vpc.fromLookup()`, the system that synthesizes the stack must have access to the account that owns the Amazon VPC, since the CDK Toolkit queries the account to find the right Amazon VPC at synthesis time\. +To use `Vpc.fromLookup()`, the system that synthesizes the stack must have access to the account that owns the Amazon VPC\. This is because the CDK Toolkit queries the account to find the right Amazon VPC at synthesis time\. -Furthermore, `Vpc.fromLookup()` works only in stacks that are defined with an explicit **account** and **region** \(see [Environments](environments.md)\)\. If the AWS CDK attempts to look up an Amazon VPC from an [environment\-agnostic stack](stacks.md#stack_api), the CDK Toolkit does not know which environment to query to find the VPC\. +Furthermore, `Vpc.fromLookup()` works only in stacks that are defined with an explicit **account** and **region** \(see [Environments](environments.md)\)\. If the AWS CDK tries to look up an Amazon VPC from an [environment\-agnostic stack](stacks.md#stack_api), the CDK Toolkit doesn't know which environment to query to find the VPC\. -You must provide `Vpc.fromLookup()` attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so specifying that you want the VPC marked as the default is sufficient\. +You must provide `Vpc.fromLookup()` attributes sufficient to uniquely identify a VPC in your AWS account\. For example, there can only ever be one default VPC, so it's sufficient to specify the VPC as the default\. ------ #### [ TypeScript ] @@ -410,7 +410,7 @@ Vpc.FromLookup(this, id = "DefaultVpc", new VpcLookupOptions { IsDefault = true ------ -You can also use the `tags` property to query for VPCs by tag\. Tags may be added to the Amazon VPC at the time of its creation using AWS CloudFormation or the AWS CDK, and they may be edited at any time after creation using the AWS Management Console, the AWS CLI, or an AWS SDK\. In addition to any tags you have added yourself, the AWS CDK automatically adds the following tags to all VPCs it creates\. +You can also use the `tags` property to query for VPCs by tag\. You can add tags to the Amazon VPC at the time of its creation by using AWS CloudFormation or the AWS CDK\. You can edit tags at any time after creation by using the AWS Management Console, the AWS CLI, or an AWS SDK\. In addition to any tags you add yourself, the AWS CDK automatically adds the following tags to all VPCs it creates\. + *Name* – The name of the VPC\. + *aws\-cdk:subnet\-name* – The name of the subnet\. + *aws\-cdk:subnet\-type* – The type of the subnet: Public, Private, or Isolated\. @@ -458,13 +458,13 @@ Vpc.FromLookup(this, id = "PublicVpc", new VpcLookupOptions ------ -Results of `Vpc.fromLookup()` are cached in the project's `cdk.context.json` file\. \(See [Runtime context](context.md)\.\) Commit this file to version control so that your app will continue to refer to the same Amazon VPC even if you later change the attributes of your VPCs in a way that would result in a different VPC being selected\. This is particularly important if you will be deploying the stack in an environment that does not have access to the AWS account that defines the VPC, such as [CDK Pipelines](cdk_pipeline.md)\. +Results of `Vpc.fromLookup()` are cached in the project's `cdk.context.json` file\. \(See [Runtime context](context.md)\.\) Commit this file to version control so that your app will continue to refer to the same Amazon VPC\. This works even if you later change the attributes of your VPCs in a way that would result in a different VPC being selected\. This is particularly important if you're deploying the stack in an environment that doesn't have access to the AWS account that defines the VPC, such as [CDK Pipelines](cdk_pipeline.md)\. Although you can use an external resource anywhere you'd use a similar resource defined in your AWS CDK app, you cannot modify it\. For example, calling `addToResourcePolicy` \(Python: `add_to_resource_policy`\) on an external `s3.Bucket` does nothing\. ## Physical names -The logical names of resources in AWS CloudFormation are different from the names of resources that are shown in the AWS Management Console after AWS CloudFormation has deployed the resources\. The AWS CDK calls these final names *physical names*\. +The logical names of resources in AWS CloudFormation are different from the names of resources that are shown in the AWS Management Console after they're deployed by AWS CloudFormation\. The AWS CDK calls these final names *physical names*\. For example, AWS CloudFormation might create the Amazon S3 bucket with the logical ID **Stack2MyBucket4DD88B4F** from the previous example with the physical name **stack2mybucket4dd88b4f\-iuv1rbv9z3to**\. @@ -514,7 +514,7 @@ var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-buc Assigning physical names to resources has some disadvantages in AWS CloudFormation\. Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource's properties that are immutable after creation, will fail if a resource has a physical name assigned\. If you end up in that state, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again\. See the [AWS CloudFormation documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) for details\. -In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value `PhysicalName.GENERATE_IF_NEEDED`, as follows\. +In some cases, such as when creating an AWS CDK app with cross\-environment references, physical names are required for the AWS CDK to function correctly\. In those cases, if you don't want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you\. To do so, use the special value `PhysicalName.GENERATE_IF_NEEDED`, as follows\. ------ #### [ TypeScript ] @@ -562,7 +562,9 @@ var bucket = new Bucket(this, "MyBucket", new BucketProps ## Passing unique identifiers -Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. For example, when you are using the low\-level AWS CloudFormation resources, or need to expose resources to the runtime components of an AWS CDK application, such as when referring to Lambda functions through environment variables\. +Whenever possible, you should pass resources by reference, as described in the previous section\. However, there are cases where you have no other choice but to refer to a resource by one of its attributes\. Example use cases include the following: ++ When you are using low\-level AWS CloudFormation resources ++ When you need to expose resources to the runtime components of an AWS CDK application, such as when referring to Lambda functions through environment variables These identifiers are available as attributes on the resources, such as the following\. @@ -685,9 +687,9 @@ new Function(this, "MyLambda", new FunctionProps ## Granting permissions -AWS constructs make least\-privilege permissions easy to achieve by offering simple, intent\-based APIs to express permission requirements\. Many AWS constructs offer grant methods that enable you to easily grant an entity, such as an IAM role or a user, permission to work with the resource without having to manually craft one or more IAM permission statements\. +AWS constructs make least\-privilege permissions achievable by offering simple, intent\-based APIs to express permission requirements\. Many AWS constructs offer grant methods that you can use to grant an entity \(such as an IAM role or user\) permission to work with the resource, without having to manually create IAM permission statements\. -The following example creates the permissions to allow a Lambda function's execution role to read and write objects to a particular Amazon S3 bucket\. If the Amazon S3 bucket is encrypted using an AWS KMS key, this method also grants the Lambda function's execution role permissions to decrypt using this key\. +The following example creates the permissions to allow a Lambda function's execution role to read and write objects to a particular Amazon S3 bucket\. If the Amazon S3 bucket is encrypted with an AWS KMS key, this method also grants permissions to the Lambda function's execution role to decrypt with the key\. ------ #### [ TypeScript ] @@ -785,7 +787,7 @@ The grant methods are built using lower\-level APIs for handling with IAM polici ## Metrics and alarms -Many resources emit CloudWatch metrics that can be used to set up monitoring dashboards and alarms\. AWS constructs have metric methods that allow easy access to the metrics without having to look up the correct name to use\. +Many resources emit CloudWatch metrics that can be used to set up monitoring dashboards and alarms\. AWS constructs have metric methods that let you access the metrics without looking up the correct name to use\. The following example shows how to define an alarm when the `ApproximateNumberOfMessagesNotVisible` of an Amazon SQS queue exceeds 100\. @@ -1004,7 +1006,7 @@ fleet1.Connections.AllowFrom(fleet2, ec2.Port.AllTraffic()); ------ -Certain resources have default ports associated with them, for example, the listener of a load balancer on the public port, and the ports on which the database engine accepts connections for instances of an Amazon RDS database\. In such cases, you can enforce tight network control without having to manually specify the port by using the `allowDefaultPortFrom` and `allowToDefaultPort` methods \(Python: `allow_default_port_from`, `allow_to_default_port`\)\. +Certain resources have default ports associated with them\. Examples include the listener of a load balancer on the public port, and the ports on which the database engine accepts connections for instances of an Amazon RDS database\. In such cases, you can enforce tight network control without having to manually specify the port\. To do so, use the `allowDefaultPortFrom` and `allowToDefaultPort` methods \(Python: `allow_default_port_from`, `allow_to_default_port`\)\. The following example shows how to enable connections from any IPV4 address, and a connection from an Auto Scaling group to access a database\. @@ -1124,10 +1126,10 @@ bucket.AddObjectCreatedNotification(new s3Nots.LambdaDestination(handler)); ## Removal policies -Resources that maintain persistent data, such as databases and Amazon S3 buckets and even Amazon ECR registries, have a *removal policy* that indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the AWS CDK `core` module\. +Resources that maintain persistent data, such as databases, Amazon S3 buckets, and Amazon ECR registries, have a *removal policy*\. The removal policy indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed\. The values specifying the removal policy are available through the `RemovalPolicy` enumeration in the AWS CDK `core` module\. **Note** -Resources besides those that store data persistently may also have a `removalPolicy` that is used for a different purpose\. For example, a Lambda function version uses a `removalPolicy` attribute to determine whether a given version is retained when a new version is deployed\. These have different meanings and defaults compared to the removal policy on an Amazon S3 bucket or DynamoDB table\. +Resources besides those that store data persistently might also have a `removalPolicy` that is used for a different purpose\. For example, a Lambda function version uses a `removalPolicy` attribute to determine whether a given version is retained when a new version is deployed\. These have different meanings and defaults compared to the removal policy on an Amazon S3 bucket or DynamoDB table\. | Value | meaning | @@ -1135,7 +1137,7 @@ Resources besides those that store data persistently may also have a `removalPol | RemovalPolicy\.RETAIN | Keep the contents of the resource when destroying the stack \(default\)\. The resource is orphaned from the stack and must be deleted manually\. If you attempt to re\-deploy the stack while the resource still exists, you will receive an error message due to a name conflict\. | | RemovalPolicy\.DESTROY | The resource will be destroyed along with the stack\. | -AWS CloudFormation does not remove Amazon S3 buckets that contain files even if their removal policy is set to `DESTROY`\. Attempting to do so is a AWS CloudFormation error\. To have the AWS CDK delete all files from the bucket before destroying it, set the bucket's `autoDeleteObjects` property to `true`\. +AWS CloudFormation does not remove Amazon S3 buckets that contain files even if their removal policy is set to `DESTROY`\. Attempting to do so is an AWS CloudFormation error\. To have the AWS CDK delete all files from the bucket before destroying it, set the bucket's `autoDeleteObjects` property to `true`\. Following is an example of creating an Amazon S3 bucket with `RemovalPolicy` of `DESTROY` and `autoDeleteOjbects` set to `true`\. @@ -1235,7 +1237,14 @@ public CdkTestStack(Construct scope, string id, IStackProps props) : base(scope, ------ -You can also apply a removal policy directly to the underlying AWS CloudFormation resource via the `applyRemovalPolicy()` method\. This method is available on some stateful resources that do not have a `removalPolicy` property in their L2 resource's props, including AWS CloudFormation stacks, Amazon Cognito user pools, Amazon DocumentDB database instances, Amazon EC2 volumes, Amazon OpenSearch Service domains, Amazon FSx file systems, and Amazon SQS queues\. +You can also apply a removal policy directly to the underlying AWS CloudFormation resource via the `applyRemovalPolicy()` method\. This method is available on some stateful resources that do not have a `removalPolicy` property in their L2 resource's props\. Examples include the following: ++ AWS CloudFormation stacks ++ Amazon Cognito user pools ++ Amazon DocumentDB database instances ++ Amazon EC2 volumes ++ Amazon OpenSearch Service domains ++ Amazon FSx file systems ++ Amazon SQS queues ------ #### [ TypeScript ] @@ -1280,4 +1289,4 @@ resource.ApplyRemovalPolicy(cdk.RemovalPolicy.DESTROY); ------ **Note** -The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`, but the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. \ No newline at end of file +The AWS CDK's `RemovalPolicy` translates to AWS CloudFormation's `DeletionPolicy`\. However, the default in AWS CDK is to retain the data, which is the opposite of the AWS CloudFormation default\. \ No newline at end of file diff --git a/v2/serverless_example.md b/v2/serverless_example.md index e8b7fdc7..4e551396 100644 --- a/v2/serverless_example.md +++ b/v2/serverless_example.md @@ -82,7 +82,7 @@ You may now open `src/MyWidgetService.sln` in Visual Studio\. ------ **Note** -The CDK names source files and classes based on the name of the project directory\. If you don't use the name `MyWidgetService` as shown above, you'll have trouble following the rest of the steps because some of the files the instructions tell you to modify aren't there \(they'll have different names\)\. +The CDK names source files and classes based on the name of the project directory\. If you don't use the name `MyWidgetService` as shown previously, it might be difficult to follow the rest of the steps\. Some of the files that the instructions tell you to modify wont' be there, because they will have different names\. The important files in the blank project are as follows\. \(We will also be adding a couple of new files\.\) @@ -533,7 +533,7 @@ cdk synth ## Deploy and test the app -Before you can deploy your first AWS CDK app, you must bootstrap your AWS environment\. This creates \(among other resources\) a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see [Bootstrapping your AWS environment](cli.md#cli-bootstrap)\. If you've already bootstrapped, you'll get a warning and nothing will change\. +Before you can deploy your first AWS CDK app, you must bootstrap your AWS environment\. Among other resources, this creates a staging bucket that the AWS CDK uses to deploy stacks containing assets\. For details, see [Bootstrapping your AWS environment](cli.md#cli-bootstrap)\. If you've already bootstrapped, you'll get a warning and nothing will change\. ``` cdk bootstrap aws://ACCOUNT-NUMBER/REGION @@ -557,15 +557,15 @@ Test your app by getting the list of widgets \(currently empty\) by navigating t curl -X GET 'https://GUID.execute-api.REGION.amazonaws.com/prod' ``` -You can also test the app by: +You can also test the app by completing the following steps: -1. Opening the AWS Management Console\. +1. Open the AWS Management Console\. -1. Navigating to the API Gateway service\. +1. Navigate to the API Gateway service\. -1. Finding **Widget Service** in the list\. +1. Find **Widget Service** in the list\. -1. Selecting **GET** and **Test** to test the function\. +1. Select **GET** and **Test** to test the function\. Because we haven't stored any widgets yet, the output should be similar to the following\. diff --git a/v2/stack_how_to_create_multiple_stacks.md b/v2/stack_how_to_create_multiple_stacks.md index 9ce296b9..c31fe24c 100644 --- a/v2/stack_how_to_create_multiple_stacks.md +++ b/v2/stack_how_to_create_multiple_stacks.md @@ -1,8 +1,13 @@ # Create an app with multiple stacks -Most of the other code examples in the *AWS CDK Developer Guide* involve only a single stack\. However, you can create apps containing any number of stacks\. Each stack results in its own AWS CloudFormation template\. Stacks are the *unit of deployment:* each stack in an app can be synthesized and deployed individually using the `cdk deploy` command\. +Most of the code examples in the *AWS CDK Developer Guide* involve only a single stack\. However, you can create apps containing any number of stacks\. Each stack results in its own AWS CloudFormation template\. Stacks are the *unit of deployment:* each stack in an app can be synthesized and deployed individually using the `cdk deploy` command\. -This topic illustrates how to extend the `Stack` class to accept new properties or arguments, how to use these properties to affect what resources the stack contains and their configuration, and how to instantiate multiple stacks from this class\. The example uses a Boolean property, named `encryptBucket` \(Python: `encrypt_bucket`\), to indicate whether an Amazon S3 bucket should be encrypted\. If so, the stack enables encryption using a key managed by AWS Key Management Service \(AWS KMS\)\. The app creates two instances of this stack, one with encryption and one without\. +This topic illustrates the following: ++ How to extend the `Stack` class to accept new properties or arguments ++ How to use these properties to affect what resources the stack contains and their configuration ++ How to instantiate multiple stacks from this class + +The example uses a Boolean property, named `encryptBucket` \(Python: `encrypt_bucket`\)\. It indicates whether an Amazon S3 bucket should be encrypted\. If so, the stack enables encryption using a key managed by AWS Key Management Service \(AWS KMS\)\. The app creates two instances of this stack, one with encryption and one without\. ## Before you begin @@ -65,9 +70,9 @@ You can open the file `src/Pipeline.sln` in Visual Studio\. ## Add optional parameter -The `props` argument of the `Stack` constructor fulfills the interface `StackProps`\. Because we want our stack to accept an additional property to tell us whether to encrypt the Amazon S3 bucket, we should create an interface or class that includes that property\. This allows the compiler to make sure the property has a Boolean value and enables autocompletion for it in your IDE\. +The `props` argument of the `Stack` constructor fulfills the interface `StackProps`\. In this example, we want the stack to accept an additional property to tell us whether to encrypt the Amazon S3 bucket\. We should create an interface or class that includes the property\. This allows the compiler to make sure that the property has a Boolean value and enables autocompletion for it in your IDE\. -So open the indicated source file in your IDE or editor and add the new interface, class, or argument\. The code should look like this after the changes\. The lines we added are shown in boldface\. +So open the indicated source file in your IDE or editor and add the new interface, class, or argument\. The code should look like this after the changes\. The lines we added are shown in bold\. ------ #### [ TypeScript ] @@ -139,7 +144,7 @@ class MultistackStack(cdk.Stack): File: `src/main/java/com/myorg/MultistackStack.java` -It's more complicated than we really want to get into to extend a props type in Java, so we'll simply write our stack's constructor to accept an optional Boolean parameter\. Since `props` is an optional argument, we'll write an additional constructor that allows you to skip it\. It will default to `false`\. +It's more complicated than we really want to get into to extend a props type in Java\. Instead, write the stack's constructor to accept an optional Boolean parameter\. Because `props` is an optional argument, we'll write an additional constructor that lets you skip it\. It will default to `false`\. ``` package com.myorg; @@ -204,7 +209,7 @@ The new property is optional\. If `encryptBucket` \(Python: `encrypt_bucket`\) i ## Define the stack class - Now let's define our stack class, using our new property\. Make the code look like the following\. The code you need to add or change is shown in boldface\. + Now let's define our stack class, using our new property\. Make the code look like the following\. The code you need to add or change is shown in bold\. ------ #### [ TypeScript ] @@ -396,7 +401,7 @@ namespace Multistack ## Create two stack instances -Now we'll add the code to instantiate two separate stacks\. As before, the lines of code shown in boldface are the ones you need to add\. Delete the existing `MultistackStack` definition\. +Now we'll add the code to instantiate two separate stacks\. As before, the lines of code shown in bold are the ones you need to add\. Delete the existing `MultistackStack` definition\. ------ #### [ TypeScript ] @@ -548,13 +553,13 @@ namespace Multistack ## Synthesize and deploy the stack -Now you can deploy stacks from the app\. First, synthesize a AWS CloudFormation template for `MyEastCdkStack`—the stack in `us-east-1`\. This is the stack with the encrypted S3 bucket\. +Now you can deploy stacks from the app\. First, synthesize an AWS CloudFormation template for `MyEastCdkStack`—the stack in `us-east-1`\. This is the stack with the encrypted S3 bucket\. ``` $ cdk synth MyEastCdkStack ``` -To deploy this stack to your AWS account, issue one of the following commands\. The first command uses your default AWS profile to obtain the credentials to deploy the stack\. The second uses a profile you specify: for *PROFILE\_NAME*, substitute the name of an AWS CLI profile that contains appropriate credentials for deploying to the `us-east-1` AWS Region\. +To deploy this stack to your AWS account, issue one of the following commands\. The first command uses your default AWS profile to obtain the credentials to deploy the stack\. The second uses a profile that you specify\. For *PROFILE\_NAME*, substitute the name of an AWS CLI profile that contains appropriate credentials for deploying to the `us-east-1` AWS Region\. ``` cdk deploy MyEastCdkStack @@ -572,4 +577,4 @@ To avoid charges for resources that you deployed, destroy the stack using the fo cdk destroy MyEastCdkStack ``` -The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket's contents, but not the bucket itself, using the AWS Management Console or the AWS CLI before destroying the stack\. \ No newline at end of file +The destroy operation fails if there is anything stored in the stack's bucket\. There shouldn't be if you've only followed the instructions in this topic\. But if you did put something in the bucket, you must delete the bucket contents before destroying the stack\. \(Do not delete the bucket itself\.\) Use the AWS Management Console or the AWS CLI to delete the bucket contents\. \ No newline at end of file diff --git a/v2/stacks.md b/v2/stacks.md index 4c6cc09f..7b542e3c 100644 --- a/v2/stacks.md +++ b/v2/stacks.md @@ -4,7 +4,9 @@ The unit of deployment in the AWS CDK is called a *stack*\. All AWS resources de Because AWS CDK stacks are implemented through AWS CloudFormation stacks, they have the same limitations as in [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html)\. -You can define any number of stacks in your AWS CDK app\. Any instance of the `Stack` construct represents a stack, and can be either defined directly within the scope of the app, like the `MyFirstStack` example shown previously, or indirectly by any construct within the tree\. +You can define any number of stacks in your AWS CDK app\. Any instance of the `Stack` construct represents a stack\. This can be defined in one of the following ways: ++ Directly within the scope of the app, like the `MyFirstStack` example shown previously ++ Indirectly by any construct within the tree For example, the following code defines an AWS CDK app with two stacks\. @@ -85,7 +87,9 @@ You can synthesize each template by specifying the stack name in the cdk synth c cdk synth stack1 ``` -This approach is conceptually different from how AWS CloudFormation templates are normally used, where a template can be deployed multiple times and parameterized through [AWS CloudFormation parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html)\. Although AWS CloudFormation parameters can be defined in the AWS CDK, they are generally discouraged because AWS CloudFormation parameters are resolved only during deployment\. This means that you cannot determine their value in your code\. For example, to conditionally include a resource in your app based on the value of a parameter, you must set up an [AWS CloudFormation condition](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) and tag the resource with this condition\. Because the AWS CDK takes an approach where concrete templates are resolved at synthesis time, you can use an **if** statement to check the value to determine whether a resource should be defined or some behavior should be applied\. +This approach is conceptually different from how AWS CloudFormation templates are normally used, where a template can be deployed multiple times and parameterized through [AWS CloudFormation parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html)\. Although AWS CloudFormation parameters can be defined in the AWS CDK, they are generally discouraged because AWS CloudFormation parameters are resolved only during deployment\. This means that you cannot determine their value in your code\. + +For example, to conditionally include a resource in your app based on a parameter value, you must set up an [AWS CloudFormation condition](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) and tag the resource with it\. The AWS CDK takes an approach where concrete templates are resolved at synthesis time\. Therefore, you can use an **if** statement to check the value to determine whether a resource should be defined or some behavior should be applied\. **Note** The AWS CDK provides as much resolution as possible during synthesis time to enable idiomatic and natural usage of your programming language\. @@ -306,7 +310,7 @@ proddataF7378CE5 prodmon631A1083 ``` -The physical names of the AWS CloudFormation stacks are automatically determined by the AWS CDK based on the stack's construct path in the tree\. By default, a stack's name is derived from the construct ID of the `Stack` object, but you can specify an explicit name using the `stackName` prop \(in Python, `stack_name`\), as follows\. +The physical names of the AWS CloudFormation stacks are automatically determined by the AWS CDK based on the stack's construct path in the tree\. By default, a stack's name is derived from the construct ID of the `Stack` object\. However, you can specify an explicit name by using the `stackName` prop \(in Python, `stack_name`\), as follows\. ------ #### [ TypeScript ] @@ -354,22 +358,26 @@ new MyStack(this, "not:a:stack:name", new StackProps The [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html) object provides a rich API, including the following: + `Stack.of(construct)` – A static method that returns the **Stack** in which a construct is defined\. This is useful if you need to interact with a stack from within a reusable construct\. The call fails if a stack cannot be found in scope\. + `stack.stackName` \(Python: `stack_name`\) – Returns the physical name of the stack\. As mentioned previously, all AWS CDK stacks have a physical name that the AWS CDK can resolve during synthesis\. -+ `stack.region` and `stack.account` – Return the AWS Region and account, respectively, into which this stack will be deployed\. These properties return either the account or Region explicitly specified when the stack was defined, or a string\-encoded token that resolves to the AWS CloudFormation pseudo\-parameters for account and Region to indicate that this stack is environment agnostic\. See [Environments](environments.md) for information about how environments are determined for stacks\. ++ `stack.region` and `stack.account` – Return the AWS Region and account, respectively, into which this stack will be deployed\. These properties return one of the following: + + The account or Region explicitly specified when the stack was defined + + A string\-encoded token that resolves to the AWS CloudFormation pseudo parameters for account and Region to indicate that this stack is environment agnostic + + For information about how environments are determined for stacks, see [Environments](environments.md)\. + `stack.addDependency(stack)` \(Python: `stack.add_dependency(stack)` – Can be used to explicitly define dependency order between two stacks\. This order is respected by the cdk deploy command when deploying multiple stacks at once\. + `stack.tags` – Returns a [TagManager](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.TagManager.html) that you can use to add or remove stack\-level tags\. This tag manager tags all resources within the stack, and also tags the stack itself when it's created through AWS CloudFormation\. -+ `stack.partition`, `stack.urlSuffix` \(Python: `url_suffix`\), `stack.stackId` \(Python: `stack_id`\), and `stack.notificationArn` \(Python: `notification_arn`\) – Return tokens that resolve to the respective AWS CloudFormation pseudo\-parameters, such as `{ "Ref": "AWS::Partition" }`\. These tokens are associated with the specific stack object so that the AWS CDK framework can identify cross\-stack references\. -+ `stack.availabilityZones` \(Python: `availability_zones`\) – Returns the set of Availability Zones available in the environment in which this stack is deployed\. For environment\-agnostic stacks, this always returns an array with two Availability Zones, but for environment\-specific stacks, the AWS CDK queries the environment and returns the exact set of Availability Zones available in the region you specified\. ++ `stack.partition`, `stack.urlSuffix` \(Python: `url_suffix`\), `stack.stackId` \(Python: `stack_id`\), and `stack.notificationArn` \(Python: `notification_arn`\) – Return tokens that resolve to the respective AWS CloudFormation pseudo parameters, such as `{ "Ref": "AWS::Partition" }`\. These tokens are associated with the specific stack object so that the AWS CDK framework can identify cross\-stack references\. ++ `stack.availabilityZones` \(Python: `availability_zones`\) – Returns the set of Availability Zones available in the environment in which this stack is deployed\. For environment\-agnostic stacks, this always returns an array with two Availability Zones\. For environment\-specific stacks, the AWS CDK queries the environment and returns the exact set of Availability Zones available in the Region that you specified\. + `stack.parseArn(arn)` and `stack.formatArn(comps)` \(Python: `parse_arn`, `format_arn`\) – Can be used to work with Amazon Resource Names \(ARNs\)\. + `stack.toJsonString(obj)` \(Python: `to_json_string`\) – Can be used to format an arbitrary object as a JSON string that can be embedded in an AWS CloudFormation template\. The object can include tokens, attributes, and references, which are only resolved during deployment\. -+ `stack.templateOptions` \(Python: `template_options`\) – Enables you to specify AWS CloudFormation template options, such as Transform, Description, and Metadata, for your stack\. ++ `stack.templateOptions` \(Python: `template_options`\) – Use to specify AWS CloudFormation template options, such as Transform, Description, and Metadata, for your stack\. ## Nested stacks -The [NestedStack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.NestedStack.html) construct offers a way around the AWS CloudFormation 500\-resource limit for stacks\. A nested stack counts as only one resource in the stack that contains it, but can itself contain up to 500 resources, including additional nested stacks\. +The [NestedStack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.NestedStack.html) construct offers a way around the AWS CloudFormation 500\-resource limit for stacks\. A nested stack counts as only one resource in the stack that contains it\. However, it can contain up to 500 resources, including additional nested stacks\. -The scope of a nested stack must be a `Stack` or `NestedStack` construct\. The nested stack needn't be declared lexically inside its parent stack; it is necessary only to pass the parent stack as the first parameter \(`scope`\) when instantiating the nested stack\. Aside from this restriction, defining constructs in a nested stack works exactly the same as in an ordinary stack\. +The scope of a nested stack must be a `Stack` or `NestedStack` construct\. The nested stack doesn't need to be declared lexically inside its parent stack\. It is necessary only to pass the parent stack as the first parameter \(`scope`\) when instantiating the nested stack\. Aside from this restriction, defining constructs in a nested stack works exactly the same as in an ordinary stack\. -At synthesis time, the nested stack is synthesized to its own AWS CloudFormation template, which is uploaded to the AWS CDK staging bucket at deployment\. Nested stacks are bound to their parent stack and are not treated as independent deployment artifacts; they are not listed by `cdk list` nor can they be deployed by `cdk deploy`\. +At synthesis time, the nested stack is synthesized to its own AWS CloudFormation template, which is uploaded to the AWS CDK staging bucket at deployment\. Nested stacks are bound to their parent stack and are not treated as independent deployment artifacts\. They aren't listed by `cdk list`, and they can't be deployed by `cdk deploy`\. References between parent stacks and nested stacks are automatically translated to stack parameters and outputs in the generated AWS CloudFormation templates, as with any [cross\-stack reference](resources.md#resource_stack)\. diff --git a/v2/tagging.md b/v2/tagging.md index 7b94fdce..1cd1c757 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -1,9 +1,13 @@ # Tagging -Tags are informational key\-value elements that you can add to constructs in your AWS CDK app\. A tag applied to a given construct also applies to all of its taggable children\. Tags are included in the AWS CloudFormation template synthesized from your app and are applied to the AWS resources it deploys\. You can use tags to identify and categorize resources to simplify management, in cost allocation, and for access control, as well as for any other purposes you devise\. +Tags are informational key\-value elements that you can add to constructs in your AWS CDK app\. A tag applied to a given construct also applies to all of its taggable children\. Tags are included in the AWS CloudFormation template synthesized from your app and are applied to the AWS resources it deploys\. You can use tags to identify and categorize resources for the following purposes: ++ Simplifying management ++ Cost allocation ++ Access control ++ Any other purposes that you devise **Tip** -For more information about how you can use tags with your AWS resources, see the white paper [Tagging Best Practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf) \(PDF\)\. +For more information about how you can use tags with your AWS resources, see the whitepaper [Tagging Best Practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf) \(PDF\)\. The [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html) class includes the static method `of()`, through which you can add tags to, or remove tags from, the specified construct\. + [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#addkey-value-props](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#addkey-value-props) applies a new tag to the given construct and all of its children\. @@ -92,9 +96,9 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities -The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. +The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\)\. The default priority for removing a tag is 200\. The following applies a tag with a priority of 300 to a construct\. @@ -153,7 +157,7 @@ Use these to manipulate tags only on a subset of resources, based on AWS CloudFo `priority` Use this to set the priority of this operation with respect to other `Tags.add()` and `Tags.remove()` operations\. Higher values take precedence over lower values\. The default is 100 for add operations \(50 for tags applied directly to AWS CloudFormation resources\) and 200 for remove operations\. -The following example applies the tag **tagname** with the value **value** and priority **100** to resources of type **AWS::Xxx::Yyy** in the construct, but not to instances launched in an Amazon EC2 Auto Scaling group or to resources of type **AWS::Xxx::Zzz**\. \(These are placeholders for two arbitrary but different AWS CloudFormation resource types\.\) +The following example applies the tag **tagname** with the value **value** and priority **100** to resources of type **AWS::Xxx::Yyy** in the construct\. It doesn't apply the tag to instances launched in an Amazon EC2 Auto Scaling group or to resources of type **AWS::Xxx::Zzz**\. \(These are placeholders for two arbitrary but different AWS CloudFormation resource types\.\) ------ #### [ TypeScript ] @@ -276,7 +280,7 @@ Tags.Of(myConstruct).Remove("tagname", new TagProps ## Example -The following example adds the tag key **StackType** with value **TheBest** to any resource created within the Stack named `MarketingSystem`\. Then it removes it again from all resources except Amazon EC2 VPC subnets\. The result is that only the subnets have the tag applied\. +The following example adds the tag key **StackType** with value **TheBest** to any resource created within the `Stack` named `MarketingSystem`\. Then it removes it again from all resources except Amazon EC2 VPC subnets\. The result is that only the subnets have the tag applied\. ------ #### [ TypeScript ] @@ -418,7 +422,7 @@ Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps { `Tags.of(scope).add(key, value)` is the standard way to add tags to constructs in the AWS CDK\. Its tree\-walking behavior, which recursively tags all taggable resources under the given scope, is almost always what you want\. Sometimes, however, you need to tag a specific, arbitrary construct \(or constructs\)\. -One such case involves applying tags whose value is derived from some property of the construct being tagged\. The standard tagging approach recursively applies the same key and value to all matching resources in the scope, but here, the value could be different for each tagged construct\. +One such case involves applying tags whose value is derived from some property of the construct being tagged\. The standard tagging approach recursively applies the same key and value to all matching resources in the scope\. However, here the value could be different for each tagged construct\. Tags are implemented using [aspects](aspects.md), and the CDK calls the tag's `visit()` method for each construct under the scope you specified using `Tags.of(scope)`\. We can call `Tag.visit()` directly to apply a tag to a single construct\. @@ -459,9 +463,9 @@ new Tag(key, value).Visit(scope); ------ -To tag all constructs under a scope but allow the values of the tags to be derived from properties of each construct, write an aspect, apply the tag in the aspect's `visit()` method as shown above, and add the aspect to the desired scope using `Aspects.of(scope).add(aspect)`\. +You can tag all constructs under a scope but let the values of the tags derive from properties of each construct\. To do so, write an aspect and apply the tag in the aspect's `visit()` method as shown in the preceding example\. Then, add the aspect to the desired scope using `Aspects.of(scope).add(aspect)`\. -The example below applies a tag to each resource in a stack containing the resource's path\. +The following example applies a tag to each resource in a stack containing the resource's path\. ------ #### [ TypeScript ] @@ -537,4 +541,4 @@ Aspects.Of(stack).Add(new PathTagger); ------ **Tip** -The logic of conditional tagging, including priorities, resource types, and so on, is built into the `Tag` class, so you can use these features when applying tags to arbitrary resources\. Also, the `Tag` class only tags taggble resources, so you don't need to test whether a construct is taggable before applying a tag\. \ No newline at end of file +The logic of conditional tagging, including priorities, resource types, and so on, is built into the `Tag` class\. You can use these features when applying tags to arbitrary resources; the tag is not applied if the conditions aren't met\. Also, the `Tag` class only tags taggable resources, so you don't need to test whether a construct is taggable before applying a tag\. \ No newline at end of file diff --git a/v2/testing.md b/v2/testing.md index 66b7b107..b859a9cc 100644 --- a/v2/testing.md +++ b/v2/testing.md @@ -1,19 +1,19 @@ # Testing constructs -With the AWS CDK, your infrastructure can be as testable as any other code you write\. This article illustrates the standard approach to testing AWS CDK apps using the AWS CDK's [assertions](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.assertions-readme.html) module and popular test frameworks such as [Jest](https://jestjs.io/) for TypeScript and JavaScript or [Pytest](https://docs.pytest.org/en/6.2.x/) for Python\. +With the AWS CDK, your infrastructure can be as testable as any other code you write\. The standard approach to testing AWS CDK apps uses the AWS CDK's [assertions](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.assertions-readme.html) module and popular test frameworks like [Jest](https://jestjs.io/) for TypeScript and JavaScript or [Pytest](https://docs.pytest.org/en/6.2.x/) for Python\. -There are two categories of tests you can write for AWS CDK apps\. -+ **Fine\-grained assertions** test specific aspects of the generated AWS CloudFormation template, such as "this resource has this property with this value\." These tests can detect regressions, and are also useful when you're developing new features using test\-driven development \(write a test first, then make it pass by writing a correct implementation\)\. Fine\-grained assertions are the tests you'll write the most of\. -+ **Snapshot tests** test the synthesized AWS CloudFormation template against a previously\-stored baseline template or "master\." Snapshot tests let you refactor freely, since you can be sure that the refactored code works exactly the same way as the original\. If the changes were intentional, you can accept a new baseline for future tests\. However, CDK upgrades can also cause synthesized templates to change, so you can't rely only on snapshots to make sure your implementation is correct\. +There are two categories of tests that you can write for AWS CDK apps\. ++ **Fine\-grained assertions** test specific aspects of the generated AWS CloudFormation template, such as "this resource has this property with this value\." These tests can detect regressions\. They're also useful when you're developing new features using test\-driven development\. \(You can write a test first, then make it pass by writing a correct implementation\.\) Fine\-grained assertions are the most frequently used tests\. ++ **Snapshot tests** test the synthesized AWS CloudFormation template against a previously stored baseline template\. Snapshot tests let you refactor freely, since you can be sure that the refactored code works exactly the same way as the original\. If the changes were intentional, you can accept a new baseline for future tests\. However, CDK upgrades can also cause synthesized templates to change, so you can't rely only on snapshots to make sure that your implementation is correct\. **Note** Complete versions of the TypeScript, Python, and Java apps used as examples in this topic are [available on GitHub](https://github.com/cdklabs/aws-cdk-testing-examples/)\. ## Getting started -To illustrate how to write these tests, we'll create a stack that contains an AWS Step Functions state machine and a AWS Lambda function\. The Lambda function is subscribed to an Amazon SNS topic and simply forwards the message to the state machine\. +To illustrate how to write these tests, we'll create a stack that contains an AWS Step Functions state machine and an AWS Lambda function\. The Lambda function is subscribed to an Amazon SNS topic and simply forwards the message to the state machine\. -First, create an empty CDK application project using the CDK Toolkit and installing the libraries we'll need\. The constructs we'll use are all in the main CDK package, which is a default dependency in projects created with the CDK Toolkit, but you'll need to install your testing framework\. +First, create an empty CDK application project using the CDK Toolkit and installing the libraries we'll need\. The constructs we'll use are all in the main CDK package, which is a default dependency in projects created with the CDK Toolkit\. However, you must install your testing framework\. ------ #### [ TypeScript ] @@ -35,7 +35,7 @@ Edit the project's `package.json` to tell NPM how to run Jest, and to tell Jest + Add Jest and its types to the `devDependencies` section + Add a new `jest` top\-level key with a `moduleFileExtensions` declaration -These changes are shown in outline below\. Place the new text where indicated in `package.json`\. The "\.\.\." placeholders indicate existing parts of the file that should not be changed\. +These changes are shown in the following outline\. Place the new text where indicated in `package.json`\. The "\.\.\." placeholders indicate existing parts of the file that should not be changed\. ``` { @@ -75,7 +75,7 @@ Edit the project's `package.json` to tell NPM how to run Jest, and to tell Jest + Add Jest to the `devDependencies` section + Add a new `jest` top\-level key with a `moduleFileExtensions` declaration -These changes are shown in outline below\. Place the new text where indicated in `package.json`\. The "\.\.\." placeholders indicate existing parts of the file that s\.hould not be changed\. +These changes are shown in the following outline\. Place the new text where indicated in `package.json`\. The "\.\.\." placeholders indicate existing parts of the file that shouldn't be changed\. ``` { @@ -133,7 +133,7 @@ Right\-click `TestProject1` and choose **Add** > **Project Reference**, and add ## The example stack -Here's the stack we'll be testing in this topic\. As we've previously described, it contains a Lambda function and a Step Functions state machine, and accepts one or more Amazon SNS topics\. The Lambda function is subscribed to the Amazon SNS topics and forwards them to the state machine\. +Here's the stack that will be tested in this topic\. As we've previously described, it contains a Lambda function and a Step Functions state machine, and accepts one or more Amazon SNS topics\. The Lambda function is subscribed to the Amazon SNS topics and forwards them to the state machine\. You don't have to do anything special to make the app testable\. In fact, this CDK stack is not different in any important way from the other example stacks in this Guide\. @@ -379,7 +379,7 @@ namespace AwsCdkAssertionSamples ------ -We'll modify the app's main entry point to not actually instantiate our stack, since we don't want to accidentally deploy it\. Our tests will create an app and an instance of the stack for testing\. This is a useful tactic when combined with test\-driven development: make sure the stack passes all tests before you enable deployment\. +We'll modify the app's main entry point so that we don't actually instantiate our stack\. We don't want to accidentally deploy it\. Our tests will create an app and an instance of the stack for testing\. This is a useful tactic when combined with test\-driven development: make sure that the stack passes all tests before you enable deployment\. ------ #### [ TypeScript ] @@ -475,9 +475,9 @@ namespace AwsCdkAssertionSamples ## The Lambda function -Our example stack includes a Lambda function that starts our state machine\. We must provide the source code for this function so the CDK can bundle it up and deploy it as part of creating the Lambda function resource\. +Our example stack includes a Lambda function that starts our state machine\. We must provide the source code for this function so the CDK can bundle and deploy it as part of creating the Lambda function resource\. + Create the folder `start-state-machine` in the app's main directory\. -+ In this folder, create at least one file\. For example, you can save the code below in `start-state-machines/index.js`\. ++ In this folder, create at least one file\. For example, you can save the following code in `start-state-machines/index.js`\. ``` exports.handler = async function (event, context) { @@ -489,7 +489,7 @@ Our example stack includes a Lambda function that starts our state machine\. We ## Running tests -For reference, here are the commands you use to run tests in your AWS CDK app\. These are the same commands you'd use to run the tests in any project using the same testing framework\. For languages that require a build step, include that to make sure your tests have been compiled\. +For reference, here are the commands you use to run tests in your AWS CDK app\. These are the same commands that you'd use to run the tests in any project using the same testing framework\. For languages that require a build step, include that to make sure that your tests have compiled\. ------ #### [ TypeScript ] @@ -538,7 +538,7 @@ The first step for testing a stack with fine\-grained assertions is to synthesiz Our `ProcessorStack` requires that we pass it the Amazon SNS topic to be forwarded to the state machine\. So in our test, we'll create a separate stack to contain the topic\. -Ordinarily, if you were writing a CDK app, you'd subclass `Stack` and instantiate the Amazon SNS topic in the stack's constructor\. In our test, we instantiate `Stack` directly, then pass this stack as the `Topic`'s scope, attaching it to the stack\. This is functionally equivalent, less verbose, and helps make stacks used only in tests "look different" from stacks you intend to deploy\. +Ordinarily, when writing a CDK app, you can subclass `Stack` and instantiate the Amazon SNS topic in the stack's constructor\. In our test, we instantiate `Stack` directly, then pass this stack as the `Topic`'s scope, attaching it to the stack\. This is functionally equivalent and less verbose\. It also helps make stacks that are used only in tests "look different" from the stacks that you intend to deploy\. ------ #### [ TypeScript ] @@ -807,7 +807,7 @@ Now we can assert that the Lambda function and the Amazon SNS subscription were ------ -Our Lambda function test asserts that two particular properties of the function resource have specific values\. By default, the `hasResourceProperties` method performs a partial match on the resource's properties as given in the synthesized CloudFormation template\. This test requires that the provided properties exist and have the specified values, but the resource can also have other properties, and these are not tested\. +Our Lambda function test asserts that two particular properties of the function resource have specific values\. By default, the `hasResourceProperties` method performs a partial match on the resource's properties as given in the synthesized CloudFormation template\. This test requires that the provided properties exist and have the specified values, but the resource can also have other properties, which are not tested\. Our Amazon SNS assertion asserts that the synthesized template contains a subscription, but nothing about the subscription itself\. We included this assertion mainly to illustrate how to assert on resource counts\. The `Template` class offers more specific methods to write assertions against the `Resources`, `Outputs`, and `Mapping` sections of the CloudFormation template\. @@ -815,7 +815,7 @@ Our Amazon SNS assertion asserts that the synthesized template contains a subscr The default partial matching behavior of `hasResourceProperties` can be changed using *matchers* from the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.assertions.Match.html#methods](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.assertions.Match.html#methods) class\. -Matchers range from the very lenient \(`Match.anyValue`\) to the quite strict \(`Match.objectEquals`\), and can be nested to apply different matching methods to different parts of the resource properties\. Using `Match.objectEquals` and `Match.anyValue` together, for example, we can test the state machine's IAM role more fully, while not requiring specific values for properties that may change\. +Matchers range from lenient \(`Match.anyValue`\) to strict \(`Match.objectEquals`\)\. They can be nested to apply different matching methods to different parts of the resource properties\. Using `Match.objectEquals` and `Match.anyValue` together, for example, we can test the state machine's IAM role more fully, while not requiring specific values for properties that may change\. ------ #### [ TypeScript ] @@ -978,7 +978,9 @@ from aws_cdk.assertions import Match ------ -Many CloudFormation resources include serialized JSON objects represented as strings\. The `Match.serializedJson()` matcher can be used to match properties inside this JSON\. For example, Step Functions state machines are defined using a string in the JSON\-based [Amazon States Language](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html)\. We'll use `Match.serializedJson()` to make sure our initial state is the only step, again using nested matchers to apply different kinds of matching to different parts of the object\. +Many CloudFormation resources include serialized JSON objects represented as strings\. The `Match.serializedJson()` matcher can be used to match properties inside this JSON\. + +For example, Step Functions state machines are defined using a string in the JSON\-based [Amazon States Language](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html)\. We'll use `Match.serializedJson()` to make sure that our initial state is the only step\. Again, we'll use nested matchers to apply different kinds of matching to different parts of the object\. ------ #### [ TypeScript ] @@ -1118,7 +1120,7 @@ It's often useful to test properties to make sure they follow specific formats, By specifying a `Capture` instance in place of a value in `hasResourceProperties`, that value is retained in the `Capture` object\. The actual captured value can be retrieved using the object's `as` methods, including `asNumber()`, `asString()`, and `asObject`, and subjected to test\. Use `Capture` with a matcher to specify the exact location of the value to be captured within the resource's properties, including serialized JSON properties\. -For example, this example tests to make sure that the starting state of our state machine has a name beginning with `Start` and also that this state is actually present within the list of states in the machine\. +The following example tests to make sure that the starting state of our state machine has a name beginning with `Start`\. It also tests that this state is present within the list of states in the machine\. ------ #### [ TypeScript ] @@ -1252,7 +1254,9 @@ import re ## Snapshot tests -In *snapshot testing*, you compare the entire synthesized CloudFormation template against a previously\-stored master\. This isn't useful in catching regressions, as fine\-grained assertions are, because it applies to the entire template, and things besides code changes can cause small \(or not\-so\-small\) differences in synthesis results\. For example, we may update a CDK construct to incorporate a new best practice, which can cause changes to the synthesized resources or how they're organized, or we might update the CDK Toolkit to report additional metadata\. Changes to context values can also affect the synthesized template\. +In *snapshot testing*, you compare the entire synthesized CloudFormation template against a previously stored master\. Unlike fine\-grained assertions, snapshot testing isn't useful in catching regressions\. This is because snapshot testing applies to the entire template, and things besides code changes can cause small \(or not\-so\-small\) differences in synthesis results\. + +For example, you might update a CDK construct to incorporate a new best practice, which can cause changes to the synthesized resources or how they're organized\. Alternatively, you might update the CDK Toolkit to report additional metadata\. Changes to context values can also affect the synthesized template\. Snapshot tests can be of great help in refactoring, though, as long as you hold constant all other factors that might affect the synthesized template\. You will know immediately if a change you made has unintentionally changed the template\. If the change is intentional, simply accept a new master and proceed\. @@ -1492,6 +1496,8 @@ namespace TestProject1 ## Tips for tests -Remember, your tests will live just as long as the code they test, and be read and modified just as often, so it pays to take a moment to consider how best to write them\. Don't copy and paste setup lines or common assertions, for example; refactor this logic into fixtures or helper functions\. Use good names that reflect what each test actually tests\. +Remember, your tests will live just as long as the code they test, and they will be read and modified just as often\. Therefore, it pays to take a moment to consider how best to write them\. + +Don't copy and paste setup lines or common assertions\. Instead, refactor this logic into fixtures or helper functions\. Use good names that reflect what each test actually tests\. -Don't try to do too much in one test\. Preferably, a test should test one and only one behavior\. If you accidentally break that behavior, exactly one test should fail, and the name of the test should tell you exactly what failed\. This is more an ideal to be striven for, however; sometimes you will unavoidably \(or inadvertently\) write tests that test more than one behavior\. Snapshot tests are, for reasons we've already described, especially prone to this problem, so use them sparingly\. \ No newline at end of file +Don't try to do too much in one test\. Preferably, a test should test one and only one behavior\. If you accidentally break that behavior, exactly one test should fail, and the name of the test should tell you what failed\. This is more an ideal to be striven for, however; sometimes you will unavoidably \(or inadvertently\) write tests that test more than one behavior\. Snapshot tests are, for reasons we've already described, especially prone to this problem, so use them sparingly\. \ No newline at end of file diff --git a/v2/tokens.md b/v2/tokens.md index b0f56739..faa745bd 100644 --- a/v2/tokens.md +++ b/v2/tokens.md @@ -8,7 +8,7 @@ ${TOKEN[Bucket.Name.1234]} This is how the AWS CDK encodes a token whose value is not yet known at construction time, but will become available later\. The AWS CDK calls these placeholders *tokens*\. In this case, it's a token encoded as a string\. -You can pass this string around as if it was the name of the bucket, such as in the following example, where the bucket name is specified as an environment variable to an AWS Lambda function\. +You can pass this string around as if it was the name of the bucket\. In the following example, the bucket name is specified as an environment variable to an AWS Lambda function\. ------ #### [ TypeScript ] @@ -85,7 +85,7 @@ Tokens are objects that implement the [IResolvable](https://docs.aws.amazon.com/ **Note** You'll hardly ever work directly with the `IResolvable` interface\. You will most likely only see string\-encoded versions of tokens\. -Other functions typically only accept arguments of basic types, such as `string` or `number`\. To use tokens in these cases, you can encode them into one of three types using static methods on the [cdk\.Token](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html) class\. +Other functions typically only accept arguments of basic types, such as `string` or `number`\. To use tokens in these cases, you can encode them into one of three types by using static methods on the [cdk\.Token](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html) class\. + [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrstringvalue-options](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrstringvalue-options) to generate a string encoding \(or call `.toString()` on the token object\) + [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrlistvalue-options](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrlistvalue-options) to generate a list encoding + [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrnumbervalue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Token.html#static-aswbrnumbervalue) to generate a numeric encoding @@ -93,7 +93,7 @@ Other functions typically only accept arguments of basic types, such as `string` These take an arbitrary value, which can be an `IResolvable`, and encode them into a primitive value of the indicated type\. **Important** -Because any one of the previous types can potentially be an encoded token, be careful when you parse or try to read their contents\. For example, if you attempt to parse a string to extract a value from it, and the string is an encoded token, your parsing will fail\. Similarly, if you attempt to query the length of an array, or perform math operations with a number, you must first verify that they are not encoded tokens\. +Because any one of the previous types can potentially be an encoded token, be careful when you parse or try to read their contents\. For example, if you attempt to parse a string to extract a value from it, and the string is an encoded token, your parsing fails\. Similarly, if you try to query the length of an array or perform math operations with a number, you must first verify that they aren't encoded tokens\. To check whether a value has an unresolved token in it, call the `Token.isUnresolved` \(Python: `is_unresolved`\) method\. @@ -146,7 +146,7 @@ if (!Token.IsUnresolved(name) && name.Length > 10) If **name** is a token, validation isn't performed, and an error could still occur in a later stage in the lifecycle, such as during deployment\. **Note** -You can use token encodings to escape the type system\. For example, you could string\-encode a token that produces a number value at synthesis time\. If you use these functions, it's your responsibility to ensure that your template resolves to a usable state after synthesis\. +You can use token encodings to escape the type system\. For example, you could string\-encode a token that produces a number value at synthesis time\. If you use these functions, it's your responsibility to make sure that your template resolves to a usable state after synthesis\. ## String\-encoded tokens @@ -238,7 +238,7 @@ Avoid manipulating the string in other ways\. For example, taking a substring of ## List\-encoded tokens -List\-encoded tokens look like the following +List\-encoded tokens look like the following: ``` ["#{TOKEN[Stack.NotificationArns.1234]}"] @@ -258,7 +258,7 @@ As with list tokens, you cannot modify the number value, as doing so is likely t ## Lazy values -In addition to representing deploy\-time values, such as AWS CloudFormation [parameters](parameters.md), Tokens are also commonly used to represent synthesis\-time lazy values\. These are values for which the final value will be determined before synthesis has completed, just not at the point where the value is constructed\. Use tokens to pass a literal string or number value to another construct, while the actual value at synthesis time may depend on some calculation that has yet to occur\. +In addition to representing deploy\-time values, such as AWS CloudFormation [parameters](parameters.md), tokens are also commonly used to represent synthesis\-time lazy values\. These are values for which the final value will be determined before synthesis has completed, but not at the point where the value is constructed\. Use tokens to pass a literal string or number value to another construct, while the actual value at synthesis time might depend on some calculation that has yet to occur\. You can construct tokens representing synth\-time lazy values using static methods on the `Lazy` class, such as [Lazy\.string](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Lazy.html#static-stringproducer-options) and [Lazy\.number](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Lazy.html#static-numberproducer)\. These methods accept an object whose `produce` property is a function that accepts a context argument and returns the final value when called\. diff --git a/v2/troubleshooting.md b/v2/troubleshooting.md index ecc10c2c..ae142217 100644 --- a/v2/troubleshooting.md +++ b/v2/troubleshooting.md @@ -6,17 +6,17 @@ This topic describes how to troubleshoot the following issues with the AWS CDK\. + [When deploying my AWS CDK stack, I receive a `forbidden: null` message](#troubleshooting_forbidden_null) + [When synthesizing an AWS CDK stack, I get the message `--app is required either in command-line, in cdk.json or in ~/.cdk.json`](#troubleshooting_app_required) + [When synthesizing an AWS CDK stack, I receive an error because the AWS CloudFormation template contains too many resources](#troubleshooting_resource_count) -+ [I specified three \(or more\) Availability Zones for my EC2 Auto\-Scaling Group or Virtual Private Cloud, but it was only deployed in two](#troubleshooting_availability_zones) ++ [I specified three \(or more\) Availability Zones for my Auto Scaling group or VPC, but it was only deployed in two](#troubleshooting_availability_zones) + [My S3 bucket, DynamoDB table, or other resource is not deleted when I issue `cdk destroy`](#troubleshooting_resource_not_deleted) **After updating the AWS CDK, the AWS CDK Toolkit \(CLI\) reports a mismatch with the AWS Construct Library** -The version of the AWS CDK Toolkit \(which provides the `cdk` command\) must be at least equal to the version of the main AWS Construct Library module, `aws-cdk-lib`\. The Toolkit is intended to be backward compatible; the latest 2\.x version of the toolkit can be used with any 1\.x or 2\.x release of the library\. For this reason, we recommend you install this component globally and keep it up\-to\-date\. +The version of the AWS CDK Toolkit \(which provides the `cdk` command\) must be at least equal to the version of the main AWS Construct Library module, `aws-cdk-lib`\. The Toolkit is intended to be backward compatible\. The latest 2\.x version of the toolkit can be used with any 1\.x or 2\.x release of the library\. For this reason, we recommend you install this component globally and keep it up to date\. ``` npm update -g aws-cdk ``` -If, for some reason, you need to work with multiple versions of the AWS CDK Toolkit, you can install a specific version of the toolkit locally in your project folder\. +If you need to work with multiple versions of the AWS CDK Toolkit, install a specific version of the toolkit locally in your project folder\. If you are using TypeScript or JavaScript, your project directory already contains a versioned local copy of the CDK Toolkit\. @@ -26,13 +26,13 @@ If you are using another language, use `npm` to install the AWS CDK Toolkit, omi npm install aws-cdk@2.0 ``` -To run a locally\-installed AWS CDK Toolkit, use the command `npx aws-cdk` rather than just `cdk`\. For example: +To run a locally installed AWS CDK Toolkit, use the command `npx aws-cdk` instead of only `cdk`\. For example: ``` npx aws-cdk deploy MyStack ``` -`npx aws-cdk` runs the local version of the AWS CDK Toolkit if one exists, and falls back to the global version when a project doesn't have a local installation\. You may find it convenient to set up a shell alias to make sure `cdk` is always invoked this way\. +`npx aws-cdk` runs the local version of the AWS CDK Toolkit if one exists\. It falls back to the global version when a project doesn't have a local installation\. You may find it convenient to set up a shell alias to make sure `cdk` is always invoked this way\. ------ #### [ macOS/Linux ] @@ -59,15 +59,15 @@ Your AWS environment has not been bootstrapped, and so does not have an Amazon S cdk bootstrap aws://ACCOUNT-NUMBER/REGION ``` -To avoid generating unexpected AWS charges, the AWS CDK does not automatically bootstrap any environment\. You must bootstrap each environment into which you will deploy explicitly\. +To avoid generating unexpected AWS charges, the AWS CDK does not automatically bootstrap any environment\. You must explicitly bootstrap each environment into which you will deploy\. -By default, the bootstrap resources are created in the region\(s\) used by stacks in the current AWS CDK application, or the region specified in your local AWS profile \(set by `aws configure`\), using that profile's account\. You can specify a different account and region on the command line as follows\. \(You must specify the account and region if you are not in an app's directory\.\) +By default, the bootstrap resources are created in the Region or Regions that are used by stacks in the current AWS CDK application\. Alternatively, they are created in the Region specified in your local AWS profile \(set by `aws configure`\), using that profile's account\. You can specify a different account and Region on the command line as follows\. \(You must specify the account and Region if you are not in an app's directory\.\) ``` cdk bootstrap aws://ACCOUNT-NUMBER/REGION ``` -For more information, see [Bootstrapping](bootstrapping.md) +For more information, see [Bootstrapping](bootstrapping.md)\. \([back to list](#troubleshooting_top)\) @@ -88,8 +88,8 @@ This message usually means that you aren't in the main directory of your AWS CDK We recommend issuing `cdk` commands only in your project's main directory, so the AWS CDK toolkit can find `cdk.json` there and successfully run your app\. If this isn't practical for some reason, the AWS CDK Toolkit looks for the app's command line in two other locations: -+ in `cdk.json` in your home directory -+ on the `cdk synth` command itself using the `-a` option ++ In `cdk.json` in your home directory ++ On the `cdk synth` command itself using the `-a` option For example, you might synthesize a stack from a TypeScript app as follows\. @@ -109,7 +109,7 @@ The AWS Construct Library's higher\-level, intent\-based constructs automaticall In our experience, real\-world use of intent\-based constructs results in 1–5 AWS CloudFormation resources per construct, though this can vary\. For serverless applications, 5–8 AWS resources per API endpoint is typical\. -Patterns, which represent a higher level of abstraction, let you define even more AWS resources with even less code\. The AWS CDK code in [Creating an AWS Fargate service using the AWS CDK](ecs_example.md), for example, generates more than fifty AWS CloudFormation resources while defining only three constructs\! +Patterns, which represent a higher level of abstraction, let you define even more AWS resources with even less code\. The AWS CDK code in [Creating an AWS Fargate service using the AWS CDK](ecs_example.md), for example, generates more than 50 AWS CloudFormation resources while defining only three constructs\! Exceeding the AWS CloudFormation resource limit is an error during AWS CloudFormation synthesis\. The AWS CDK issues a warning if your stack exceeds 80% of the limit\. You can use a different limit by setting the `maxResources` property on your stack, or disable validation by setting `maxResources` to 0\. @@ -130,27 +130,27 @@ if (path) fs.readFile(path, 'utf8', function(err, contents) { }); else console.log("Please specify the path to the stack's output .json file"); ``` -As your stack's resource count approaches the limit, consider re\-architecting to reduce the number of resources your stack contains: for example, by combining some Lambda functions, or by breaking your stack into multiple stacks\. The CDK supports [references between stacks](resources.md#resource_stack), so it is straightforward to separate your app's functionality into different stacks in whatever way makes the most sense to you\. +As your stack's resource count approaches the limit, consider re\-architecting to reduce the number of resources your stack contains: for example, by combining some Lambda functions, or by breaking your stack into multiple stacks\. The CDK supports [references between stacks](resources.md#resource_stack), so you can separate your app's functionality into different stacks in whatever way makes the most sense to you\. **Note** AWS CloudFormation experts often suggest the use of nested stacks as a solution to the resource limit\. The AWS CDK supports this approach via the [`NestedStack`](stacks.md#stack_nesting) construct\. \([back to list](#troubleshooting_top)\) -**I specified three \(or more\) Availability Zones for my EC2 Auto\-Scaling Group or Virtual Private Cloud, but it was only deployed in two** -To get the number of Availability Zones you requested, specify the account and region in the stack's `env` property\. If you do not specify both, the AWS CDK, by default, synthesizes the stack as environment\-agnostic, such that it can be deployed to any region\. You can then deploy the stack to a specific region using AWS CloudFormation\. Because some regions have only two availability zones, an environment\-agnostic template never uses more than two\. +**I specified three \(or more\) Availability Zones for my Auto Scaling group or VPC, but it was only deployed in two** +To get the number of Availability Zones that you request, specify the account and Region in the stack's `env` property\. If you do not specify both, the AWS CDK, by default, synthesizes the stack as environment\-agnostic\. You can then deploy the stack to a specific Region using AWS CloudFormation\. Because some Regions have only two Availability Zones, an environment\-agnostic template doesn't use more than two\. **Note** -In the past, regions have occasionally launched with only one availability zone\. Environment\-agnostic AWS CDK stacks cannot be deployed to such regions\. At this writing, however, all AWS regions have at least two AZs\. +In the past, Regions have occasionally launched with only one Availability Zone\. Environment\-agnostic AWS CDK stacks cannot be deployed to such Regions\. At this writing, however, all AWS Regions have at least two AZs\. -You can change this behavior by overriding your stack's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones) \(Python: `availability_zones`\) property to explicitly specify the zones you want to use\. +You can change this behavior by overriding your stack's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#availabilityzones) \(Python: `availability_zones`\) property to explicitly specify the zones that you want to use\. For more information about specifying a stack's account and region at synthesis time, while retaining the flexibility to deploy to any region, see [Environments](environments.md)\. \([back to list](#troubleshooting_top)\) **My S3 bucket, DynamoDB table, or other resource is not deleted when I issue `cdk destroy`** -By default, resources that can contain user data have a `removalPolicy` \(Python: `removal_policy`\) property of `RETAIN`, and the resource is not deleted when the stack is destroyed\. Instead, the resource is orphaned from the stack\. You must then delete the resource manually after the stack is destroyed\. Until you do, redeploying the stack fails, because the name of the new resource being created during deployment conflicts with the name of the orphaned resource\. +By default, resources that can contain user data have a `removalPolicy` \(Python: `removal_policy`\) property of `RETAIN`, and the resource is not deleted when the stack is destroyed\. Instead, the resource is orphaned from the stack\. You must then delete the resource manually after the stack is destroyed\. Until you do, redeploying the stack fails\. This is because the name of the new resource being created during deployment conflicts with the name of the orphaned resource\. If you set a resource's removal policy to `DESTROY`, that resource will be deleted when the stack is destroyed\. diff --git a/v2/use_cfn_public_registry.md b/v2/use_cfn_public_registry.md index 0d89f351..ea1c70e3 100644 --- a/v2/use_cfn_public_registry.md +++ b/v2/use_cfn_public_registry.md @@ -1,35 +1,35 @@ # Using resources from the AWS CloudFormation Public Registry - The AWS CloudFormation Public Registry is a collection of AWS CloudFormation extensions from both AWS and third parties that are available for use by all AWS customers\. You can also publish your own extension for others to use\. Extensions are of two types: resources and modules\. You can use public resource extensions in your AWS CDK app using the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html) construct\. + The AWS CloudFormation Public Registry is a collection of AWS CloudFormation extensions from both AWS and third parties\. The extensions are available for use by all AWS customers\. You can also publish your own extension for others to use\. Extensions are of two types: resources and modules\. You can use public resource extensions in your AWS CDK app using the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html) construct\. -All public extensions published by AWS are available to all accounts in all regions without any action on your part\. On the other hand, you must activate each third\-party extension you want to use, in each account and region where you want to use it\. +All public extensions published by AWS are available to all accounts in all Regions without any action on your part\. However, you must activate each third\-party extension you want to use, in each account and Region where you want to use it\. **Note** -When you use AWS CloudFormation with third\-party resource types, you will incur charges based on the number of handler operations you run per month and handler operation duration\. See [CloudFormation pricing](http://aws.amazon.com/cloudformation/pricing/) for complete details\. +When you use AWS CloudFormation with third\-party resource types, you will incur charges\. Charges are based on the number of handler operations you run per month and handler operation duration\. See [CloudFormation pricing](http://aws.amazon.com/cloudformation/pricing/) for complete details\. See [Using public extensions in CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry-public.html) for complete documentation of this feature from the AWS CloudFormation side\. -## Activating a third\-party resource in your account and region +## Activating a third\-party resource in your account and Region -Extensions published by AWS do not require activation; they are always available in every account and region\. You can activate a third\-party extension through the AWS Management Console, via the AWS Command Line Interface, or by deploying a special AWS CloudFormation resource\. +Extensions published by AWS do not require activation; they are always available in every account and Region\. You can activate a third\-party extension through the AWS Management Console, via the AWS Command Line Interface, or by deploying a special AWS CloudFormation resource\. -To activate a third\-party extension through the AWS Management Console, or to simply see what resources are available, follow these steps\. +To activate a third\-party extension through the AWS Management Console, or to see what resources are available, follow these steps\. ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/cdk/v2/guide/images/activate-cfn-extension.png) -1. Log in to the AWS account in which you want to use the extension, then switch to the region where you want to use it\. +1. Sign in to the AWS account in which you want to use the extension, then switch to the Region where you want to use it\. 1. Navigate to the CloudFormation console via the **Services** menu\. -1. Click **Public extensions** on the navigation bar, then activate the **Third party** radio button under **Publisher**\. A list of the available third\-party public extensions appears\. \(You may also choose **AWS** to see a list of the public extensions published by AWS, though you don't need to activate them\.\) +1. Choose **Public extensions** on the navigation bar, then activate the **Third party** radio button under **Publisher**\. A list of the available third\-party public extensions appears\. \(You may also choose **AWS** to see a list of the public extensions published by AWS, though you don't need to activate them\.\) -1. Browse the list and find the extension you want to activate, or search for it, then activate the radio button in the upper right corner of the extension's card\. +1. Browse the list and find the extension you want to activate\. Alternatively, search for it, then activate the radio button in the upper right corner of the extension's card\. -1. Click the **Activate** button at the top of the list to activate the selected extension\. The extension's **Activate** page appears\. +1. Choose the **Activate** button at the top of the list to activate the selected extension\. The extension's **Activate** page appears\. -1. In the **Activate** page, you may override the extension's default name, specify an execution role and logging configuration, and choose whether to automatically update the extension when a new version is released\. When you have set these options as you like, click **Activate extension** at the bottom of the page\. +1. In the **Activate** page, you can override the extension's default name and specify an execution role and logging configuration\. You can also choose whether to automatically update the extension when a new version is released\. When you have set these options as you like, choose **Activate extension** at the bottom of the page\. -To activate a third\-party extension using the AWS CLI, use the `activate-type `command, substituting the ARN of the custom type you want to use for the one given\. +To activate a third\-party extension using the AWS CLI, use the `activate-type `command\. Substitute the ARN of the custom type you want to use where indicated\. ``` aws cloudformation activate-type --public-type-arn public_extension_ARN --auto-update-activated @@ -37,18 +37,18 @@ aws cloudformation activate-type --public-type-arn public_extension_ARN --auto-u To activate an extension through CloudFormation or the CDK, deploy a resource of type `AWS::CloudFormation::TypeActivation`, specifying the following properties\. + `TypeName` \- The name of the type, such as `AWSQS::EKS::Cluster`\. -+ `MajorVersion` \- The major version number of the extension that you want; omit if you want the latest version\. ++ `MajorVersion` \- The major version number of the extension that you want\. Omit if you want the latest version\. + `AutoUpdate` \- Whether to automatically update this extension when a new minor version is released by the publisher\. \(Major version updates require explicitly changing the `MajorVersion` property\.\) + `ExecutionRoleArn` \- The ARN of the IAM role under which this extension will run\. + `LoggingConfig` \- The logging configuration for the extension\. -The `TypeActivation` resource can be deployed by the CDK using the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html) construct, as shown below for the actual extensions\. +The `TypeActivation` resource can be deployed by the CDK using the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html) construct\. This is shown for the actual extensions in the following section\. ## Adding a resource from the AWS CloudFormation Public Registry to your CDK app Use the [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnResource.html) construct to include a resource from the AWS CloudFormation Public Registry in your application\. This construct is in the CDK's `aws-cdk-lib` module\. -For example, suppose there is a public resource named `MY::S5::UltimateBucket` that you want to use in your AWS CDK application\. This resource takes one property: the bucket name\. The corresponding `CfnResource` instantiation looks like this\. +For example, suppose that there is a public resource named `MY::S5::UltimateBucket` that you want to use in your AWS CDK application\. This resource takes one property: the bucket name\. The corresponding `CfnResource` instantiation looks like this\. ------ #### [ TypeScript ] diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 0cdcf380..7cc85195 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -1,15 +1,15 @@ # Import or migrate an existing AWS CloudFormation template -The [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include-readme.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include-readme.html) construct converts the resources in an imported AWS CloudFormation template to AWS CDK L1 constructs\. You can work with these in your app just as if they were defined in AWS CDK code, even using them within higher\-level AWS CDK constructs, letting you use \(for example\) the L2 permission grant methods with the resources they define\. +The [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include-readme.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include-readme.html) construct converts the resources in an imported AWS CloudFormation template to AWS CDK L1 constructs\. You can work with these in your app in the same way that you would if they were defined in AWS CDK code\. You can use these L1 constructs within higher\-level AWS CDK constructs\. For example, this can let you use the L2 permission grant methods with the resources they define\. -This construct essentially adds an AWS CDK API wrapper to any resource in the template\. You can use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time in order to take advantage of the AWS CDK's convenient higher\-level abstractions, or just to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\. +This construct essentially adds an AWS CDK API wrapper to any resource in the template\. Use this capability to migrate your existing AWS CloudFormation templates to the AWS CDK a piece at a time\. This way, you can take advantage of the AWS CDK's convenient higher\-level abstractions\. You can also use this feature to vend your AWS CloudFormation templates to AWS CDK developers by providing an AWS CDK construct API\. **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template - Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. + Here is a simple AWS CloudFormation template to use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed\. You can get this template from the AWS CloudFormation console\. **Tip** You can use either a JSON or YAML template\. We recommend JSON if available, since YAML parsers can vary slightly in what they accept\. @@ -134,9 +134,9 @@ namespace MyApp ------ -By default, importing a resource preserves the resource's original logical ID from the template\. This behavior is suitable for migrating an AWS CloudFormation template to the AWS CDK, where the logical IDs must be retained for AWS CloudFormation to recognize these as the same resources from the AWS CloudFormation template\. +By default, importing a resource preserves the resource's original logical ID from the template\. This behavior is suitable for migrating an AWS CloudFormation template to the AWS CDK, where the logical IDs must be retained\. AWS CloudFormation needs this to recognize these as the same resources from the AWS CloudFormation template\. -If you are instead developing an AWS CDK construct wrapper for the template so it can be used by AWS CDK developers \("vending"\), have the AWS CDK generate new resource IDs instead, so the construct can be used multiple times in a stack without name conflicts\. To do this, set the `preserveLogicalIds` property to false when importing the template\. +You might instead be developing an AWS CDK construct wrapper for the template so it can be used by AWS CDK developers \("vending"\)\. If you're doing this, have the AWS CDK generate new resource IDs instead\. That way, the construct can be used multiple times in a stack without name conflicts\. To do this, set the `preserveLogicalIds` property to `false` when importing the template\. ------ #### [ TypeScript ] @@ -267,7 +267,7 @@ To verify that there will be no unintended changes to the AWS resources in the s cdk diff --no-version-reporting --no-path-metadata --no-asset-metadata ``` -When you `cdk deploy` the stack, your AWS CDK app becomes the source of truth for the stack\. Going forward, make changes to the AWS CDK app, not to the AWS CloudFormation template\. +When you `cdk deploy` the stack, your AWS CDK app becomes the source of truth for the stack\. In the future, make changes to the AWS CDK app, not to the AWS CloudFormation template\. ## Accessing imported resources @@ -355,7 +355,7 @@ Other L2 constructs have similar methods for creating the construct from an exis Constructing the `Bucket` this way doesn't create a second Amazon S3 bucket; instead, the new `Bucket` instance encapsulates the existing `CfnBucket`\. -In the example, `bucket` is now an L2 `Bucket` construct that you can use as you would one you declared yourself\. For example, if `lambdaFunc` is an AWS Lambda function, and you wish to grant it write access to the bucket, you can do so using the bucket's convenient [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrwriteidentity-objectskeypattern](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrwriteidentity-objectskeypattern) method, without needing to construct the necessary IAM policy yourself\. +In the example, `bucket` is now an L2 `Bucket` construct that you can use as you would one you declared yourself\. For example, let's say that `lambdaFunc` is an AWS Lambda function, and you want to grant it write access to the bucket\. To do so, use the bucket's convenient [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrwriteidentity-objectskeypattern](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#grantwbrwriteidentity-objectskeypattern) method\. You don't need to construct the necessary IAM policy yourself\. ------ #### [ TypeScript ] @@ -396,7 +396,7 @@ bucket.GrantWrite(lambdaFunc); ## Replacing parameters -If your included AWS CloudFormation template has parameters, you can replace these with build\-time values when you import the template, using the `parameters` property\. In the example below, we replace the `UploadBucket` parameter with the ARN of a bucket defined elsewhere in our AWS CDK code\. +If your included AWS CloudFormation template has parameters, you can replace these with build\-time values when you import the template, using the `parameters` property\. In the following example, we replace the `UploadBucket` parameter with the ARN of a bucket defined elsewhere in our AWS CDK code\. ------ #### [ TypeScript ] @@ -461,15 +461,15 @@ var template = new cfnInc.CfnInclude(this, "Template", new cfnInc.CfnIncludeProp ## Other template elements -You can import any AWS CloudFormation template element, not just resources\. The imported elements become part of the AWS CDK stack\. To import these elements, use the following methods of the `CfnInclude` object\. +You can import any AWS CloudFormation template element, not only resources\. The imported elements become part of the AWS CDK stack\. To import these elements, use the following methods of the `CfnInclude` object\. + [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrconditionconditionname](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrconditionconditionname) \- AWS CloudFormation [conditions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) -+ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrhookhooklogicalid](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrhookhooklogicalid) \- AWS CloudFormation [hooks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/blue-green.html) for blue\-green deployments ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrhookhooklogicalid](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrhookhooklogicalid) \- AWS CloudFormation [hooks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/blue-green.html) for blue/green deployments + [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrmappingmappingname](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrmappingmappingname) \- AWS CloudFormation [mappings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html) + [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbroutputlogicalid](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbroutputlogicalid) \- AWS CloudFormation [outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html) + [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrparameterparametername](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrparameterparametername) \- AWS CloudFormation [parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) -+ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrrulerulename](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrrulerulename) \- AWS CloudFormation [rules](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/reference-template_constraint_rules.html) for Service Catalog templates ++ [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrrulerulename](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrrulerulename) \- AWS CloudFormation [rules](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/reference-template_constraint_rules.html) for AWS Service Catalog templates -Each of these methods returns an instance of a class representing the specific type of AWS CloudFormation element\. These objects are mutable; changes you make to them will appear in the template generated from the AWS CDK stack\. The code below, for example, imports a parameter from the template and modifies its default\. +Each of these methods returns an instance of a class representing the specific type of AWS CloudFormation element\. These objects are mutable; changes that you make to them will appear in the template generated from the AWS CDK stack\. The following code, for example, imports a parameter from the template and modifies its default\. ------ #### [ TypeScript ] @@ -516,7 +516,7 @@ param.Default = "AWS CDK"; ## Nested stacks -You may import [nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html) by specifying them either when you import their main template, or at some later point\. The nested template must be stored in a local file, but referenced as a `NestedStack` resource in the main template, and the resource name used in the AWS CDK code must match the name used for the nested stack in the main template\. +You may import [nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html) by specifying them either when you import their main template, or at some later point\. The nested template must be stored in a local file, but referenced as a `NestedStack` resource in the main template\. Also, the resource name used in the AWS CDK code must match the name used for the nested stack in the main template\. Given this resource definition in the main template, the following code shows how to import the referenced nested stack both ways\. @@ -622,7 +622,7 @@ var nestedTemplate = mainTemplate.LoadNestedStack("NestedTemplate", new cfnInc.C ------ -You can import multiple nested stacks with either or both methods\. When importing the main template, you provide a mapping between the resource name of each nested stack and its template file, and this mapping can contain any number of entries\. To do it after the initial import, call `loadNestedStack()` once for each nested stack\. +You can import multiple nested stacks with either or both methods\. When importing the main template, you provide a mapping between the resource name of each nested stack and its template file\. This mapping can contain any number of entries\. To do it after the initial import, call `loadNestedStack()` once for each nested stack\. After importing a nested stack, you can access it using the main template's [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrnestedwbrstacklogicalid](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrnestedwbrstacklogicalid) method\. @@ -663,4 +663,4 @@ var nestedStack = mainTemplate.GetNestedStack("NestedStack").Stack; ------ -The `getNestedStack()` method returns an [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrnestedwbrstacklogicalid](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrnestedwbrstacklogicalid) instance, from which you can access the AWS CDK [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.NestedStack.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.NestedStack.html) instance via the `stack` property \(as shown in the example\) or the original AWS CloudFormation template object via `includedTemplate`, from which you can load resources and other AWS CloudFormation elements\. \ No newline at end of file +The `getNestedStack()` method returns an [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrnestedwbrstacklogicalid](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.cloudformation_include.CfnInclude.html#getwbrnestedwbrstacklogicalid) instance\. From this instance, you can access the AWS CDK [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.NestedStack.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.NestedStack.html) instance via the `stack` property \(as shown in the example\)\. You can also access the original AWS CloudFormation template object via `includedTemplate`, from which you can load resources and other AWS CloudFormation elements\. \ No newline at end of file diff --git a/v2/vscode.md b/v2/vscode.md index 3c089740..fc236ba9 100644 --- a/v2/vscode.md +++ b/v2/vscode.md @@ -1,3 +1,3 @@ # AWS Toolkit for Visual Studio Code -The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plug\-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the AWS Toolkit](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. \ No newline at end of file +The [AWS Toolkit for Visual Studio Code](https://aws.amazon.com/visualstudiocode/) is an open source plugin for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS\. The toolkit provides an integrated experience for developing AWS CDK applications\. It includes the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application\. [Install the AWS Toolkit](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html) and learn more about [using the AWS CDK Explorer](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/cdk-explorer.html)\. \ No newline at end of file diff --git a/v2/work-with-cdk-csharp.md b/v2/work-with-cdk-csharp.md index 1e9b19e5..40bd2dda 100644 --- a/v2/work-with-cdk-csharp.md +++ b/v2/work-with-cdk-csharp.md @@ -13,7 +13,7 @@ To work with the AWS CDK, you must have an AWS account and credentials and have C\# AWS CDK applications require \.NET Core v3\.1 or later, [available here](https://dotnet.microsoft.com/download/dotnet-core/3.1)\. **Note** -Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. +Third\-party language deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. The \.NET toolchain includes `dotnet`, a command\-line tool for building and running \.NET applications and managing NuGet packages\. Even if you work mainly in Visual Studio, this command can be useful for batch operations and for installing AWS Construct Library packages\. diff --git a/v2/work-with-cdk-go.md b/v2/work-with-cdk-go.md index 2c97e0f3..90c17cdd 100644 --- a/v2/work-with-cdk-go.md +++ b/v2/work-with-cdk-go.md @@ -13,7 +13,7 @@ To work with the AWS CDK, you must have an AWS account and credentials and have The Go bindings for the AWS CDK use the standard [Go toolchain](https://golang.org/dl/), v1\.18 or later\. You can use the editor of your choice\. **Note** -Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. +Third\-party language deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. ## Creating a project diff --git a/v2/work-with-cdk-java.md b/v2/work-with-cdk-java.md index bddb3650..78f841e4 100644 --- a/v2/work-with-cdk-java.md +++ b/v2/work-with-cdk-java.md @@ -18,7 +18,7 @@ To work with the AWS CDK, you must have an AWS account and credentials and have Java AWS CDK applications require Java 8 \(v1\.8\) or later\. We recommend [Amazon Corretto](https://aws.amazon.com/corretto/), but you can use any OpenJDK distribution or [Oracle's JDK](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)\. You will also need [Apache Maven](https://maven.apache.org/download.cgi) 3\.5 or later\. You can also use tools such as Gradle, but the application skeletons generated by the AWS CDK Toolkit are Maven projects\. **Note** -Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. +Third\-party language deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. ## Creating a project diff --git a/v2/work-with-cdk-javascript.md b/v2/work-with-cdk-javascript.md index 442d2676..e7bee1bf 100644 --- a/v2/work-with-cdk-javascript.md +++ b/v2/work-with-cdk-javascript.md @@ -2,7 +2,7 @@ JavaScript is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in JavaScript uses familiar tools, including [Node\.js](https://nodejs.org/) and the Node Package Manager \(`npm`\)\. You may also use [Yarn](https://yarnpkg.com/) if you prefer, though the examples in this Guide use NPM\. The modules comprising the AWS Construct Library are distributed via the NPM repository, [npmjs\.org](https://www.npmjs.com/)\. -You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://vscodium.com/)\), which has good support for JavaScript\. +You can use any editor or IDE\. Many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://vscodium.com/)\), which has good support for JavaScript\. ## Prerequisites @@ -11,7 +11,7 @@ To work with the AWS CDK, you must have an AWS account and credentials and have JavaScript AWS CDK applications require no additional prerequisites beyond these\. **Note** -Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. +Third\-party language deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. ## Creating a project diff --git a/v2/work-with-cdk-python.md b/v2/work-with-cdk-python.md index c115d018..379a6a96 100644 --- a/v2/work-with-cdk-python.md +++ b/v2/work-with-cdk-python.md @@ -11,7 +11,7 @@ To work with the AWS CDK, you must have an AWS account and credentials and have Python AWS CDK applications require Python 3\.6 or later\. If you don't already have it installed, [download a compatible version](https://www.python.org/downloads/) for your operating system at [python\.org](https://www.python.org/)\. If you run Linux, your system may have come with a compatible version, or you may install it using your distro's package manager \(`yum`, `apt`, etc\.\)\. Mac users may be interested in [Homebrew](https://brew.sh/), a Linux\-style package manager for macOS\. **Note** -Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. +Third\-party language deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. The Python package installer, `pip`, and virtual environment manager, `virtualenv`, are also required\. Windows installations of compatible Python versions include these tools\. On Linux, `pip` and `virtualenv` may be provided as separate packages in your package manager\. Alternatively, you may install them with the following commands: diff --git a/v2/work-with-cdk-typescript.md b/v2/work-with-cdk-typescript.md index 3aad420b..41179d3f 100644 --- a/v2/work-with-cdk-typescript.md +++ b/v2/work-with-cdk-typescript.md @@ -2,7 +2,7 @@ TypeScript is a fully\-supported client language for the AWS CDK and is considered stable\. Working with the AWS CDK in TypeScript uses familiar tools, including Microsoft's TypeScript compiler \(`tsc`\), [Node\.js](https://nodejs.org/) and the Node Package Manager \(`npm`\)\. You may also use [Yarn](https://yarnpkg.com/) if you prefer, though the examples in this Guide use NPM\. The modules comprising the AWS Construct Library are distributed via the NPM repository, [npmjs\.org](https://www.npmjs.com/)\. -You can use any editor or IDE; many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://vscodium.com/)\), which has excellent support for TypeScript\. +You can use any editor or IDE\. Many AWS CDK developers use [Visual Studio Code](https://code.visualstudio.com/) \(or its open\-source equivalent [VSCodium](https://vscodium.com/)\), which has excellent support for TypeScript\. ## Prerequisites @@ -20,7 +20,7 @@ If you get a permission error, and have administrator access on your system, try Keep TypeScript up to date with a regular `npm update -g typescript`\. **Note** -Third\-party Language Deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. +Third\-party language deprecation: language version is only supported until its EOL \(End Of Life\) shared by the vendor or community and is subject to change with prior notice\. ## Creating a project diff --git a/v2/work-with.md b/v2/work-with.md index 34452937..542db749 100644 --- a/v2/work-with.md +++ b/v2/work-with.md @@ -31,7 +31,7 @@ If you get a permission error, and have administrator access on your system, try Test the installation by issuing `cdk --version`\. -If you get an error message at this point, try uninstalling \(`npm uninstall -g aws-cdk`\) and reinstalling\. As a last resort, delete the `node-modules` folder from the current project as well as the global `node-modules` folder\. To figure out where this folder is, issue `npm config get prefix`\. +If you get an error message at this point, try uninstalling \(`npm uninstall -g aws-cdk`\) and reinstalling\. As a last resort, delete the `node-modules` folder from the current project and also from the global `node-modules` folder\. To figure out where this folder is, issue `npm config get prefix`\. ### Language\-specific prerequisites From ad173d6cf8885a0be2f83f4611847e052430489e Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 27 Oct 2022 14:34:06 +0000 Subject: [PATCH 629/655] fix parameter name --- v2/tagging.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/v2/tagging.md b/v2/tagging.md index 1cd1c757..4f92052d 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -473,7 +473,7 @@ The following example applies a tag to each resource in a stack containing the r ``` class PathTagger implements cdk.IAspect { visit(node: IConstruct) { - new cdk.Tag("aws-cdk-path", node.node.path).visit(scope); + new cdk.Tag("aws-cdk-path", node.node.path).visit(node); } } @@ -487,7 +487,7 @@ cdk.Aspects.of(stack).add(new PathTagger()) ``` class PathTagger { visit(node) { - new cdk.Tag("aws-cdk-path", node.node.path).visit(scope); + new cdk.Tag("aws-cdk-path", node.node.path).visit(node); } } @@ -502,7 +502,7 @@ cdk.Aspects.of(stack).add(new PathTagger()) @jsii.implements(cdk.IAspect) class PathTagger: def visit(self, node: IConstruct): - cdk.Tag("aws-cdk-path", node.node.path).visit(scope) + cdk.Tag("aws-cdk-path", node.node.path).visit(node) stack = MyStack(app) cdk.Aspects.of(stack).add(PathTagger()) From 56a144a268fccdc0e0c9d52a067be124de6c771d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Thu, 27 Oct 2022 14:44:09 +0000 Subject: [PATCH 630/655] update imports --- v2/testing.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/v2/testing.md b/v2/testing.md index b859a9cc..4cd8508b 100644 --- a/v2/testing.md +++ b/v2/testing.md @@ -1379,8 +1379,8 @@ We can test it like this: #### [ TypeScript ] ``` -import { Match, Template } from "@aws-cdk/assertions"; -import * as cdk from "@aws-cdk/core"; +import { Match, Template } from "aws-cdk-lib/assertions"; +import * as cdk from "aws-cdk-lib"; import { DeadLetterQueue } from "../lib/dead-letter-queue"; describe("DeadLetterQueue", () => { @@ -1398,8 +1398,8 @@ describe("DeadLetterQueue", () => { #### [ JavaScript ] ``` -const { Match, Template } = require("@aws-cdk/assertions"); -const cdk = require("@aws-cdk/core"); +const { Match, Template } = require("aws-cdk-lib/assertions"); +const cdk = require("aws-cdk-lib"); const { DeadLetterQueue } = require("../lib/dead-letter-queue"); describe("DeadLetterQueue", () => { @@ -1417,8 +1417,8 @@ describe("DeadLetterQueue", () => { #### [ Python ] ``` -from aws_cdk import core as cdk -from aws_cdk.assertions import Match, Template +import aws_cdk_lib as cdk +from aws_cdk_lib.assertions import Match, Template from app.dead_letter_queue import DeadLetterQueue @@ -1440,7 +1440,7 @@ import org.junit.jupiter.api.Test; import au.com.origin.snapshots.Expect; import software.amazon.awscdk.assertions.Match; import software.amazon.awscdk.assertions.Template; -import software.amazon.awscdk.core.Stack; +import software.amazon.awscdk.Stack; import java.util.Collections; import java.util.Map; From 35f3de4d58b46632ab4a4b1df7469571346ed137 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 31 Oct 2022 18:51:48 +0000 Subject: [PATCH 631/655] fix link --- v2/resources.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/resources.md b/v2/resources.md index f244b77e..0f39fddc 100644 --- a/v2/resources.md +++ b/v2/resources.md @@ -269,7 +269,7 @@ If the AWS CDK determines that the resource is in the same account and Region, b Referencing a resource from one stack in a different stack creates a dependency between the two stacks\. This makes sure that they're deployed in the right order\. After the stacks are deployed, this dependency is concrete\. After that, removing the use of the shared resource from the consuming stack can cause an unexpected deployment failure\. This happens if there is another dependency between the two stacks that force them to be deployed in the same order\. It can also happen without a dependency if the producing stack is simply chosen by the CDK Toolkit to be deployed first\. The AWS CloudFormation export is removed from the producing stack because it's no longer needed, but the exported resource is still being used in the consuming stack because its update is not yet deployed\. Therefore, deploying the producer stack fails\. -To break this deadlock, remove the use of the shared resource from the consuming stack\. \(This removes the automatic export from the producing stack\.\) Next, manually add the same export to the producing stack using exactly the same logical ID as the automatically generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then, remove the manual export \(and the shared resource if it's no longer needed\) and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html#static-fromwbrlookupscope-id-options)` method is a convenient way to create the manual export for this purpose\. \(See the example in the linked method reference\.\) +To break this deadlock, remove the use of the shared resource from the consuming stack\. \(This removes the automatic export from the producing stack\.\) Next, manually add the same export to the producing stack using exactly the same logical ID as the automatically generated export\. Remove the use of the shared resource in the consuming stack and deploy both stacks\. Then, remove the manual export \(and the shared resource if it's no longer needed\) and deploy both stacks again\. The stack's `[exportValue\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#exportwbrvalueexportedvalue-options)` method is a convenient way to create the manual export for this purpose\. \(See the example in the linked method reference\.\) ## Referencing resources in your AWS account From 56f17adaeb05eae5600d3ea8854b290e53b8dc2d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 31 Oct 2022 18:52:18 +0000 Subject: [PATCH 632/655] fix typo --- v2/cdk_pipeline.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index 82906305..bc549588 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -51,7 +51,7 @@ npx cdk bootstrap aws://ACCOUNT-NUMBER/REGION --profile ADMIN-PROFILE ^ ------ -To bootstrap additional environments into which AWS CDK applications will be deployed by the pipeline, use the following commandsinstead\. The \-\-trust option indicates which other account should have permissions to deploy AWS CDK applications into this environment\. For this option, specify the pipeline's AWS account ID\. +To bootstrap additional environments into which AWS CDK applications will be deployed by the pipeline, use the following commands instead\. The \-\-trust option indicates which other account should have permissions to deploy AWS CDK applications into this environment\. For this option, specify the pipeline's AWS account ID\. Again, you can omit the \-\-profile option in the following situations: + If your default AWS profile contains the necessary credentials From 8ae6d8ece34dbb8591a1c77c7f99c4689cc884a3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 7 Nov 2022 19:24:14 +0000 Subject: [PATCH 633/655] improve feature flags documentation --- v1/featureflags.md | 2 +- v2/featureflags.md | 15 ++++++++++----- v2/migrating-v2.md | 19 ++++++++++++++----- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/v1/featureflags.md b/v1/featureflags.md index 52139603..38d506cb 100644 --- a/v1/featureflags.md +++ b/v1/featureflags.md @@ -15,6 +15,6 @@ The names of all feature flags begin with the NPM name of the package affected b Feature flags are disabled by default, so existing projects that do not specify the flag will continue to work as expected with later AWS CDK releases\. New projects created using cdk init include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the old behavior, or to add flags to enable new behaviors after upgrading the AWS CDK\. -See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. The AWS CDK source file [https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts) provides a complete list of all current feature flags\. +See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. A list of all current feature flags can be found on the AWS CDK GitHub repository in [https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/cx-api/FEATURE_FLAGS.md](https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/cx-api/FEATURE_FLAGS.md)\. As feature flags are stored in `cdk.json`, they are not removed by the cdk context \-\-reset or cdk context \-\-clear commands\. \ No newline at end of file diff --git a/v2/featureflags.md b/v2/featureflags.md index bc9a0d20..6a9f4af5 100644 --- a/v2/featureflags.md +++ b/v2/featureflags.md @@ -4,9 +4,9 @@ The AWS CDK uses *feature flags* to enable potentially breaking behaviors in a r Feature flags are disabled by default\. Existing projects that do not specify the flag will continue to work as before with later AWS CDK releases\. New projects created using cdk init include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the earlier behavior\. You can also add flags to enable new behaviors after upgrading the AWS CDK\. -See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. The AWS CDK source file [https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts](https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/cx-api/lib/features.ts) provides a complete list of all current feature flags\. +See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. A list of all current feature flags can be found on the AWS CDK GitHub repository in [https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/cx-api/FEATURE_FLAGS.md](https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/cx-api/FEATURE_FLAGS.md)\. -## Enabling features with flags +## Enabling features with flags The following feature flags may be set to `true` to enable the described behavior\. @@ -43,9 +43,12 @@ The AWS CDK fails at synthesis time if the `SNAPSHOT` removal policy is not supp `@aws-cdk/aws-ecs:arnFormatIncludesClusterName` Use the new ARN format when importing an Amazon EC2 or Fargate cluster\. -## Disabling features with flags +## Reverting to v1 behavior -In CDK v2, a few feature flags are supported to revert certain behaviors to their v1 defaults\. The following flags, set to `false`, revert to specific AWS CDK v1 behaviors\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. +In CDK v2, the defaults for a set of feature flags have been changed with respect to v1\. You can set these back to `false` to revert to specific AWS CDK v1 behavior\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. + +`@aws-cdk/core:newStyleStackSynthesis` +Use the new stack synthesis method, which assumes bootstrap resources with well\-known names\. Requires [modern bootstrapping](bootstrapping.md), but in turn allows CI/CD via [CDK Pipelines](cdk_pipeline.md) and cross\-account deployments out of the box\. `@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId` If your application uses multiple Amazon API Gateway API keys and associates them to usage plans\. @@ -60,17 +63,19 @@ If your application uses Amazon RDS database instance or database clusters, and If your application uses multiple stacks and you refer to resources from one stack in another, this determines whether absolute or relative path is used to construct AWS CloudFormation exports\. `@aws-cdk/aws-lambda:recognizeVersionProps` -If set to `false`, the CDK includes metadata when detecting whether a Lambda function has changed\. This can cause deployment failures when only the metadata has changed, since duplicate versions are not allowed\. +If set to `false`, the CDK includes metadata when detecting whether a Lambda function has changed\. This can cause deployment failures when only the metadata has changed, since duplicate versions are not allowed\. There is no need to revert this flag if you've made at least one change to all Lambda Functions in your application\. The syntax for reverting these flags in `cdk.json` is shown here\. ``` { "context": { + "@aws-cdk/core:newStyleStackSynthesis": false, "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": false, "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": false, "@aws-cdk/aws-rds:lowercaseDbIdentifier": false, "@aws-cdk/core:stackRelativeExports": false, + "@aws-cdk/aws-lambda:recognizeVersionProps": false } } ``` \ No newline at end of file diff --git a/v2/migrating-v2.md b/v2/migrating-v2.md index f4fe5854..fc9b4a11 100644 --- a/v2/migrating-v2.md +++ b/v2/migrating-v2.md @@ -87,9 +87,18 @@ To migrate your app to AWS CDK v2, first update the feature flags in `cdk.json`\ ### Updating feature flags -Remove all v1 feature flags from `cdk.json`, as these are all active by default in AWS CDK v2\. +Remove the following v1 feature flags from `cdk.json` if they exist, as these are all active by default in AWS CDK v2\. If their old effect is important for your infrastructure, you will need to make source code changes\. See [the list of flags on GitHub](https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/cx-api/FEATURE_FLAGS.md) for more information\. ++ `@aws-cdk/core:enableStackNameDuplicates` ++ `aws-cdk:enableDiffNoFail` ++ `@aws-cdk/aws-ecr-assets:dockerIgnoreSupport` ++ `@aws-cdk/aws-secretsmanager:parseOwnedSecretName` ++ `@aws-cdk/aws-kms:defaultKeyPolicies` ++ `@aws-cdk/aws-s3:grantWriteWithoutAcl` ++ `@aws-cdk/aws-efs:defaultEncryptionAtRest` -A handful of v1 feature flags can be set to `false` in order to revert to specific AWS CDK v1 behaviors; see [Disabling features with flags](featureflags.md#featureflags_disabling) for a complete list\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. +A handful of v1 feature flags can be set to `false` in order to revert to specific AWS CDK v1 behaviors; see [Reverting to v1 behavior](featureflags.md#featureflags_disabling) or the list on GitHub for a complete reference\. + +For both types of flags, use the `cdk diff` command to inspect the changes to your synthesized template to see if the changes to any of these flags affect your infrastructure\. ### CDK Toolkit compatibility @@ -152,7 +161,7 @@ Note that `aws-cdk-lib` appears both as a peer dependency and a dev dependency\. "aws-cdk-lib": "^2.0.0", "constructs": "^10.0.0", "typescript": "~3.9.0" - } + } } ``` @@ -237,10 +246,10 @@ import aws_cdk.aws_codestar_alpha as codestar # experimental module class MyConstruct(Construct): # ... - + class MyStack(Stack): # ... - + s3.Bucket(...) ``` From a99ff6fa7ec713904677f8a8a17bc38d81ebae99 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 7 Nov 2022 19:24:46 +0000 Subject: [PATCH 634/655] autogenerated id churn --- v1/cli.md | 26 +++++++++++++------------- v1/manage-dependencies.md | 10 +++++----- v1/tagging.md | 2 +- v1/use_cfn_template.md | 2 +- v2/cli.md | 26 +++++++++++++------------- v2/manage-dependencies.md | 10 +++++----- v2/tagging.md | 2 +- v2/use_cfn_template.md | 2 +- 8 files changed, 40 insertions(+), 40 deletions(-) diff --git a/v1/cli.md b/v1/cli.md index dae12068..c4a6fb69 100644 --- a/v1/cli.md +++ b/v1/cli.md @@ -351,7 +351,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most\-frequently\-used options are covered below\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -370,7 +370,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -378,7 +378,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -454,7 +454,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -476,7 +476,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -733,7 +733,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -746,7 +746,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -767,7 +767,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -847,7 +847,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -925,7 +925,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -944,7 +944,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -970,7 +970,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -992,7 +992,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v1/manage-dependencies.md b/v1/manage-dependencies.md index bb65af42..02de3280 100644 --- a/v1/manage-dependencies.md +++ b/v1/manage-dependencies.md @@ -31,7 +31,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, just without the TypeScript\-related entries\. @@ -72,7 +72,7 @@ All AWS CDK dependencies must have the same version\. Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -99,7 +99,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`, or they will not be installed, and you will receive a warning about unresolved peer dependencies -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -145,7 +145,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project, which allows each project to have its own versions of dependencies, as well as a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -169,7 +169,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file and used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(indluding transitive ones\) to the exact versions you tested with\. To avoid problems when upgrading packages later, use a separate file for this, e\.g\. `freeze.txt` not `requirements.txt`, and regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v1/tagging.md b/v1/tagging.md index 5b8ab603..7d837a72 100644 --- a/v1/tagging.md +++ b/v1/tagging.md @@ -92,7 +92,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\) and removing a tag has a priority of 200\. diff --git a/v1/use_cfn_template.md b/v1/use_cfn_template.md index 51d7210b..dd288e5e 100644 --- a/v1/use_cfn_template.md +++ b/v1/use_cfn_template.md @@ -56,7 +56,7 @@ dotnet add package Amazon.CDK.CloudFormation.Include ------ -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template we'll use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed, which you can obtain from the AWS CloudFormation console\. diff --git a/v2/cli.md b/v2/cli.md index 4ee77719..1da651e8 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -343,7 +343,7 @@ The CDK Toolkit actually runs your app and synthesizes fresh templates before mo See `cdk synth --help` for all available options\. A few of the most frequently used options are covered in the following section\. -### Specifying context values +### Specifying context values Use the `--context` or `-c` option to pass [runtime context](context.md) values to your CDK app\. @@ -362,7 +362,7 @@ When deploying multiple stacks, the specified context values are normally passed cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2 ``` -### Specifying display format +### Specifying display format By default, the synthesized template is displayed in YAML format\. Add the `--json` flag to display it in JSON format instead\. @@ -370,7 +370,7 @@ By default, the synthesized template is displayed in YAML format\. Add the `--js cdk synth --json MyStack ``` -### Specifying output directory +### Specifying output directory Add the `--output` \(`-o`\) option to write the synthesized templates to a directory other than `cdk.out`\. @@ -446,7 +446,7 @@ Git\-style wildcards, both `*` and `**`, can be used in the `"watch"` and `"buil **Important** Watch mode is not recommended for production deployments\. -### Specifying AWS CloudFormation parameters +### Specifying AWS CloudFormation parameters The AWS CDK Toolkit supports specifying AWS CloudFormation [parameters](parameters.md) at deployment\. You may provide these on the command line following the `--parameters` flag\. @@ -468,7 +468,7 @@ cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly\. Use the `--no-previous-parameters` flag to require all parameters to be specified\. -### Specifying outputs file +### Specifying outputs file If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment\. To write them to a file in JSON format, use the `--outputs-file` flag\. @@ -725,7 +725,7 @@ If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. ``` -### `cdk list` \(`ls`\) +### `cdk list` \(`ls`\) ``` cdk list [STACKS..] @@ -738,7 +738,7 @@ Options: [boolean] [default: false] ``` -### `cdk synthesize` \(`synth`\) +### `cdk synthesize` \(`synth`\) ``` cdk synthesize [STACKS..] @@ -759,7 +759,7 @@ Options: [boolean] [default: false] ``` -### `cdk bootstrap` +### `cdk bootstrap` ``` cdk bootstrap [ENVIRONMENTS..] @@ -839,7 +839,7 @@ Options: example) [string] ``` -### `cdk deploy` +### `cdk deploy` ``` cdk deploy [STACKS..] @@ -917,7 +917,7 @@ Options: [boolean] [default: true] ``` -### `cdk destroy` +### `cdk destroy` ``` cdk destroy [STACKS..] @@ -936,7 +936,7 @@ Options: stacks [boolean] ``` -### `cdk diff` +### `cdk diff` ``` cdk diff [STACKS..] @@ -962,7 +962,7 @@ Options: [boolean] [default: false] ``` -### `cdk init` +### `cdk init` ``` cdk init [TEMPLATE] @@ -984,7 +984,7 @@ Options: project [boolean] [default: false] ``` -### `cdk context` +### `cdk context` ``` cdk context diff --git a/v2/manage-dependencies.md b/v2/manage-dependencies.md index 1d41115e..b90077aa 100644 --- a/v2/manage-dependencies.md +++ b/v2/manage-dependencies.md @@ -33,7 +33,7 @@ If you prefer, you may use Yarn in place of NPM\. However, the CDK does not supp nodeLinker: node-modules ``` -### Applications +### Applications The following is an example `package.json` generated by cdk init \-\-language typescript\. The file generated for JavaScript is similar, only without the TypeScript\-related entries\. @@ -73,7 +73,7 @@ Specify exact versions for alpha construct library modules, which have APIs that Specify versions of libraries and tools needed to test your app \(for example, the `jest` testing framework\) in the `devDependencies` section of `package.json`\. Optionally, use ^ to specify that later compatible versions are acceptable\. -### Construct libraries +### Construct libraries If you're developing a construct library, specify its dependencies via a combination of the `peerDependencies` and `devDependencies` sections, as shown in the following example `package.json` file\. @@ -103,7 +103,7 @@ In `devDependencies`, specify the tools and libraries you need for testing, opti **Warning** `peerDependencies` are installed automatically only by NPM 7 and later\. If you are using NPM 6 or earlier, or if you are using Yarn, you must include the dependencies of your dependencies in `devDependencies`\. Otherwise, they won't be installed, and you will receive a warning about unresolved peer dependencies\. -### Installing and updating dependencies +### Installing and updating dependencies Run the following command to install your project's dependencies\. @@ -149,7 +149,7 @@ The python \-m pip invocation works on most systems; pip requires that PIP's exe cdk init \-\-language python creates a virtual environment for your new project\. This lets each project have its own versions of dependencies, and also a basic `requirements.txt` file\. You must activate this virtual environment \(source \.venv/bin/activate\) each time you begin working with the project\. -### Applications +### Applications An example `requirements.txt` follows\. Because PIP does not have a dependency\-locking feature, we recommend that you use the == operator to specify exact versions for all dependencies, as shown here\. @@ -169,7 +169,7 @@ python -m pip install -r requirements.txt **Tip** The pip freeze command outputs the versions of all installed dependencies in a format that can be written to a text file\. This can be used as a requirements file with `pip install -r`\. This file is convenient for pinning all dependencies \(including transitive ones\) to the exact versions that you tested with\. To avoid problems when upgrading packages later, use a separate file for this, such as `freeze.txt` \(not `requirements.txt`\)\. Then, regenerate it when you upgrade your project's dependencies\. -### Construct libraries +### Construct libraries In libraries, dependencies are specified in `setup.py`, so that transitive dependencies are automatically downloaded when the package is consumed by an application\. Otherwise, every application that wants to use your package needs to copy your dependencies into their `requirements.txt`\. An example `setup.py` is shown here\. diff --git a/v2/tagging.md b/v2/tagging.md index 4f92052d..ab2db769 100644 --- a/v2/tagging.md +++ b/v2/tagging.md @@ -96,7 +96,7 @@ Tags.Of(myConstruct).Remove("key"); If you are using `Stage` constructs, apply the tag at the `Stage` level or below\. Tags are not applied across `Stage` boundaries\. -## Tag priorities +## Tag priorities The AWS CDK applies and removes tags recursively\. If there are conflicts, the tagging operation with the highest priority wins\. \(Priorities are set using the optional `priority` property\.\) If the priorities of two operations are the same, the tagging operation closest to the bottom of the construct tree wins\. By default, applying a tag has a priority of 100 \(except for tags added directly to an AWS CloudFormation resource, which has a priority of 50\)\. The default priority for removing a tag is 200\. diff --git a/v2/use_cfn_template.md b/v2/use_cfn_template.md index 7cc85195..1dc1e90f 100644 --- a/v2/use_cfn_template.md +++ b/v2/use_cfn_template.md @@ -7,7 +7,7 @@ This construct essentially adds an AWS CDK API wrapper to any resource in the te **Note** AWS CDK v1 also included [https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.CfnInclude.html), which was previously used for the same general purpose\. However, it lacks much of the functionality of `cloudformation-include.CfnInclude`\. -## Importing an AWS CloudFormation template +## Importing an AWS CloudFormation template Here is a simple AWS CloudFormation template to use for the examples in this topic\. Save it as `my-template.json`\. After you've tried these examples with the provided template, you might explore further using a template for an actual stack you've already deployed\. You can get this template from the AWS CloudFormation console\. From dfc2d4d32f9ba85dbfcaa088e235c19050dcfadf Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Tue, 22 Nov 2022 20:07:48 +0000 Subject: [PATCH 635/655] remove reference section from CLI doc since it is easily accessible from the CLI and always up-to-date there --- v2/cli.md | 409 +----------------------------------------------------- 1 file changed, 2 insertions(+), 407 deletions(-) diff --git a/v2/cli.md b/v2/cli.md index 1da651e8..df835d10 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -31,7 +31,7 @@ All CDK Toolkit commands start with `cdk`, which is followed by a subcommand \(` | `cdk docs` \(`doc`\) | Opens the CDK API Reference in your browser | | `cdk doctor` | Checks your CDK project for potential problems | -For the options available for each command, see [Toolkit reference](#cli-ref) or [Built\-in help](#cli-help)\. +For the options available for each command, see [Built\-in help](#cli-help)\. ## Specifying options and their values @@ -591,409 +591,4 @@ Default values for many CDK Toolkit command line flags can be stored in a projec | toolkitBucketName | The name of the Amazon S3 bucket used for deploying assets such as Lambda functions and container images \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-bucket\-name | | toolkitStackName | The name of the bootstrap stack \(see [Bootstrapping your AWS environment](#cli-bootstrap)\. | \-\-toolkit\-stack\-name | | versionReporting | If false, opts out of version reporting\. | \-\-no\-version\-reporting | -| watch | JSON object containing "include" and "exclude" keys that indicate which files should \(or should not\) trigger a rebuild of the project when changed\. See [Watch mode](#cli-deploy-watch)\. | \-\-watch | - -## Toolkit reference - -This section provides a reference for the AWS CDK Toolkit derived from its help\. First there's a general reference with the options available with all commands\. Then \(in collapsible sections\), you can find specific references with options that are available only with specific subcommands\. - -``` -Usage: cdk -a COMMAND - -Commands: - - cdk list [STACKS..] Lists all stacks in the app [aliases: ls] - - cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation - template for this stack [aliases: synth] - - cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS - environment - - cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your - AWS account - - cdk import [STACK] Import existing resource(s) into the given - STACK - - cdk watch [STACKS..] Shortcut for 'deploy --watch' - - cdk destroy [STACKS..] Destroy the stack(s) named STACKS - - cdk diff [STACKS..] Compares the specified stack with the deployed - stack or a local template file, and returns - with status 1 if any difference is found - - cdk metadata [STACK] Returns all metadata associated with this - stack - - cdk acknowledge [ID] Acknowledge a notice so that it does not show - up anymore [aliases: ack] - - cdk notices Returns a list of relevant notices - - cdk init [TEMPLATE] Create a new, empty CDK project from a - template. - - cdk context Manage cached context values - - cdk docs Opens the reference documentation in a browser - [aliases: doc] - - cdk doctor Check your set-up for potential problems - -Options: - - -a, --app REQUIRED: command-line for executing your app or a - cloud assembly directory (e.g. "node bin/my-app.js") - [string] - - --build Command-line for a pre-synth build [string] - - -c, --context Add contextual string parameter (KEY=VALUE) [array] - - -p, --plugin Name or path of a node package that extend the CDK - features. Can be specified multiple times [array] - - --trace Print trace for stack warnings [boolean] - - --strict Do not construct stacks with warnings [boolean] - - --lookups Perform context lookups (synthesis fails if this is - disabled and context lookups need to be performed) - [boolean] [default: true] - - --ignore-errors Ignores synthesis errors, which will likely produce - an invalid output [boolean] [default: false] - - -j, --json Use JSON output instead of YAML when templates are - printed to STDOUT [boolean] [default: false] - - -v, --verbose Show debug logs (specify multiple times to increase - verbosity) [count] [default: false] - - --debug Enable emission of additional debugging information, - such as creation stack traces of tokens - [boolean] [default: false] - - --profile Use the indicated AWS profile as the default - environment [string] - - --proxy Use the indicated proxy. Will read from HTTPS_PROXY - environment variable if not specified [string] - - --ca-bundle-path Path to CA certificate to use when validating HTTPS - requests. Will read from AWS_CA_BUNDLE environment - variable if not specified [string] - - -i, --ec2creds Force trying to fetch EC2 instance credentials. - Default: guess EC2 instance status [boolean] - - --version-reporting Include the "AWS::CDK::Metadata" resource in - synthesized templates (enabled by default) [boolean] - - --path-metadata Include "aws:cdk:path" CloudFormation metadata for - each resource (enabled by default) - [boolean] [default: true] - - --asset-metadata Include "aws:asset:*" CloudFormation metadata for - resources that uses assets (enabled by default) - [boolean] [default: true] - - -r, --role-arn ARN of Role to use when invoking CloudFormation - [string] - - --staging Copy assets to the output directory (use --no-staging - to disable, needed for local debugging the source - files with SAM CLI) [boolean] [default: true] - - -o, --output Emits the synthesized cloud assembly into a directory - (default: cdk.out) [string] - - --notices Show relevant notices [boolean] - - --no-color Removes colors and other style from console output - [boolean] [default: false] - - --version Show version number [boolean] - - -h, --help Show help [boolean] - -If your app has a single stack, there is no need to specify the stack name - -If one of cdk.json or ~/.cdk.json exists, options specified there will be used -as defaults. Settings in cdk.json take precedence. -``` - -### `cdk list` \(`ls`\) - -``` -cdk list [STACKS..] - -Lists all stacks in the app - -Options: - - -l, --long Display environment information for each stack - [boolean] [default: false] -``` - -### `cdk synthesize` \(`synth`\) - -``` -cdk synthesize [STACKS..] - -Synthesizes and prints the CloudFormation template for this stack - -Options: - - -e, --exclusively Only synthesize requested stacks, don't include - dependencies [boolean] - - --validation After synthesis, validate stacks with the - "validateOnSynth" attribute set (can also be - controlled with CDK_VALIDATION) - [boolean] [default: true] - - -q, --quiet Do not output CloudFormation Template to stdout - [boolean] [default: false] -``` - -### `cdk bootstrap` - -``` -cdk bootstrap [ENVIRONMENTS..] - -Deploys the CDK toolkit stack into an AWS environment - -Options: - - -b, --bootstrap-bucket-name, The name of the CDK toolkit bucket; - --toolkit-bucket-name bucket will be created and must not - exist [string] - - --bootstrap-kms-key-id AWS KMS master key ID used for the - SSE-KMS encryption [string] - - --bootstrap-customer-key Create a Customer Master Key (CMK) - for the bootstrap bucket (you will - be charged but can customize - permissions, modern bootstrapping - only) [boolean] - - --qualifier String which must be unique for each - bootstrap stack. You must configure - it on your CDK app if you change - this from the default. [string] - - --public-access-block-configuration Block public access configuration - on CDK toolkit bucket (enabled by - default) [boolean] - - -t, --tags Tags to add for the stack - (KEY=VALUE) [array] [default: []] - - --execute Whether to execute ChangeSet - (--no-execute will NOT execute the - ChangeSet) [boolean] [default: true] - - --trust The AWS account IDs that should be - trusted to perform deployments into - this environment (may be repeated, - modern bootstrapping only) - [array] [default: []] - - --trust-for-lookup The AWS account IDs that should be - trusted to look up values in this - environment (may be repeated, modern - bootstrapping only) - [array] [default: []] - - --cloudformation-execution-policies The Managed Policy ARNs that should - be attached to the role performing - deployments into this environment - (may be repeated, modern - bootstrapping only) - [array] [default: []] - - -f, --force Always bootstrap even if it would - downgrade template version - [boolean] [default: false] - - --termination-protection Toggle CloudFormation termination - protection on the bootstrap stacks - [boolean] - - --show-template Instead of actual bootstrapping, - print the current CLI's - bootstrapping template to stdout for - customization - [boolean] [default: false] - - --toolkit-stack-name The name of the CDK toolkit stack to - create [string] - - --template Use the template from the given file - instead of the built-in one (use - --show-template to obtain an - example) [string] -``` - -### `cdk deploy` - -``` -cdk deploy [STACKS..] - -Deploys the stack(s) named STACKS into your AWS account - -Options: - - --all Deploy all available stacks - [boolean] [default: false] - - -E, --build-exclude Do not rebuild asset with the given ID. Can be - specified multiple times [array] [default: []] - - -e, --exclusively Only deploy requested stacks, don't include - dependencies [boolean] - - --require-approval What security-sensitive changes need manual - approval - [string] [choices: "never", "any-change", "broadening"] - - --ci Force CI detection [boolean] [default: false] - - --notification-arns ARNs of SNS topics that CloudFormation will notify - with stack related events [array] - - -t, --tags Tags to add to the stack (KEY=VALUE), overrides - tags from Cloud Assembly (deprecated) [array] - - --execute Whether to execute ChangeSet (--no-execute will NOT - execute the ChangeSet) [boolean] [default: true] - - --change-set-name Name of the CloudFormation change set to create - [string] - - -f, --force Always deploy stack even if templates are identical - [boolean] [default: false] - - --parameters Additional parameters passed to CloudFormation at - deploy time (STACK:KEY=VALUE) [array] [default: {}] - - -O, --outputs-file Path to file where stack outputs will be written as - JSON [string] - - --previous-parameters Use previous values for existing parameters (you - must specify all parameters on every deployment if - this is disabled) [boolean] [default: true] - - --toolkit-stack-name The name of the existing CDK toolkit stack (only - used for app using legacy synthesis) [string] - - --progress Display mode for stack activity events - [string] [choices: "bar", "events"] - - --rollback Rollback stack to stable state on failure. Defaults - to 'true', iterate more rapidly with --no-rollback - or -R. Note: do **not** disable this flag for - deployments with resource replacements, as that - will always fail [boolean] - - --hotswap Attempts to perform a 'hotswap' deployment, which - skips CloudFormation and updates the resources - directly, and falls back to a full deployment if - that is not possible. Do not use this in production - environments [boolean] - - --watch Continuously observe the project files, and deploy - the given stack(s) automatically when changes are - detected. Implies --hotswap by default [boolean] - - --logs Show CloudWatch log events from all resources in - the selected Stacks in the terminal. 'true' by - default, use --no-logs to turn off. Only in effect - if specified alongside the '--watch' option - [boolean] [default: true] -``` - -### `cdk destroy` - -``` -cdk destroy [STACKS..] - -Destroy the stack(s) named STACKS - -Options: - - --all Destroy all available stacks - [boolean] [default: false] - - -e, --exclusively Only destroy requested stacks, don't include - dependees [boolean] - - -f, --force Do not ask for confirmation before destroying the - stacks [boolean] -``` - -### `cdk diff` - -``` -cdk diff [STACKS..] - -Compares the specified stack with the deployed stack or a local template file, -and returns with status 1 if any difference is found - -Options: - - -e, --exclusively Only diff requested stacks, don't include - dependencies [boolean] - - --context-lines Number of context lines to include in arbitrary JSON - diff rendering [number] [default: 3] - - --template The path to the CloudFormation template to compare - with [string] - - --security-only Only diff for broadened security changes - [boolean] [default: false] - - --fail Fail with exit code 1 in case of diff - [boolean] [default: false] -``` - -### `cdk init` - -``` -cdk init [TEMPLATE] - -Create a new, empty CDK project from a template. - -Options: - - -l, --language The language to be used for the new project (default - can be configured in ~/.cdk.json) - [string] [choices: "csharp", "fsharp", "go", "java", "javascript", "python", - "typescript"] - - --list List the available templates [boolean] - - --generate-only If true, only generates project files, without - executing additional operations such as setting up a - git repo, installing dependencies or compiling the - project [boolean] [default: false] -``` - -### `cdk context` - -``` -cdk context - -Manage cached context values - -Options: - - -e, --reset The context key (or its index) to reset [string] - - --clear Clear all context [boolean] -``` \ No newline at end of file +| watch | JSON object containing "include" and "exclude" keys that indicate which files should \(or should not\) trigger a rebuild of the project when changed\. See [Watch mode](#cli-deploy-watch)\. | \-\-watch | \ No newline at end of file From 8290ce7a889e5c315ee2809ab8a24d5101a75f49 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 15:50:28 +0000 Subject: [PATCH 636/655] revise wording around problemating 'master' in snapshot section --- v2/testing.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/v2/testing.md b/v2/testing.md index 4cd8508b..eb1a434a 100644 --- a/v2/testing.md +++ b/v2/testing.md @@ -1254,11 +1254,11 @@ import re ## Snapshot tests -In *snapshot testing*, you compare the entire synthesized CloudFormation template against a previously stored master\. Unlike fine\-grained assertions, snapshot testing isn't useful in catching regressions\. This is because snapshot testing applies to the entire template, and things besides code changes can cause small \(or not\-so\-small\) differences in synthesis results\. +In *snapshot testing*, you compare the entire synthesized CloudFormation template against a previously stored baseline \(often called a "master"\) template\. Unlike fine\-grained assertions, snapshot testing isn't useful in catching regressions\. This is because snapshot testing applies to the entire template, and things besides code changes can cause small \(or not\-so\-small\) differences in synthesis results\. These changes may not even affect your deployment, but they will still cause a snapshot test to fail\. -For example, you might update a CDK construct to incorporate a new best practice, which can cause changes to the synthesized resources or how they're organized\. Alternatively, you might update the CDK Toolkit to report additional metadata\. Changes to context values can also affect the synthesized template\. +For example, you might update a CDK construct to incorporate a new best practice, which can cause changes to the synthesized resources or how they're organized\. Alternatively, you might update the CDK Toolkit to a version that reports additional metadata\. Changes to context values can also affect the synthesized template\. -Snapshot tests can be of great help in refactoring, though, as long as you hold constant all other factors that might affect the synthesized template\. You will know immediately if a change you made has unintentionally changed the template\. If the change is intentional, simply accept a new master and proceed\. +Snapshot tests can be of great help in refactoring, though, as long as you hold constant all other factors that might affect the synthesized template\. You will know immediately if a change you made has unintentionally changed the template\. If the change is intentional, simply accept the new template as the baseline\. For example, if we have this `DeadLetterQueue` construct: From 2bb722f27d6bcffd67dd124ac9cbad66169d9e35 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 15:51:19 +0000 Subject: [PATCH 637/655] use DockerImageAsset that we just showed how to create in Fargate example --- v2/assets.md | 58 +++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 41 insertions(+), 17 deletions(-) diff --git a/v2/assets.md b/v2/assets.md index 51635955..7fcbea10 100644 --- a/v2/assets.md +++ b/v2/assets.md @@ -28,7 +28,7 @@ These are Docker images that the AWS CDK uploads to Amazon ECR\. These asset types are explained in the following sections\. -### Amazon S3 assets +## Amazon S3 assets You can define local files and directories as assets, and the AWS CDK packages and uploads them to Amazon S3 through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets-readme.html) module\. @@ -132,7 +132,7 @@ var fileAsset = new Asset(this, "SampleSingleFileAsset", new AssetProps In most cases, you don't need to directly use the APIs in the `aws-s3-assets` module\. Modules that support assets, such as `aws-lambda`, have convenience methods so that you can use assets\. For Lambda functions, the [fromAsset\(\)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Code.html#static-fromwbrassetpath-options) static method enables you to specify a directory or a \.zip file in the local file system\. -#### Lambda function example +### Lambda function example A common use case is creating Lambda functions with the handler code as an Amazon S3 asset\. @@ -273,7 +273,7 @@ The `Function` method uses assets to bundle the contents of the directory and us **Tip** Java `.jar` files are ZIP files with a different extension\. These are uploaded as\-is to Amazon S3, but when deployed as a Lambda function, the files they contain are extracted, which you might not want\. To avoid this, place the `.jar` file in a directory and specify that directory as the asset\. -#### Deploy\-time attributes example +### Deploy\-time attributes example Amazon S3 asset types also expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. @@ -414,7 +414,7 @@ new Function(this, "myLambdaFunction", new FunctionProps ------ -#### Permissions +### Permissions If you use Amazon S3 assets directly through the [aws\-s3\-assets](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets-readme.html) module, IAM roles, users, or groups, and you need to read assets in runtime, then grant those assets IAM permissions through the [asset\.grantRead](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets.Asset.html#grantwbrreadgrantee) method\. @@ -511,7 +511,7 @@ asset.GrantRead(group); ------ -### Docker image assets +## Docker image assets The AWS CDK supports bundling local Docker images as assets through the [aws\-ecr\-assets](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr_assets-readme.html) module\. @@ -573,7 +573,7 @@ using Amazon.CDK.AWS.ECR.Assets; var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps { - Directory = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "my-image")) + Directory = Path.Combine(Directory.GetCurrentDirectory(), "my-image") }); ``` @@ -581,7 +581,7 @@ var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps The `my-image` directory must include a Dockerfile\. The AWS CDK CLI builds a Docker image from `my-image`, pushes it to an Amazon ECR repository, and specifies the name of the repository as an AWS CloudFormation parameter to your stack\. Docker image asset types expose [deploy\-time attributes](resources.md#resources_attributes) that can be referenced in AWS CDK libraries and apps\. The AWS CDK CLI command cdk synth displays asset properties as AWS CloudFormation parameters\. -#### Amazon ECS task definition example +### Amazon ECS task definition example A common use case is to create an Amazon ECS [TaskDefinition](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.TaskDefinition.html) to run Docker containers\. The following example specifies the location of a Docker image asset that the AWS CDK builds locally and pushes to Amazon ECR\. @@ -590,6 +590,7 @@ A common use case is to create an Amazon ECS [TaskDefinition](https://docs.aws.a ``` import * as ecs from 'aws-cdk-lib/aws-ecs'; +import * as ecr_assets from 'aws-cdk-lib/aws-ecr-assets'; import * as path from 'path'; const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { @@ -597,8 +598,12 @@ const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { cpu: 512 }); +const asset = new ecr_assets.DockerImageAsset(this, 'MyBuildImage', { + directory: path.join(__dirname, 'my-image') +}); + taskDefinition.addContainer("my-other-container", { - image: ecs.ContainerImage.fromAsset(path.join(__dirname, "..", "demo-image")) + image: ecs.ContainerImage.fromDockerImageAsset(asset) }); ``` @@ -607,6 +612,7 @@ taskDefinition.addContainer("my-other-container", { ``` const ecs = require('aws-cdk-lib/aws-ecs'); +const ecr_assets = require('aws-cdk-lib/aws-ecr-assets'); const path = require('path'); const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { @@ -614,8 +620,12 @@ const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { cpu: 512 }); +const asset = new ecr_assets.DockerImageAsset(this, 'MyBuildImage', { + directory: path.join(__dirname, 'my-image') +}); + taskDefinition.addContainer("my-other-container", { - image: ecs.ContainerImage.fromAsset(path.join(__dirname, "..", "demo-image")) + image: ecs.ContainerImage.fromDockerImageAsset(asset) }); ``` @@ -624,6 +634,7 @@ taskDefinition.addContainer("my-other-container", { ``` import aws_cdk.aws_ecs as ecs +import aws_cdk.aws_ecr_assets as ecr_assets import os.path dirname = os.path.dirname(__file__) @@ -632,9 +643,11 @@ task_definition = ecs.FargateTaskDefinition(self, "TaskDef", memory_limit_mib=1024, cpu=512) +asset = ecr_assets.DockerImageAsset(self, 'MyBuildImage', + directory=os.path.join(dirname, 'my-image')) + task_definition.add_container("my-other-container", - image=ecs.ContainerImage.from_asset( - os.path.join(dirname, "..", "demo-image"))) + image=ecs.ContainerImage.from_docker_image_asset(asset)) ``` ------ @@ -647,15 +660,20 @@ import software.amazon.awscdk.services.ecs.FargateTaskDefinition; import software.amazon.awscdk.services.ecs.ContainerDefinitionOptions; import software.amazon.awscdk.services.ecs.ContainerImage; +import software.amazon.awscdk.services.ecr.assets.DockerImageAsset; + File startDir = new File(System.getProperty("user.dir")); FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create( this, "TaskDef").memoryLimitMiB(1024).cpu(512).build(); +DockerImageAsset asset = DockerImageAsset.Builder.create(this, "MyBuildImage") + .directory(new File(startDir, "my-image").toString()).build(); + taskDefinition.addContainer("my-other-container", ContainerDefinitionOptions.builder() - .image(ContainerImage.fromAsset(new File(startDir, - "demo-image").toString())).build()); + .image(ContainerImage.fromDockerImageAsset(asset)) + .build(); ``` ------ @@ -664,6 +682,7 @@ taskDefinition.addContainer("my-other-container", ``` using System.IO; using Amazon.CDK.AWS.ECS; +using Amazon.CDK.AWS.Ecr.Assets; var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps { @@ -671,15 +690,20 @@ var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskD Cpu = 512 }); +var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps +{ + Directory = Path.Combine(Directory.GetCurrentDirectory(), "my-image") +}); + taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions { - Image = ContainerImage.FromAsset(Path.Combine(Directory.GetCurrentDirectory(), "demo-image"); + Image = ContainerImage.FromDockerImageAsset(asset) }); ``` ------ -#### Deploy\-time attributes example +### Deploy\-time attributes example The following example shows how to use the deploy\-time attributes `repository` and `imageUri` to create an Amazon ECS task definition with the AWS Fargate launch type\. Note that the Amazon ECR repo lookup requires the image's tag, not its URI, so we snip it from the end of the asset's URI\. @@ -803,7 +827,7 @@ taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions ------ -#### Build arguments example +### Build arguments example You can provide customized build arguments for the Docker build step through the `buildArgs` \(Python: `build_args`\) property option when the AWS CDK CLI builds the image during deployment\. @@ -866,7 +890,7 @@ var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps ------ -#### Permissions +### Permissions If you use a module that supports Docker image assets, such as [aws\-ecs](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs-readme.html), the AWS CDK manages permissions for you when you use assets directly or through [ContainerImage\.fromEcrRepository](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ContainerImage.html#static-fromwbrecrwbrrepositoryrepository-tag) \(Python: `from_ecr_repository`\)\. If you use Docker image assets directly, make sure that the consuming principal has permissions to pull the image\. From 9cf194112a805ed18947235a40315cb084c72a32 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 15:52:41 +0000 Subject: [PATCH 638/655] remove explicit list of feature flags (hard to keep updated) since we already have a link to canonical list on GitHub --- v2/featureflags.md | 41 ++--------------------------------------- 1 file changed, 2 insertions(+), 39 deletions(-) diff --git a/v2/featureflags.md b/v2/featureflags.md index 6a9f4af5..a8e1ef4e 100644 --- a/v2/featureflags.md +++ b/v2/featureflags.md @@ -4,48 +4,11 @@ The AWS CDK uses *feature flags* to enable potentially breaking behaviors in a r Feature flags are disabled by default\. Existing projects that do not specify the flag will continue to work as before with later AWS CDK releases\. New projects created using cdk init include flags enabling all features available in the release that created the project\. Edit `cdk.json` to disable any flags for which you prefer the earlier behavior\. You can also add flags to enable new behaviors after upgrading the AWS CDK\. -See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. A list of all current feature flags can be found on the AWS CDK GitHub repository in [https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/cx-api/FEATURE_FLAGS.md](https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/cx-api/FEATURE_FLAGS.md)\. - -## Enabling features with flags - -The following feature flags may be set to `true` to enable the described behavior\. - -`@aws-cdk/core:checkSecretUsage` -Makes it impossible to use Secrets Manager values in unsafe locations\. - -`@aws-cdk/aws-lambda:recognizeLayerVersion` -Verify that updating a layer associated with a Lambda function creates a new version of the function\. - -`@aws-cdk/core:target-partitions` -Verify that Amazon EC2 Systems Manager service principals are generated correctly\. - -`@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver` -Enables logging in service extensions containers by default\. - -`@aws-cdk/aws-ec2:uniqueImdsv2TemplateName` -Causes [https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.InstanceRequireImdsv2Aspect.html](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.InstanceRequireImdsv2Aspect.html) to verify that the generated name is unique\. - -`@aws-cdk/aws-iam:minimizePolicies` -Minimize the creation of IAM policies when possible\. - -`@aws-cdk/aws-sns-subscriptions:restrictSqsDecryption` -In an Amazon SQS queue subscribed to an Amazon SNS topic, restrict decryption permissions to only the topic instead of all of Amazon SNS\. - -`@aws-cdk/aws-s3:createDefaultLoggingPolicy` -When using an S3 bucket with a service that will automatically create a bucket policy at deployment, have the AWS CDK configure the necessary policy\. - -`@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName` -Make sure cross\-account key alias is unique in pipelines\. - -`@aws-cdk/core:validateSnapshotRemovalPolicy` -The AWS CDK fails at synthesis time if the `SNAPSHOT` removal policy is not supported for a given resource\. - -`@aws-cdk/aws-ecs:arnFormatIncludesClusterName` -Use the new ARN format when importing an Amazon EC2 or Fargate cluster\. +A list of all current feature flags can be found on the AWS CDK GitHub repository in [https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/cx-api/FEATURE_FLAGS.md](https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/cx-api/FEATURE_FLAGS.md)\. See the `CHANGELOG` in a given release for a description of any new feature flags added in that release\. ## Reverting to v1 behavior -In CDK v2, the defaults for a set of feature flags have been changed with respect to v1\. You can set these back to `false` to revert to specific AWS CDK v1 behavior\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. +In CDK v2, the defaults for some feature flags have been changed with respect to v1\. You can set these back to `false` to revert to specific AWS CDK v1 behavior\. Use the `cdk diff` command to inspect the changes to your synthesized template to see if any of these flags are needed\. `@aws-cdk/core:newStyleStackSynthesis` Use the new stack synthesis method, which assumes bootstrap resources with well\-known names\. Requires [modern bootstrapping](bootstrapping.md), but in turn allows CI/CD via [CDK Pipelines](cdk_pipeline.md) and cross\-account deployments out of the box\. From 90c76444565e152c250f78e67d4a936b6135b6cf Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 16:51:23 +0000 Subject: [PATCH 639/655] remove example interfaces that don't actually exist --- v2/work-with.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/work-with.md b/v2/work-with.md index 542db749..7a20282b 100644 --- a/v2/work-with.md +++ b/v2/work-with.md @@ -115,7 +115,7 @@ The AWS CDK supports using resources defined outside CDK applications using meth When instantiating resources in your CDK app, then, you should always use concrete classes such as `Bucket`\. When specifying the type of an argument you are accepting in one of your own constructs, use the interface type such as `IBucket` if you are prepared to deal with external resources \(that is, you won't need to change them\)\. If you require a CDK\-defined construct, specify the most general type you can use\. -Some interfaces are minimum versions of properties or options bundles \(shown in the AWS CDK API Reference as Structs\) that are associated with specific constructs\. For example, `IBucketProps` is the smallest set of properties required to instantiate a bucket\. Such interfaces can be useful when subclassing constructs to accept arguments that you'll pass on to your parent class\. If you require one or more additional properties, you'll want to implement or derive from this interface, or from a more specific type such as `BucketProps`\. +Some interfaces are minimum versions of properties or options bundles associated with specific classes, rather than constructs\. Such interfaces can be useful when subclassing to accept arguments that you'll pass on to your parent class\. If you require one or more additional properties, you'll want to implement or derive from this interface, or from a more specific type\. **Note** Some programming languages supported by the AWS CDK don't have an interface feature\. In these languages, interfaces are just ordinary classes\. You can identify them by their names, which follow the pattern of an initial "I" followed by the name of some other construct \(e\.g\. `IBucket`\)\. The same rules apply\. \ No newline at end of file From e36961b15a8b6468b3d8bdfec726c37c864c7901 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 16:51:35 +0000 Subject: [PATCH 640/655] clarify where publishing rules are assumed from --- v2/bootstrapping.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index bb2cf023..6272ab64 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -350,11 +350,11 @@ new DefaultStackSynthesizer({ deployRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}', deployRoleExternalId: '', - // ARN of the role used for file asset publishing (assumed from the deploy role) + // ARN of the role used for file asset publishing (assumed from the CLI role) fileAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}', fileAssetPublishingExternalId: '', - // ARN of the role used for Docker asset publishing (assumed from the deploy role) + // ARN of the role used for Docker asset publishing (assumed from the CLI role) imageAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}', imageAssetPublishingExternalId: '', @@ -390,11 +390,11 @@ new DefaultStackSynthesizer({ deployRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}', deployRoleExternalId: '', - // ARN of the role used for file asset publishing (assumed from the deploy role) + // ARN of the role used for file asset publishing (assumed from the CLI role) fileAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}', fileAssetPublishingExternalId: '', - // ARN of the role used for Docker asset publishing (assumed from the deploy role) + // ARN of the role used for Docker asset publishing (assumed from the CLI role) imageAssetPublishingRoleArn: 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}', imageAssetPublishingExternalId: '', @@ -429,11 +429,11 @@ DefaultStackSynthesizer( deploy_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}", deploy_role_external_id="", - # ARN of the role used for file asset publishing (assumed from the deploy role) + # ARN of the role used for file asset publishing (assumed from the CLI role) file_asset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", file_asset_publishing_external_id="", - # ARN of the role used for Docker asset publishing (assumed from the deploy role) + # ARN of the role used for Docker asset publishing (assumed from the CLI role) image_asset_publishing_role_arn="arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}", image_asset_publishing_external_id="", @@ -468,11 +468,11 @@ DefaultStackSynthesizer.Builder.create() .deployRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}") .deployRoleExternalId("") - // ARN of the role used for file asset publishing (assumed from the deploy role) + // ARN of the role used for file asset publishing (assumed from the CLI role) .fileAssetPublishingRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}") .fileAssetPublishingExternalId("") - // ARN of the role used for Docker asset publishing (assumed from the deploy role) + // ARN of the role used for Docker asset publishing (assumed from the CLI role) .imageAssetPublishingRoleArn("arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}") .imageAssetPublishingExternalId("") @@ -507,11 +507,11 @@ new DefaultStackSynthesizer(new DefaultStackSynthesizerProps DeployRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-deploy-role-${AWS::AccountId}-${AWS::Region}", DeployRoleExternalId = "", - // ARN of the role used for file asset publishing (assumed from the deploy role) + // ARN of the role used for file asset publishing (assumed from the CLI role) FileAssetPublishingRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-file-publishing-role-${AWS::AccountId}-${AWS::Region}", FileAssetPublishingExternalId = "", - // ARN of the role used for Docker asset publishing (assumed from the deploy role) + // ARN of the role used for Docker asset publishing (assumed from the CLI role) ImageAssetPublishingRoleArn = "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-${Qualifier}-image-publishing-role-${AWS::AccountId}-${AWS::Region}", ImageAssetPublishingExternalId = "", From 8b4fd8c3a4b0305b3ba6acfcbb1df20531299246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Herv=C3=A9=20Guillon?= <33336471+hrvg@users.noreply.github.com> Date: Fri, 25 Nov 2022 09:12:57 -0800 Subject: [PATCH 641/655] fix: Add Construct import in python code for Create CDK Pipeline page (#428) * fix: Add Construct import in python code for Create CDK Pipeline page At the moment Construct is undefined when defining the cdk.Stack. This commit imports Construct from constructs. * fix: Fix Python code when validation tests are from inputs in Create CDK Pipeline page Python code when tests come from inputs is a copy from previous block. --- v2/cdk_pipeline.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index bc549588..1e97ef5b 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -269,6 +269,7 @@ In `my-pipeline/my-pipeline-stack.py` \(may vary if your project folder isn't na ``` import aws_cdk as cdk from aws_cdk.pipelines import CodePipeline, CodePipelineSource, ShellStep +from constructs import Construct class MyPipelineStack(cdk.Stack): @@ -1202,7 +1203,7 @@ stage = pipeline.add_stage(MyApplicationStage(self, "test", env=cdk.Environment(account="111111111111", region="eu-west-1"))) stage.add_post(ShellStep("validate", input=source, - commands=["curl -Ssf https://my.webservice.com/"], + commands=["sh ./tests/validate.sh"], )) ``` From fd744890775b17f4dc7b66983a47e2ad06ac9a48 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 17:25:50 +0000 Subject: [PATCH 642/655] update command line for validation test --- v2/cdk_pipeline.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index 1e97ef5b..dcf7334f 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -268,8 +268,8 @@ In `my-pipeline/my-pipeline-stack.py` \(may vary if your project folder isn't na ``` import aws_cdk as cdk +from constructs import Constuct from aws_cdk.pipelines import CodePipeline, CodePipelineSource, ShellStep -from constructs import Construct class MyPipelineStack(cdk.Stack): @@ -993,7 +993,7 @@ In its simplest form, adding validation actions looks like this: // stage was returned by pipeline.addStage stage.addPost(new ShellStep("validate", { - commands: ['curl -Ssf https://my.webservice.com/'], + commands: ['../tests/validate.sh'], })); ``` @@ -1004,7 +1004,7 @@ stage.addPost(new ShellStep("validate", { // stage was returned by pipeline.addStage stage.addPost(new ShellStep("validate", { - commands: ['curl -Ssf https://my.webservice.com/'], + commands: ['../tests/validate.sh'], })); ``` @@ -1015,7 +1015,7 @@ stage.addPost(new ShellStep("validate", { # stage was returned by pipeline.add_stage stage.add_post(ShellStep("validate", - commands=['curl -Ssf https://my.webservice.com/'] + commands=[''../tests/validate.sh''] )) ``` @@ -1026,7 +1026,7 @@ stage.add_post(ShellStep("validate", // stage was returned by pipeline.addStage stage.addPost(ShellStep.Builder.create("validate") - .commands(Arrays.asList("curl -Ssf https://my.webservice.com/")) + .commands(Arrays.asList("'../tests/validate.sh'")) .build()); ``` @@ -1038,7 +1038,7 @@ stage.addPost(ShellStep.Builder.create("validate") stage.AddPost(new ShellStep("validate", new ShellStepProps { - Commands = new string[] { "curl -Ssf https://my.webservice.com/" } + Commands = new string[] { "'../tests/validate.sh'" } })); ``` @@ -1157,7 +1157,7 @@ const stage = pipeline.addStage(new MyPipelineAppStage(this, 'test', { stage.addPost(new ShellStep('validate', { input: source, - commands: ['sh ./tests/validate.sh'] + commands: ['sh ../tests/validate.sh'] })); ``` @@ -1181,7 +1181,7 @@ const stage = pipeline.addStage(new MyPipelineAppStage(this, 'test', { stage.addPost(new ShellStep('validate', { input: source, - commands: ['sh ./tests/validate.sh'] + commands: ['sh ../tests/validate.sh'] })); ``` @@ -1203,7 +1203,7 @@ stage = pipeline.add_stage(MyApplicationStage(self, "test", env=cdk.Environment(account="111111111111", region="eu-west-1"))) stage.add_post(ShellStep("validate", input=source, - commands=["sh ./tests/validate.sh"], + commands=["sh ../tests/validate.sh"], )) ``` @@ -1231,7 +1231,7 @@ final StageDeployment stage = stage.addPost(ShellStep.Builder.create("validate") .input(source) - .commands(Arrays.asList("sh ./tests/validate.sh")) + .commands(Arrays.asList("sh ../tests/validate.sh")) .build()); ``` @@ -1262,7 +1262,7 @@ var stage = pipeline.AddStage(new MyPipelineAppStage(this, "test", new StageProp stage.AddPost(new ShellStep("validate", new ShellStepProps { Input = source, - Commands = new string[] { "sh ./tests/validate.sh" } + Commands = new string[] { "sh ../tests/validate.sh" } })); ``` From bbfc0d2fe4856ad765a5233340a320d203d2f886 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sylwester=20K=C4=85kol?= <39565249+s-kakol@users.noreply.github.com> Date: Fri, 25 Nov 2022 18:28:34 +0100 Subject: [PATCH 643/655] Remove duplicate code example (#429) --- v2/hello_world.md | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/v2/hello_world.md b/v2/hello_world.md index 14e8bcc7..26b5bdd4 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -486,20 +486,6 @@ Update `hello-cdk.go`\. }) ``` ------- -#### [ C\# ] - -Update `src/HelloCdk/HelloCdkStack.cs`\. - -``` -new Bucket(this, "MyFirstBucket", new BucketProps -{ - Versioned = true, - RemovalPolicy = RemovalPolicy.DESTROY, - AutoDeleteObjects = true -}); -``` - ------ Here, we haven't written any code that, in itself, changes our Amazon S3 bucket\. Instead, our code defines the desired state of the bucket\. The AWS CDK synthesizes that state to a new AWS CloudFormation template\. Then, it deploys a changeset that makes only the changes necessary to reach that state\. From 04e93252d4de85cdd20d4ef5b2f6f72183fee53a Mon Sep 17 00:00:00 2001 From: Fredrik Johansen Date: Fri, 25 Nov 2022 18:36:00 +0100 Subject: [PATCH 644/655] Updated import cdk statement (#427) --- v2/getting_started.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/v2/getting_started.md b/v2/getting_started.md index 21340b3a..4461d040 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -33,7 +33,7 @@ The actual package name of the main CDK package varies by language\. | Install | `npm install aws-cdk-lib` | | --- |--- | -| Import | `import 'aws-cdk-lib' as cdk;` | +| Import | `import * as cdk from 'aws-cdk-lib';` | | --- |--- | ------ @@ -335,4 +335,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Abstractions and escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? From 5f85c837bee0c2c2918aa4169f33f493fc5a4475 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 17:46:18 +0000 Subject: [PATCH 645/655] use same stack name for all examples --- v2/testing.md | 92 +++++++++++++++++++++++++-------------------------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/v2/testing.md b/v2/testing.md index eb1a434a..06abe244 100644 --- a/v2/testing.md +++ b/v2/testing.md @@ -150,12 +150,12 @@ import * as lambda from "aws-cdk-lib/aws-lambda"; import * as sfn from "aws-cdk-lib/aws-stepfunctions"; import { Construct } from "constructs"; -export interface ProcessorStackProps extends cdk.StackProps { +export interface StateMachineStackProps extends cdk.StackProps { readonly topics: sns.Topic[]; } -export class ProcessorStack extends cdk.Stack { - constructor(scope: Construct, id: string, props: ProcessorStackProps) { +export class StateMachineStack extends cdk.Stack { + constructor(scope: Construct, id: string, props: StateMachineStackProps) { super(scope, id, props); // In the future this state machine will do some work... @@ -194,7 +194,7 @@ const sns_subscriptions = require("aws-cdk-lib/aws-sns-subscriptions"); const lambda = require("aws-cdk-lib/aws-lambda"); const sfn = require("aws-cdk-lib/aws-stepfunctions"); -class ProcessorStack extends cdk.Stack { +class StateMachineStack extends cdk.Stack { constructor(scope, id, props) { super(scope, id, props); @@ -221,7 +221,7 @@ class ProcessorStack extends cdk.Stack { } } -module.exports = { ProcessorStack } +module.exports = { StateMachineStack } ``` ------ @@ -238,7 +238,7 @@ import aws_cdk.aws_sns_subscriptions as sns_subscriptions import aws_cdk.aws_stepfunctions as sfn import aws_cdk as cdk -class ProcessorStack(cdk.Stack): +class StateMachineStack(cdk.Stack): def __init__( self, scope: cdk.Construct, @@ -293,12 +293,12 @@ import software.amazon.awscdk.services.stepfunctions.StateMachine; import java.util.Collections; import java.util.List; -public class ProcessorStack extends Stack { - public ProcessorStack(final Construct scope, final String id, final List topics) { +public class StateMachineStack extends Stack { + public StateMachineStack(final Construct scope, final String id, final List topics) { this(scope, id, null, topics); } - public ProcessorStack(final Construct scope, final String id, final StackProps props, final List topics) { + public StateMachineStack(final Construct scope, final String id, final StackProps props, final List topics) { super(scope, id, props); // In the future this state machine will do some work... @@ -536,7 +536,7 @@ dotnet test src The first step for testing a stack with fine\-grained assertions is to synthesize the stack, because we're writing assertions against the generated AWS CloudFormation template\. -Our `ProcessorStack` requires that we pass it the Amazon SNS topic to be forwarded to the state machine\. So in our test, we'll create a separate stack to contain the topic\. +Our `StateMachineStackStack` requires that we pass it the Amazon SNS topic to be forwarded to the state machine\. So in our test, we'll create a separate stack to contain the topic\. Ordinarily, when writing a CDK app, you can subclass `Stack` and instantiate the Amazon SNS topic in the stack's constructor\. In our test, we instantiate `Stack` directly, then pass this stack as the `Topic`'s scope, attaching it to the stack\. This is functionally equivalent and less verbose\. It also helps make stacks that are used only in tests "look different" from the stacks that you intend to deploy\. @@ -547,28 +547,28 @@ Ordinarily, when writing a CDK app, you can subclass `Stack` and instantiate the import { Capture, Match, Template } from "aws-cdk-lib/assertions"; import * as cdk from "aws-cdk-lib"; import * as sns from "aws-cdk-lib/aws-sns"; -import { ProcessorStack } from "../lib/processor-stack"; +import { StateMachineStack } from "../lib/state-machine-stack"; -describe("ProcessorStack", () => { +describe("StateMachineStack", () => { test("synthesizes the way we expect", () => { const app = new cdk.App(); - // Since the ProcessorStack consumes resources from a separate stack + // Since the StateMachineStack consumes resources from a separate stack // (cross-stack references), we create a stack for our SNS topics to live - // in here. These topics can then be passed to the ProcessorStack later, + // in here. These topics can then be passed to the StateMachineStack later, // creating a cross-stack reference. const topicsStack = new cdk.Stack(app, "TopicsStack"); // Create the topic the stack we're testing will reference. const topics = [new sns.Topic(topicsStack, "Topic1", {})]; - // Create the ProcessorStack. - const processorStack = new ProcessorStack(app, "ProcessorStack", { + // Create the StateMachineStack. + const stateMachineStack = new StateMachineStack(app, "StateMachineStack", { topics: topics, // Cross-stack reference }); // Prepare the stack for assertions. - const template = Template.fromStack(processorStack); + const template = Template.fromStack(stateMachineStack); } @@ -581,28 +581,28 @@ describe("ProcessorStack", () => { const { Capture, Match, Template } = require("aws-cdk-lib/assertions"); const cdk = require("aws-cdk-lib"); const sns = require("aws-cdk-lib/aws-sns"); -const { ProcessorStack } = require("../lib/processor-stack"); +const { StateMachineStack } = require("../lib/state-machine-stack"); -describe("ProcessorStack", () => { +describe("StateMachineStack", () => { test("synthesizes the way we expect", () => { const app = new cdk.App(); - // Since the ProcessorStack consumes resources from a separate stack + // Since the StateMachineStack consumes resources from a separate stack // (cross-stack references), we create a stack for our SNS topics to live - // in here. These topics can then be passed to the ProcessorStack later, + // in here. These topics can then be passed to the StateMachineStack later, // creating a cross-stack reference. const topicsStack = new cdk.Stack(app, "TopicsStack"); // Create the topic the stack we're testing will reference. const topics = [new sns.Topic(topicsStack, "Topic1", {})]; - // Create the ProcessorStack. - const processorStack = new ProcessorStack(app, "ProcessorStack", { + // Create the StateMachineStack. + const StateMachineStack = new StateMachineStack(app, "StateMachineStack", { topics: topics, // Cross-stack reference }); // Prepare the stack for assertions. - const template = Template.fromStack(processorStack); + const template = Template.fromStack(stateMachineStack); ``` ------ @@ -613,27 +613,27 @@ from aws_cdk import aws_sns as sns import aws_cdk as cdk from aws_cdk.assertions import Template -from app.processor_stack import ProcessorStack +from app.state_machine_stack import StateMachineStack def test_synthesizes_properly(): app = cdk.App() - # Since the ProcessorStack consumes resources from a separate stack + # Since the StateMachineStack consumes resources from a separate stack # (cross-stack references), we create a stack for our SNS topics to live - # in here. These topics can then be passed to the ProcessorStack later, + # in here. These topics can then be passed to the StateMachineStack later, # creating a cross-stack reference. topics_stack = cdk.Stack(app, "TopicsStack") # Create the topic the stack we're testing will reference. topics = [sns.Topic(topics_stack, "Topic1")] - # Create the ProcessorStack. - processor_stack = ProcessorStack( - app, "ProcessorStack", topics=topics # Cross-stack reference + # Create the StateMachineStack. + state_machine_stack = StateMachineStack( + app, "StateMachineStack", topics=topics # Cross-stack reference ) # Prepare the stack for assertions. - template = Template.from_stack(processor_stack) + template = Template.from_stack(state_machine_stack) ``` ------ @@ -654,28 +654,28 @@ import java.util.*; import static org.assertj.core.api.Assertions.assertThat; -public class ProcessorStackTest { +public class StateMachineStackTest { @Test public void testSynthesizesProperly() { final App app = new App(); - // Since the ProcessorStack consumes resources from a separate stack (cross-stack references), we create a stack - // for our SNS topics to live in here. These topics can then be passed to the ProcessorStack later, creating a + // Since the StateMachineStack consumes resources from a separate stack (cross-stack references), we create a stack + // for our SNS topics to live in here. These topics can then be passed to the StateMachineStack later, creating a // cross-stack reference. final Stack topicsStack = new Stack(app, "TopicsStack"); // Create the topic the stack we're testing will reference. final List topics = Collections.singletonList(Topic.Builder.create(topicsStack, "Topic1").build()); - // Create the ProcessorStack. - final ProcessorStack processorStack = new ProcessorStack( + // Create the StateMachineStack. + final StateMachineStack stateMachineStack = new StateMachineStack( app, - "ProcessorStack", + "StateMachineStack", topics // Cross-stack reference ); // Prepare the stack for assertions. - final Template template = Template.fromStack(processorStack) + final Template template = Template.fromStack(stateMachineStack) ``` ------ @@ -695,29 +695,29 @@ using StringDict = System.Collections.Generic.Dictionary; namespace TestProject1 { [TestClass] - public class ProcessorStackTest + public class StateMachineStackTest { [TestMethod] public void TestMethod1() { var app = new App(); - // Since the ProcessorStack consumes resources from a separate stack (cross-stack references), we create a stack - // for our SNS topics to live in here. These topics can then be passed to the ProcessorStack later, creating a + // Since the StateMachineStack consumes resources from a separate stack (cross-stack references), we create a stack + // for our SNS topics to live in here. These topics can then be passed to the StateMachineStack later, creating a // cross-stack reference. var topicsStack = new Stack(app, "TopicsStack"); // Create the topic the stack we're testing will reference. var topics = new Topic[] { new Topic(topicsStack, "Topic1") }; - // Create the ProcessorStack. - var processorStack = new StateMachineStack(app, "ProcessorStack", new StateMachineStackProps + // Create the StateMachineStack. + var StateMachineStack = new StateMachineStack(app, "StateMachineStack", new StateMachineStackProps { Topics = topics }); // Prepare the stack for assertions. - var template = Template.FromStack(processorStack); + var template = Template.FromStack(stateMachineStack); // test will go here } @@ -793,7 +793,7 @@ Now we can assert that the Lambda function and the Amazon SNS subscription were ``` // Prepare the stack for assertions. - var template = Template.FromStack(processorStack); + var template = Template.FromStack(stateMachineStack); // Assert it creates the function with the correct properties... template.HasResourceProperties("AWS::Lambda::Function", new StringDict { @@ -1473,7 +1473,7 @@ using StringDict = System.Collections.Generic.Dictionary; namespace TestProject1 { [TestClass] - public class ProcessorStackTest + public class StateMachineStackTest [TestClass] public class DeadLetterQueueTest From ca9bf8c538d2d62e3b2f3b62cb86ad164b8f7767 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 17:46:28 +0000 Subject: [PATCH 646/655] churn --- v2/getting_started.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/getting_started.md b/v2/getting_started.md index 4461d040..23ef67d0 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -335,4 +335,4 @@ Where do you go now that you've dipped your toes in the AWS CDK? + Dig deeper into concepts like [Environments](environments.md), [Assets](assets.md), [Bootstrapping](bootstrapping.md), [Permissions](permissions.md), [Runtime context](context.md), [Parameters](parameters.md), and [Abstractions and escape hatches](cfn_layer.md)\. + Explore [Examples](https://github.com/aws-samples/aws-cdk-examples) of using the AWS CDK\. -The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? +The AWS CDK is an open\-source project\. Want to [contribute](https://github.com/aws/aws-cdk)? \ No newline at end of file From bab8ee94f7444ce1ac6c56bf552cd154467fecdd Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 18:00:55 +0000 Subject: [PATCH 647/655] add link to explanation of how unique identifiers are generated --- v2/identifiers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/identifiers.md b/v2/identifiers.md index 42e30350..5cc1f58e 100644 --- a/v2/identifiers.md +++ b/v2/identifiers.md @@ -274,7 +274,7 @@ string addr = myConstruct.Node.Addr; Unique IDs serve as the *logical identifiers* \(or *logical names*\) of resources in the generated AWS CloudFormation templates for constructs that represent AWS resources\. -For example, the Amazon S3 bucket in the previous example that is created within `Stack2` results in an `AWS::S3::Bucket` resource\. The resource's logical ID is `Stack2MyBucket4DD88B4F` in the resulting AWS CloudFormation template\. +For example, the Amazon S3 bucket in the previous example that is created within `Stack2` results in an `AWS::S3::Bucket` resource\. The resource's logical ID is `Stack2MyBucket4DD88B4F` in the resulting AWS CloudFormation template\. \(For details on how this identifier is generated, see [Unique IDs](#identifiers_unique_ids)\.\) ### Logical ID stability From 631d674ab1c7a2be6de637e234baace847037f18 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 19:02:45 +0000 Subject: [PATCH 648/655] remove reference to obsolete command line flag --- v2/bootstrapping.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/bootstrapping.md b/v2/bootstrapping.md index 6272ab64..5882f422 100644 --- a/v2/bootstrapping.md +++ b/v2/bootstrapping.md @@ -137,7 +137,7 @@ The following command line options, when used with CDK Toolkit's cdk bootstrap, ``` **Important** To avoid deployment failures, be sure the policies that you specify are sufficient for any deployments you will perform in the environment being bootstrapped\. -+ \-\-qualifier is a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid resource name clashes when you provision multiple bootstrap stacks in the same environment using \-\-toolkit\-stack\-name\. The default is `hnb659fds` \(this value has no significance\)\. ++ \-\-qualifier is a string that is added to the names of all resources in the bootstrap stack\. A qualifier lets you avoid resource name clashes when you provision multiple bootstrap stacks in the same environment\. The default is `hnb659fds` \(this value has no significance\)\. Changing the qualifier also requires that your CDK app pass the changed value to the stack synthesizer\. For more information, see [Stack synthesizers](#bootstrapping-synthesizers)\. + \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. From 8804ec022a7766344867e320f19993bea7a806f3 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 19:03:20 +0000 Subject: [PATCH 649/655] fix stack filename --- v2/cdk_pipeline.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/cdk_pipeline.md b/v2/cdk_pipeline.md index dcf7334f..35d3dfcf 100644 --- a/v2/cdk_pipeline.md +++ b/v2/cdk_pipeline.md @@ -614,7 +614,7 @@ class MyPipelineAppStage(cdk.Stage): lambdaStack = MyLambdaStack(self, "LambdaStack") ``` -Edit `my_pipeline/my_pipeline_stack.py` to add the stage to our pipeline\. +Edit `my_pipeline/my-pipeline-stack.py` to add the stage to our pipeline\. ``` import aws_cdk as cdk From c0ceffa291983aa7da19345fcd26ac5d5acf567d Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 19:04:01 +0000 Subject: [PATCH 650/655] fix command line option name --- v2/cli.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/cli.md b/v2/cli.md index df835d10..62c971a4 100644 --- a/v2/cli.md +++ b/v2/cli.md @@ -578,7 +578,7 @@ Default values for many CDK Toolkit command line flags can be stored in a projec | language | The language to be used for initializing new projects\. | \-\-language | | lookups | If false, no context lookups are permitted\. Synthesis will fail if any context lookups need to be performed\. | \-\-no\-lookups | | notices | If false, suppresses the display of messages about security vulnerabilities, regressions, and unsupported versions\. | \-\-no\-notices | -| output | The name of the directory into which the synthesized cloud assembly will be emitted \(default "cdk\.out"\)\. | \-\-outputs\-file | +| output | The name of the directory into which the synthesized cloud assembly will be emitted \(default "cdk\.out"\)\. | \-\-output | | outputsFile | The file to which AWS CloudFormation outputs from deployed stacks will be written \(in JSON format\)\. | \-\-outputs\-file | | pathMetadata | If false, CDK path metadata is not added to synthesized templates\. | \-\-no\-path\-metadata | | plugin | JSON array specifying the package names or local paths of packages that extend the CDK | \-\-plugin | From ef97d90103d033a9c3e78ed0f7777e6c8cf1cb11 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 19:05:03 +0000 Subject: [PATCH 651/655] add CDK IAM policy, remove reference to specific Node version --- v2/getting_started.md | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/v2/getting_started.md b/v2/getting_started.md index 23ef67d0..dde955ea 100644 --- a/v2/getting_started.md +++ b/v2/getting_started.md @@ -22,7 +22,7 @@ Constructs \(and also stacks and apps\) are represented as classes \(types\) in The AWS CDK includes the CDK Toolkit \(also called the CLI\), a command line tool for working with your AWS CDK apps and stacks\. Among other functions, the Toolkit provides the ability to do the following: + Convert one or more AWS CDK stacks to AWS CloudFormation templates and related assets \(a process called *synthesis*\) -+ Deploy your stacks to an AWS account ++ Deploy your stacks to an AWS account and Region The AWS CDK includes a library of AWS constructs called the AWS Construct Library, organized into various modules\. The library contains constructs for each AWS service\. The main CDK package is called `aws-cdk-lib`, and it contains the majority of the AWS Construct Library\. It also contains base classes like `Stack` and `App` that are used in most CDK applications\. @@ -200,7 +200,7 @@ TypeScript was the first language supported by the AWS CDK, and much AWS CDK exa Here's what you need to install to use the AWS CDK\. -All AWS CDK developers, even those working in Python, Java, or C\#, need [Node\.js](https://nodejs.org/en/download/) 10\.13\.0 or later\. All supported languages use the same backend, which runs on Node\.js\. We recommend a version in [active long\-term support](https://nodejs.org/en/about/releases/), which, at this writing, is the latest 16\.x release\. Your organization may have a different recommendation\. +All AWS CDK developers, even those working in Python, Java, or C\#, need [Node\.js](https://nodejs.org/en/download/) 10\.13\.0 or later\. All supported languages use the same backend, which runs on Node\.js\. We recommend a version in [active long\-term support](https://nodejs.org/en/about/releases/)\. Your organization may have a different recommendation\. **Important** Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. @@ -235,7 +235,24 @@ The AWS CDK natively supports AWS IAM Identity Center \(successor to AWS Single Alternatively, you can set the environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` to appropriate values\. **Important** -We strongly recommend against using your AWS root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. Best practices are to change this account's access key regularly and to use a least\-privileges role \(specifying `--role-arn`\) when deploying\. +Using your AWS root account is the fastest way to get started with the AWS CDK\. Once you've worked through a few tutorials, however, we strongly recommend against using your root account for day\-to\-day tasks\. Instead, create a user in IAM and use its credentials with the CDK\. Best practices are to change this account's access key regularly and to use a least\-privileges role\. The AWS CDK includes roles that your account should have permission to assume, for example using the policy here\. + +``` +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "sts:AssumeRole" + ], + "Resource": [ + "arn:aws:iam::*:role/cdk-*" + ] + } + ] +} +``` Other prerequisites depend on the language in which you develop AWS CDK applications and are as follows\. From 641edf3963fd53253c86dce9aca9db1a9f3be347 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 19:05:33 +0000 Subject: [PATCH 652/655] remove reference to specific Node version --- v2/work-with.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/work-with.md b/v2/work-with.md index 7a20282b..65037ac9 100644 --- a/v2/work-with.md +++ b/v2/work-with.md @@ -18,7 +18,7 @@ If you have the [AWS CLI](https://aws.amazon.com/cli/) installed, the simplest w aws configure ``` -All AWS CDK applications require Node\.js 10\.13 or later, even if you work in Python, Java, C\#, or Go\. You may download a compatible version at [nodejs\.org](https://nodejs.org/)\. We recommend the [active LTS version](https://nodejs.org/en/about/releases/) \(at this writing, the latest 16\.x release\)\. Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. +All AWS CDK applications require Node\.js 10\.13 or later, even if you work in Python, Java, C\#, or Go\. You may download a compatible version at [nodejs\.org](https://nodejs.org/)\. We recommend the [active LTS version](https://nodejs.org/en/about/releases/)\. Node\.js versions 13\.0\.0 through 13\.6\.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies\. After installing Node\.js, install the AWS CDK Toolkit \(the `cdk` command\): From 80dbcdcf9bc076a6c9a6bfbe1cd5144ef3d7af73 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Fri, 25 Nov 2022 23:05:19 +0000 Subject: [PATCH 653/655] add and update Go examples --- v2/constructs.md | 193 +++++++++++++++++++++++++++++++++++++++++++++- v2/hello_world.md | 2 +- v2/home.md | 2 +- 3 files changed, 193 insertions(+), 4 deletions(-) diff --git a/v2/constructs.md b/v2/constructs.md index b49c9bcb..8eec8e44 100644 --- a/v2/constructs.md +++ b/v2/constructs.md @@ -163,6 +163,25 @@ namespace HelloCdkApp } ``` +------ +#### [ Go ] + +``` +func NewHelloCdkStack(scope constructs.Construct, id string, props *HelloCdkStackProps) awscdk.Stack { + var sprops awscdk.StackProps + if props != nil { + sprops = props.StackProps + } + stack := awscdk.NewStack(scope, &id, &sprops) + + awss3.NewBucket(stack, jsii.String("MyFirstBucket"), &awss3.BucketProps{ + Versioned: jsii.Bool(true), + }) + + return stack +} +``` + ------ As you can see, you need a scope within which to define your bucket\. Resources eventually need to be deployed as part of an AWS CloudFormation stack into an *AWS [environment](environments.md)*\. The environment covers a specific AWS account and AWS Region\. AWS constructs, such as `s3.Bucket`, must be defined within the scope of a [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html)\. @@ -288,8 +307,17 @@ var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps ``` ------ +#### [ Go ] -In Python, Java, and C\#, L1 construct properties that aren't simple Booleans, strings, numbers, or containers are represented by types defined as inner classes of the L1 construct\. For example, the optional property `corsConfiguration` of a `CfnBucket` requires a wrapper of type `CfnBucket.CorsConfigurationProperty`\. Here we are defining `corsConfiguration` on a `CfnBucket` instance\. +``` + awss3.NewCfnBucket(stack, jsii.String("MyBucket"), &awss3.CfnBucketProps{ + BucketName: jsii.String("MyBucket"), + }) +``` + +------ + +Construct properties that aren't simple Booleans, strings, numbers, or containers are handled differently in the supported languages\. ------ #### [ TypeScript ] @@ -324,6 +352,8 @@ const bucket = new s3.CfnBucket(this, "MyBucket", { ------ #### [ Python ] +In Python, these properties are represented by types defined as inner classes of the L1 construct\. For example, the optional property `cors_configuraiton` of a `CfnBucket` requires a wrapper of type `CfnBucket.CorsConfigurationProperty`\. Here we are defining `cors_onfiguration` on a `CfnBucket` instance\. + ``` bucket = CfnBucket(self, "MyBucket", bucket_name="MyBucket", cors_configuration=CfnBucket.CorsConfigurationProperty( @@ -338,6 +368,8 @@ bucket = CfnBucket(self, "MyBucket", bucket_name="MyBucket", ------ #### [ Java ] +In Java, these properties are represented by types defined as inner classes of the L1 construct\. For example, the optional property `corsConfiguration` of a `CfnBucket` requires a wrapper of type `CfnBucket.CorsConfigurationProperty`\. Here we are defining `corsConfiguration` on a `CfnBucket` instance\. + ``` CfnBucket bucket = CfnBucket.Builder.create(this, "MyBucket") .bucketName("MyBucket") @@ -353,6 +385,8 @@ CfnBucket bucket = CfnBucket.Builder.create(this, "MyBucket") ------ #### [ C\# ] +In C\#, these properties are represented by types defined as inner classes of the L1 construct\. For example, the optional property `CorsConfiguration` of a `CfnBucket` requires a wrapper of type `CfnBucket.CorsConfigurationProperty`\. Here we are defining `CorsConfiguration` on a `CfnBucket` instance\. + ``` var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps { @@ -370,10 +404,29 @@ var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps }); ``` +------ +#### [ Go ] + +In Go, these types are named using the name of the L1 construct, an underscore, and the property name\. For example, the optional property `CorsConfiguration` of a `CfnBucket` requires a wrapper of type `CfnBucket_CorsConfigurationProperty`\. Here we are defining `CorsConfiguration` on a `CfnBucket` instance\. + +``` + awss3.NewCfnBucket(stack, jsii.String("MyBucket"), &awss3.CfnBucketProps{ + BucketName: jsii.String("MyBucket"), + CorsConfiguration: &awss3.CfnBucket_CorsConfigurationProperty{ + CorsRules: []awss3.CorsRule{ + awss3.CorsRule{ + AllowedOrigins: jsii.Strings("*"), + AllowedMethods: &[]awss3.HttpMethods{"GET"}, + }, + }, + }, + }) +``` + ------ **Important** -You can't use L2 property types with L1 constructs, or vice versa\. When working with L1 constructs, always use the types defined inside the L1 construct you're using\. Do not use types from other L1 constructs \(some may have the same name, but they are not the same type\)\. +You can't use L2 property types with L1 constructs, or vice versa\. When working with L1 constructs, always use the types defined for the L1 construct you're using\. Do not use types from other L1 constructs \(some may have the same name, but they are not the same type\)\. Some of our language\-specific API references currently have errors in the paths to L1 property types, or don't document these classes at all\. We hope to fix this soon\. In the meantime, remember that such types are always inner classes of the L1 construct they are used with\. ## Using L2 constructs @@ -447,6 +500,21 @@ new Bucket(this, "MyFirstBucket", new BucketProps }); ``` +------ +#### [ Go ] + +``` +import ( + "github.com/aws/aws-cdk-go/awscdk/v2/awss3" + "github.com/aws/jsii-runtime-go" +) + +// stack is HelloCdkStack +awss3.NewBucket(stack, jsii.String("MyFirstBucket"), &awss3.BucketProps{ + Versioned: jsii.Bool(true), + })> +``` + ------ The [AWS Construct Library](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) includes constructs that represent many AWS resources\. @@ -506,6 +574,16 @@ new Bucket(this, "MyEncryptedBucket", new BucketProps }); ``` +------ +#### [ Go ] + +``` + awss3.NewBucket(stack, jsii.String("MyEncryptedBucket"), &awss3.BucketProps{ + Encryption: awss3.BucketEncryption_KMS, + WebsiteIndexDocument: jsii.String("index.html"), + }) +``` + ------ AWS constructs are designed around the concept of "sensible defaults\." Most constructs have a minimal required configuration, enabling you to quickly get started while also providing full control over the configuration when you need it\. @@ -563,6 +641,15 @@ var dataScience = new Group(this, "data-science"); rawData.GrantRead(dataScience); ``` +------ +#### [ Go ] + +``` + rawData := awss3.NewBucket(stack, jsii.String("raw-data"), nil) + dataScience := awsiam.NewGroup(stack, jsii.String("data-science"), nil) + rawData.GrantRead(dataScience, nil) +``` + ------ Another common pattern is for AWS constructs to set one of the resource's attributes from data supplied elsewhere\. Attributes can include Amazon Resource Names \(ARNs\), names, or URLs\. @@ -644,6 +731,20 @@ var createJobLambda = new Function(this, "create-job", new FunctionProps }); ``` +------ +#### [ Go ] + +``` + createJobLambda := awslambda.NewFunction(stack, jsii.String("create-job"), &awslambda.FunctionProps{ + Runtime: awslambda.Runtime_NODEJS_14_X(), + Handler: jsii.String("index.handler"), + Code: awslambda.Code_FromAsset(jsii.String(".\\create-job-lambda-code"), nil), + Environment: &map[string]*string{ + "QUEUE_URL": jsii.String(*jobsQueue.QueueUrl()), + }, + }) +``` + ------ For information about the most common API patterns in the AWS Construct Library, see [Resources](resources.md)\. @@ -759,6 +860,34 @@ public class NotifyingBucket : Construct } ``` +------ +#### [ Go ] + +``` +type NotifyingBucketProps struct { + awss3.BucketProps + Prefix *string +} + +func NewNotifyingBucket(scope constructs.Construct, id *string, props *NotifyingBucketProps) awss3.Bucket { + var bucket awss3.Bucket + if props == nil { + bucket = awss3.NewBucket(scope, jsii.String(*id+"Bucket"), nil) + } else { + bucket = awss3.NewBucket(scope, jsii.String(*id+"Bucket"), &props.BucketProps) + } + topic := awssns.NewTopic(scope, jsii.String(*id+"Topic"), nil) + if props == nil { + bucket.AddObjectCreatedNotification(awss3notifications.NewSnsDestination(topic)) + } else { + bucket.AddObjectCreatedNotification(awss3notifications.NewSnsDestination(topic), &awss3.NotificationKeyFilter{ + Prefix: props.Prefix, + }) + } + return bucket +} +``` + ------ **Note** @@ -801,6 +930,13 @@ new NotifyingBucket(this, "MyNotifyingBucket"); new NotifyingBucket(this, "MyNotifyingBucket"); ``` +------ +#### [ Go ] + +``` +NewNotifyingBucket(stack, jsii.String("MyNotifyingBucket"), nil) +``` + ------ Or you could use `props` \(in Java, an additional parameter\) to specify the path prefix to filter on, for example: @@ -843,6 +979,15 @@ new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketProps }); ``` +------ +#### [ Go ] + +``` +NewNotifyingBucket(stack, jsii.String("MyNotifyingBucket"), &NotifyingBucketProps{ + Prefix: jsii.String("images/"), +}) +``` + ------ Typically, you would also want to expose some properties or methods on your constructs\. It's not very useful to have a topic hidden behind your construct, because users of your construct aren't able to subscribe to it\. Adding a `topic` property lets consumers access the inner topic, as shown in the following example: @@ -946,6 +1091,39 @@ public class NotifyingBucket : Construct } ``` +------ +#### [ Go ] + +To do this in Go, we'll need a little extra plumbing\. Our original `NewNotifyingBucket` function returned an `awss3.Bucket`\. We'll need to extend `Bucket` to include a `topic` member by creating a `NotifyingBucket` struct\. Our function will then return this type\. + +``` +type NotifyingBucket struct { + awss3.Bucket + topic awssns.Topic +} + +func NewNotifyingBucket(scope constructs.Construct, id *string, props *NotifyingBucketProps) NotifyingBucket { + var bucket awss3.Bucket + if props == nil { + bucket = awss3.NewBucket(scope, jsii.String(*id+"Bucket"), nil) + } else { + bucket = awss3.NewBucket(scope, jsii.String(*id+"Bucket"), &props.BucketProps) + } + topic := awssns.NewTopic(scope, jsii.String(*id+"Topic"), nil) + if props == nil { + bucket.AddObjectCreatedNotification(awss3notifications.NewSnsDestination(topic)) + } else { + bucket.AddObjectCreatedNotification(awss3notifications.NewSnsDestination(topic), &awss3.NotificationKeyFilter{ + Prefix: props.Prefix, + }) + } + var nbucket NotifyingBucket + nbucket.Bucket = bucket + nbucket.topic = topic + return nbucket +} +``` + ------ Now, consumers can subscribe to the topic, for example: @@ -997,6 +1175,17 @@ var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketP images.topic.AddSubscription(new SqsSubscription(queue)); ``` +------ +#### [ Go ] + +``` + queue := awssqs.NewQueue(stack, jsii.String("NewImagesQueue"), nil) + images := NewNotifyingBucket(stack, jsii.String("MyNotifyingBucket"), &NotifyingBucketProps{ + Prefix: jsii.String("/images"), + }) + images.topic.AddSubscription(awssnssubscriptions.NewSqsSubscription(queue, nil)) +``` + ------ ## The construct tree diff --git a/v2/hello_world.md b/v2/hello_world.md index 26b5bdd4..3ac8ecaa 100644 --- a/v2/hello_world.md +++ b/v2/hello_world.md @@ -306,7 +306,7 @@ func NewHelloCdkStack(scope constructs.Construct, id string, props *HelloCdkStac if props != nil { sprops = props.StackProps } - stack := awscdk.NewStack(scope, &id, sprops) + stack := awscdk.NewStack(scope, &id, &sprops) awss3.NewBucket(stack, jsii.String("MyFirstBucket"), &awss3.BucketProps{ Versioned: jsii.Bool(true), diff --git a/v2/home.md b/v2/home.md index 9364957c..92301a9e 100644 --- a/v2/home.md +++ b/v2/home.md @@ -186,7 +186,7 @@ func NewMyEcsConstructStack(scope constructs.Construct, id string, props *MyEcsC sprops = props.StackProps } - stack := awscdk.NewStack(scope, &id, sprops) + stack := awscdk.NewStack(scope, &id, &sprops) vpc := awsec2.NewVpc(stack, jsii.String("MyVpc"), &awsec2.VpcProps{ MaxAzs: jsii.Number(3), // Default is all AZs in region From 3dbae859397682dcc8c16ed64cb8b3bb6e54d2aa Mon Sep 17 00:00:00 2001 From: mkandyli Date: Thu, 8 Dec 2022 16:04:52 +0000 Subject: [PATCH 654/655] feat: added golang example --- v2/ecs_example.md | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/v2/ecs_example.md b/v2/ecs_example.md index a3fb5945..c22274fd 100644 --- a/v2/ecs_example.md +++ b/v2/ecs_example.md @@ -87,6 +87,17 @@ You may now open `src/MyEcsConstruct.sln` in Visual Studio\. ------ +#### [ Go ] + +``` +mkdir MyEcsConstruct +cd MyEcsConstruct +cdk init --language go +go get +``` + +------ + Run the app and confirm that it creates an empty stack\. ``` @@ -159,6 +170,18 @@ using Amazon.CDK.AWS.ECS.Patterns; ------ +#### [ Go ] + +File: `my_ecs_construct/my_ecs_construct.go` + +``` +"github.com/aws/aws-cdk-go/awscdk/v2/awsec2" +"github.com/aws/aws-cdk-go/awscdk/v2/awsecs" +"github.com/aws/aws-cdk-go/awscdk/v2/awsecspatterns" +``` + +------ + Replace the comment at the end of the constructor with the following code\. ------ @@ -280,6 +303,31 @@ Replace the comment at the end of the constructor with the following code\. ); ``` +------ +#### [ Go ] + +``` +vpc := awsec2.NewVpc(stack, jsii.String("MyVpc"), &awsec2.VpcProps{ + MaxAzs: jsii.Number(3), // Default is all AZs in region +}) + +cluster := awsecs.NewCluster(stack, jsii.String("EcsCluster"), &awsecs.ClusterProps{ + Vpc: vpc, +}) + +awsecspatterns.NewApplicationLoadBalancedFargateService(stack, jsii.String("MyFargateService"), &awsecspatterns.ApplicationLoadBalancedFargateServiceProps{ + Cluster: cluster, // Required + Cpu: jsii.Number(512), // Default is 256 + DesiredCount: jsii.Number(6), // Default is 1 + TaskImageOptions: &awsecspatterns.ApplicationLoadBalancedTaskImageOptions{ + Image: awsecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample"), &awsecs.RepositoryImageProps{}), + }, + MemoryLimitMiB: jsii.Number(2048), // Default is 512 + PublicLoadBalancer: jsii.Bool(true), // Default is true +}) + +``` + ------ Save it and make sure it runs and creates a stack\. From 293f2116337a007fdf53f0c4d95167f551f422a5 Mon Sep 17 00:00:00 2001 From: mkandyli Date: Thu, 8 Dec 2022 16:10:18 +0000 Subject: [PATCH 655/655] corected the path for go construct --- v2/ecs_example.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/ecs_example.md b/v2/ecs_example.md index c22274fd..f1001147 100644 --- a/v2/ecs_example.md +++ b/v2/ecs_example.md @@ -172,7 +172,7 @@ using Amazon.CDK.AWS.ECS.Patterns; #### [ Go ] -File: `my_ecs_construct/my_ecs_construct.go` +File: `my_ecs_construct.go` ``` "github.com/aws/aws-cdk-go/awscdk/v2/awsec2"