From f8086457ef28a9956c7fd7d13afa85d221bed2e0 Mon Sep 17 00:00:00 2001 From: James Siri Date: Thu, 13 Dec 2018 11:53:02 -0800 Subject: [PATCH 001/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] [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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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/298] 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 f1639f39b165764b23fcab68fcc433fd41396178 Mon Sep 17 00:00:00 2001 From: Jerry Kindall Date: Mon, 21 Sep 2020 17:43:22 +0000 Subject: [PATCH 296/298] change default branch --- README.md | 31 +- doc_source/about_examples.md | 5 - doc_source/apps.md | 319 --- doc_source/aspects.md | 214 -- doc_source/assets.md | 883 -------- doc_source/bootstrapping.md | 539 ----- doc_source/cdk_pipeline.md | 1773 ----------------- doc_source/cfn_layer.md | 418 ---- doc_source/cli.md | 703 ------- doc_source/codepipeline_example.md | 1281 ------------ doc_source/compliance-validation.md | 16 - doc_source/constructs.md | 977 --------- doc_source/context.md | 308 --- doc_source/core_concepts.md | 5 - doc_source/disaster-recovery-resiliency.md | 11 - doc_source/doc-history.md | 28 - doc_source/ecs_example.md | 369 ---- doc_source/environments.md | 389 ---- doc_source/examples.md | 6 - doc_source/featureflags.md | 20 - doc_source/get_cfn_param.md | 5 - doc_source/get_context_var.md | 104 - doc_source/get_env_var.md | 68 - doc_source/get_secrets_manager_value.md | 112 -- doc_source/get_ssm_value.md | 170 -- doc_source/getting_started.md | 216 -- doc_source/hello_world.md | 536 ----- doc_source/home.md | 254 --- doc_source/how_to_set_cw_alarm.md | 239 --- doc_source/how_tos.md | 3 - doc_source/identifiers.md | 240 --- doc_source/index.md | 73 - doc_source/infrastructure-security.md | 3 - doc_source/multiple_languages.md | 335 ---- doc_source/my_ecs_construct-stack.yaml | 516 ----- doc_source/parameters.md | 208 -- doc_source/permissions.md | 490 ----- doc_source/pgp-keys.md | 95 - doc_source/reference.md | 66 - doc_source/resources.md | 1264 ------------ doc_source/sam.md | 74 - doc_source/security-iam.md | 11 - doc_source/security.md | 15 - doc_source/serverless_example.md | 877 -------- .../stack_how_to_create_multiple_stacks.md | 635 ------ doc_source/stacks.md | 373 ---- doc_source/tagging.md | 420 ---- doc_source/testing.md | 352 ---- doc_source/tokens.md | 427 ---- doc_source/tools.md | 8 - doc_source/troubleshooting.md | 351 ---- doc_source/use_cfn_template.md | 128 -- doc_source/videos.md | 16 - doc_source/vscode.md | 3 - doc_source/work-with-cdk-csharp.md | 185 -- doc_source/work-with-cdk-java.md | 147 -- doc_source/work-with-cdk-javascript.md | 262 --- doc_source/work-with-cdk-python.md | 214 -- doc_source/work-with-cdk-typescript.md | 133 -- doc_source/work-with.md | 37 - 60 files changed, 3 insertions(+), 17957 deletions(-) delete mode 100644 doc_source/about_examples.md delete mode 100644 doc_source/apps.md delete mode 100644 doc_source/aspects.md delete mode 100644 doc_source/assets.md delete mode 100644 doc_source/bootstrapping.md delete mode 100644 doc_source/cdk_pipeline.md delete mode 100644 doc_source/cfn_layer.md delete mode 100644 doc_source/cli.md delete mode 100644 doc_source/codepipeline_example.md delete mode 100644 doc_source/compliance-validation.md delete mode 100644 doc_source/constructs.md delete mode 100644 doc_source/context.md delete mode 100644 doc_source/core_concepts.md delete mode 100644 doc_source/disaster-recovery-resiliency.md delete mode 100644 doc_source/doc-history.md delete mode 100644 doc_source/ecs_example.md delete mode 100644 doc_source/environments.md delete mode 100644 doc_source/examples.md delete mode 100644 doc_source/featureflags.md delete mode 100644 doc_source/get_cfn_param.md delete mode 100644 doc_source/get_context_var.md delete mode 100644 doc_source/get_env_var.md delete mode 100644 doc_source/get_secrets_manager_value.md delete mode 100644 doc_source/get_ssm_value.md delete mode 100644 doc_source/getting_started.md delete mode 100644 doc_source/hello_world.md delete mode 100644 doc_source/home.md delete mode 100644 doc_source/how_to_set_cw_alarm.md delete mode 100644 doc_source/how_tos.md delete mode 100644 doc_source/identifiers.md delete mode 100644 doc_source/index.md delete mode 100644 doc_source/infrastructure-security.md delete mode 100644 doc_source/multiple_languages.md delete mode 100644 doc_source/my_ecs_construct-stack.yaml delete mode 100644 doc_source/parameters.md delete mode 100644 doc_source/permissions.md delete mode 100644 doc_source/pgp-keys.md delete mode 100644 doc_source/reference.md delete mode 100644 doc_source/resources.md delete mode 100644 doc_source/sam.md delete mode 100644 doc_source/security-iam.md delete mode 100644 doc_source/security.md delete mode 100644 doc_source/serverless_example.md delete mode 100644 doc_source/stack_how_to_create_multiple_stacks.md delete mode 100644 doc_source/stacks.md delete mode 100644 doc_source/tagging.md delete mode 100644 doc_source/testing.md delete mode 100644 doc_source/tokens.md delete mode 100644 doc_source/tools.md delete mode 100644 doc_source/troubleshooting.md delete mode 100644 doc_source/use_cfn_template.md delete mode 100644 doc_source/videos.md delete mode 100644 doc_source/vscode.md delete mode 100644 doc_source/work-with-cdk-csharp.md delete mode 100644 doc_source/work-with-cdk-java.md delete mode 100644 doc_source/work-with-cdk-javascript.md delete mode 100644 doc_source/work-with-cdk-python.md delete mode 100644 doc_source/work-with-cdk-typescript.md delete mode 100644 doc_source/work-with.md diff --git a/README.md b/README.md index 652e671c..e067e972 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,4 @@ -# Welcome to the AWS CDK Developer Guide +# Default branch -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. - -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. - -> :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. - -## 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 repo](https://github.com/aws-samples/aws-cdk-intro-workshop). - -## 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. You can help us prioritize our work by +1'ing issues that are important to you. - -## 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. +The default branch for this repo has changed to "main." If you have cloned the previous default branch, +please update yur local repo to use the "main" branch. diff --git a/doc_source/about_examples.md b/doc_source/about_examples.md deleted file mode 100644 index ccf624e9..00000000 --- a/doc_source/about_examples.md +++ /dev/null @@ -1,5 +0,0 @@ -# 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 diff --git a/doc_source/apps.md b/doc_source/apps.md deleted file mode 100644 index a7df08fc..00000000 --- a/doc_source/apps.md +++ /dev/null @@ -1,319 +0,0 @@ -# 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\. - -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/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(); -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.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\. - -![\[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` \(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 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 \-\-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" -} -``` - ------- -#### [ JavaScript ] - -``` -{ - "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\. - -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/aspects.md b/doc_source/aspects.md deleted file mode 100644 index 080bb27e..00000000 --- a/doc_source/aspects.md +++ /dev/null @@ -1,214 +0,0 @@ -# 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) \(Python: `apply_aspect`\) with a new aspect, as shown in the following example\. - ------- -#### [ TypeScript ] - -``` -myConstruct.node.applyAspect(new SomeAspect(/*...*/)); -``` - ------- -#### [ JavaScript ] - -``` -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\. - ------- -#### [ 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 `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\. - -## 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\. - ------- -#### [ 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')) { - 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'); - } - } - } -} - -// Apply to the stack -stack.node.applyAspect(new BucketVersioningChecker()); -``` - ------- -#### [ 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 deleted file mode 100644 index dc6eb5bd..00000000 --- a/doc_source/assets.md +++ /dev/null @@ -1,883 +0,0 @@ -# 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 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 - -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/latest/docs/aws-s3-assets-readme.html) module\. - -The following example defines a local directory asset and a file asset\. - ------- -#### [ TypeScript ] - -``` -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') -}); -``` - ------- -#### [ JavaScript ] - -``` -const { Asset } = require('@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 ] - -``` -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 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/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) { - 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/core'); -const lambda = require('@aws-cdk/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.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 - -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\. - ------- -#### [ TypeScript ] - -``` -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 - } -}); -``` - ------- -#### [ JavaScript ] - -``` -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") -}); - -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 - -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 * 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/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 -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(self, "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'; - -const asset = new DockerImageAsset(this, 'MyBuildImage', { - directory: path.join(__dirname, 'my-image') -}); -``` - ------- -#### [ JavaScript ] - -``` -const { DockerImageAsset } = require('@aws-cdk/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/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 * 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")) -}); -``` - ------- -#### [ JavaScript ] - -``` -const ecs = require('@aws-cdk/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/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.split(":").pop()) -}); -``` - ------- -#### [ JavaScript ] - -``` -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") -}); - -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.fromEcrRepository( - 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/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 \(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 - -**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/doc_source/bootstrapping.md b/doc_source/bootstrapping.md deleted file mode 100644 index 11f7666d..00000000 --- a/doc_source/bootstrapping.md +++ /dev/null @@ -1,539 +0,0 @@ -# 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)\. -+ A 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 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\. 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\. - -``` -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\. - -[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) - -\* *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\. - ------- -#### [ 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 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 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\. - -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 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\. -+ \-\-tags adds one or more AWS CloudFormation tags to the bootstrap stack\. -+ \-\-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\. 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 - -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 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 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\. - - -| 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 - -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 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 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\. - ------- -#### [ 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 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 - -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 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 - -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 deleted file mode 100644 index cf4fc9a2..00000000 --- a/doc_source/cdk_pipeline.md +++ /dev/null @@ -1,1773 +0,0 @@ -# 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\. - -**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\. - -\-\-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 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 ] - -``` -export 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, 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 ] - -``` -export 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 -``` - ------- - -**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 `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 -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`\. - -**Mac OS X/Linux** - -``` -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=Environment(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/cfn_layer.md b/doc_source/cfn_layer.md deleted file mode 100644 index e97e37b6..00000000 --- a/doc_source/cfn_layer.md +++ /dev/null @@ -1,418 +0,0 @@ -# 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 AWS CloudFormation resource -const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; - -// Change its properties -cfnBucket.analyticsConfiguration = [ - { - id: 'Config', - // ... - } -]; -``` - ------- -#### [ JavaScript ] - -``` -// Get the AWS CloudFormation resource -const cfnBucket = bucket.node.defaultChild; - -// Change its properties -cfnBucket.analyticsConfiguration = [ - { - id: 'Config' - // ... - } -]; -``` - ------- -#### [ Python ] - -``` -# Get the AWS CloudFormation resource -cfn_bucket = bucket.node.default_child - -# Change its properties -cfn_bucket.analytics_configuration = [ - { - "id": "Config", - # ... - } -] -``` - ------- -#### [ Java ] - -``` -// Get the AWS CloudFormation resource -CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); - -cfnBucket.setAnalyticsConfigurations( - Arrays.asList(new HashMap() {{ - put("Id", "Config"); - // ... - }})); -``` - ------- -#### [ C\# ] - -``` -// Get the AWS 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 AWS 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'); - -// addPropertyOverride is a convenience function, which implies the -// path starts with "Properties." -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 ] - -``` -# 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") -``` - ------- -#### [ 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\# ] - -``` -// 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\. - -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/doc_source/cli.md b/doc_source/cli.md deleted file mode 100644 index 7eaa2f7c..00000000 --- a/doc_source/cli.md +++ /dev/null @@ -1,703 +0,0 @@ -# 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 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 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)\. - -## 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 -+ AWS Render Farm Deployment Kit 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,aws-rfdk=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` \(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` - - ``` - [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 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\. - -## 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 - -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 - -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 -``` - -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 -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\. - -## 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 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\. - -### 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 `--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 -``` - -## 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] - - --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] - - --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: - - --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 [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), overrides tags - from Cloud Assembly [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] - - --progress Display mode for stack activity events. - [string] [choices: "bar", "events"] -``` - -### `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] -``` \ 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 a8de53ee..00000000 --- a/doc_source/codepipeline_example.md +++ /dev/null @@ -1,1281 +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`, 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** -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\. - ------- -#### [ TypeScript ] - - ``` - 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 ] - - ``` - 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 ] - - A couple of commands differ between Windows and Mac OS X or Linux\. - - **Mac OS X/Linux** - - ``` - 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 - 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 ] - - ``` - 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 - 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\# ] - - ``` - cd pipeline - cdk init --language csharp - ``` - - 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 - 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\. - ------- -#### [ Mac OS X/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, - }); - - 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 - }); - - 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_ - -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, - ) - - 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; - -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).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; - -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 - }); - - 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 * as s3 from '@aws-cdk/aws-s3'; -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_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], - }), - ], - }, - ], - }); - } -} -``` - ------- -#### [ 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_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] - }) - ] - } - ] - }); - } -} - -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_, aws_s3 as s3) - -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_2_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", - 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_2_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") - .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 = WindowsBuildImage.WINDOWS_BASE_2_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", - 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 diff --git a/doc_source/compliance-validation.md b/doc_source/compliance-validation.md deleted file mode 100644 index 67d4b7a1..00000000 --- a/doc_source/compliance-validation.md +++ /dev/null @@ -1,16 +0,0 @@ -# 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/constructs.md b/doc_source/constructs.md deleted file mode 100644 index 3f587574..00000000 --- a/doc_source/constructs.md +++ /dev/null @@ -1,977 +0,0 @@ -# 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\. - -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 - -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 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, 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\. - -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)\. - -## 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 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\. - -## 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\. - -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/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'; -import * as s3 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', { - versioned: true - }); - } -} - -const app = new App(); -new HelloCdkStack(app, "HelloCdkStack"); -``` - ------- -#### [ JavaScript ] - -``` -const { App , Stack } = require('@aws-cdk/core'); -const s3 = require('@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 ] - -``` -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; - -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/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) { - super(scope, id, props); - - //... - } -} -``` - ------- -#### [ JavaScript ] - -``` -class HelloCdkStack extends Stack { - constructor(scope, id, props) { - super(scope, id, props); - - //... - } -} -``` - ------- -#### [ 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(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 `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 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/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 ] - -``` -import * as s3 from '@aws-cdk/aws-s3'; - -// "this" is HelloCdkStack -new s3.Bucket(this, 'MyFirstBucket', { - versioned: true -}); -``` - ------- -#### [ JavaScript ] - -``` -const s3 = require('@aws-cdk/aws-s3'); - -// "this" is HelloCdkStack -new s3.Bucket(this, 'MyFirstBucket', { - versioned: true -}); -``` - ------- -#### [ 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/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 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/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); -``` - ------- -#### [ 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_10_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_10_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_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](resources.md)\. - -## 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/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; -} - -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(core.Construct): - - 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), - 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 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'); -``` - ------- -#### [ 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, props); - 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, props); - 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(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(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, 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, props) - { - 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)); -``` - ------- \ No newline at end of file diff --git a/doc_source/context.md b/doc_source/context.md deleted file mode 100644 index 51df8c97..00000000 --- a/doc_source/context.md +++ /dev/null @@ -1,308 +0,0 @@ -# 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\. - -## Construct context - -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 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\. - -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 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-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) -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 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 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\. - -## 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 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\. - -``` -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/core'; -import * as ec2 from '@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(), - }); - } -} -``` - ------- -#### [ JavaScript ] - -``` -const cdk = require('@aws-cdk/core'); -const ec2 = require('@aws-cdk/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.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(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.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: - -``` -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/doc_source/core_concepts.md b/doc_source/core_concepts.md deleted file mode 100644 index acecfa92..00000000 --- a/doc_source/core_concepts.md +++ /dev/null @@ -1,5 +0,0 @@ -# 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/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/disaster-recovery-resiliency.md b/doc_source/disaster-recovery-resiliency.md deleted file mode 100644 index c99d21f9..00000000 --- a/doc_source/disaster-recovery-resiliency.md +++ /dev/null @@ -1,11 +0,0 @@ -# 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/doc-history.md b/doc_source/doc-history.md deleted file mode 100644 index a9536a05..00000000 --- a/doc_source/doc-history.md +++ /dev/null @@ -1,28 +0,0 @@ -# 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 | -| --- |--- |--- | -| [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 | -| [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 | -| [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 | -| [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 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 | -| [General availability](#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 deleted file mode 100644 index 5846733a..00000000 --- a/doc_source/ecs_example.md +++ /dev/null @@ -1,369 +0,0 @@ -# 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/latest/docs/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 .env/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 -``` - -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 - Properties: - 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 - -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 -``` - ------- -#### [ JavaScript ] - -``` -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\. - -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/aws-ec2"; -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` - -``` -const ec2 = require("@aws-cdk/aws-ec2"); -const ecs = require("@aws-cdk/aws-ecs"); -const 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 - }); - - 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 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\. - -## 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 deleted file mode 100644 index 7c8e90c3..00000000 --- a/doc_source/environments.md +++ /dev/null @@ -1,389 +0,0 @@ -# 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 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`\)\. - -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\. - -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 = 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) -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=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\. 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=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`\. 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 ] - -``` -#!/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 "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 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 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\): - ------- -#### [ Mac OS X/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\. - ------- -#### [ Mac OS X/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/doc_source/examples.md b/doc_source/examples.md deleted file mode 100644 index 40557422..00000000 --- a/doc_source/examples.md +++ /dev/null @@ -1,6 +0,0 @@ -# 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 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 deleted file mode 100644 index aa34a875..00000000 --- a/doc_source/featureflags.md +++ /dev/null @@ -1,20 +0,0 @@ -# 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 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\. - -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/doc_source/get_cfn_param.md b/doc_source/get_cfn_param.md deleted file mode 100644 index 5f9582fb..00000000 --- a/doc_source/get_cfn_param.md +++ /dev/null @@ -1,5 +0,0 @@ -# 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 diff --git a/doc_source/get_context_var.md b/doc_source/get_context_var.md deleted file mode 100644 index 74cbd767..00000000 --- a/doc_source/get_context_var.md +++ /dev/null @@ -1,104 +0,0 @@ -# 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/doc_source/get_env_var.md b/doc_source/get_env_var.md deleted file mode 100644 index 77ee780a..00000000 --- a/doc_source/get_env_var.md +++ /dev/null @@ -1,68 +0,0 @@ -# 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 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 deleted file mode 100644 index 15a2a1b7..00000000 --- a/doc_source/get_secrets_manager_value.md +++ /dev/null @@ -1,112 +0,0 @@ -# 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\. - ------- -#### [ TypeScript ] - -``` -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: ... - }); -``` - ------- -#### [ JavaScript ] - -``` -const sm = require("@aws-cdk/aws-secretsmanager"); - -class SecretsManagerStack extends core.Stack { - constructor(scope, id, props) { - 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: ... - }); - } -} - -module.exports = { SecretsManagerStack } -``` - ------- -#### [ 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(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=.... - ) -``` - ------- -#### [ 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: - -``` -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/get_ssm_value.md b/doc_source/get_ssm_value.md deleted file mode 100644 index b79e7d75..00000000 --- a/doc_source/get_ssm_value.md +++ /dev/null @@ -1,170 +0,0 @@ -# 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/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 * 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 -``` - ------- -#### [ JavaScript ] - -``` -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 -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/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 * as ssm from '@aws-cdk/aws-ssm'; - -const stringValue = ssm.StringParameter.valueFromLookup(this, 'my-plain-parameter-name'); -``` - ------- -#### [ JavaScript ] - -``` -const ssm = require('@aws-cdk/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"); -``` - ------- - -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\. - -``` -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/doc_source/getting_started.md b/doc_source/getting_started.md deleted file mode 100644 index 98942b2f..00000000 --- a/doc_source/getting_started.md +++ /dev/null @@ -1,216 +0,0 @@ -# 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 five 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 a 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\. - -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\. - -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\. 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 `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 - -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: - ------- -#### [ TypeScript ] - -``` -const bucket = new s3.Bucket(this, 'MyBucket', { - bucketName: 'my-bucket', - versioned: true, - websiteRedirect: {host: 'aws.amazon.com'}}); -``` - ------- -#### [ JavaScript ] - -``` -const bucket = new s3.Bucket(this, 'MyBucket', { - bucketName: 'my-bucket', - versioned: true, - websiteRedirect: {host: 'aws.amazon.com'}}); -``` - ------- -#### [ Python ] - -``` -bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=true, - website_redirect=s3.WebsiteRedirect(host_name="aws.amazon.com")) -``` - ------- -#### [ Java ] - -``` -Bucket bucket = Bucket.Builder.create(self, "MyBucket") - .bucketName("my-bucket") - .versioned(true) - .websiteRedirect(new websiteRedirect.Builder() - .hostName("aws.amazon.com").build()) - .build(); -``` - ------- -#### [ C\# ] - -``` -var bucket = new Bucket(this, "MyBucket", new BucketProps { - BucketName = "my-bucket", - Versioned = true, - WebsiteRedirect = new WebsiteRedirect { - 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/latest/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) - -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 - -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\. - -**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: - -``` -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\. -+ 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 - ``` - -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\. - ------- -#### [ 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\# ] - -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 - -Visual Studio 2019 \(any edition\) 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 -``` - -## 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 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/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), [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/hello_world.md b/doc_source/hello_world.md deleted file mode 100644 index 2643ebd0..00000000 --- a/doc_source/hello_world.md +++ /dev/null @@ -1,536 +0,0 @@ -# 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\. - -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 -``` - -**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\. - -``` -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 -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\. - ------- - -**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 - -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 ] - -``` -npm run build -``` - ------- -#### [ JavaScript ] - -No build step is necessary\. - ------- -#### [ Python ] - -No build step is necessary\. - ------- -#### [ Java ] - -``` -mvn compile -q -``` - -**Note** -Or press Control\-B in Eclipse \(other Java IDEs may vary\) - ------- -#### [ C\# ] - -``` -dotnet build src -``` - -**Note** -Or press F6 in Visual Studio - ------- - -## 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 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 ] - -Add the following to the `` container of `pom.xml`\. - -``` - - software.amazon.awscdk - s3 - ${cdk.version} - -``` - -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\# ] - -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/docs/@aws-cdk_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/HelloCdkStack.java`: - -``` -package com.myorg; - -import software.amazon.awscdk.core.*; -import software.amazon.awscdk.services.s3.Bucket; - -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\# ] - -Update `HelloCdkStack.cs` to look like this\. - -``` -using Amazon.CDK; -using Amazon.CDK.AWS.S3; - -namespace HelloCdk -{ - 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 - }); - } - } -} -``` - ------- - -`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 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\.\) -+ 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 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\. - -``` -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.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](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\. - -## 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 `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 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 ] - -Update `hello_cdk/hello_cdk_stack.py` - -``` -bucket = s3.Bucket(self, - "MyFirstBucket", - versioned=True, - removal_policy=core.RemovalPolicy.DESTROY) -``` - ------- -#### [ Java ] - -Update `src/main/java/com/myorg/HelloCdkStack.java`\. - -``` -import software.amazon.awscdk.services.s3.BucketEncryption; -``` - -``` -Bucket.Builder.create(this, "MyFirstBucket") - .versioned(true) - .removalPolicy(RemovalPolicy.DESTROY) - .build(); -``` - ------- -#### [ C\# ] - -Update `HelloCdkStack.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 `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\. - -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... - 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 - -Stack ARN: -arn:aws:cloudformation:REGION:ACCOUNT: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 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\. - -## 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 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\. - -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 deleted file mode 100644 index 9baf542d..00000000 --- a/doc_source/home.md +++ /dev/null @@ -1,254 +0,0 @@ -# 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\. - -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 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)\. - -![\[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)\)\. - ------- -#### [ TypeScript ] - -``` -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 - }); - - 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 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 - }); - } -} - -module.exports = { MyEcsConstructStack } -``` - ------- -#### [ 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\# ] - -``` -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) - { - 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) -+ [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::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) - -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 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\. - -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\. - -**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 - -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 - -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/) -+ [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) -+ [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 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) - -## 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/doc_source/how_to_set_cw_alarm.md b/doc_source/how_to_set_cw_alarm.md deleted file mode 100644 index 0c2659f9..00000000 --- a/doc_source/how_to_set_cw_alarm.md +++ /dev/null @@ -1,239 +0,0 @@ -# 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\. - -## 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 [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 ] - -``` -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\. 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/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 ] - -``` -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/doc_source/how_tos.md b/doc_source/how_tos.md deleted file mode 100644 index 229bd4c7..00000000 --- a/doc_source/how_tos.md +++ /dev/null @@ -1,3 +0,0 @@ -# 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 deleted file mode 100644 index eca8b65b..00000000 --- a/doc_source/identifiers.md +++ /dev/null @@ -1,240 +0,0 @@ -# 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 co\-exist in the same app without any issues\. - ------- -#### [ TypeScript ] - -``` -import { App, Construct, Stack, StackProps } from '@aws-cdk/core'; -import * as s3 from '@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'); -``` - ------- -#### [ JavaScript ] - -``` -const { App , Stack } = require('@aws-cdk/core'); -const s3 = require('@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 ] - -``` -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 - -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\. 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_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 ] - -``` -const uid: string = myConstruct.node.uniqueId; -``` - ------- -#### [ JavaScript ] - -``` -const uid = 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\. - -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 deleted file mode 100644 index 4168e708..00000000 --- a/doc_source/index.md +++ /dev/null @@ -1,73 +0,0 @@ -# AWS Cloud Development Kit (AWS CDK) Developer Guide - ------ -*****Copyright © 2020 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** - ------ -Amazon's trademarks and trade dress may not be used in - connection with any product or service that is not Amazon's, - in any manner that is likely to cause confusion among customers, - or in any manner that disparages or discredits Amazon. All other - trademarks not owned by Amazon are the property of their respective - owners, who may or may not be affiliated with, connected to, or - sponsored by Amazon. - ------ -## Contents -+ [What is 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) -+ [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) -+ [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 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) - + [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/doc_source/infrastructure-security.md b/doc_source/infrastructure-security.md deleted file mode 100644 index e2052b67..00000000 --- a/doc_source/infrastructure-security.md +++ /dev/null @@ -1,3 +0,0 @@ -# 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 deleted file mode 100644 index 9fa456dd..00000000 --- a/doc_source/multiple_languages.md +++ /dev/null @@ -1,335 +0,0 @@ -# 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 module, or individual objects from a module\. - -``` -// Import entire module as s3 into current namespace -import * as s3 from '@aws-cdk/aws-s3'; - -// 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-s3'); - -// Now use s3 to access the S3 types -const bucket = s3.Bucket(...); - -// 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'; - -// Now use Bucket to instantiate an S3 bucket -const bucket = Bucket(...); -``` - ------- - ------- -#### [ Python ] - -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 - -# 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 - -# 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 for AWS CDK packages is `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 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/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 -import jsii - -@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\# ] - -``` -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/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/doc_source/parameters.md b/doc_source/parameters.md deleted file mode 100644 index 60b559bd..00000000 --- a/doc_source/parameters.md +++ /dev/null @@ -1,208 +0,0 @@ -# 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/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."}); -``` - ------- -#### [ 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/doc_source/permissions.md b/doc_source/permissions.md deleted file mode 100644 index ee5e0c69..00000000 --- a/doc_source/permissions.md +++ /dev/null @@ -1,490 +0,0 @@ -# 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/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_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)`\. - -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\. - ------- -#### [ 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/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 ] - -``` -import * as iam from '@aws-cdk/aws-iam'; - -const role = new iam.Role(this, 'Role', { - assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'), // required -}); -``` - ------- -#### [ JavaScript ] - -``` -const iam = require('@aws-cdk/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/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\. - ------- -#### [ 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/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 * 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: 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/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/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, - 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/doc_source/pgp-keys.md b/doc_source/pgp-keys.md deleted file mode 100644 index 333f8d9d..00000000 --- a/doc_source/pgp-keys.md +++ /dev/null @@ -1,95 +0,0 @@ -# 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/doc_source/reference.md b/doc_source/reference.md deleted file mode 100644 index a13cbf89..00000000 --- a/doc_source/reference.md +++ /dev/null @@ -1,66 +0,0 @@ -# API reference - -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 - -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 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 - -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. -``` - -**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 - -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 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 -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\. - -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\. - -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 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 | -| --- |--- | -| TypeScript | Stable | -| JavaScript | Stable | -| Python | Stable | -| Java | Stable | -| C\#/\.NET | Stable | \ No newline at end of file diff --git a/doc_source/resources.md b/doc_source/resources.md deleted file mode 100644 index 381d91fd..00000000 --- a/doc_source/resources.md +++ /dev/null @@ -1,1264 +0,0 @@ -# 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/latest/docs/@aws-cdk_aws-sqs.Queue.html) construct from the AWS Construct Library\. - ------- -#### [ TypeScript ] - -``` -import * as sqs from '@aws-cdk/aws-sqs'; - -new sqs.Queue(this, 'MyQueue', { - encryption: sqs.QueueEncryption.KMS_MANAGED -}); -``` - ------- -#### [ JavaScript ] - -``` -const sqs = require('@aws-cdk/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/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/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\# ] - -``` -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 = 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 - -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 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: core.PhysicalName.GENERATE_IF_NEEDED, -}); -``` - ------- -#### [ JavaScript ] - -``` -const bucket = new s3.Bucket(this, 'MyBucket', { - 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 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, 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 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.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', -}); -``` - ------- -#### [ 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 ] - -``` -# 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 ] - -``` -// 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" }); -``` - ------- - -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.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/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 - -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/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, - // ... -}); -``` - ------- -#### [ JavaScript ] - -``` -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'); - -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.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)\. - -## 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`\. - ------- -#### [ TypeScript ] - -``` -import * as asg from '@aws-cdk/aws-autoscaling'; -import * as ec2 from '@aws-cdk/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/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 })); - -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 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"); -``` - ------- - -## 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/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/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, 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\. - - -| 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\. 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`\. - ------- -#### [ 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 ] - -``` -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 } -``` - ------- -#### [ 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'); -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/sam.md b/doc_source/sam.md deleted file mode 100644 index ec64abf3..00000000 --- a/doc_source/sam.md +++ /dev/null @@ -1,74 +0,0 @@ -# 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)\. - -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/security-iam.md b/doc_source/security-iam.md deleted file mode 100644 index 55f220ba..00000000 --- a/doc_source/security-iam.md +++ /dev/null @@ -1,11 +0,0 @@ -# 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 deleted file mode 100644 index bf319928..00000000 --- a/doc_source/security.md +++ /dev/null @@ -1,15 +0,0 @@ -# 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/doc_source/serverless_example.md b/doc_source/serverless_example.md deleted file mode 100644 index 971acd50..00000000 --- a/doc_source/serverless_example.md +++ /dev/null @@ -1,877 +0,0 @@ -# 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\. -+ An Amazon API Gateway API to call the Lambda function\. -+ An Amazon S3 bucket that contains the Lambda function code\. - -This tutorial contains the following steps\. - -1. Creates a AWS CDK app - -1. Creates a Lambda function that gets a list of widgets with HTTP GET / - -1. Creates the service that calls the Lambda function - -1. Adds the service to the AWS CDK app - -1. Tests the app - -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 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 .env/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\. - ------- - -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 like the following, where *CDK\-VERSION* is the version of the AWS 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\. 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 - -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 -``` - ------- -#### [ JavaScript ] - -``` -npm install @aws-cdk/aws-apigateway @aws-cdk/aws-lambda @aws-cdk/aws-s3 -``` - ------- -#### [ 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 * 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 / - } -} -``` - ------- -#### [ JavaScript ] - -File: `lib/widget_service.js` - -``` -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"); - -class WidgetService extends core.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_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 / - } -} - -module.exports = { WidgetService } -``` - ------- -#### [ 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\. - -``` -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 -``` - -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` - -``` - // 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/doc_source/stack_how_to_create_multiple_stacks.md b/doc_source/stack_how_to_create_multiple_stacks.md deleted file mode 100644 index ca6661b2..00000000 --- a/doc_source/stack_how_to_create_multiple_stacks.md +++ /dev/null @@ -1,635 +0,0 @@ -# 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 ./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 -``` - ------- -#### [ JavaScript ] - -``` -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 * as cdk from '@aws-cdk/core'; -import * as s3 from '@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 - } -} -``` - ------- -#### [ 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/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 ] - -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; } - } - - - 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/core'; -import * as s3 from '@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); - - // 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}); - } - } -} -``` - ------- -#### [ JavaScript ] - -File: `lib/multistack-stack.js` - -``` -const cdk = require('@aws-cdk/core'); -const s3 = require('@aws-cdk/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 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}); - } - } -} - -module.exports = { MultistackStack } -``` - ------- -#### [ 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(self, "MyGroovyBucket", - encryption=s3.BucketEncryption.KMS_MANAGED, - removal_policy=core.RemovalPolicy.DESTROY) - else: - s3.Bucket(self, "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; - -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 -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 -}); -``` - ------- -#### [ JavaScript ] - -File: `bin/multistack.js` - -``` -#!/usr/bin/env node -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 -}); - -new MultistackStack(app, "MyEastCdkStack", { - env: {region: "us-east-1"}, - encryptBucket: true -}); -``` - ------- -#### [ 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=True) -``` - ------- -#### [ 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\. - -## 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 -``` - -The output should look similar to the following AWS CloudFormation template \(there might be slight differences\)\. - -``` -Resources: - MyGroovyBucketFD9882AC: - Type: AWS::S3::Bucket - Properties: - BucketEncryption: - ServerSideEncryptionConfiguration: - - ServerSideEncryptionByDefault: - SSEAlgorithm: aws:kms - 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 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/doc_source/stacks.md b/doc_source/stacks.md deleted file mode 100644 index 55b997d2..00000000 --- a/doc_source/stacks.md +++ /dev/null @@ -1,373 +0,0 @@ -# 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, 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 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 , Construct , Stack } = require("@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 ] - -``` -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, "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; - -// 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/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` \(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.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/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, 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 deleted file mode 100644 index b5135e17..00000000 --- a/doc_source/tagging.md +++ /dev/null @@ -1,420 +0,0 @@ -# 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\. - -**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\. - ------- -#### [ TypeScript ] - -``` -Tag.add(myConstruct, 'key', 'value'); -``` - ------- -#### [ JavaScript ] - -``` -Tag.add(myConstruct, 'key', 'value'); -``` - ------- -#### [ 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'); -``` - ------- -#### [ JavaScript ] - -``` -Tag.remove(my_construct, 'key'); -``` - ------- -#### [ Python ] - -``` -Tag.remove(my_construct, "key") -``` - ------- -#### [ Java ] - -``` -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 a construct\. - ------- -#### [ TypeScript ] - -``` -Tag.add(myConstruct, 'key', 'value', { - priority: 300 -}); -``` - ------- -#### [ JavaScript ] - -``` -Tag.add(myConstruct, 'key', 'value', { - priority: 300 -}); -``` - ------- -#### [ 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::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 ] - -``` -Tag.add(myConstruct, 'tagname', 'value', { - applyToLaunchedInstances: false, - includeResourceTypes: ['AWS::Xxx::Yyy'], - excludeResourceTypes: ['AWS::Xxx::Zzz'], - priority: 100, -}); -``` - ------- -#### [ JavaScript ] - -``` -Tag.add(myConstruct, 'tagname', 'value', { - applyToLaunchedInstances: false, - includeResourceTypes: ['AWS::Xxx::Yyy'], - excludeResourceTypes: ['AWS::Xxx::Zzz'], - priority: 100 -}); -``` - ------- -#### [ 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 \(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', { - includeResourceTypes: ['AWS::Xxx::Yyy'], - excludeResourceTypes: ['AWS::Xxx::Zzz'], - priority: 200, -}); -``` - ------- -#### [ JavaScript ] - -``` -Tag.remove(myConstruct, 'tagname', { - includeResourceTypes: ['AWS::Xxx::Yyy'], - excludeResourceTypes: ['AWS::Xxx::Zzz'], - priority: 200 -}); -``` - ------- -#### [ 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 -\(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\. - ------- -#### [ TypeScript ] - -``` -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'] -}); -``` - ------- -#### [ JavaScript ] - -``` -const { App , Stack , Tag } = require('@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 ] - -``` -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']}); -``` - ------- -#### [ JavaScript ] - -``` -Tag.add(theBestStack, 'StackType', 'TheBest', - { includeResourceTypes: ['AWS::EC2::Subnet']}); -``` - ------- -#### [ 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 deleted file mode 100644 index 8e8bea72..00000000 --- a/doc_source/testing.md +++ /dev/null @@ -1,352 +0,0 @@ -# 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 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\. - -## 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/index.ts`: - -``` -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) { - 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 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 -``` - -### Updating `package.json` - -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 `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"] - } -} -``` - -## 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 * as dlq from '../lib/index'; - -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 `index.ts`\. - -``` - 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 * as dlq from '../lib/index'; - -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 `props` 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 deleted file mode 100644 index cf14052d..00000000 --- a/doc_source/tokens.md +++ /dev/null @@ -1,427 +0,0 @@ -# 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\. - -``` -${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/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\. -+ [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 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\.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(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/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 -}); -``` - ------- -#### [ 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/doc_source/tools.md b/doc_source/tools.md deleted file mode 100644 index d0df8f1a..00000000 --- a/doc_source/tools.md +++ /dev/null @@ -1,8 +0,0 @@ -# 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/doc_source/troubleshooting.md b/doc_source/troubleshooting.md deleted file mode 100644 index c9834bbe..00000000 --- a/doc_source/troubleshooting.md +++ /dev/null @@ -1,351 +0,0 @@ -# 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) -+ [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) - -**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\. - -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\#\. - ------- -#### [ 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 -``` - -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 -``` - -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 -``` - ------- -#### [ 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)\) - -**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.50.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 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 -``` - -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\. - -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 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 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 - -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 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\. - -\([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 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/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 ] - -``` -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 } -``` - ------- -#### [ 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 - }); -} -``` - ------- - -**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 deleted file mode 100644 index aeb902d8..00000000 --- a/doc_source/use_cfn_template.md +++ /dev/null @@ -1,128 +0,0 @@ -# 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: - -``` -{ - "S3Bucket": { - "Type": "AWS::S3::Bucket", - "Properties": { - "prop1": "value1" - } - } -} -``` - -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 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 ] - -``` -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 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 - -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 diff --git a/doc_source/videos.md b/doc_source/videos.md deleted file mode 100644 index f2c160f9..00000000 --- a/doc_source/videos.md +++ /dev/null @@ -1,16 +0,0 @@ -# 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 - -## Faster deployments with CDK Pipelines - -## How to contribute to the AWS CDK using GitPod \ No newline at end of file diff --git a/doc_source/vscode.md b/doc_source/vscode.md deleted file mode 100644 index 3c089740..00000000 --- a/doc_source/vscode.md +++ /dev/null @@ -1,3 +0,0 @@ -# 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 deleted file mode 100644 index 90faf17f..00000000 --- a/doc_source/work-with-cdk-csharp.md +++ /dev/null @@ -1,185 +0,0 @@ -# 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 Mac OS X or Linux\), 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\.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/) - -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` 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 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\. - -**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/)\. - -### 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](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 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\. - -``` -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](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 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\), 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\. - -### 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\#\. - -### 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 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-cdk-java.md b/doc_source/work-with-cdk-java.md deleted file mode 100644 index 068648e6..00000000 --- a/doc_source/work-with-cdk-java.md +++ /dev/null @@ -1,147 +0,0 @@ -# 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.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 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` 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`\. - -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: - -``` - - software.amazon.awscdk - s3 - ${cdk.version} - -``` - -**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\. - -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 -``` - -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 - -### 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\. - -### 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\. - -``` -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 `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 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-cdk-javascript.md b/doc_source/work-with-cdk-javascript.md deleted file mode 100644 index 3e02d13d..00000000 --- a/doc_source/work-with-cdk-javascript.md +++ /dev/null @@ -1,262 +0,0 @@ -# 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 [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\. - -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 -``` - -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 -``` - -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\.\) -+ 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 - -### 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, 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, 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; - -class myStack extends core.Stack { - bucket: s3.Bucket; - // ... -} - -function makeEnv(account: string, region: string) : object { - // ... -} -``` - ------- -#### [ JavaScript ] - -``` -var encrypted = true; - -class myStack extends core.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 [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 - -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 deleted file mode 100644 index dc38fb23..00000000 --- a/doc_source/work-with-cdk-python.md +++ /dev/null @@ -1,214 +0,0 @@ -# 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 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 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\. - -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 -``` - -**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: - -``` -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 - -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 -``` - -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 -``` - -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 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\. - -``` -aws-cdk.aws-s3==X.YY.ZZ -aws-cdk.aws-lambda==X.YY.ZZ -``` - -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 -``` - -**Important** -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 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 - -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\. - -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) - # ... -``` - -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 - -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.core 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 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\. - -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 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-cdk-typescript.md b/doc_source/work-with-cdk-typescript.md deleted file mode 100644 index d1fd5120..00000000 --- a/doc_source/work-with-cdk-typescript.md +++ /dev/null @@ -1,133 +0,0 @@ -# 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\. 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/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\. - -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 -``` - -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 -``` - -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 - -### 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/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/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\. - -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 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 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 deleted file mode 100644 index c6243475..00000000 --- a/doc_source/work-with.md +++ /dev/null @@ -1,37 +0,0 @@ -# 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 -``` - -**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\. - -**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 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 89d1e50af06510102d4e41ddf01f944c7ea23f3c Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Mon, 21 Sep 2020 12:05:16 -0700 Subject: [PATCH 297/298] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e067e972..bfb56a0b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ # Default branch The default branch for this repo has changed to "main." If you have cloned the previous default branch, -please update yur local repo to use the "main" branch. +please update your local repo to use the "main" branch. From a7c65a49d955efc96f84dacd72b38f961fe60856 Mon Sep 17 00:00:00 2001 From: Jerry Kindall <52084730+Jerry-AWS@users.noreply.github.com> Date: Mon, 21 Sep 2020 12:17:25 -0700 Subject: [PATCH 298/298] Create doc-source --- doc-source | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 doc-source diff --git a/doc-source b/doc-source new file mode 100644 index 00000000..bfb56a0b --- /dev/null +++ b/doc-source @@ -0,0 +1,4 @@ +# Default branch + +The default branch for this repo has changed to "main." If you have cloned the previous default branch, +please update your local repo to use the "main" branch.