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. diff --git a/.gitignore b/.gitignore deleted file mode 100644 index c6d8587a..00000000 --- a/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ -# Editor backup files -*~ -*.bak -*.lock - -# System files -.attach* -.DS_Store - -# Build directories -build/ - -# IDE files -.idea/ -.vscode/ -.amazonq/ - -# Generated documentation -*.html -*.pdf -*.docx -*.xlsx -*.rtf -*.mobi - -# Archives -*.7z -*.rar -*.tar - -# Other -*.running.properties.txt \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 5dccd4cf..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. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 50a0d080..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 **main** 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 **main** branch. -2. You check [existing open](https://github.com/awsdocs/aws-cdk-guide/pulls), and [recently closed](https://github.com/awsdocs/aws-cdk-guide/pulls?q=is:pr+is:closed), 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-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-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-guide/issues) in this repository for some ideas. - -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-guide/blob/main/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. \ No newline at end of file diff --git a/Config b/Config deleted file mode 100755 index 2e9c79bf..00000000 --- a/Config +++ /dev/null @@ -1,30 +0,0 @@ -# -*-perl-*- - -package.AWSCDKDocs = { - flavors = { - map = single; - generation = 1; - }; - - interfaces = (3.0); - deploy = { - generic = true; - }; - scope = webservices; - - build-system = zonbooktrails; - build-environment = { - chroot = basic; - network-access = blocked; - }; - - build-tools = { - 3.0 = { - ZonBookTrails = 1.0; - - ZonBook = 5.0; - AWSDocsSdkExamplesPublic = 1.0; - AWSDocsChecklistCDK = 2.0; - }; - }; -}; 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. 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. 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. diff --git a/README.md b/README.md index 0634f8fd..bfb56a0b 100644 --- a/README.md +++ b/README.md @@ -1,20 +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. PRs should target the main branch, not master, which has been deprecated. - -* `v2` - contains the Markdown files for the CDK v2 Developer Guide - -Feel free to make a Pull Request against only one of these content sets (we'll make sure it gets into both). - -Issues reported through the Feedback link at the bottom of the individual pages of the AWS CDK Developer Guide go to an internal Amazon issue tracker and may not appear here. However, we try to track most substantive AWS CDK Developer Guide work on GitHub -so the community can see, comment, and contribute. - -## 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). - -## 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. \ No newline at end of file +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. diff --git a/build b/build deleted file mode 120000 index d386ee6d..00000000 --- a/build +++ /dev/null @@ -1 +0,0 @@ -/workplace/pgasca/AWSCDKDocs_1/build/AWSCDKDocs/AWSCDKDocs-3.0/AL2_x86_64/DEV.STD.PTHREAD/build \ No newline at end of file diff --git a/build-info.xml b/build-info.xml deleted file mode 100755 index 55b11604..00000000 --- a/build-info.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - cdk - AWS Cloud Development Kit - 0 - CDK - - 0 - - - - - - guide - awscdk - Developer Guide - CDK - v2 - v2 - v2/guide - en_us - - - - - Developer Guide Updates - awscdkv2 - - - - 1 - - - - - - awsdocs - aws-cdk-guide - main - v2/guide - - - - - - - - diff --git a/build.xml b/build.xml deleted file mode 100755 index e8ba5d4f..00000000 --- a/build.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - This is the entry point for happy trails builds (package builder and eclipse). - - - - \ No newline at end of file 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. 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 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 diff --git a/v2/guide/CDK_Project.xpr b/v2/guide/CDK_Project.xpr deleted file mode 100644 index 129faa06..00000000 --- a/v2/guide/CDK_Project.xpr +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - editor.detect.indent.on.open - false - - - editor.hard.line.wrap - true - - - editor.indent.size.v9.2 - 2 - - - editor.line.width - 160 - - - key.editor.format.option.pane.group - true - - - validation.scenarios - - - - - - - - - - diff --git a/v2/guide/apps.adoc b/v2/guide/apps.adoc deleted file mode 100644 index 8486ec83..00000000 --- a/v2/guide/apps.adoc +++ /dev/null @@ -1,128 +0,0 @@ -include::attributes.txt[] - -// Attributes -[.topic] -:info_titleabbrev: Apps -:keywords: {aws} CDK, {aws} CDK app - -[#apps] -= {aws} CDK apps - -[abstract] --- -The {aws} Cloud Development Kit ({aws} CDK) application or _app_ is a collection of one or more CDK xref:stacks[stacks]. Stacks are a collection of one or more xref:constructs[constructs], which define {aws} resources and properties. Therefore, the overall grouping of your stacks and constructs are known as your CDK app. --- - -// Content start - -The {aws} Cloud Development Kit ({aws} CDK) application or _app_ is a collection of one or more CDK xref:stacks[stacks]. Stacks are a collection of one or more xref:constructs[constructs], which define {aws} resources and properties. Therefore, the overall grouping of your stacks and constructs are known as your CDK app. - -[#apps-define] -== How to create a CDK app - -You create an app by defining an app instance in the application file of your xref:projects[project]. To do this, you import and use the https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.App.html[App] construct from the {aws} Construct Library. The `App` construct doesn't require any initialization arguments. It is the only construct that can be used as the root. - -The `https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.App.html[App]` and `https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html[Stack]` classes from the {aws} Construct Library are unique constructs. Compared to other constructs, they don't configure {aws} resources on their own. Instead, they are used to provide context for your other constructs. All constructs that represent {aws} resources must be defined, directly or indirectly, within the scope of a `Stack` construct. `Stack` constructs are defined within the scope of an `App` construct. - -Apps are then synthesized to create {aws} CloudFormation templates for your stacks. The following is an example: - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -const app = new App(); -new MyFirstStack(app, 'hello-cdk'); -app.synth(); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -const app = new App(); -new MyFirstStack(app, 'hello-cdk'); -app.synth(); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -app = App() -MyFirstStack(app, "hello-cdk") -app.synth() ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -App app = new App(); -new MyFirstStack(app, "hello-cdk"); -app.synth(); ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -var app = new App(); -new MyFirstStack(app, "hello-cdk"); -app.Synth(); ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -app := awscdk.NewApp(nil) - -MyFirstStack(app, "MyFirstStack", &MyFirstStackProps{ - awscdk.StackProps{ - Env: env(), - }, -}) - -app.Synth(nil) ----- -==== - -Stacks within a single app can easily refer to each other's resources and properties. The {aws} CDK infers dependencies between stacks so that they can be deployed in the correct order. You can deploy any or all of the stacks within an app with a single `cdk deploy` command. - -[#apps-tree] -== The construct tree - -Constructs are defined inside of other constructs using the `scope` argument that is passed to every construct, with the `App` class as the root. In this way, an {aws} CDK app defines a hierarchy of constructs known as the _construct tree_. - -The root of this tree is your app, which is an instance of the `App` class. Within the app, you instantiate one or more stacks. Within stacks, you instantiate constructs, which may themselves instantiate resources or other constructs, and so on down the tree. - -Constructs are _always_ explicitly defined within the scope of another construct, which creates relationships between constructs. Almost always, you should pass `this` (in Python, `self`) as the scope, indicating that the new construct is a child of the current construct. The intended pattern is that you derive your construct from https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html[`Construct`], then instantiate the constructs it uses in its constructor. - -Passing the scope explicitly allows each construct to add itself to the tree, with this behavior entirely contained within the https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html[`Construct` base class]. It works the same way in every language supported by the {aws} CDK and does not require additional customization. - -[IMPORTANT] -==== - -Technically, it's possible to pass some scope other than `this` when instantiating a construct. You can add constructs anywhere in the tree, or even in another stack in the same app. For example, you could write a mixin-style function that adds constructs to a scope passed in as an argument. The practical difficulty here is that you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope. The practice also makes your code more difficult to understand, maintain, and reuse. Therefore, we recommend that you use the general structure of the construct tree. - -==== - -The {aws} CDK uses the IDs of all constructs in the path from the tree's root to each child construct to generate the unique IDs required by {aws} CloudFormation. This approach means that construct IDs only need to be unique within their scope, rather than within the entire stack as in native {aws} CloudFormation. However, if you move a construct to a different scope, its generated stack-unique ID changes, and {aws} CloudFormation won't consider it the same resource. - -The construct tree is separate from the constructs that you define in your {aws} CDK code. However, it's accessible through any construct's `node` attribute, which is a reference to the node that represents that construct in the tree. Each node is a https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Node.html[`Node`] instance, the attributes of which provide access to the tree's root and to the node's parent scopes and children. - -. `node.children` – The direct children of the construct. -. `node.id` – The identifier of the construct within its scope. -. `node.path` – The full path of the construct including the IDs of all of its parents. -. `node.root` – The root of the construct tree (the app). -. `node.scope` – The scope (parent) of the construct, or undefined if the node is the root. -. `node.scopes` – All parents of the construct, up to the root. -. `node.uniqueId` – The unique alphanumeric identifier for this construct within the tree (by default, generated from `node.path` and a hash). - -The construct tree defines an implicit order in which constructs are synthesized to resources in the final {aws} CloudFormation template. Where one resource must be created before another, {aws} CloudFormation or the {aws} Construct Library generally infers the dependency. They then make sure that the resources are created in the right order. - -You can also add an explicit dependency between two nodes by using `node.addDependency()`. For more information, see https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html#dependencies[Dependencies] in the _{aws} CDK API Reference_. - -The {aws} CDK provides a simple way to visit every node in the construct tree and perform an operation on each one. For more information, see xref:aspects[Aspects and the {aws} CDK]. \ No newline at end of file diff --git a/v2/guide/aspects.adoc b/v2/guide/aspects.adoc deleted file mode 100644 index d7b5bcf0..00000000 --- a/v2/guide/aspects.adoc +++ /dev/null @@ -1,252 +0,0 @@ -include::attributes.txt[] - -// Attributes -[.topic] -[#aspects] -= Aspects and the {aws} CDK -:info_titleabbrev: Aspects -:keywords: {aws} CDK, aspects - -[abstract] --- -Aspects are a way to apply an operation to all constructs in a given scope. The aspect could modify the constructs, such as by adding tags. Or it could verify something about the state of the constructs, such as making sure that all buckets are encrypted. --- - -// Content start - -Aspects are a way to apply an operation to all constructs in a given scope. The aspect could modify the constructs, such as by adding tags. Or it could verify something about the state of the constructs, such as making sure that all buckets are encrypted. - -To apply an aspect to a construct and all constructs in the same scope, call `link:https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Aspects.html#static-ofscope[Aspects].of().add()` with a new aspect, as shown in the following example. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -Aspects.of(myConstruct).add(new SomeAspect(...)); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -Aspects.of(myConstruct).add(new SomeAspect(...)); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -Aspects.of(my_construct).add(SomeAspect(...)) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -Aspects.of(myConstruct).add(new SomeAspect(...)); ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -Aspects.Of(myConstruct).add(new SomeAspect(...)); ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -awscdk.Aspects_Of(stack).Add(awscdk.NewTag(...)) ----- -==== - -The {aws} CDK uses aspects to xref:tagging[tag resources], but the framework can also be used for other purposes. For example, you can use it to validate or change the {aws} CloudFormation resources that are defined for you by higher-level constructs. - -[#aspects-detail] -== Aspects in detail - -Aspects employ the link:https://en.wikipedia.org/wiki/Visitor_pattern[visitor pattern]. An aspect is a class that implements the following interface. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -interface IAspect { - visit(node: IConstruct): void;} ----- - -JavaScript:: -JavaScript doesn't have interfaces as a language feature. Therefore, an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on. - -Python:: -Python doesn't have interfaces as a language feature. Therefore, an aspect is simply an instance of a class having a `visit` method that accepts the node to be operated on. - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -public interface IAspect { - public void visit(Construct node); -} ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -public interface IAspect -{ - void Visit(IConstruct node); -} ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -type IAspect interface { - Visit(node constructs.IConstruct) -} ----- -==== - -When you call `Aspects.of().add(...)`, the construct adds the aspect to an internal list of aspects. You can obtain the list with `Aspects.of()`. - -During the xref:deploy-how-synth-app[prepare phase], the {aws} CDK calls the `visit` method of the object for the construct and each of its children in top-down order. - -The `visit` method is free to change anything in the construct. In strongly typed languages, cast the received construct to a more specific type before accessing construct-specific properties or methods. - -Aspects don't propagate across `Stage` construct boundaries, because `Stages` are self-contained and immutable after definition. Apply aspects on the `Stage` construct itself (or lower) if you want them to visit constructs inside the ``Stage``. - -[#aspects-example] -== Example - -The following example validates that all buckets created in the stack have versioning enabled. The aspect adds an error annotation to the constructs that fail the validation. This results in the `synth` operation failing and prevents deploying the resulting cloud assembly. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -class BucketVersioningChecker implements IAspect { - public visit(node: IConstruct): void { - // See that we're dealing with a CfnBucket - if (node instanceof s3.CfnBucket) { - - // Check for versioning property, exclude the case where the property - // can be a token (IResolvable). - if (!node.versioningConfiguration - || (!Tokenization.isResolvable(node.versioningConfiguration) - && node.versioningConfiguration.status !== 'Enabled')) { - Annotations.of(node).addError('Bucket versioning is not enabled'); - } - } - } -} - -// Later, apply to the stack -Aspects.of(stack).add(new BucketVersioningChecker()); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -class BucketVersioningChecker { - visit(node) { - // See that we're dealing with a CfnBucket - if ( node instanceof s3.CfnBucket) { - - // Check for versioning property, exclude the case where the property - // can be a token (IResolvable). - if (!node.versioningConfiguration - || !Tokenization.isResolvable(node.versioningConfiguration) - && node.versioningConfiguration.status !== 'Enabled')) { - Annotations.of(node).addError('Bucket versioning is not enabled'); - } - } - } -} - -// Later, apply to the stack -Aspects.of(stack).add(new BucketVersioningChecker()); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -@jsii.implements(cdk.IAspect) -class BucketVersioningChecker: - - def visit(self, node): - # See that we're dealing with a CfnBucket - if isinstance(node, s3.CfnBucket): - - # Check for versioning property, exclude the case where the property - # can be a token (IResolvable). - if (not node.versioning_configuration or - not Tokenization.is_resolvable(node.versioning_configuration) - and node.versioning_configuration.status != "Enabled"): - Annotations.of(node).add_error('Bucket versioning is not enabled') - -# Later, apply to the stack -Aspects.of(stack).add(BucketVersioningChecker()) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -public class BucketVersioningChecker implements IAspect -{ - @Override - public void visit(Construct node) - { - // See that we're dealing with a CfnBucket - if (node instanceof CfnBucket) - { - CfnBucket bucket = (CfnBucket)node; - Object versioningConfiguration = bucket.getVersioningConfiguration(); - if (versioningConfiguration == null || - !Tokenization.isResolvable(versioningConfiguration.toString()) && - !versioningConfiguration.toString().contains("Enabled")) - Annotations.of(bucket.getNode()).addError("Bucket versioning is not enabled"); - } - } -} - -// Later, apply to the stack -Aspects.of(stack).add(new BucketVersioningChecker()); ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -class BucketVersioningChecker : Amazon.Jsii.Runtime.Deputy.DeputyBase, IAspect -{ - public void Visit(IConstruct node) - { - // See that we're dealing with a CfnBucket - if (node is CfnBucket) - { - var bucket = (CfnBucket)node; - if (bucket.VersioningConfiguration is null || - !Tokenization.IsResolvable(bucket.VersioningConfiguration) && - !bucket.VersioningConfiguration.ToString().Contains("Enabled")) - Annotations.Of(bucket.Node).AddError("Bucket versioning is not enabled"); - } - } -} - -// Later, apply to the stack -Aspects.Of(stack).add(new BucketVersioningChecker()); ----- -==== \ No newline at end of file diff --git a/v2/guide/assets.adoc b/v2/guide/assets.adoc deleted file mode 100644 index 51003074..00000000 --- a/v2/guide/assets.adoc +++ /dev/null @@ -1,1182 +0,0 @@ -include::attributes.txt[] - -// Attributes -[.topic] -:info_titleabbrev: Assets -:keywords: {aws} CDK, Assets, Amazon S3, Amazon ECR - -[#assets] -= Assets and the {aws} CDK - -[abstract] --- -Assets are local files, directories, or Docker images. --- - -// Content start - -Assets are local files, directories, or Docker images that can be bundled into {aws} CDK libraries and apps. For example, an asset might be a directory that contains the handler code for an {aws} Lambda function. Assets can represent any artifact that the app needs to operate. - -The following tutorial video provides a comprehensive overview of CDK assets, and explains how you can use them in your infrastructure as code (IaC). - -video::jHNtXQmkKfw[youtube,align = center,height = 390,fileref = https://www.youtube.com/embed/jHNtXQmkKfw,width = 480] - -You add assets through APIs that are exposed by specific {aws} constructs. For example, when you define a https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html[`lambda.Function`] construct, the https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html#code[`code`] property lets you pass an https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Code.html#static-fromwbrassetpath-options[`asset`] (directory). `Function` uses assets to bundle the contents of the directory and use it for the function's code. Similarly, https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ContainerImage.html#static-fromwbrassetdirectory-props[`ecs.ContainerImage.fromAsset`] uses a Docker image built from a local directory when defining an Amazon ECS task definition. - -[#assets-details] -== Assets in detail - -When you refer to an asset in your app, the xref:deploy-how-synth-assemblies[cloud assembly] that's synthesized from your application includes metadata information with instructions for the {aws} CDK CLI. The instructions include where to find the asset on the local disk and what type of bundling to perform based on the asset type, such as a directory to compress (zip) or a Docker image to build. - -The {aws} CDK generates a source hash for assets. This can be used at construction time to determine whether the contents of an asset have changed. - -By default, the {aws} CDK creates a copy of the asset in the cloud assembly directory, which defaults to `cdk.out`, under the source hash. This way, the cloud assembly is self-contained, so if it moved over to a different host for deployment, it can still be deployed. See xref:deploy-how-synth-assemblies[Cloud assemblies] for details. - -When the {aws} CDK deploys an app that references assets (either directly by the app code or through a library), the {aws} CDK CLI first prepares and publishes the assets to an Amazon S3 bucket or Amazon ECR repository. (The S3 bucket or repository is created during bootstrapping.) Only then are the resources defined in the stack deployed. - -This section describes the low-level APIs available in the framework. - -[#assets-types] -== 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. - -[#assets-types-s3] -== 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 https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets-readme.html[`aws-s3-assets`] module. - -The following example defines a local directory asset and a file asset. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -import { Asset } from 'aws-cdk-lib/aws-s3-assets'; - -// Archived and uploaded to Amazon S3 as a .zip file -const directoryAsset = new Asset(this, "SampleZippedDirAsset", { - path: path.join(__dirname, "sample-asset-directory") -}); - -// Uploaded to Amazon S3 as-is -const fileAsset = new Asset(this, 'SampleSingleFileAsset', { - path: path.join(__dirname, 'file-asset.txt') -}); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -const { Asset } = require('aws-cdk-lib/aws-s3-assets'); - -// Archived and uploaded to Amazon S3 as a .zip file -const directoryAsset = new Asset(this, "SampleZippedDirAsset", { - path: path.join(__dirname, "sample-asset-directory") -}); - -// Uploaded to Amazon S3 as-is -const fileAsset = new Asset(this, 'SampleSingleFileAsset', { - path: path.join(__dirname, 'file-asset.txt') -}); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -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:: -+ -[source,java,subs="verbatim,attributes"] ----- -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#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -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") -}); ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -dirName, err := os.Getwd() -if err != nil { - panic(err) -} - -awss3assets.NewAsset(stack, jsii.String("SampleZippedDirAsset"), &awss3assets.AssetProps{ - Path: jsii.String(path.Join(dirName, "sample-asset-directory")), -}) - -awss3assets.NewAsset(stack, jsii.String("SampleSingleFileAsset"), &awss3assets.AssetProps{ - Path: jsii.String(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 so that you can use assets. For Lambda functions, the https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Code.html#static-fromwbrassetpath-options[`fromAsset()`] static method enables you to specify a directory or a .zip file in the local file system. - -[#assets-types-s3-lambda] -=== Lambda function example - -A common use case is creating Lambda functions with the handler code as an Amazon S3 asset. - -The following example uses an Amazon S3 asset to define a Python handler in the local directory `handler`. It also creates a Lambda function with the local directory asset as the `code` property. Following is the Python code for the handler. - -[source,python,subs="verbatim,attributes"] ----- -def lambda_handler(event, context): - message = 'Hello World!' - return { - 'message': message - } ----- - -The code for the main {aws} CDK app should look like the following. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -import * as cdk from 'aws-cdk-lib'; -import { Constructs } from 'constructs'; -import * as lambda from 'aws-cdk-lib/aws-lambda'; -import * as path from 'path'; - -export class HelloAssetStack extends cdk.Stack { - constructor(scope: Construct, id: string, props?: cdk.StackProps) { - super(scope, id, props); - - new lambda.Function(this, 'myLambdaFunction', { - code: lambda.Code.fromAsset(path.join(__dirname, 'handler')), - runtime: lambda.Runtime.PYTHON_3_6, - handler: 'index.lambda_handler' - }); - } -} ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -const cdk = require('aws-cdk-lib'); -const lambda = require('aws-cdk-lib/aws-lambda'); -const path = require('path'); - -class HelloAssetStack extends cdk.Stack { - constructor(scope, id, props) { - super(scope, id, props); - - new lambda.Function(this, 'myLambdaFunction', { - code: lambda.Code.fromAsset(path.join(__dirname, 'handler')), - runtime: lambda.Runtime.PYTHON_3_6, - handler: 'index.lambda_handler' - }); - } -} - -module.exports = { HelloAssetStack } ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -from aws_cdk import Stack -from constructs import Construct -from aws_cdk import aws_lambda as lambda_ - -import os.path -dirname = os.path.dirname(__file__) - -class HelloAssetStack(Stack): - def __init__(self, scope: Construct, id: str, **kwargs): - super().__init__(scope, id, **kwargs) - - lambda_.Function(self, 'myLambdaFunction', - code=lambda_.Code.from_asset(os.path.join(dirname, 'handler')), - runtime=lambda_.Runtime.PYTHON_3_6, - handler="index.lambda_handler") ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -import java.io.File; - -import software.amazon.awscdk.Stack; -import software.amazon.awscdk.StackProps; -import software.amazon.awscdk.services.lambda.Function; -import software.amazon.awscdk.services.lambda.Runtime; - -public class HelloAssetStack extends Stack { - - public HelloAssetStack(final App scope, final String id) { - this(scope, id, null); - } - - public HelloAssetStack(final App scope, final String id, final StackProps props) { - super(scope, id, props); - - File startDir = new File(System.getProperty("user.dir")); - - Function.Builder.create(this, "myLambdaFunction") - .code(Code.fromAsset(new File(startDir, "handler").toString())) - .runtime(Runtime.PYTHON_3_6) - .handler("index.lambda_handler").build(); - } -} ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -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" - }); - } -} ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -import ( - "os" - "path" - - "github.com/aws/aws-cdk-go/awscdk/v2" - "github.com/aws/aws-cdk-go/awscdk/v2/awslambda" - "github.com/aws/aws-cdk-go/awscdk/v2/awss3assets" - "github.com/aws/constructs-go/constructs/v10" - "github.com/aws/jsii-runtime-go" -) - -func HelloAssetStack(scope constructs.Construct, id string, props *HelloAssetStackProps) awscdk.Stack { - var sprops awscdk.StackProps - if props != nil { - sprops = props.StackProps - } - stack := awscdk.NewStack(scope, &id, &sprops) - - dirName, err := os.Getwd() - if err != nil { - panic(err) - } - - awslambda.NewFunction(stack, jsii.String("myLambdaFunction"), &awslambda.FunctionProps{ - Code: awslambda.AssetCode_FromAsset(jsii.String(path.Join(dirName, "handler")), &awss3assets.AssetOptions{}), - Runtime: awslambda.Runtime_PYTHON_3_6(), - Handler: jsii.String("index.lambda_handler"), - }) - - return stack -} ----- -==== - -The `Function` method uses assets to bundle the contents of the directory and use it for the function's code. - -[TIP] -==== - -Java `.jar` files are ZIP files with a different extension. These are uploaded as-is to Amazon S3, but when deployed as a Lambda function, the files they contain are extracted, which you might not want. To avoid this, place the `.jar` file in a directory and specify that directory as the asset. - -==== - -[#assets-types-s3-deploy] -=== Deploy-time attributes example - -Amazon S3 asset types also expose xref:resources-attributes[deploy-time attributes] that can be referenced in {aws} CDK libraries and apps. The {aws} CDK CLI command `cdk synth` displays asset properties as {aws} CloudFormation parameters. - -The following example uses deploy-time attributes to pass the location of an image asset into a Lambda function as environment variables. (The kind of file doesn't matter; the PNG image used here is only an example.) - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -import { Asset } from 'aws-cdk-lib/aws-s3-assets'; -import * as path from 'path'; - -const imageAsset = new Asset(this, "SampleAsset", { - path: path.join(__dirname, "images/my-image.png") -}); - -new lambda.Function(this, "myLambdaFunction", { - code: lambda.Code.asset(path.join(__dirname, "handler")), - runtime: lambda.Runtime.PYTHON_3_6, - handler: "index.lambda_handler", - environment: { - 'S3_BUCKET_NAME': imageAsset.s3BucketName, - 'S3_OBJECT_KEY': imageAsset.s3ObjectKey, - 'S3_OBJECT_URL': imageAsset.s3ObjectUrl - } -}); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -const { Asset } = require('aws-cdk-lib/aws-s3-assets'); -const path = require('path'); - -const imageAsset = new Asset(this, "SampleAsset", { - path: path.join(__dirname, "images/my-image.png") -}); - -new lambda.Function(this, "myLambdaFunction", { - code: lambda.Code.asset(path.join(__dirname, "handler")), - runtime: lambda.Runtime.PYTHON_3_6, - handler: "index.lambda_handler", - environment: { - 'S3_BUCKET_NAME': imageAsset.s3BucketName, - 'S3_OBJECT_KEY': imageAsset.s3ObjectKey, - 'S3_OBJECT_URL': imageAsset.s3ObjectUrl - } -}); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -import os.path - -import aws_cdk.aws_lambda as lambda_ -from aws_cdk.aws_s3_assets import Asset - -dirname = os.path.dirname(__file__) - -image_asset = Asset(self, "SampleAsset", - path=os.path.join(dirname, "images/my-image.png")) - -lambda_.Function(self, "myLambdaFunction", - code=lambda_.Code.asset(os.path.join(dirname, "handler")), - runtime=lambda_.Runtime.PYTHON_3_6, - handler="index.lambda_handler", - environment=dict( - S3_BUCKET_NAME=image_asset.s3_bucket_name, - S3_OBJECT_KEY=image_asset.s3_object_key, - S3_OBJECT_URL=image_asset.s3_object_url)) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -import java.io.File; - -import software.amazon.awscdk.Stack; -import software.amazon.awscdk.StackProps; -import software.amazon.awscdk.services.lambda.Function; -import software.amazon.awscdk.services.lambda.Runtime; -import software.amazon.awscdk.services.s3.assets.Asset; - -public class FunctionStack extends Stack { - public FunctionStack(final App scope, final String id, final StackProps props) { - super(scope, id, props); - - File startDir = new File(System.getProperty("user.dir")); - - Asset imageAsset = Asset.Builder.create(this, "SampleAsset") - .path(new File(startDir, "images/my-image.png").toString()).build()) - - Function.Builder.create(this, "myLambdaFunction") - .code(Code.fromAsset(new File(startDir, "handler").toString())) - .runtime(Runtime.PYTHON_3_6) - .handler("index.lambda_handler") - .environment(java.util.Map.of( // Java 9 or later - "S3_BUCKET_NAME", imageAsset.getS3BucketName(), - "S3_OBJECT_KEY", imageAsset.getS3ObjectKey(), - "S3_OBJECT_URL", imageAsset.getS3ObjectUrl())) - .build(); - } -} ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -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_OBJECT_URL"] = imageAsset.S3ObjectUrl - } -}); ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -import ( - "os" - "path" - - "github.com/aws/aws-cdk-go/awscdk/v2" - "github.com/aws/aws-cdk-go/awscdk/v2/awslambda" - "github.com/aws/aws-cdk-go/awscdk/v2/awss3assets" -) - -dirName, err := os.Getwd() -if err != nil { - panic(err) -} - -imageAsset := awss3assets.NewAsset(stack, jsii.String("SampleAsset"), &awss3assets.AssetProps{ - Path: jsii.String(path.Join(dirName, "images/my-image.png")), -}) - -awslambda.NewFunction(stack, jsii.String("myLambdaFunction"), &awslambda.FunctionProps{ - Code: awslambda.AssetCode_FromAsset(jsii.String(path.Join(dirName, "handler"))), - Runtime: awslambda.Runtime_PYTHON_3_6(), - Handler: jsii.String("index.lambda_handler"), - Environment: &map[string]*string{ - "S3_BUCKET_NAME": imageAsset.S3BucketName(), - "S3_OBJECT_KEY": imageAsset.S3ObjectKey(), - "S3_URL": imageAsset.S3ObjectUrl(), - }, -}) ----- -==== - -[#assets-types-s3-permissions] -=== Permissions - -If you use Amazon S3 assets directly through the https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets-readme.html[`aws-s3-assets`] module, IAM roles, users, or groups, and you need to read assets in runtime, then grant those assets IAM permissions through the https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_assets.Asset.html#grantwbrreadgrantee[`asset.grantRead`] method. - -The following example grants an IAM group read permissions on a file asset. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -import { Asset } from 'aws-cdk-lib/aws-s3-assets'; -import * as path from 'path'; - -const asset = new Asset(this, 'MyFile', { - path: path.join(__dirname, 'my-image.png') -}); - -const group = new iam.Group(this, 'MyUserGroup'); -asset.grantRead(group); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -const { Asset } = require('aws-cdk-lib/aws-s3-assets'); -const path = require('path'); - -const asset = new Asset(this, 'MyFile', { - path: path.join(__dirname, 'my-image.png') -}); - -const group = new iam.Group(this, 'MyUserGroup'); -asset.grantRead(group); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -from aws_cdk.aws_s3_assets import Asset -import aws_cdk.aws_iam as iam - -import os.path -dirname = os.path.dirname(__file__) - - asset = Asset(self, "MyFile", - path=os.path.join(dirname, "my-image.png")) - - group = iam.Group(self, "MyUserGroup") - asset.grant_read(group) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -import java.io.File; - -import software.amazon.awscdk.Stack; -import software.amazon.awscdk.StackProps; -import software.amazon.awscdk.services.iam.Group; -import software.amazon.awscdk.services.s3.assets.Asset; - -public class GrantStack extends Stack { - public GrantStack(final App scope, final String id, final StackProps props) { - super(scope, id, props); - - File startDir = new File(System.getProperty("user.dir")); - - Asset asset = Asset.Builder.create(this, "SampleAsset") - .path(new File(startDir, "images/my-image.png").toString()).build(); - - Group group = new Group(this, "MyUserGroup"); - asset.grantRead(group); } -} ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -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); ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -import ( - "os" - "path" - - "github.com/aws/aws-cdk-go/awscdk/v2" - "github.com/aws/aws-cdk-go/awscdk/v2/awsiam" - "github.com/aws/aws-cdk-go/awscdk/v2/awss3assets" -) - -dirName, err := os.Getwd() -if err != nil { - panic(err) -} - -asset := awss3assets.NewAsset(stack, jsii.String("MyFile"), &awss3assets.AssetProps{ - Path: jsii.String(path.Join(dirName, "my-image.png")), -}) - -group := awsiam.NewGroup(stack, jsii.String("MyUserGroup"), &awsiam.GroupProps{}) - -asset.GrantRead(group) ----- -==== - -[#assets-types-docker] -== Docker image assets - -The {aws} CDK supports bundling local Docker images as assets through the https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr_assets-readme.html[`aws-ecr-assets`] 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. The images can be naturally referenced in your {aws} CDK app. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -import { DockerImageAsset } from 'aws-cdk-lib/aws-ecr-assets'; - -const asset = new DockerImageAsset(this, 'MyBuildImage', { - directory: path.join(__dirname, 'my-image') -}); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -const { DockerImageAsset } = require('aws-cdk-lib/aws-ecr-assets'); - -const asset = new DockerImageAsset(this, 'MyBuildImage', { - directory: path.join(__dirname, 'my-image') -}); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -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:: -+ -[source,java,subs="verbatim,attributes"] ----- -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#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -using System.IO; -using Amazon.CDK.{aws}.ECR.Assets; - -var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps -{ - Directory = Path.Combine(Directory.GetCurrentDirectory(), "my-image") -}); ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -import ( - "os" - "path" - - "github.com/aws/aws-cdk-go/awscdk/v2" - "github.com/aws/aws-cdk-go/awscdk/v2/awsecrassets" -) - -dirName, err := os.Getwd() -if err != nil { - panic(err) -} - -asset := awsecrassets.NewDockerImageAsset(stack, jsii.String("MyBuildImage"), &awsecrassets.DockerImageAssetProps{ - Directory: jsii.String(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 xref:resources-attributes[deploy-time 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. - -[#assets-types-docker-ecs] -=== Amazon ECS task definition example - -A common use case is to create an Amazon ECS https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.TaskDefinition.html[`TaskDefinition`] 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. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -import * as ecs from 'aws-cdk-lib/aws-ecs'; -import * as ecr_assets from 'aws-cdk-lib/aws-ecr-assets'; -import * as path from 'path'; - -const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { - memoryLimitMiB: 1024, - cpu: 512 -}); - -const asset = new ecr_assets.DockerImageAsset(this, 'MyBuildImage', { - directory: path.join(__dirname, 'my-image') -}); - -taskDefinition.addContainer("my-other-container", { - image: ecs.ContainerImage.fromDockerImageAsset(asset) -}); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -const ecs = require('aws-cdk-lib/aws-ecs'); -const ecr_assets = require('aws-cdk-lib/aws-ecr-assets'); -const path = require('path'); - -const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { - memoryLimitMiB: 1024, - cpu: 512 -}); - -const asset = new ecr_assets.DockerImageAsset(this, 'MyBuildImage', { - directory: path.join(__dirname, 'my-image') -}); - -taskDefinition.addContainer("my-other-container", { - image: ecs.ContainerImage.fromDockerImageAsset(asset) -}); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -import aws_cdk.aws_ecs as ecs -import aws_cdk.aws_ecr_assets as ecr_assets - -import os.path -dirname = os.path.dirname(__file__) - -task_definition = ecs.FargateTaskDefinition(self, "TaskDef", - memory_limit_mib=1024, - cpu=512) - -asset = ecr_assets.DockerImageAsset(self, 'MyBuildImage', - directory=os.path.join(dirname, 'my-image')) - -task_definition.add_container("my-other-container", - image=ecs.ContainerImage.from_docker_image_asset(asset)) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -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; - -import software.amazon.awscdk.services.ecr.assets.DockerImageAsset; - -File startDir = new File(System.getProperty("user.dir")); - -FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create( - this, "TaskDef").memoryLimitMiB(1024).cpu(512).build(); - -DockerImageAsset asset = DockerImageAsset.Builder.create(this, "MyBuildImage") - .directory(new File(startDir, "my-image").toString()).build(); - -taskDefinition.addContainer("my-other-container", - ContainerDefinitionOptions.builder() - .image(ContainerImage.fromDockerImageAsset(asset)) - .build(); -) ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -using System.IO; -using Amazon.CDK.{aws}.ECS; -using Amazon.CDK.{aws}.Ecr.Assets; - -var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps -{ - MemoryLimitMiB = 1024, - Cpu = 512 -}); - -var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps -{ - Directory = Path.Combine(Directory.GetCurrentDirectory(), "my-image") -}); - -taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions -{ - Image = ContainerImage.FromDockerImageAsset(asset) -}); ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -import ( - "os" - "path" - - "github.com/aws/aws-cdk-go/awscdk/v2" - "github.com/aws/aws-cdk-go/awscdk/v2/awsecrassets" - "github.com/aws/aws-cdk-go/awscdk/v2/awsecs" -) - -dirName, err := os.Getwd() -if err != nil { - panic(err) -} - -taskDefinition := awsecs.NewTaskDefinition(stack, jsii.String("TaskDef"), &awsecs.TaskDefinitionProps{ - MemoryMiB: jsii.String("1024"), - Cpu: jsii.String("512"), -}) - -asset := awsecrassets.NewDockerImageAsset(stack, jsii.String("MyBuildImage"), &awsecrassets.DockerImageAssetProps{ - Directory: jsii.String(path.Join(dirName, "my-image")), -}) - -taskDefinition.AddContainer(jsii.String("MyOtherContainer"), &awsecs.ContainerDefinitionOptions{ - Image: awsecs.ContainerImage_FromDockerImageAsset(asset), -}) ----- -==== - - -[#assets-types-docker-deploy] -=== 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. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -import * as ecs from 'aws-cdk-lib/aws-ecs'; -import * as path from 'path'; -import { DockerImageAsset } from 'aws-cdk-lib/aws-ecr-assets'; - -const asset = new DockerImageAsset(this, 'my-image', { - directory: path.join(__dirname, "..", "demo-image") -}); - -const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { - memoryLimitMiB: 1024, - cpu: 512 -}); - -taskDefinition.addContainer("my-other-container", { - image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri.split(":").pop()) -}); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -const ecs = require('aws-cdk-lib/aws-ecs'); -const path = require('path'); -const { DockerImageAsset } = require('aws-cdk-lib/aws-ecr-assets'); - -const asset = new DockerImageAsset(this, 'my-image', { - directory: path.join(__dirname, "..", "demo-image") -}); - -const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { - memoryLimitMiB: 1024, - cpu: 512 -}); - -taskDefinition.addContainer("my-other-container", { - image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri.split(":").pop()) -}); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -import aws_cdk.aws_ecs as ecs -from aws_cdk.aws_ecr_assets import DockerImageAsset - -import os.path -dirname = os.path.dirname(__file__) - -asset = DockerImageAsset(self, 'my-image', - directory=os.path.join(dirname, "..", "demo-image")) - -task_definition = ecs.FargateTaskDefinition(self, "TaskDef", - memory_limit_mib=1024, cpu=512) - -task_definition.add_container("my-other-container", - image=ecs.ContainerImage.from_ecr_repository( - asset.repository, asset.image_uri.rpartition(":")[-1])) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -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#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -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()) -}); ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -import ( - "os" - "path" - - "github.com/aws/aws-cdk-go/awscdk/v2" - "github.com/aws/aws-cdk-go/awscdk/v2/awsecrassets" - "github.com/aws/aws-cdk-go/awscdk/v2/awsecs" -) - -dirName, err := os.Getwd() -if err != nil { - panic(err) -} - -asset := awsecrassets.NewDockerImageAsset(stack, jsii.String("MyImage"), &awsecrassets.DockerImageAssetProps{ - Directory: jsii.String(path.Join(dirName, "demo-image")), -}) - -taskDefinition := awsecs.NewFargateTaskDefinition(stack, jsii.String("TaskDef"), &awsecs.FargateTaskDefinitionProps{ - MemoryLimitMiB: jsii.Number(1024), - Cpu: jsii.Number(512), -}) - -taskDefinition.AddContainer(jsii.String("MyOtherContainer"), &awsecs.ContainerDefinitionOptions{ - Image: awsecs.ContainerImage_FromEcrRepository(asset.Repository(), asset.ImageTag()), -}) ----- -==== - -[#assets-types-docker-build] -=== 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. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -const asset = new DockerImageAsset(this, 'MyBuildImage', { - directory: path.join(__dirname, 'my-image'), - buildArgs: { - HTTP_PROXY: 'http://10.20.30.2:1234' - } -}); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -const asset = new DockerImageAsset(this, 'MyBuildImage', { - directory: path.join(__dirname, 'my-image'), - buildArgs: { - HTTP_PROXY: 'http://10.20.30.2:1234' - } -}); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -asset = DockerImageAsset(self, "MyBuildImage", - directory=os.path.join(dirname, "my-image"), - build_args=dict(HTTP_PROXY="http://10.20.30.2:1234")) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -DockerImageAsset asset = DockerImageAsset.Builder.create(this, "my-image"), - .directory(new File(startDir, "my-image").toString()) - .buildArgs(java.util.Map.of( // Java 9 or later - "HTTP_PROXY", "http://10.20.30.2:1234")) - .build(); ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -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" - } -}); ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -dirName, err := os.Getwd() -if err != nil { - panic(err) -} - -asset := awsecrassets.NewDockerImageAsset(stack, jsii.String("MyBuildImage"), &awsecrassets.DockerImageAssetProps{ - Directory: jsii.String(path.Join(dirName, "my-image")), - BuildArgs: &map[string]*string{ - "HTTP_PROXY": jsii.String("http://10.20.30.2:1234"), - }, -}) ----- -==== - -[#assets-types-docker-permissions] -=== Permissions - -If you use a module that supports Docker image assets, such as https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs-readme.html[`aws-ecs`], the {aws} CDK manages permissions for you when you use assets directly or through https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.ContainerImage.html#static-fromwbrecrwbrrepositoryrepository-tag[`ContainerImage.fromEcrRepository`] (Python: `from_ecr_repository`). If you use Docker image assets directly, make sure that the consuming principal has permissions to pull the image. - -In most cases, you should use https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr.Repository.html#grantwbrpullgrantee[`asset.repository.grantPull`] method (Python: `grant_pull`). This modifies the IAM policy of the principal to enable it to pull images from this repository. If the principal that is pulling the image is not in the same account, or if it's an {aws} service that doesn't assume a role in your account (such as {aws} CodeBuild), you must grant pull permissions on the resource policy and not on the principal's policy. Use the https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr.Repository.html#addwbrtowbrresourcewbrpolicystatement[`asset.repository.addToResourcePolicy`] method (Python: `add_to_resource_policy`) to grant the appropriate principal permissions. - -[#assets-cfn] -== {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 xref:sam[{aws} SAM integration] for details. - -==== - -To enable such use cases, external tools consult a set of metadata entries on {aws} CloudFormation resources: - -* `aws:asset:path` – Points to the local path of the asset. -* `aws:asset:property` – The name of the resource property where the asset is used. - -Using these two metadata entries, tools can identify that assets are used by a certain resource, and enable advanced local experiences. - -To add these metadata entries to a resource, use the `asset.addResourceMetadata` (Python: `add_resource_metadata`) method. \ No newline at end of file diff --git a/v2/guide/attributes.txt b/v2/guide/attributes.txt deleted file mode 100644 index 39276e28..00000000 --- a/v2/guide/attributes.txt +++ /dev/null @@ -1,4 +0,0 @@ -// Entities that differ depending on the AWS Region build such as China -:arn-aws: pass:q[[.shared]``region.arn``] -:aws: pass:q[[.shared]``AWS``] -:aws-management-console: pass:q[[.shared]``consolelong``] diff --git a/v2/guide/best-practices-security.adoc b/v2/guide/best-practices-security.adoc deleted file mode 100644 index a17049c5..00000000 --- a/v2/guide/best-practices-security.adoc +++ /dev/null @@ -1,133 +0,0 @@ -include::attributes.txt[] - -// Attributes - -[.topic] -[[best-practices-security,best-practices-security.title]] -= {aws} CDK security best practices -:info_titleabbrev: Security -:keywords: {aws} CDK, IAM, security, permissions, infrastructure, {aws} CloudFormation, {aws} CDK deployments - -[abstract] --- -The {aws} Cloud Development Kit ({aws} CDK) is a powerful tool that developers can use to configure {aws} services and provision infrastructure on {aws}. With any tool that provides such control and capabilities, organizations will need to establish policies and practices to ensure that the tool is being used in safe and secure ways. For example, organizations may want to restrict developer access to specific services to ensure that they can't tamper with compliance or cost control measures that are configured in the account. --- - -// Content start - -The {aws} Cloud Development Kit ({aws} CDK) is a powerful tool that developers can use to configure {aws} services and provision infrastructure on {aws}. With any tool that provides such control and capabilities, organizations will need to establish policies and practices to ensure that the tool is being used in safe and secure ways. For example, organizations may want to restrict developer access to specific services to ensure that they can't tamper with compliance or cost control measures that are configured in the account. - -Often, there can be a tension between security and productivity, and each organization needs to establish the proper balance for themselves. This topic provides security best practices for the {aws} CDK that you can consider as you create and implement your own security policies. The following best practices are general guidelines and don`'t represent a complete security solution. Because these best practices might not be appropriate or sufficient for your environment, treat them as helpful considerations rather than prescriptions. - -[#best-practices-security-iam] -== Follow IAM security best practices - -{aws} Identity and Access Management (IAM) is a web service that helps you securely control access to {aws} resources. Organizations, individuals, and the {aws} CDK use IAM to manage permissions that determine the actions that can be performed on {aws} resources. When using IAM, follow the IAM security best practices. For more information, see https://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPracticesAndUseCases.html[Security best practices and use cases in {aws} Identity and Access Management] in the _IAM User Guide_. - -[#best-practices-security-permissions] -== Manage permissions for the {aws} CDK - -When you use the {aws} CDK across your organization to develop and manage your infrastructure, you'll want to consider the following scenarios where managing permissions will be important: - -* *Permissions for {aws} CDK deployments* – These permissions determine who can make changes to your {aws} resources and what changes they can make. -* *Permissions between resources* – These are the permissions that allow interactions between the {aws} resources that you create and manage with the {aws} CDK. - -[#best-practices-security-permissions-deployments] -=== Manage permissions for {aws} CDK deployments - -Developers use the {aws} CDK to define infrastructure locally on their development machines. This infrastructure is implemented in {aws} environments through deployments that typically involve using the {aws} CDK Command Line Interface ({aws} CDK CLI). With deployments, you may want to control what changes developers can make in your environments. For example, you might have an Amazon Virtual Private Cloud (Amazon VPC) resource that you don't want developers to modify. - -By default, the CDK CLI uses a combination of the actor's security credentials and IAM roles that are created during bootstrapping to receive permissions for deployments. The actor's security credentials are first used for authentication and IAM roles are then assumed to perform various actions during deployment, such as using the {aws} CloudFormation service to create resources. For more information on how CDK deployments work, including the IAM roles that are used, see xref:deploy[Deploy {aws} CDK applications]. - -To restrict who can perform deployments and the actions that can be performed during deployment, consider the following: - -* The actor's security credentials are the first set of credentials used to authenticate to {aws}. From here, the permissions used to perform actions during deployment are granted to the IAM roles that are assumed during the deployment workflow. You can restrict who can perform deployments by limiting who can assume these roles. You can also restrict the actions that can be performed during deployment by replacing these IAM roles with your own. -* Permissions for performing deployments are given to the `DeploymentActionRole`. You can control permissions for who can perform deployments by limiting who can assume this role. By using a role for deployments, you can perform cross-account deployments since the role can be assumed by {aws} identities in a different account. By default, all identities in the same {aws} account with the appropriate `AssumeRole` policy statement can assume this role. -* Permissions for creating and modifying resources through {aws} CloudFormation are given to the `CloudFormationExecutionRole`. This role also requires permission to read from the bootstrap resources. You control the permissions that CDK deployments have by using a managed policy for the `CloudFormationExecutionRole` and optionally by configuring a permissions boundary. By default, this role has `AdministratorAccess` permissions with no permission boundary. -* Permissions for interacting with bootstrap resources are given to the `FilePublishingRole` and `ImagePublishingRole`. The actor performing deployments must have permission to assume these roles. By default, all identities in the same {aws} account with the appropriate `AssumeRole` policy statement can assume this role. -* Permissions for accessing bootstrap resources to perform lookups are given to the `LookupRole`. The actor performing deployments must have permission to assume this role. By default, this role has `readOnly` access to the bootstrap resources. By default, all identities in the same {aws} account with the appropriate `AssumeRole` policy statement can assume this role. - -To configure the IAM identities in your {aws} account with permission to assume these roles, add a policy with the following policy statement to the identities: - -[source,json,subs="verbatim,attributes"] ----- -{ - "Version": "2012-10-17", - "Statement": [{ - "Sid": "AssumeCDKRoles", - "Effect": "Allow", - "Action": "sts:AssumeRole", - "Resource": "*", - "Condition": { - "StringEquals": { - "iam:ResourceTag/aws-cdk:bootstrap-role": [ - "image-publishing", - "file-publishing", - "deploy", - "lookup" - ] - } - } - }] -} ----- - -[#best-practices-security-permissions-deployments-roles] -==== Modify the permissions for the roles assumed during deployment - -By modifying permissions for the roles assumed during deployment, you can manage the actions that can be performed during deployment. To modify permissions, you create your own IAM roles and specify them when bootstrapping your environment. When you customize bootstrapping, you will have to customize synthesis. For general instructions, see xref:bootstrapping-customizing[Customize {aws} CDK bootstrapping]. - -[#best-practices-security-permissions-deployments-creds] -==== Modify the security credentials and roles used during deployment - -The roles and bootstrap resources that are used during deployments are determined by the CDK stack synthesizer that you use. To modify this behavior, you can customize synthesis. For more information, see xref:configure-synth[Configure and perform CDK stack synthesis]. - -[#best-practices-security-permissions-deployments-least] -==== Considerations for granting least privilege access - -Granting least privilege access is a security best practice that we recommend that you consider as you develop your security strategy. For more information, see link:https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/sec_permissions_least_privileges.html[SEC03-BP02 Grant least privilege access] in the _{aws} Well-Architected Framework Guide_. - -Often, granting least privilege access involves restricting IAM policies to the minimum access necessary to perform a given task. Attempting to grant least privilege access through fine-grained permissions with the CDK using this approach can impact CDK deployments and cause you to have to create wider-scoped permissions than you`'d like. The following are a few things to consider when using this approach: - -* Determining an exhaustive list of permissions that allow developers to use the {aws} CDK to provision infrastructure through CloudFormation is difficult and complex. -* If you want to be fine-grained, permissions may become too long to fit within the maximum length of IAM policy documents. -* Providing an incomplete set of permissions can severely impact developer productivity and deployments. - -With the CDK, deployments are performed using CloudFormation. CloudFormation initiates a set of {aws} API calls in order using the permissions that are provided. The permissions necessary at any point in time depends on many factors: - -* The {aws} services that are being modified. Specifically, the resources and properties that are being used and changed. -* The current state of the CloudFormation stack. -* Issues that may occur during deployments and if rollbacks are needed, which will require `Delete` permissions in addition to `Create`. - -When the provided permissions are incomplete, manual intervention will be required. The following are a few examples: - -* If you discover incomplete permissions during roll forward, you'll need to pause deployment, and take time to discuss and provision new permissions before continuing. -* If deployment rolls back and the permissions to apply the roll back are missing, it may leave your CloudFormation stack in a state that will require a lot of manual work to recover from. - -Since this approach can result in complications and severely limit developer productivity, we don't recommend it. Instead, we recommend implementing guardrails and preventing bypass. - -[#best-practices-security-permissions-deployments-guardrails] -==== Implementing guardrails and preventing bypass - -You can implement guardrails, compliance rules, auditing, and monitoring by using services such as {aws} Control Tower, {aws} Config, {aws} CloudTrail, {aws} Security Hub, and others. With this approach, you grant developers permission to do everything, except tampering with the existing validation mechanisms. Developers have the freedom to implement changes quickly, as long as they stay within policy. This is the approach we recommend when using the {aws} CDK. For more information on guardrails, see https://docs.aws.amazon.com/wellarchitected/latest/management-and-governance-guide/controls.html[Controls] in the _Management and Governance Cloud Environment Guide_. - -We also recommend using _permissions boundaries_ or _service control policies (SCPs)_ as a way of implementing guardrails. For more information on implementing permissions boundaries with the {aws} CDK, see xref:customize-permissions-boundaries[Create and apply permissions boundaries for the {aws} CDK]. - -If you are using any compliance control mechanisms, set them up during the bootstrapping phase. Make sure that the `CloudFormationExecutionRole` or developer-accessible identities have policies or permissions boundaries attached that prevent bypass of the mechanisms that you put in place. The appropriate policies depends on the specific mechanisms that you use. - -[#best-practices-security-permissions-resources] -=== Manage permissions between resources provisioned by the {aws} CDK - -How you manage permissions between resources that are provisioned by the {aws} CDK depends on whether you allow the CDK to create roles and policies. - -When you use L2 constructs from the {aws} Construct Library to define your infrastructure, you can use the provided `grant` methods to provision permissions between resources. With `grant` methods, you specify the type of access you want between resources and the {aws} CDK provisions least privilege IAM roles to accomplish your intent. This approach meets security requirements for most organizations while being efficient for developers. For more information, see xref:define-iam-l2[Define permissions for L2 constructs with the {aws} CDK]. - -If you want to work around this feature by replacing the automatically generated roles with manually created ones, consider the following: - -* Your IAM roles will need to be manually created, slowing down application development. -* When IAM roles need to be manually created and managed, people will often combine multiple logical roles into a single role to make them easier to manage. This runs counter to the least privilege principle. -* Since these roles will need to be created before deployment, the resources that need to be referenced will not yet exist. Therefore, you`'ll need to use wildcards, which runs counter to the least privilege principle. -* A common workaround to using wildcards is to mandate that all resources be given a predictable name. However, this interferes with CloudFormation`'s ability to replace resources when necessary and may slow down or block development. Because of this, we recommend that you allow CloudFormation to create unique resource names for you. -* It will be impossible to perform continuous delivery since manual actions must be performed prior to every deployment. - -When organizations want to prevent the CDK from creating roles, it is usually to prevent developers from being able to create IAM roles. The concern is that by giving developers permission to create IAM roles using the {aws} CDK, they could possibly elevate their own privileges. To mitigate against this, we recommend using _permission boundaries_ or _service control policies (SCPs)_. With permission boundaries, you can set limits for what developers and the CDK are allowed to do. For more information on using permission boundaries with the CDK, see xref:customize-permissions-boundaries[Create and apply permissions boundaries for the {aws} CDK]. \ No newline at end of file diff --git a/v2/guide/best-practices.adoc b/v2/guide/best-practices.adoc deleted file mode 100644 index 0e9d3d9b..00000000 --- a/v2/guide/best-practices.adoc +++ /dev/null @@ -1,241 +0,0 @@ -include::attributes.txt[] - -// Attributes - -[.topic] -[#best-practices] -= Best practices for developing and deploying cloud infrastructure with the {aws} CDK -:info_titleabbrev: Best practices - -// Content start - -With the {aws} CDK, developers or administrators can define their cloud infrastructure by using a supported programming language. CDK applications should be organized into logical units, such as API, database, and monitoring resources, and optionally have a pipeline for automated deployments. The logical units should be implemented as constructs including the following: - -* Infrastructure (such as Amazon S3 buckets, Amazon RDS databases, or an Amazon VPC network) -* Runtime code (such as {aws} Lambda functions) -* Configuration code - -Stacks define the deployment model of these logical units. For a more detailed introduction to the concepts behind the CDK, see xref:getting-started[Getting started with the {aws} CDK]. - -The {aws} CDK reflects careful consideration of the needs of our customers and internal teams and of the failure patterns that often arise during the deployment and ongoing maintenance of complex cloud applications. We discovered that failures are often related to "out-of-band" changes to an application that aren't fully tested, such as configuration changes. Therefore, we developed the {aws} CDK around a model in which your entire application is defined in code, not only business logic but also infrastructure and configuration. That way, proposed changes can be carefully reviewed, comprehensively tested in environments resembling production to varying degrees, and fully rolled back if something goes wrong. - -image::./images/all-in-one.jpg["Software development lifecycle icons representing infrastructure, application, source code, configuration, and deployment.",scaledwidth=100%] - -At deployment time, the {aws} CDK synthesizes a cloud assembly that contains the following: - -* {aws} CloudFormation templates that describe your infrastructure in all target environments -* File assets that contain your runtime code and their supporting files - -With the CDK, every commit in your application's main version control branch can represent a complete, consistent, deployable version of your application. Your application can then be deployed automatically whenever a change is made. - -The philosophy behind the {aws} CDK leads to our recommended best practices, which we have divided into four broad categories. - -* xref:best-practices-organization[Organization best practices] -* xref:best-practices-code[Coding best practices] -* xref:best-practices-constructs[Construct best practices] -* xref:best-practices-apps[Application best practices] - -[TIP] -==== - -Also consider https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html[best practices for {aws} CloudFormation] and the individual {aws} services that you use, where applicable to CDK-defined infrastructure. - -==== - -[#best-practices-organization] -== Organization best practices - -In the beginning stages of {aws} CDK adoption, it's important to consider how to set up your organization for success. It's a best practice to have a team of experts responsible for training and guiding the rest of the company as they adopt the CDK. The size of this team might vary, from one or two people at a small company to a full-fledged Cloud Center of Excellence (CCoE) at a larger company. This team is responsible for setting standards and policies for cloud infrastructure at your company, and also for training and mentoring developers. - -The CCoE might provide guidance on what programming languages should be used for cloud infrastructure. Details will vary from one organization to the next, but a good policy helps make sure that developers can understand and maintain the company's cloud infrastructure. - -The CCoE also creates a "landing zone" that defines your organizational units within {aws}. A landing zone is a pre-configured, secure, scalable, multi-account {aws} environment based on best practice blueprints. To tie together the services that make up your landing zone, you can use https://aws.amazon.com/controltower/[{aws} Control Tower], which configures and manages your entire multi-account system from a single user interface. - -Development teams should be able to use their own accounts for testing and deploy new resources in these accounts as needed. Individual developers can treat these resources as extensions of their own development workstation. Using xref:cdk-pipeline[CDK Pipelines], the {aws} CDK applications can then be deployed via a CI/CD account to testing, integration, and production environments (each isolated in its own {aws} Region or account). This is done by merging the developers' code into your organization's canonical repository. - -image::./images/best-practice-deploy-to-multiple-accounts.png["Diagram showing deployment process from developer accounts to multiple target accounts via CI/CD pipeline.",scaledwidth=100%] - -[#best-practices-code] -== Coding best practices - -This section presents best practices for organizing your {aws} CDK code. The following diagram shows the relationship between a team and that team's code repositories, packages, applications, and construct libraries. - -image::./images/code-organization.jpg["Diagram showing team's code organization: repository, package, CDK app or construct library.",scaledwidth=100%] - -[#best-practices-code-kiss] -*Start simple and add complexity only when you need it*:: -+ -The guiding principle for most of our best practices is to keep things simple as possible--but no simpler. Add complexity only when your requirements dictate a more complicated solution. With the {aws} CDK, you can refactor your code as necessary to support new requirements. You don't have to architect for all possible scenarios upfront. - -[#best-practices-code-well-architected] -*Align with the {aws} Well-Architected Framework*:: -+ -The https://aws.amazon.com/architecture/well-architected/[{aws} Well-Architected] Framework defines a _component_ as the code, configuration, and {aws} resources that together deliver against a requirement. A component is often the unit of technical ownership, and is decoupled from other components. The term _workload_ is used to identify a set of components that together deliver business value. A workload is usually the level of detail that business and technology leaders communicate about. -+ -An {aws} CDK application maps to a component as defined by the {aws} Well-Architected Framework. {aws} CDK apps are a mechanism to codify and deliver Well-Architected cloud application best practices. You can also create and share components as reusable code libraries through artifact repositories, such as {aws} CodeArtifact. - -[#best-practices-code-package] -*Every application starts with a single package in a single repository*:: -+ -A single package is the entry point of your {aws} CDK app. Here, you define how and where to deploy the different logical units of your application. You also define the CI/CD pipeline to deploy the application. The app's constructs define the logical units of your solution. -+ -Use additional packages for constructs that you use in more than one application. (Shared constructs should also have their own lifecycle and testing strategy.) Dependencies between packages in the same repository are managed by your repo's build tooling. -+ -Although it's possible, we don't recommend putting multiple applications in the same repository, especially when using automated deployment pipelines. Doing this increases the "blast radius" of changes during deployment. When there are multiple applications in a repository, changes to one application trigger deployment of the others (even if the others haven't changed). Furthermore, a break in one application prevents the other applications from being deployed. - -[#best-practices-code-repo] -*Move code into repositories based on code lifecycle or team ownership*:: -+ -When packages begin to be used in multiple applications, move them to their own repository. This way, the packages can be referenced by application build systems that use them, and they can also be updated on cadences independent of the application lifecycles. However, at first it might make sense to put all shared constructs in one repository. -+ -Also, move packages to their own repository when different teams are working on them. This helps enforce access control. -+ -To consume packages across repository boundaries, you need a private package repository--similar to NPM, PyPi, or Maven Central, but internal to your organization. You also need a release process that builds, tests, and publishes the package to the private package repository. https://docs.aws.amazon.com/codeartifact/latest/ug/[CodeArtifact] can host packages for most popular programming languages. -+ -Dependencies on packages in the package repository are managed by your language's package manager, such as NPM for TypeScript or JavaScript applications. Your package manager helps to make sure that builds are repeatable. It does this by recording the specific versions of every package that your application depends on. It also lets you upgrade those dependencies in a controlled manner. -+ -Shared packages need a different testing strategy. For a single application, it might be good enough to deploy the application to a testing environment and confirm that it still works. But shared packages must be tested independently of the consuming application, as if they were being released to the public. (Your organization might choose to actually release some shared packages to the public.) -+ -Keep in mind that a construct can be arbitrarily simple or complex. A `Bucket` is a construct, but `CameraShopWebsite` could be a construct, too. - -[#best-practices-code-all] -*Infrastructure and runtime code live in the same package*:: -+ -In addition to generating {aws} CloudFormation templates for deploying infrastructure, the {aws} CDK also bundles runtime assets like Lambda functions and Docker images and deploys them alongside your infrastructure. This makes it possible to combine the code that defines your infrastructure and the code that implements your runtime logic into a single construct. It's a best practice to do this. These two kinds of code don't need to live in separate repositories or even in separate packages. -+ -To evolve the two kinds of code together, you can use a self-contained construct that completely describes a piece of functionality, including its infrastructure and logic. With a self-contained construct, you can test the two kinds of code in isolation, share and reuse the code across projects, and version all the code in sync. - -[#best-practices-constructs] -== Construct best practices - -This section contains best practices for developing constructs. Constructs are reusable, composable modules that encapsulate resources. They're the building blocks of {aws} CDK apps. - -[#best-practices-constructs-model] -*Model with constructs, deploy with stacks*:: -+ -Stacks are the unit of deployment: everything in a stack is deployed together. So when building your application's higher-level logical units from multiple {aws} resources, represent each logical unit as a https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html[Construct], not as a https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html[Stack]. Use stacks only to describe how your constructs should be composed and connected for your various deployment scenarios. -+ -For example, if one of your logical units is a website, the constructs that make it up (such as an Amazon S3 bucket, API Gateway, Lambda functions, or Amazon RDS tables) should be composed into a single high-level construct. Then that construct should be instantiated in one or more stacks for deployment. -+ -By using constructs for building and stacks for deploying, you improve reuse potential of your infrastructure and give yourself more flexibility in how it's deployed. - -[#best-practices-constructs-config] -*Configure with properties and methods, not environment variables*:: -+ -Environment variable lookups inside constructs and stacks are a common anti-pattern. Both constructs and stacks should accept a properties object to allow for full configurability completely in code. Doing otherwise introduces a dependency on the machine that the code will run on, which creates yet more configuration information that you have to track and manage. -+ -In general, environment variable lookups should be limited to the top level of an {aws} CDK app. They should also be used to pass in information that's needed for running in a development environment. For more information, see xref:environments[Environments for the {aws} CDK]. - -[#best-practices-constructs-test] -*Unit test your infrastructure*:: -+ -To consistently run a full suite of unit tests at build time in all environments, avoid network lookups during synthesis and model all your production stages in code. (These best practices are covered later.) If any single commit always results in the same generated template, you can trust the unit tests that you write to confirm that the generated templates look the way you expect. For more information, see xref:testing[Test {aws} CDK applications]. - -[#best-practices-constructs-logicalid] -*Don't change the logical ID of stateful resources*:: -+ -Changing the logical ID of a resource results in the resource being replaced with a new one at the next deployment. For stateful resources like databases and S3 buckets, or persistent infrastructure like an Amazon VPC, this is seldom what you want. Be careful about any refactoring of your {aws} CDK code that could cause the ID to change. Write unit tests that assert that the logical IDs of your stateful resources remain static. The logical ID is derived from the `id` you specify when you instantiate the construct, and the construct's position in the construct tree. For more information, see xref:identifiers-logical-ids[Logical IDs]. - -[#best-practices-constructs-compliance] -*Constructs aren't enough for compliance*:: -+ -Many enterprise customers write their own wrappers for L2 constructs (the "curated" constructs that represent individual {aws} resources with built-in sane defaults and best practices). These wrappers enforce security best practices such as static encryption and specific IAM policies. For example, you might create a `MyCompanyBucket` that you then use in your applications in place of the usual Amazon S3 `Bucket` construct. This pattern is useful for surfacing security guidance early in the software development lifecycle, but don't rely on it as the sole means of enforcement. -+ -Instead, use {aws} features such as link:https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html[service control policies] and link:https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html[permission boundaries] to enforce your security guardrails at the organization level. Use xref:aspects[Aspects and the {aws} CDK] or tools like https://github.com/aws-cloudformation/cloudformation-guard[CloudFormation Guard] to make assertions about the security properties of infrastructure elements before deployment. Use {aws} CDK for what it does best. -+ -Finally, keep in mind that writing your own "L2+" constructs might prevent your developers from taking advantage of {aws} CDK packages such as https://docs.aws.amazon.com/solutions/latest/constructs/welcome.html[{aws} Solutions Constructs] or third-party constructs from Construct Hub. These packages are typically built on standard {aws} CDK constructs and won't be able to use your wrapper constructs. - -[#best-practices-apps] -== Application best practices - -In this section we discuss how to write your {aws} CDK applications, combining constructs to define how your {aws} resources are connected. - -[#best-practices-apps-synth] -*Make decisions at synthesis time*:: -+ -Although {aws} CloudFormation lets you make decisions at deployment time (using `Conditions`, `{ Fn::If }`, and `Parameters`), and the {aws} CDK gives you some access to these mechanisms, we recommend against using them. The types of values that you can use and the types of operations you can perform on them are limited compared to what's available in a general-purpose programming language. -+ -Instead, try to make all decisions, such as which construct to instantiate, in your {aws} CDK application by using your programming language's `if` statements and other features. For example, a common CDK idiom, iterating over a list and instantiating a construct with values from each item in the list, simply isn't possible using {aws} CloudFormation expressions. -+ -Treat {aws} CloudFormation as an implementation detail that the {aws} CDK uses for robust cloud deployments, not as a language target. You're not writing {aws} CloudFormation templates in TypeScript or Python, you're writing CDK code that happens to use CloudFormation for deployment. - -[#best-practices-apps-names] -*Use generated resource names, not physical names*:: -+ -Names are a precious resource. Each name can only be used once. Therefore, if you hardcode a table name or bucket name into your infrastructure and application, you can't deploy that piece of infrastructure twice in the same account. (The name we're talking about here is the name specified by, for example, the `bucketName` property on an Amazon S3 bucket construct.) -+ -What's worse, you can't make changes to the resource that require it to be replaced. If a property can only be set at resource creation, such as the `KeySchema` of an Amazon DynamoDB table, then that property is immutable. Changing this property requires a new resource. However, the new resource must have the same name in order to be a true replacement. But it can't have the same name while the existing resource is still using that name. -+ -A better approach is to specify as few names as possible. If you omit resource names, the {aws} CDK will generate them for you in a way that won't cause problems. Suppose you have a table as a resource. You can then pass the generated table name as an environment variable into your {aws} Lambda function. In your {aws} CDK application, you can reference the table name as `table.tableName`. Alternatively, you can generate a configuration file on your Amazon EC2 instance on startup, or write the actual table name to the {aws} Systems Manager Parameter Store so your application can read it from there. -+ -If the place you need it is another {aws} CDK stack, that's even more straightforward. Supposing that one stack defines the resource and another stack needs to use it, the following applies: -+ -* If the two stacks are in the same {aws} CDK app, pass a reference between the two stacks. For example, save a reference to the resource's construct as an attribute of the defining stack (`this.stack.uploadBucket = amzn-s3-demo-bucket`). Then, pass that attribute to the constructor of the stack that needs the resource. -* When the two stacks are in different {aws} CDK apps, use a static `from` method to use an externally defined resource based on its ARN, name, or other attributes. (For example, use `Table.fromArn()` for a DynamoDB table). Use the `CfnOutput` construct to print the ARN or other required value in the output of `cdk deploy`, or look in the {aws} Management Console. Alternatively, the second app can read the CloudFormation template generated by the first app and retrieve that value from the `Outputs` section. - -[#best-practices-apps-removal-logs] -*Define removal policies and log retention*:: -+ -The {aws} CDK attempts to keep you from losing data by defaulting to policies that retain everything you create. For example, the default removal policy on resources that contain data (such as Amazon S3 buckets and database tables) is not to delete the resource when it is removed from the stack. Instead, the resource is orphaned from the stack. Similarly, the CDK's default is to retain all logs forever. In production environments, these defaults can quickly result in the storage of large amounts of data that you don't actually need, and a corresponding {aws} bill. -+ -Consider carefully what you want these policies to be for each production resource and specify them accordingly. Use xref:aspects[Aspects and the {aws} CDK] to validate the removal and logging policies in your stack. - -[#best-practices-apps-separate] -*Separate your application into multiple stacks as dictated by deployment requirements*:: -+ -There is no hard and fast rule to how many stacks your application needs. You'll usually end up basing the decision on your deployment patterns. Keep in mind the following guidelines: -+ -* It's typically more straightforward to keep as many resources in the same stack as possible, so keep them together unless you know you want them separated. -* Consider keeping stateful resources (like databases) in a separate stack from stateless resources. You can then turn on termination protection on the stateful stack. This way, you can freely destroy or create multiple copies of the stateless stack without risk of data loss. -* Stateful resources are more sensitive to construct renaming--renaming leads to resource replacement. Therefore, don't nest stateful resources inside constructs that are likely to be moved around or renamed (unless the state can be rebuilt if lost, like a cache). This is another good reason to put stateful resources in their own stack. - -[#best-practices-apps-context] -*Commit `cdk.context.json` to avoid non-deterministic behavior*:: -+ -Determinism is key to successful {aws} CDK deployments. An {aws} CDK app should have essentially the same result whenever it is deployed to a given environment. -+ -Since your {aws} CDK app is written in a general-purpose programming language, it can execute arbitrary code, use arbitrary libraries, and make arbitrary network calls. For example, you could use an {aws} SDK to retrieve some information from your {aws} account while synthesizing your app. Recognize that doing so will result in additional credential setup requirements, increased latency, and a chance, however small, of failure every time you run `cdk synth`. -+ -Never modify your {aws} account or resources during synthesis. Synthesizing an app should not have side effects. Changes to your infrastructure should happen only in the deployment phase, after the {aws} CloudFormation template has been generated. This way, if there's a problem, {aws} CloudFormation can automatically roll back the change. To make changes that can't be easily made within the {aws} CDK framework, use link:https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.custom_resources-readme.html[custom resources] to execute arbitrary code at deployment time. -+ -Even strictly read-only calls are not necessarily safe. Consider what happens if the value returned by a network call changes. What part of your infrastructure will that impact? What will happen to already-deployed resources? Following are two example situations in which a sudden change in values might cause a problem. -+ --- -* If you provision an Amazon VPC to all available Availability Zones in a specified Region, and the number of AZs is two on deployment day, then your IP space gets split in half. If {aws} launches a new Availability Zone the next day, the next deployment after that tries to split your IP space into thirds, requiring all subnets to be recreated. This probably won't be possible because your Amazon EC2 instances are still running, and you'll have to clean this up manually. -* If you query for the latest Amazon Linux machine image and deploy an Amazon EC2 instance, and the next day a new image is released, a subsequent deployment picks up the new AMI and replaces all your instances. This might not be what you expected to happen. --- -+ -These situations can be pernicious because the {aws}-side change might occur after months or years of successful deployments. Suddenly your deployments are failing "for no reason" and you long ago forgot what you did and why. -+ -Fortunately, the {aws} CDK includes a mechanism called _context providers_ to record a snapshot of non-deterministic values. This allows future synthesis operations to produce exactly the same template as they did when first deployed. The only changes in the new template are the changes that _you_ made in your code. When you use a construct's `.fromLookup()` method, the result of the call is cached in `cdk.context.json`. You should commit this to version control along with the rest of your code to make sure that future executions of your CDK app use the same value. The CDK Toolkit includes commands to manage the context cache, so you can refresh specific entries when you need to. For more information, see xref:context[Context values and the {aws} CDK]. -+ -If you need some value (from {aws} or elsewhere) for which there is no native CDK context provider, we recommend writing a separate script. The script should retrieve the value and write it to a file, then read that file in your CDK app. Run the script only when you want to refresh the stored value, not as part of your regular build process. - -[#best-practices-apps-roles] -*Let the {aws} CDK manage roles and security groups*:: -+ -With the {aws} CDK construct library's `grant()` convenience methods, you can create {aws} Identity and Access Management roles that grant access to one resource by another using minimally scoped permissions. For example, consider a line like the following: -+ -[source,javascript,subs="verbatim,attributes"] ----- -amzn-s3-demo-bucket.grantRead(myLambda) ----- -+ -This single line adds a policy to the Lambda function's role (which is also created for you). That role and its policies are more than a dozen lines of CloudFormation that you don't have to write. The {aws} CDK grants only the minimal permissions required for the function to read from the bucket. -+ -If you require developers to always use predefined roles that were created by a security team, {aws} CDK coding becomes much more complicated. Your teams could lose a lot of flexibility in how they design their applications. A better alternative is to use link:https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html[service control policies] and link:https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html[permission boundaries] to make sure that developers stay within the guardrails. - -[#best-practices-apps-stages] -*Model all production stages in code*:: -+ -In traditional {aws} CloudFormation scenarios, your goal is to produce a single artifact that is parameterized so that it can be deployed to various target environments after applying configuration values specific to those environments. In the CDK, you can, and should, build that configuration into your source code. Create a stack for your production environment, and create a separate stack for each of your other stages. Then, put the configuration values for each stack in the code. Use services like https://aws.amazon.com/secrets-manager/[Secrets Manager] and https://aws.amazon.com/systems-manager/[Systems Manager] Parameter Store for sensitive values that you don't want to check in to source control, using the names or ARNs of those resources. -+ -When you synthesize your application, the cloud assembly created in the `cdk.out` folder contains a separate template for each environment. Your entire build is deterministic. There are no out-of-band changes to your application, and any given commit always yields the exact same {aws} CloudFormation template and accompanying assets. This makes unit testing much more reliable. - -[#best-practices-apps-measure] -*Measure everything*:: -+ -Achieving the goal of full continuous deployment, with no human intervention, requires a high level of automation. That automation is only possible with extensive amounts of monitoring. To measure all aspects of your deployed resources, create metrics, alarms, and dashboards. Don't stop at measuring things like CPU usage and disk space. Also record your business metrics, and use those measurements to automate deployment decisions like rollbacks. Most of the L2 constructs in {aws} CDK have convenience methods to help you create metrics, such as the `metricUserErrors()` method on the link:https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_dynamodb.Table.html[`dynamodb.Table`] class. - - -include::best-practices-security.adoc[leveloffset=+1] \ No newline at end of file diff --git a/v2/guide/book.adoc b/v2/guide/book.adoc deleted file mode 100644 index 0ff49eb0..00000000 --- a/v2/guide/book.adoc +++ /dev/null @@ -1,76 +0,0 @@ -include::attributes.txt[] - -:doctype: book -:toc: left -:icons: font -:experimental: -:idprefix: -:idseparator: - -:info_subtitle: Developer Guide -:info_edition: 2 -:info_corpauthor: {aws} -:info_publisher: {aws} -:keywords: CDK, {aws} CDK, {aws} Cloud Development Kit -:info_copyright: 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. -:info_legalnotice: 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. - -[[top]] -= {aws} Cloud Development Kit ({aws} CDK) v2 - -[abstract] --- -Provides a conceptual overview and practical examples to help you understand the features provided by the {aws} CDK and how to use them. --- - -[.banner.info] -This is the {aws} CDK v2 Developer Guide. The older CDK v1 entered maintenance on June 1, 2022 and ended support on June 1, 2023. - -include::home.adoc[leveloffset=+1] - -include::core-concepts.adoc[leveloffset=+1] - -include::prerequisites.adoc[leveloffset=+1] - -include::getting-started.adoc[leveloffset=+1] - -include::work-with-cdk.adoc[leveloffset=+1] - -include::best-practices.adoc[leveloffset=+1] - -include::work-with-cdk-v2.adoc[leveloffset=+1] - -include::migrate.adoc[leveloffset=+1] - -include::configure-access.adoc[leveloffset=+1] - -include::configure-env.adoc[leveloffset=+1] - -include::bootstrapping-env.adoc[leveloffset=+1] - -include::chapter-develop.adoc[leveloffset=+1] - -include::configure-synth.adoc[leveloffset=+1] - -include::chapter-deploy.adoc[leveloffset=+1] - -include::toolkit-library.adoc[leveloffset=+1] - -include::testing.adoc[leveloffset=+1] - -include::cli.adoc[leveloffset=+1] - -include::ref-cli-cmd.adoc[leveloffset=+1] - -include::reference.adoc[leveloffset=+1] - -include::how-tos.adoc[leveloffset=+1] - -include::tools.adoc[leveloffset=+1] - -include::security.adoc[leveloffset=+1] - -include::troubleshooting.adoc[leveloffset=+1] - -include::pgp-keys.adoc[leveloffset=+1] - -include::doc-history.adoc[leveloffset=+1] \ No newline at end of file diff --git a/v2/guide/bootstrapping-customizing.adoc b/v2/guide/bootstrapping-customizing.adoc deleted file mode 100644 index c5c483b4..00000000 --- a/v2/guide/bootstrapping-customizing.adoc +++ /dev/null @@ -1,193 +0,0 @@ -include::attributes.txt[] - -// Attributes - -[.topic] -[#bootstrapping-customizing] -= Customize {aws} CDK bootstrapping -:info_titleabbrev: Customize bootstrapping -:keywords: {aws} CDK, {aws} Cloud Development Kit ({aws} CDK), {aws} account, {aws} Region, Bootstrapping, Bootstrap, Environment, Customize - -[abstract] --- -You can customize {aws} Cloud Development Kit ({aws} CDK) bootstrapping by using the {aws} CDK Command Line Interface ({aws} CDK CLI) or by modifying and deploying the {aws} CloudFormation bootstrap template. --- - -// Content start - -You can customize {aws} Cloud Development Kit ({aws} CDK) bootstrapping by using the {aws} CDK Command Line Interface ({aws} CDK CLI) or by modifying and deploying the {aws} CloudFormation bootstrap template. - -For an introduction to bootstrapping, see xref:bootstrapping[{aws} CDK bootstrapping]. - -[#bootstrapping-customizing-cli] -== Use the CDK CLI to customize bootstrapping - -The following are a few examples of how you can customize bootstrapping by using the CDK CLI. For a list of all `cdk bootstrap` options, see xref:ref-cli-cmd-bootstrap[cdk bootstrap]. - -[#bootstrapping-customizing-cli-s3-name] -*Override the name of the Amazon S3 bucket*:: -Use the `--bootstrap-bucket-name` option to override the default Amazon S3 bucket name. This may require that you modify template synthesis. For more information, see xref:bootstrapping-custom-synth[Customize CDK stack synthesis]. - -[#bootstrapping-customizing-keys] -*Modify server-side encryption keys for the Amazon S3 bucket*:: -By default, the Amazon S3 bucket in the bootstrap stack is configure to use {aws} managed keys for server-side encryption. To use an existing customer managed key, use the `--bootstrap-kms-key-id` option and provide a value for the {aws} Key Management Service ({aws} KMS) key to use. If you want more control over the encryption key, provide `--bootstrap-customer-key` to use a customer managed key. - -[#bootstrapping-customizing-cli-deploy-role] -*Attach managed policies to the deployment role assumed by {aws} CloudFormation*:: -By default, stacks are deployed with full administrator permissions using the `AdministratorAccess` policy. To use your own managed policies, use the `--cloudformation-execution-policies` option and provide the ARNs of the managed policies to attach to the deployment role. -+ -To provide multiple policies, pass them a single string, separated by commas: -+ -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap --cloudformation-execution-policies "arn:aws:iam::aws:policy/AWSLambda_FullAccess,arn:aws:iam::aws:policy/AWSCodeDeployFullAccess" ----- -+ -To avoid deployment failures, be sure that the policies you specify are sufficient for any deployments that you will perform into the environment being bootstrapped. -+ -[#bootstrapping-customizing-cli-qualifier] -*Change the qualifier that is added to the names of resources in your bootstrap stack*:: -By default, the `hnb659fds` qualifier is added to the physical ID of resources in your bootstrap stack. To change this value, use the `--qualifier` option. -+ -This modification is useful when provisioning multiple bootstrap stacks in the same environment to avoid name clashes. -+ -Changing the qualifier 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 CloudFormation execution role, there are no permission isolation benefits to having two different bootstrap stacks in a single account. Therefore, there's usually no need to change this value. -+ -When you change the qualifier, your CDK app must pass the changed value to the stack synthesizer. For more information, see xref:bootstrapping-custom-synth[Customize CDK stack synthesis]. -+ -[#bootstrapping-customizing-cli-tags] -*Add tags to the bootstrap stack*:: -Use the `--tags` option in the format of `KEY=VALUE` to add CloudFormation tags to your bootstrap stack. -+ -[#bootstrapping-customizing-cli-accounts-deploy] -*Specify additional {aws} accounts that can deploy into the environment being bootstrapped*:: -Use the `--trust` option to provide additional {aws} accounts that are allowed to deploy into the environment being bootstrapped. By default, the account performing the bootstrapping will always be trusted. -+ -This option is useful when you are bootstrapping an environment that a CDK [.noloc]`Pipeline` from another environment will deploy into. -+ -When you use this option, you must also provide `--cloudformation-execution-policies`. -+ -To add trusted accounts to an existing bootstrap stack, you must specify all of the accounts to trust, including those that you may have previously provided. If you only provide new accounts to trust, the previously trusted accounts will be removed. -+ -The following is an example that trusts two accounts: -+ -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap aws://123456789012/us-west-2 --trust 234567890123 --trust 987654321098 --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess - ⏳ Bootstrapping environment aws://123456789012/us-west-2... -Trusted accounts for deployment: 234567890123, 987654321098 -Trusted accounts for lookup: (none) -Execution policies: arn:aws:iam::aws:policy/AdministratorAccess -CDKToolkit: creating CloudFormation changeset... - ✅ Environment aws://123456789012/us-west-2 bootstrapped. ----- - -[#bootstrapping-customizing-cli-accounts-lookup] -*Specify additional {aws} accounts that can look up information in the environment being bootstrapped*:: -+ -Use the `--trust-for-lookup` option to specify {aws} accounts that are allowed to look up context information from the environment being bootstrapped. This option is useful to give accounts permission to synthesize stacks that will be deployed into the environment, without actually giving them permission to deploy those stacks directly. - -[#bootstrapping-customizing-cli-protection] -*Enable termination protection for the bootstrap stack*:: -If a bootstrap stack is deleted, the {aws} resources that were originally provisioned in the environment will also be deleted. After your environment is bootstrapped, we recommend that you don't delete and recreate the environment's bootstrap stack, unless you are intentionally doing so. Instead, try to update the bootstrap stack to a new version by running the `cdk bootstrap` command again. -+ -Use the `--termination-protection` option to manage termination protection settings for the bootstrap stack. By enabling termination protection, you prevent the bootstrap stack and its resources from being accidentally deleted. This is especially important if you use CDK [.noloc]`Pipelines` since there is no general recovery option if you accidentally delete the bootstrap stack. -+ -After enabling termination protection, you can use the {aws} CLI or {aws} CloudFormation console to verify. -+ -*To enable termination protection*::: -+ -. Run the following command to enable termination protection on a new or existing bootstrap stack: -+ -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap --termination-protection ----- -+ -. Use the {aws} CLI or CloudFormation console to verify. The following is an example, using the {aws} CLI. If you modified your bootstrap stack name, replace `CDKToolkit` with your stack name: -+ -[source,none,subs="verbatim,attributes"] ----- -$ aws cloudformation describe-stacks --stack-name --query "Stacks[0].EnableTerminationProtection" -true ----- - -[#bootstrapping-customizing-template] -== Modify the default bootstrap template - -When you need more customization than the CDK CLI can provide, you can modify the bootstrap template as needed. Then, deploy the template to bootstrap your environment. - -*To modify and deploy the default bootstrap template*:: -+ -. Obtain the default bootstrap template using the `--show-template` option. By default, the CDK CLI will output the template in your terminal window. You can modify the CDK CLI command to save the template to your local machine. The following is an example: -+ -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap --show-template > ----- -. Modify the bootstrap template as needed. Any changes that you make should adhere to the bootstrapping template contract. For more information on the bootstrapping template contract, see xref:bootstrapping-contract[Follow the bootstrap contract]. -+ -To ensure that your customizations are not accidentally overwritten later by someone running `cdk bootstrap` using the default template, change the default value of the `BootstrapVariant` template parameter. The CDK CLI will only allow overwriting the bootstrap stack with templates that have the same `BootstrapVariant` and an equal or higher version than the template that is currently deployed. -+ -. Deploy your modified template using your preferred {aws} CloudFormation deployment method. The following is an example that uses the CDK CLI: -+ -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap --template ----- - -[#bootstrapping-contract] -== Follow the bootstrap contract - -For your CDK apps to properly deploy, the CloudFormation templates produced during synthesis must correctly specify the resources created during bootstrapping. These resources are commonly referred to as _bootstrap resources_. Bootstrapping creates resources in your {aws} environment that are used by the {aws} CDK to perform deployments and manage application assets. Synthesis produces CloudFormation templates from each CDK stack in your application. These templates don't just define the {aws} resources that will be provisioned from your application. They also specify the bootstrap resources to use during deployment. - -During synthesis, the CDK CLI doesn't know specifically how your {aws} environment has been bootstrapped. Instead, the CDK CLI produces CloudFormation templates based on the synthesizer that you configure. Therefore, when you customize bootstrapping, you may need to customize synthesis. For instructions on customizing synthesis, see xref:bootstrapping-custom-synth[Customize CDK stack synthesis]. The purpose is to ensure that your synthesized CloudFormation templates are compatible with your bootstrapped environment. This compatibility is referred to as the _bootstrap contract_. - -The simplest method to customize stack synthesis is by modifying the `DefaultStackSynthesizer` class in your `Stack` instance. If you require customization beyond what this class can offer, you can write your own synthesizer as a class that implements `link:https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.IStackSynthesizer.html[IStackSynthesizer]` (perhaps deriving from `DefaultStackSynthesizer`). - -When you customize bootstrapping, follow the bootstrap template contract to remain compatible with `DefaultStackSynthesizer`. If you modify bootstrapping beyond the bootstrap template contract, you will need to write your own synthesizer. - -[#bootstrapping-contract-versioning] -=== Versioning - -The bootstrap template should contain a resource to create an Amazon EC2 Systems Manager (SSM) parameter with a well-known name and an output to reflect the template's version: - -[source,yaml,subs="verbatim,attributes"] ----- -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] ----- - -[#bootstrapping-contract-roles] -=== Roles - -The `DefaultStackSynthesizer` requires five IAM roles for five different purposes. If you are not using the default roles, you must specify your IAM role ARNs within your `DefaultStackSynthesizer` object. The roles are as follows: - -* The _deployment role_ is assumed by the CDK CLI and by {aws} CodePipeline to deploy into an environment. Its `AssumeRolePolicy` controls who can deploy into the environment. In the template, you can see the permissions that this role needs. -* The _lookup role_ is assumed by the CDK CLI to perform context lookups in an environment. Its `AssumeRolePolicy` controls who can deploy into the environment. The permissions this role needs can be seen in the template. -* The _file publishing role_ and the _image publishing role_ are assumed by the CDK CLI and by {aws} CodeBuild projects to publish assets into an environment. They're used to write to the Amazon S3 bucket and the Amazon 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. - -[#bootstrapping-contract-outputs] -=== Outputs - -The CDK CLI 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. - -[#bootstrapping-contract-history] -=== Template history - -The bootstrap template is versioned and evolves over time with the {aws} CDK itself. If you provide your own bootstrap template, keep it up to date with the canonical default template. You want to make sure that your template continues to work with all CDK features. For more information, see xref:bootstrap-template-history[Bootstrap template version history]. \ No newline at end of file diff --git a/v2/guide/bootstrapping-env.adoc b/v2/guide/bootstrapping-env.adoc deleted file mode 100644 index 7e4badb3..00000000 --- a/v2/guide/bootstrapping-env.adoc +++ /dev/null @@ -1,610 +0,0 @@ -include::attributes.txt[] - -// Attributes -[.topic] -[#bootstrapping-env] -= Bootstrap your environment for use with the {aws} CDK -:info_titleabbrev: Bootstrap your environment -:keywords: {aws} CDK, {aws} Cloud Development Kit ({aws} CDK), {aws} account, {aws} Region, Bootstrapping, Bootstrap, Environment - -[abstract] --- -Bootstrap your {aws} environment before using the {aws} Cloud Development Kit ({aws} CDK) to deploy CDK stacks into your environment. --- - -// Content start - -Bootstrap your {aws} environment to prepare it for {aws} Cloud Development Kit ({aws} CDK) stack deployments. - -* For an introduction to environments, see xref:environments[Environments for the {aws} CDK]. -* For an introduction to bootstrapping, see xref:bootstrapping[{aws} CDK bootstrapping]. - -[#bootstrapping-howto] -== How to bootstrap your environment - -You can use the {aws} CDK Command Line Interface ({aws} CDK CLI) or your preferred {aws} CloudFormation deployment tool to bootstrap your environment. - -[#bootstrapping-howto-cli] -*Use the CDK CLI*:: -+ -You can use the CDK CLI `cdk bootstrap` command to bootstrap your environment. This is the method that we recommend if you don't require significant modifications to bootstrapping. -+ -*Bootstrap from any working directory*::: -+ -To bootstrap from any working directory, provide the environment to bootstrap as a command line argument. The following is an example: -+ -[source,bash,subs="verbatim,attributes"] ----- -$ cdk bootstrap ----- -+ -[TIP] --- -If you don't have your {aws} account number, you can get it from the {aws} Management Console. You can also use the following {aws} CLI command to display your default account information, including your account number: - -[source,none,subs="verbatim,attributes"] ----- -$ aws sts get-caller-identity ----- - -If you have named profiles in your {aws} `config` and `credentials` files, use the `--profile` option to retrieve account information for a specific profile. The following is an example: - -[source,none,subs="verbatim,attributes"] ----- -$ aws sts get-caller-identity --profile ----- - -To display the default Region, use the `aws configure get` command: - -[source,none,subs="verbatim,attributes"] ----- -$ aws configure get region -$ aws configure get region --profile ----- --- -+ - -When providing an argument, the `aws://` prefix is optional. The following is valid: -+ -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap <123456789012/us-east-1> ----- -+ -To bootstrap multiple environments at the same time, provide multiple arguments: -+ -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap ----- - -*Bootstrap from the parent directory of a CDK project*::: -+ -You can run `cdk bootstrap` from the parent directory of a CDK project containing a `cdk.json` file. If you don`'t provide an environment as an argument, the CDK CLI will obtain environment information from default sources, such as your `config` and `credentials` files or any environment information specified for your CDK stack. -+ -When you bootstrap from the parent directory of a CDK project, environments provided from command line arguments take precedence over other sources. -+ -To bootstrap an environment that is specified in your `config` and `credentials` files, use the `--profile` option: -+ -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap --profile ----- -+ - -For more information on the `cdk bootstrap` command and supported options, see xref:ref-cli-cmd-bootstrap[cdk bootstrap]. - -[#bootstrapping-howto-cfn] -*Use any {aws} CloudFormation tool*:: -+ -You can copy the https://github.com/aws/aws-cdk-cli/blob/main/packages/aws-cdk/lib/api/bootstrap/bootstrap-template.yaml[bootstrap template] from the _aws-cdk-cli GitHub repository_ or obtain the template with the `cdk bootstrap --show-template` command. Then, use any {aws} CloudFormation tool to deploy the template into your environment. -+ -With this method, you can use {aws} CloudFormation StackSets or {aws} Control Tower. You can also use the {aws} CloudFormation console or the {aws} Command Line Interface ({aws} CLI). You can make modifications to your template before you deploy it. This method may be more flexible and suitable for large-scale deployments. -+ -The following is an example of using the `--show-template` option to retrieve and save the bootstrap template to your local machine: -+ -==== -[role="tablist"] -macOS/Linux:: -+ -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap --show-template > bootstrap-template.yaml ----- - -Windows:: -On Windows, PowerShell must be used to preserve the encoding of the template. -+ -[source,none,subs="verbatim,attributes"] ----- -powershell "cdk bootstrap --show-template | Out-File -encoding utf8 bootstrap-template.yaml" ----- -==== -+ - -[NOTE] -==== - -If CDK notices are appearing in your {aws} CloudFormation template output, provide the `--no-notices` option with your command. - -==== -+ -To deploy this template using the CDK CLI, you can run the following: -+ -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap --template ----- -+ -The following is an example of using the {aws} CLI to deploy the template: -+ -==== -[role="tablist"] -macOS/Linux:: -+ -[source,none,subs="verbatim,attributes"] ----- -aws cloudformation create-stack \ - --stack-name CDKToolkit \ - --template-body file://bootstrap-template.yaml \ - --capabilities CAPABILITY_NAMED_IAM \ - --region ----- - -Windows:: -+ -[source,none,subs="verbatim,attributes"] ----- -aws cloudformation create-stack ^ - --stack-name CDKToolkit ^ - --template-body file://bootstrap-template.yaml ^ - --capabilities CAPABILITY_NAMED_IAM ^ - --region ----- -==== -+ - -For information on using CloudFormation StackSets to bootstrap multiple environments, see https://aws.amazon.com/blogs/mt/bootstrapping-multiple-aws-accounts-for-aws-cdk-using-cloudformation-stacksets/[Bootstrapping multiple {aws} accounts for {aws} CDK using CloudFormation StackSets] in the __{aws} Cloud Operations & Migrations Blog__. - -[#bootstrapping-env-when] -== When to bootstrap your environment - -You must bootstrap each {aws} environment before you deploy into the environment. We recommend that you proactively bootstrap each environment that you plan to use. You can do this before you plan on actually deploying CDK apps into the environment. By proactively bootstrapping your environments, you prevent potential future issues such as Amazon S3 bucket name conflicts or deploying CDK apps into environments that haven't been bootstrapped. - -It's okay to bootstrap an environment more than once. If an environment has already been bootstrapped, the bootstrap stack will be upgraded if necessary. Otherwise, nothing will happen. - -If you attempt to deploy a CDK stack into an environment that hasn`'t been bootstrapped, you will see an error like the following: - -[source,none,subs="verbatim,attributes"] ----- -$ cdk deploy - -✨ Synthesis time: 2.02s - - ❌ Deployment failed: Error: BootstrapExampleStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) ----- - - -[#bootstrapping-env-when-update] -*Update your bootstrap stack*:: -+ -Periodically, the CDK team will update the bootstrap template to a new version. When this happens, we recommend that you update your bootstrap stack. If you haven`'t customized the bootstrapping process, you can update your bootstrap stack by following the same steps that you took to originally bootstrap your environment. For more information, see xref:bootstrap-template-history[Bootstrap template version history]. - -[#bootstrapping-env-default] -== Default resources created during bootstrapping - -[#bootstrapping-env-roles] -*IAM roles created during bootstrapping*:: -+ -By default, bootstrapping provisions the following {aws} Identity and Access Management (IAM) roles in your environment: -+ --- -* `CloudFormationExecutionRole` -* `DeploymentActionRole` -* `FilePublishingRole` -* `ImagePublishingRole` -* `LookupRole` --- -+ -[#bootstrapping-env-roles-cfn] -`CloudFormationExecutionRole`::: -+ -This IAM role is a CloudFormation service role that grants CloudFormation permission to perform stack deployments on your behalf. This role gives CloudFormation permission to perform {aws} API calls in your account, including deploying stacks. -+ -By using a service role, the permissions provisioned for the service role determine what actions can be performed on your CloudFormation resources. Without this service role, the security credentials you provide with the CDK CLI would determine what CloudFormation is allowed to do. -+ -[#bootstrapping-env-roles-deploy] -`DeploymentActionRole`::: -+ -This IAM role grants permission to perform deployments into your environment. It is assumed by the CDK CLI during deployments. -+ -By using a role for deployments, you can perform cross-account deployments since the role can be assumed by {aws} identities in a different account. -+ -[#bootstrapping-env-roles-s3] -`FilePublishingRole`::: -+ -This IAM role grants permission to perform actions against the bootstrapped Amazon Simple Storage Service (Amazon S3) bucket, including uploading and deleting assets. It is assumed by the CDK CLI during deployments. -+ -[#bootstrapping-env-roles-ecr] -`ImagePublishingRole`::: -+ -This IAM role grants permission to perform actions against the bootstrapped Amazon Elastic Container Registry (Amazon ECR) repository. It is assumed by the CDK CLI during deployments. -+ -[#bootstrapping-env-roles-lookup] -`LookupRole`::: -+ -This IAM role grants `readOnly` permission to look up xref:context[context values] from the {aws} environment. It is assumed by the CDK CLI when performing tasks such as template synthesis and deployments. - -[#bootstrapping-env-default-id] -*Resource IDs created during bootstrapping*:: -+ -When you deploy the default bootstrap template, physical IDs for bootstrap resources are created using the following structure: `cdk----`. -+ --- -* *Qualifier* – A nine character unique string value of `hnb659fds`. The actual value has no significance. -* *Description* – A short description of the resource. For example, `container-assets`. -* *Account ID* – The {aws} account ID of the environment. -* *Region* – The {aws} Region of the environment. --- -+ -The following is an example physical ID of the Amazon S3 staging bucket created during bootstrapping: `cdk-hnb659fds-assets-012345678910-us-west-1`. - -[#bootstrapping-env-permissions] -== Permissions to use when bootstrapping your environment - -When bootstrapping an {aws} environment, the IAM identity performing the bootstrapping must have at least the following permissions: - -[source,json,subs="verbatim,attributes"] ----- -{ - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": [ - "cloudformation:*", - "ecr:*", - "ssm:*", - "s3:*", - "iam:*" - ], - "Resource": "*" - } - ] -} ----- - -Over time, the bootstrap stack, including the resources that are created and permissions they require, may change. With future changes, you may need to modify the permissions required to bootstrap an environment. - -[#bootstrapping-env-customize] -== Customize bootstrapping - -If the default bootstrap template doesn`'t suit your needs, you can customize the bootstrapping of resources into your environment in the following ways: - -* Use command line options with the `cdk bootstrap` command – This method is best for making small, specific changes that are supported through command line options. -* Modify the default bootstrap template and deploy it – This method is best for making complex changes or if you want complete control over the configuration of resources provisioned during bootstrapping. - -For more information on customizing bootstrapping, see xref:bootstrapping-customizing[Customize {aws} CDK bootstrapping]. - -[#bootstrapping-env-pipelines] -== Bootstrapping with CDK Pipelines - -If you are using CDK Pipelines to deploy into another account's environment, and you receive a message like the following: - -[source,none,subs="verbatim,attributes"] ----- -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. The most likely cause is that the environment has not been bootstrapped. Bootstrap the environment and try again. - -[#bootstrapping-env-pipelines-protect] -*Protecting your bootstrap stack from deletion*:: -+ -If a bootstrap stack is deleted, the {aws} resources that were originally provisioned in the environment to support CDK deployments will also be deleted. This will cause the pipeline to stop working. If this happens, there is no general solution for recovery. -+ -After your environment is bootstrapped, do not delete and recreate the environment's bootstrap stack. Instead, try to update the bootstrap stack to a new version by running the `cdk bootstrap` command again. -+ -To protect against accidental deletion of your bootstrap stack, we recommend that you provide the `--termination-protection` option with the `cdk bootstrap` command to enable termination protection. You can enable termination protection on new or existing bootstrap stacks. For instructions on enabling termination protection, see xref:bootstrapping-customizing-cli-protection[Enable termination protection for the bootstrap stack]. - -[#bootstrap-template-history] -== Bootstrap template version history - -The bootstrap template is versioned and evolves over time with the {aws} CDK itself. If you provide your own bootstrap template, keep it up to date with the canonical default template. You want to make sure that your template continues to work with all CDK features. - -[NOTE] -==== - -Earlier versions of the bootstrap template created an {aws} KMS key in each bootstrapped environment by default. To avoid charges for the KMS key, re-bootstrap these environments using `--no-bootstrap-customer-key`. The current default is no KMS key, which helps avoid these charges. - -==== - -This section contains a list of the changes made in each version. - -[cols="1,1,1", options="header"] -|=== -| Template version -| {aws} CDK version -| Changes - -|**1** -|1.40.0 -|Initial version of template with Bucket, Key, Repository, and Roles. - -|**2** -|1.45.0 -|Split asset publishing role into separate file and image publishing roles. - -|**3** -|1.46.0 -|Add `FileAssetKeyArn` export to be able to add decrypt permissions to asset consumers. - -|**4** -|1.61.0 -|{aws} KMS permissions are now implicit via Amazon S3 and no longer require `FileAssetKeyArn`. Add `CdkBootstrapVersion` SSM parameter so the bootstrap stack version can be verified without knowing the stack name. - -|**5** -|1.87.0 -|Deployment role can read SSM parameter. - -|**6** -|1.108.0 -|Add lookup role separate from deployment role. - -|**6** -|1.109.0 -|Attach `aws-cdk:bootstrap-role` tag to deployment, file publishing, and image publishing roles. - -|**7** -|1.110.0 -|Deployment role can no longer read Buckets in the target account directly. (However, this role is effectively an administrator, and could always use its {aws} CloudFormation permissions to make the bucket readable anyway). - -|**8** -|1.114.0 -|The lookup role has full read-only permissions to the target environment, and has a `aws-cdk:bootstrap-role` tag as well. - -|**9** -|2.1.0 -|Fixes Amazon S3 asset uploads from being rejected by commonly referenced encryption SCP. - -|**10** -|2.4.0 -|Amazon ECR ScanOnPush is now enabled by default. - -|**11** -|2.18.0 -|Adds policy allowing Lambda to pull from Amazon ECR repos so it survives re-bootstrapping. - -|**12** -|2.20.0 -|Adds support for experimental `cdk import`. - -|**13** -|2.25.0 -|Makes container images in bootstrap-created Amazon ECR repositories immutable. - -|**14** -|2.34.0 -|Turns off Amazon ECR image scanning at the repository level by default to allow bootstrapping Regions that do not support image scanning. - -|**15** -|2.60.0 -|KMS keys cannot be tagged. - -|**16** -|2.69.0 -|Addresses Security Hub finding link:https://docs.aws.amazon.com/securityhub/latest/userguide/kms-controls.html#kms-2[KMS.2]. - -|**17** -|2.72.0 -|Addresses Security Hub finding link:https://docs.aws.amazon.com/securityhub/latest/userguide/ecr-controls.html#ecr-3[ECR.3]. - -|**18** -|2.80.0 -|Reverted changes made for version 16 as they don't work in all partitions and are are not recommended. - -|**19** -|2.106.1 -|Reverted changes made to version 18 where AccessControl property was removed from the template. (https://github.com/aws/aws-cdk/issues/27964[#27964]) - -|**20** -|2.119.0 -|Add `ssm:GetParameters` action to the {aws} CloudFormation deploy IAM role. For more information, see link:https://github.com/aws/aws-cdk/pull/28336/files#diff-4fdac38426c4747aa17d515b01af4994d3d2f12c34f7b6655f24328259beb7bf[#28336]. - -|**21** -|2.149.0 -|Add condition to the file publishing role. - -|**22** -|2.160.0 -|Add `sts:TagSession` permissions to the trust policy of bootstrap IAM roles. - -|**23** -|2.161.0 -|Add `cloudformation:RollbackStack` and `cloudformation:ContinueUpdateRollback` permissions to the trust policy of the deploy IAM role. This provides permissions for the `cdk rollback` command. - -|**24** -|2.165.0 -|Change the duration of days that noncurrent objects in the bootstrap bucket will be retained, from 365 to 30 days. Since the new `cdk gc` command introduces the ability to delete objects in the bootstrap bucket, this new behavior ensures that deleted objects remain in the bootstrap bucket for 30 days instead of 365 days. For more information on this change, see `aws-cdk` PR https://github.com/aws/aws-cdk/pull/31949[#31949]. - -|**25** -|2.165.0 -|Add support to the bootstrap bucket for the removal of incomplete multipart uploads. Incomplete multipart uploads will be deleted after 1 day. For more information on this change, see `aws-cdk` PR https://github.com/aws/aws-cdk/pull/31956[#31956]. - -|**26** -|2.1002.0 -|Add two deletion-related policies (`UpdateReplacePolicy` and `DeletionPolicy` to the `FileAssetsBucketEncryptionKey`) resource. These policies ensure that the old {aws} KMS key resource will be properly deleted when the bootstrap stack is updated or deleted. For more information on this change, see `aws-cdk-cli` PR https://github.com/aws/aws-cdk-cli/pull/100[#100]. - -|**27** -|2.1003.0 -|Add new Amazon ECR resource policy to grant Amazon EMR Serverless specific permissions for retrieving container images. For more information on this change, see `aws-cdk-cli` PR https://github.com/aws/aws-cdk-cli/pull/112[#112]. -|=== - -[#bootstrapping-template] -== Upgrade from legacy to modern bootstrap template - -The {aws} CDK v1 supported two bootstrapping templates, legacy and modern. CDK v2 supports only the modern template. For reference, here are the high-level differences between these two templates. - -[cols="1h,1,1", options="header"] -|=== -| Feature -| Legacy (v1 only) -| Modern (v1 and v2) - - -|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 (for example, by using `--trust`) - -|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 -a| - -* Amazon S3 bucket -* {aws} KMS key -* IAM roles -* Amazon ECR repository -* SSM parameter for versioning - -|{aws} KMS key -|IAM roles -|Amazon ECR repository - -//|SSM parameter for versioning - -|Resource naming -|Automatically generated -|Deterministic - -|Bucket encryption -|Default key -|{aws} managed key by default. You can customize to use a customer managed key. -|=== - -* _We will add additional resources to the bootstrap template as needed._ - -An environment that was bootstrapped using the legacy template must be upgraded to use the modern template for CDK v2 by re-bootstrapping. Re-deploy all {aws} CDK applications in the environment at least once before deleting the legacy bucket. - -[#bootstrapping-securityhub] -== Address Security Hub Findings - -If you are using {aws} Security Hub, you may see findings reported on some of the resources created by the {aws} CDK bootstrapping process. Security Hub findings help you find resource configurations you should double-check for accuracy and safety. We have reviewed these specific resource configurations with {aws} Security and are confident they do not constitute a security problem. - -[#bootstrapping-securityhub-kms2] -*[KMS.2] IAM principals should not have IAM inline policies that allow decryption actions on all KMS keys*:: -+ -The _deploy role_ (`DeploymentActionRole`) grants permission to read encrypted data, which is necessary for cross-account deployments with CDK Pipelines. Policies in this role do not grant permission to all data. It only grants permission to read encrypted data from Amazon S3 and {aws} KMS, and only when those resources allow it through their bucket or key policy. -+ -The following is a snippet of these two statements in the _deploy role_ from the bootstrap template: -+ -[source,yaml,subs="verbatim,attributes"] ----- -DeploymentActionRole: - Type: {aws}::IAM::Role - Properties: - ... - Policies: - - PolicyDocument: - Statement: - ... - - Sid: PipelineCrossAccountArtifactsBucket - Effect: Allow - Action: - - s3:GetObject* - - s3:GetBucket* - - s3:List* - - s3:Abort* - - s3:DeleteObject* - - s3:PutObject* - Resource: "*" - Condition: - StringNotEquals: - s3:ResourceAccount: - Ref: {aws}::AccountId - - Sid: PipelineCrossAccountArtifactsKey - Effect: Allow - Action: - - kms:Decrypt - - kms:DescribeKey - - kms:Encrypt - - kms:ReEncrypt* - - kms:GenerateDataKey* - Resource: "*" - Condition: - StringEquals: - kms:ViaService: - Fn::Sub: s3.${{aws}::Region}.amazonaws.com - ... ----- -+ -[#bootstrapping-securityhub-kms2-why] -*Why does Security Hub flag this?*::: -+ -The policies contain a `Resource: \*` combined with a `Condition` clause. Security Hub flags the `*` wildcard. This wildcard is used because at the time the account is bootstrapped, the {aws} KMS key created by CDK Pipelines for the CodePipeline artifact bucket does not exist yet, and therefore, can`'t be referenced on the bootstrap template by ARN. In addition, Security Hub does not consider the `Condition` clause when raising this flag. This `Condition` restricts `Resource: *` to requests made from the same {aws} account of the {aws} KMS key. These requests must come from Amazon S3 in the same {aws} Region as the {aws} KMS key. -+ -[#bootstrapping-securityhub-kms2-decide] -*Do I need to fix this finding?*::: -+ -As long as you have not modified the {aws} KMS key on your bootstrap template to be overly permissive, the _deploy role_ does not allow more access than it needs. Therefore, it is not necessary to fix this finding. -+ -[#bootstrapping-securityhub-kms2-fix] -*What if I want to fix this finding?*::: -+ -How you fix this finding depends on whether or not you will be using CDK Pipelines for cross-account deployments. -+ -*To fix the Security Hub finding and use CDK Pipelines for cross-account deployments*:::: -+ -. If you have not done so, deploy the CDK bootstrap stack using the `cdk bootstrap` command. -. If you have not done so, create and deploy your CDK [.noloc]``Pipeline``. For instructions, see xref:cdk-pipeline[Continuous integration and delivery (CI/CD) using CDK Pipelines]. -. Obtain the {aws} KMS key ARN of the CodePipeline artifact bucket. This resource is created during pipeline creation. -. Obtain a copy of the CDK bootstrap template to modify it. The following is an example, using the {aws} CDK CLI: -+ -[source,bash,subs="verbatim,attributes"] ----- -$ cdk bootstrap --show-template > bootstrap-template.yaml ----- -. Modify the template by replacing `Resource: *` of the `PipelineCrossAccountArtifactsKey` statement with your ARN value. -. Deploy the template to update your bootstrap stack. The following is an example, using the CDK CLI: -+ -[source,bash,subs="verbatim,attributes"] ----- -$ cdk bootstrap aws:/// --template bootstrap-template.yaml ----- -+ - -*To fix the Security Hub finding if you’re not using CDK Pipelines for cross-account deployments*:::: -+ -. Obtain a copy of the CDK bootstrap template to modify it. The following is an example, using the CDK CLI: -+ -[source,bash,subs="verbatim,attributes"] ----- -$ cdk bootstrap --show-template > bootstrap-template.yaml ----- -. Delete the `PipelineCrossAccountArtifactsBucket` and `PipelineCrossAccountArtifactsKey` statements from the template. -. Deploy the template to update your bootstrap stack. The following is an example, using the CDK CLI: -+ -[source,bash,subs="verbatim,attributes"] ----- -$ cdk bootstrap aws:/// --template bootstrap-template.yaml ----- - -[#bootstrapping-env-considerations] -== Considerations - -Since bootstrapping provisions resources in your environment, you may incur {aws} charges when those resources are used with the {aws} CDK. - -include::bootstrapping-customizing.adoc[leveloffset=+1] - - -include::customize-permissions-boundaries.adoc[leveloffset=+1] - - -include::bootstrapping-troubleshoot.adoc[leveloffset=+1] diff --git a/v2/guide/bootstrapping-troubleshoot.adoc b/v2/guide/bootstrapping-troubleshoot.adoc deleted file mode 100644 index 84dfd1fb..00000000 --- a/v2/guide/bootstrapping-troubleshoot.adoc +++ /dev/null @@ -1,271 +0,0 @@ -include::attributes.txt[] - -// Attributes - -[.topic] -[#bootstrapping-troubleshoot] -= Troubleshoot {aws} CDK bootstrapping issues -:info_titleabbrev: Troubleshoot bootstrapping -:keywords: {aws} CDK, Bootstrapping, Troubleshoot - -[abstract] --- -Troubleshoot common issues when bootstrapping your environment with the {aws} Cloud Development Kit ({aws} CDK). --- - -// Content start - -Troubleshoot common issues when bootstrapping your environment with the {aws} Cloud Development Kit ({aws} CDK). - -* For an introduction to bootstrapping, see xref:bootstrapping[{aws} CDK bootstrapping]. -* For instructions on bootstrapping, see xref:bootstrapping-env[Bootstrap your environment for use with the {aws} CDK]. - -[#bootstrapping-troubleshoot-s3-bucket-name] -== When bootstrapping using the default template, you get a 'CREATE_FAILED' error for the Amazon S3 bucket - -When bootstrapping using the {aws} CDK Command Line Interface (CDK CLI) `cdk bootstrap` command with the default bootstrap template, you receive the following error: - -[source,none,subs="verbatim,attributes"] ----- -CREATE_FAILED | {aws}::S3::Bucket | already exists ----- - -Before troubleshooting, ensure that you are using the latest version of the CDK CLI. - -* To check your version, run `cdk --version`. -* To install the latest version, run `npm install -g aws-cdk`. - -After installing the latest version, try bootstrapping your environment again. If you still receive the same error, continue with troubleshooting. - -[#bootstrapping-troubleshoot-s3-bucket-name-causes] -=== Common causes - -When you bootstrap your environment, the {aws} CDK generates physical IDs for your bootstrap resources. For more information, see xref:bootstrapping-env-default-id[Resource IDs created during bootstrapping]. - -Unlike the other bootstrap resources, Amazon S3 bucket names are global. This means that each bucket name must be unique across all {aws} accounts in all {aws} Regions within a partition. For more information, see https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucket.html[Buckets overview] in the _Amazon S3 User Guide_. Therefore, the most common cause of this error is that the physical ID generated as your bucket name already exists somewhere within the partition. This could be within your account or another account. - -The following is an example bucket name: `cdk-hnb659fds-assets-012345678910-us-west-1`. While unlikely, due to the qualifier and account ID being a part of the name, it is possible that this name for an Amazon S3 bucket is used by another {aws} account. Since bucket names are globally scoped, it can`'t be used by you if its used by a different account in the same partition. Most likely, a bucket with the same name exists somewhere in your account. This could be in the Region you are attempting to bootstrap, or another Region. - -Generally, the resolution is to locate this bucket in your account and determine what to do with it, or customize bootstrapping to create bootstrap resources of a different name. - -[#bootstrapping-troubleshoot-s3-bucket-name-resolution] -=== Resolution - -First, determine if a bucket with the same name exists within your {aws} account. Using an {aws} identity with valid permissions to lookup Amazon S3 buckets in your account, you can do this in the following ways: - -* Use the {aws} Command Line Interface ({aws} CLI) `aws s3 ls` command to view a list of all your buckets. -* Look up bucket names for each Region in your account using the https://console.aws.amazon.com/s3[Amazon S3 console]. - -If a bucket with the same name exists, determine if it's being used. If it's not being used, consider deleting the bucket and attempting to bootstrap your environment again. - -If a bucket with the same name exists and you don't want to delete it, determine if it's already associated with a bootstrap stack in your account. You may have to check multiple Regions. The Region in the Amazon S3 bucket name doesn't necessarily mean that the bucket is in that Region. To check if it's associated with the `CDKToolkit` bootstrap stack, you can do either of the following for each Region: - -* Use the {aws} CLI `aws cloudformation describe-stack-resources --stack-name --region ` command to view the resources in your bootstrap stack and check if the bucket is listed. -* In the https://console.aws.amazon.com/cloudformation[{aws} CloudFormation console], locate the `CDKToolkit` stack. Then, on the *Resources* tab, check if the bucket exists. - -If the bucket is associated with a bootstrap stack, determine if the bootstrap stack is in the same Region that you are attempting to bootstrap. If it is, your environment is already bootstrapped and you should be able to start using the CDK to deploy applications into your environment. If the Amazon S3 bucket is associated with a bootstrap stack in a different Region, you`'ll need to determine what to do. Possible resolutions include renaming the existing Amazon S3 bucket, deleting the current Amazon S3 bucket if its not being used, or using a new name for the Amazon S3 bucket you are attempting to create. - -If you are unable to locate an Amazon S3 bucket with the same name in your account, it may exist in a different account. To resolve this, you`'ll need to customize bootstrapping to create new names for all of your bootstrap resources or for just your Amazon S3 bucket. To create new names for all bootstrap resources, you can modify the qualifier. To create a new name for only your Amazon S3 bucket, you can provide a new bucket name. - -To customize bootstrapping, you can use options with the CDK CLI `cdk bootstrap` command or by modifying the bootstrap template. For instructions, see xref:bootstrapping-customizing[Customize {aws} CDK bootstrapping]. - -If you customize bootstrapping, you will need to apply the same changes to synthesis before you can properly deploy an application. For instructions, see xref:bootstrapping-custom-synth[Customize CDK stack synthesis]. - -For example, you can provide a new qualifier with `cdk bootstrap`: - -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap --qualifier ----- - -The following is an example Amazon S3 bucket name that will be created with this modification: `cdk-abcde0123-assets-012345678910-us-west-1`. All bootstrap resources created during bootstrapping will use this qualifier. - -When developing your CDK app, you must specify your custom qualifier in your synthesizer. This helps the CDK with identifying your bootstrap resources during synthesis and deployment. The following is an example of customizing the default synthesizer for your stack instance: - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -new MyStack(this, 'MyStack', { - synthesizer: new DefaultStackSynthesizer({ - qualifier: 'abcde0123', - }), -}); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -new MyStack(this, 'MyStack', { - synthesizer: new DefaultStackSynthesizer({ - qualifier: 'abcde0123', - }), -}) ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -MyStack(self, "MyStack", - synthesizer=DefaultStackSynthesizer( - qualifier="abcde0123" -)) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -new MyStack(app, "MyStack", StackProps.builder() - .synthesizer(DefaultStackSynthesizer.Builder.create() - .qualifier("abcde0123") - .build()) - .build(); -) ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -new MyStack(app, "MyStack", new StackProps -{ - Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps - { - Qualifier = "abcde0123" - }) -}); ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -func NewMyStack(scope constructs.Construct, id string, props *MyStackProps) awscdk.Stack { - var sprops awscdk.StackProps - if props != nil { - sprops = props.StackProps - } - stack := awscdk.NewStack(scope, &id, &sprops) - - synth := awscdk.NewDefaultStackSynthesizer(&awscdk.DefaultStackSynthesizerProps{ - Qualifier: jsii.String("abcde0123"), - }) - - stack.SetSynthesizer(synth) - - return stack -} ----- - -You can also specify the new qualifier in the `cdk.json` file of your CDK project: - -[source,json,subs="verbatim,attributes"] ----- -{ - "app": "...", - "context": { - "@aws-cdk/core:bootstrapQualifier": "abcde0123" - } -} ----- - -To modify only the Amazon S3 bucket name, you can use the ``xref:ref-cli-cmd-bootstrap-options-bootstrap-bucket-name[--bootstrap-bucket-name]`` option. The following is an example: - -[source,none,subs="verbatim,attributes"] ----- -$ cdk bootstrap --bootstrap-bucket-name '' ----- -==== - -When developing your CDK app, you must specify your new bucket name in your synthesizer. The following is an example of customizing the default synthesizer for your stack instance: - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -new MyStack(this, 'MyStack', { - synthesizer: new DefaultStackSynthesizer({ - fileAssetsBucketName: 'my-new-bucket-name', - }), -}); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -new MyStack(this, 'MyStack', { - synthesizer: new DefaultStackSynthesizer({ - fileAssetsBucketName: 'my-new-bucket-name', - }), -}) ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -MyStack(self, "MyStack", - synthesizer=DefaultStackSynthesizer( - file_assets_bucket_name='my-new-bucket-name' -)) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -new MyStack(app, "MyStack", StackProps.builder() - .synthesizer(DefaultStackSynthesizer.Builder.create() - .fileAssetsBucketName("my-new-bucket-name") - .build()) - .build(); -) ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -new MyStack(app, "MyStack", new StackProps -{ - Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps - { - FileAssetsBucketName = "my-new-bucket-name" - }) -}); ----- - -Go:: -+ -[source,go,subs="verbatim,attributes"] ----- -func NewMyStack(scope constructs.Construct, id string, props *MyStackProps) awscdk.Stack { - var sprops awscdk.StackProps - if props != nil { - sprops = props.StackProps - } - stack := awscdk.NewStack(scope, &id, &sprops) - - synth := awscdk.NewDefaultStackSynthesizer(&awscdk.DefaultStackSynthesizerProps{ - FileAssetsBucketName: jsii.String("my-new-bucket-name"), - }) - - stack.SetSynthesizer(synth) - - return stack -} ----- -==== - -[#bootstrapping-troubleshoot-s3-bucket-name-prevention] -=== Prevention - -We recommend that you proactively bootstrap each {aws} environment that you plan to use. For more information, see xref:bootstrapping-env-when[When to bootstrap your environment]. Specifically for the Amazon S3 bucket naming issue, this will create Amazon S3 buckets in each {aws} environment and prevent others from using your Amazon S3 bucket name. \ No newline at end of file diff --git a/v2/guide/bootstrapping.adoc b/v2/guide/bootstrapping.adoc deleted file mode 100644 index 0f3e2beb..00000000 --- a/v2/guide/bootstrapping.adoc +++ /dev/null @@ -1,43 +0,0 @@ -include::attributes.txt[] - -// Attributes -[.topic] -:info_titleabbrev: Bootstrapping -:keywords: {aws} CDK, {aws} Cloud Development Kit ({aws} CDK), {aws} account, {aws} Region, Bootstrapping, Bootstrap, Environment - -[#bootstrapping] -= {aws} CDK bootstrapping - -[abstract] --- -_Bootstrapping_ is the process of preparing your {aws} environment for usage with the {aws} Cloud Development Kit ({aws} CDK). Before you deploy a CDK stack into an {aws} environment, the environment must first be bootstrapped. --- - -// Content start - -_Bootstrapping_ is the process of preparing your {aws} environment for usage with the {aws} Cloud Development Kit ({aws} CDK). Before you deploy a CDK stack into an {aws} environment, the environment must first be bootstrapped. - -[#bootstrapping-what] -== What is bootstrapping? - -Bootstrapping prepares your {aws} environment by provisioning specific {aws} resources in your environment that are used by the {aws} CDK. These resources are commonly referred to as your _bootstrap resources_. They include the following: - -* *Amazon Simple Storage Service (Amazon S3) bucket* – Used to store your CDK project files, such as {aws} Lambda function code and assets. -* *Amazon Elastic Container Registry (Amazon ECR) repository* – Used primarily to store [.noloc]`Docker` images. -* *{aws} Identity and Access Management (IAM) roles* – Configured to grant permissions needed by the {aws} CDK to perform deployments. For more information about the IAM roles created during bootstrapping, see xref:bootstrapping-env-roles[IAM roles created during bootstrapping]. - -[#bootstrapping-how] -== How does bootstrapping work? - -Resources and their configuration that are used by the CDK are defined in an {aws} CloudFormation template. This template is created and managed by the CDK team. For the latest version of this template, see https://github.com/aws/aws-cdk-cli/blob/main/packages/aws-cdk/lib/api/bootstrap/bootstrap-template.yaml[`bootstrap-template.yaml`] in the _aws-cdk-cli [.noloc]`GitHub` repository_. - -To bootstrap an environment, you use the {aws} CDK Command Line Interface ({aws} CDK CLI) `cdk bootstrap` command. The CDK CLI retrieves the template and deploys it to {aws} CloudFormation as a stack, known as the _bootstrap stack_. By default, the stack name is `CDKToolkit`. By deploying this template, CloudFormation provisions the resources in your environment. After deployment, the bootstrap stack will appear in the {aws} CloudFormation console of your environment. - -You can also customize bootstrapping by modifying the template or by using CDK CLI options with the `cdk bootstrap` command. - -{aws} environments are independent. Each environment that you want to use with the {aws} CDK must first be bootstrapped. - -[#bootstrapping-learn] -== Learn more - -For instructions on bootstrapping your environment, see xref:bootstrapping-env[Bootstrap your environment for use with the {aws} CDK]. \ No newline at end of file diff --git a/v2/guide/build-containers.adoc b/v2/guide/build-containers.adoc deleted file mode 100644 index fd69e0a8..00000000 --- a/v2/guide/build-containers.adoc +++ /dev/null @@ -1,133 +0,0 @@ -include::attributes.txt[] - -// Attributes - -[.topic] -[#build-containers] -= Build and deploy container image assets in CDK apps -:info_titleabbrev: Build and deploy container image assets -:keywords: Docker, Dockerfile, Finch, Container, Container image, Container image asset, Amazon ECR, {aws} CDK, {aws} CDK CLI, Deploy, Build - -[abstract] --- -When you build container image assets with the {aws} Cloud Development Kit ({aws} CDK), Docker is utilized by default to perform these actions. If you want to use a different container management tool, you can replace Docker through the `CDK_DOCKER` environment variable. --- - -// Content start - -When you build container image assets with the {aws} Cloud Development Kit ({aws} CDK), Docker is utilized by default to perform these actions. If you want to use a different container management tool, you can replace Docker through the `CDK_DOCKER` environment variable. - -[#build-containers-intro-example] -== Example: Build and publish a container image asset with the {aws} CDK - -The following is a simple example of an {aws} CDK app that builds and publishes a container asset to Amazon Elastic Container Registry (Amazon ECR) using Docker by default: - -*Project structure*:: -+ -[source,none] ----- -my-cdk-app/ -├── lib/ -│ ├── my-stack.ts -│ └── docker/ -│ ├── Dockerfile -│ └── app/ -│ └── index.js -├── bin/ -│ └── my-cdk-app.ts -├── package.json -├── tsconfig.json -└── cdk.json ----- - -*Dockerfile*:: -+ -[source,auto] ----- -FROM public.ecr.aws/lambda/nodejs:16 - -# Copy application code -COPY app/ /var/task/ - -# (Optional) Install dependencies -# RUN npm install - -# The Lambda Node.js base image looks for index.handler by default ----- - -*Application code*:: -+ -In `lib/docker/app/index.js`: -+ -[source,javascript] ----- -console.log("Hello from inside the container!"); ----- - -*CDK stack*:: -+ -[source,javascript] ----- -import * as cdk from 'aws-cdk-lib'; -import { Construct } from 'constructs'; -import * as ecr_assets from 'aws-cdk-lib/aws-ecr-assets'; - -export class MyStack extends cdk.Stack { - constructor(scope: Construct, id: string) { - super(scope, id); - - // Define a Docker image asset - const dockerImageAsset = new ecr_assets.DockerImageAsset(this, 'MyDockerImage', { - directory: 'lib/docker', // Path to the directory containing the Dockerfile - }); - - // Output the ECR URI - new cdk.CfnOutput(this, 'ECRImageUri', { - value: dockerImageAsset.imageUri, - }); - } -} ----- - -*CDK app*:: -+ -[source,javascript] ----- -#!/usr/bin/env node -import * as cdk from 'aws-cdk-lib'; -import { MyStack } from '../lib/my-stack'; - -const app = new cdk.App(); -new MyStack(app, 'MyStack'); ----- - -When we run `cdk deploy`, the {aws} Cloud Development Kit ({aws} CDK) Command Line Interface (CLI) does the following: - -. *Build the Docker image* – Run `docker build` locally based on the `Dockerfile` in the specified directory (`lib/docker`). -. *Tag the image* – Run `docker tag` to tag the built image with a unique hash, based on the image contents. -. *Publish to Amazon ECR* – Run `docker push` to publish the container image to an Amazon ECR repository. This repository must already exist. It is created during the default bootstrapping process. -. *Output the Image URI* – After a successful deployment, the Amazon ECR URI of the published container image is output in your command prompt. This is the URI of our Docker image in Amazon ECR. - -[#build-container-replace] -== How to replace Docker with another container management tool - -Use the `CDK_DOCKER` environment variable to specify the path to the binary of your replacement container management tool. The following is an example of replacing Docker with [noloc]``Finch``: - -[source,none,subs="verbatim,attributes"] ----- -$ which finch -/usr/local/bin/finch # Locate the path to the binary - -$ export CDK_DOCKER='/usr/local/bin/finch' # Set the environment variable - -$ cdk deploy # Deploy using the replacement ----- - -Aliasing or linking is not supported. To replace Docker, you must use the `CDK_DOCKER` environment variable. - -[#build-container-supported] -== Supported Docker drop-in replacement engines - -[noloc]`Finch` is supported, although there may be some Docker features that are unavailable or may work differently as the tool evolves. For more information on Finch, see https://aws.amazon.com/blogs/opensource/ready-for-flight-announcing-finch-1-0-ga/[Ready for Flight: Announcing Finch 1.0 GA!] in the _{aws} Open Source Blog_. - -Other container management tools may work. The CDK doesn't check which Docker replacement you are using to determine if it's supported. If the tool has equivalent Docker commands and behaves similarly, it should work. \ No newline at end of file diff --git a/v2/guide/cfn-layer.adoc b/v2/guide/cfn-layer.adoc deleted file mode 100644 index 1b928c94..00000000 --- a/v2/guide/cfn-layer.adoc +++ /dev/null @@ -1,534 +0,0 @@ -include::attributes.txt[] - -// Attributes -[.topic] -[#cfn-layer] -= Customize constructs from the {aws} Construct Library -:info_titleabbrev: Customize constructs - -[abstract] --- -Customize constructs from the {aws} Construct Library through escape hatches, raw overrides, and custom resources. --- - -// Content start - -Customize constructs from the {aws} Construct Library through escape hatches, raw overrides, and custom resources. - -[#develop-customize-escape] -== Use escape hatches - -The {aws} Construct Library provides xref:constructs[constructs] of varying levels of abstraction. - -At the highest level, your {aws} CDK application and the stacks in it are themselves abstractions of your entire cloud infrastructure, or significant chunks of it. They can be parameterized to deploy them in different environments or for different needs. - -Abstractions are powerful tools for designing and implementing cloud applications. The {aws} CDK gives you the power not only to build with its abstractions, but also to create new abstractions. Using the existing open-source L2 and L3 constructs as guidance, you can build your own L2 and L3 constructs to reflect your own organization's best practices and opinions. - -No abstraction is perfect, and even good abstractions cannot cover every possible use case. During development, you may find a construct that almost fits your needs, requiring a small or large customization. - -For this reason, the {aws} CDK provides ways to _break out_ of the construct model. This includes moving to a lower-level abstraction or to a different model entirely. Escape hatches let you _escape_ the {aws} CDK paradigm and customize it in ways that suit your needs. Then, you can wrap your changes in a new construct to abstract away the underlying complexity and provide a clean API for other developers. - -The following are examples of situations where you can use escape hatches: - -* An {aws} service feature is available through {aws} CloudFormation, but there are no L2 constructs for it. -* An {aws} service feature is available through {aws} CloudFormation, and there are L2 constructs for the service, but these don't yet expose the feature. Because L2 constructs are curated by the CDK team, they may not be immediately available for new features. -* The feature is not yet available through {aws} CloudFormation at all. -+ -To determine whether a feature is available through {aws} CloudFormation, see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html[{aws} Resource and Property Types Reference]. - -[#develop-customize-escape-l1] -=== Develop escape hatches for L1 constructs - -If L2 constructs are not available for the service, you can use the automatically generated L1 constructs. 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 example, to instantiate a low-level Amazon S3 bucket L1 with analytics enabled, you would write something like the following. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -new s3.CfnBucket(this, 'amzn-s3-demo-bucket', { - analyticsConfigurations: [ - { - id: 'Config', - // ... - } - ] -}); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -new s3.CfnBucket(this, 'amzn-s3-demo-bucket', { - analyticsConfigurations: [ - { - id: 'Config' - // ... - } - ] -}); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -s3.CfnBucket(self, "amzn-s3-demo-bucket", - analytics_configurations: [ - dict(id="Config", - # ... - ) - ] -) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -CfnBucket.Builder.create(this, "amzn-s3-demo-bucket") - .analyticsConfigurations(Arrays.asList(java.util.Map.of( // Java 9 or later - "id", "Config", // ... - ))).build(); ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -new CfnBucket(this, 'amzn-s3-demo-bucket', new CfnBucketProps { - AnalyticsConfigurations = new Dictionary - { - ["id"] = "Config", - // ... - } -}); ----- -==== - -There might be rare cases where you want to define a resource that doesn't have a corresponding `CfnXxx` class. This could be a new resource type that hasn't yet been published in the {aws} CloudFormation resource specification. In cases like this, you can instantiate the `cdk.CfnResource` directly and specify the resource type and properties. This is shown in the following example. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -new cdk.CfnResource(this, 'amzn-s3-demo-bucket', { - type: '{aws}::S3::Bucket', - properties: { - // Note the PascalCase here! These are CloudFormation identifiers. - AnalyticsConfigurations: [ - { - Id: 'Config', - // ... - } - ] - } -}); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -new cdk.CfnResource(this, 'amzn-s3-demo-bucket', { - type: '{aws}::S3::Bucket', - properties: { - // Note the PascalCase here! These are CloudFormation identifiers. - AnalyticsConfigurations: [ - { - Id: 'Config' - // ... - } - ] - } -}); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -cdk.CfnResource(self, 'amzn-s3-demo-bucket', - type="{aws}::S3::Bucket", - properties=dict( - # Note the PascalCase here! These are CloudFormation identifiers. - "AnalyticsConfigurations": [ - { - "Id": "Config", - # ... - } - ] - ) -) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -CfnResource.Builder.create(this, "amzn-s3-demo-bucket") - .type("{aws}::S3::Bucket") - .properties(java.util.Map.of( // Map.of requires Java 9 or later - // Note the PascalCase here! These are CloudFormation identifiers - "AnalyticsConfigurations", Arrays.asList( - java.util.Map.of("Id", "Config", // ... - )))) - .build(); ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -new CfnResource(this, "amzn-s3-demo-bucket", new CfnResourceProps -{ - Type = "{aws}::S3::Bucket", - Properties = new Dictionary - { // Note the PascalCase here! These are CloudFormation identifiers - ["AnalyticsConfigurations"] = new Dictionary[] - { - new Dictionary { - ["Id"] = "Config" - } - } - } -}); ----- -==== - -[#develop-customize-escape-l2] -=== Develop escape hatches for L2 constructs - -If an L2 construct is missing a feature or you're trying to work around an issue, you can modify the L1 construct that's encapsulated by the L2 construct. - -All L2 constructs contain within them the corresponding L1 construct. For example, the high-level `Bucket` construct wraps the low-level `CfnBucket` construct. Because the `CfnBucket` corresponds directly to the {aws} CloudFormation resource, it exposes all features that are available through {aws} CloudFormation. - -The basic approach to get access to the L1 construct 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`. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -// Get the CloudFormation resource -const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; - -// Change its properties -cfnBucket.analyticsConfiguration = [ - { - id: 'Config', - // ... - } -]; ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -// Get the CloudFormation resource -const cfnBucket = bucket.node.defaultChild; - -// Change its properties -cfnBucket.analyticsConfiguration = [ - { - id: 'Config' - // ... - } -]; ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -# Get the CloudFormation resource -cfn_bucket = bucket.node.default_child - -# Change its properties -cfn_bucket.analytics_configuration = [ - { - "id": "Config", - # ... - } -] ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -// Get the CloudFormation resource -CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); - -cfnBucket.setAnalyticsConfigurations( - Arrays.asList(java.util.Map.of( // Java 9 or later - "Id", "Config", // ... - )); -) ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -// Get the CloudFormation resource -var cfnBucket = (CfnBucket)bucket.Node.DefaultChild; - -cfnBucket.AnalyticsConfigurations = new List { - new Dictionary - { - ["Id"] = "Config", - // ... - } -}; ----- -==== - -You can also use this object to change {aws} CloudFormation options such as `Metadata` and ``UpdatePolicy``. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -cfnBucket.cfnOptions.metadata = { - MetadataKey: 'MetadataValue' -}; ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -cfnBucket.cfnOptions.metadata = { - MetadataKey: 'MetadataValue' -}; ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -cfn_bucket.cfn_options.metadata = { - "MetadataKey": "MetadataValue" -} ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -cfnBucket.getCfnOptions().setMetadata(java.util.Map.of( // Java 9+ - "MetadataKey", "Metadatavalue")); ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -cfnBucket.CfnOptions.Metadata = new Dictionary -{ - ["MetadataKey"] = "Metadatavalue" -}; ----- -==== - -[#develop-customize-unescape] -== Use un-escape hatches - -The {aws} CDK also provides the capability to go _up_ an abstraction level, which we might refer to as an "un-escape" hatch. If you have an L1 construct, such as `CfnBucket`, you can create a new L2 construct (`Bucket` in this case) to wrap the L1 construct. - -This is convenient when you create an L1 resource but want to use it with a construct that requires an L2 resource. It's also helpful when you want to use convenience methods like `.grantXxxxx()` that aren't available on the L1 construct. - -You move to the higher abstraction level using a static method on the L2 class called `.fromCfnXxxxx()`--for example, `Bucket.fromCfnBucket()` for Amazon S3 buckets. The L1 resource is the only parameter. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -b1 = new s3.CfnBucket(this, "buck09", { ... }); -b2 = s3.Bucket.fromCfnBucket(b1); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -b1 = new s3.CfnBucket(this, "buck09", { ...} ); -b2 = s3.Bucket.fromCfnBucket(b1); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -b1 = s3.CfnBucket(self, "buck09", ...) - b2 = s3.from_cfn_bucket(b1) ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -CfnBucket b1 = CfnBucket.Builder.create(this, "buck09") - // .... - .build(); -IBucket b2 = Bucket.fromCfnBucket(b1); ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -var b1 = new CfnBucket(this, "buck09", new CfnBucketProps { ... }); -var v2 = Bucket.FromCfnBucket(b1); ----- -==== - -L2 constructs created from L1 constructs are proxy objects that refer to the L1 resource, similar to those created from resource names, ARNs, or lookups. Modifications to these constructs do not affect the final synthesized {aws} CloudFormation template (since you have the L1 resource, however, you can modify that instead). For more information on proxy objects, see xref:resources-external[Referencing resources in your {aws} account]. - -To avoid confusion, do not create multiple L2 constructs that refer to the same L1 construct. For example, if you extract the `CfnBucket` from a `Bucket` using the technique in the xref:develop-customize-escape-l2[previous section], you shouldn't create a second `Bucket` instance by calling `Bucket.fromCfnBucket()` with that `CfnBucket`. It actually works as you'd expect (only one `{aws}::S3::Bucket` is synthesized) but it makes your code more difficult to maintain. - -[#develop-customize-override] -== Use raw overrides - -If there are properties that are missing from the L1 construct, you can bypass all typing using raw overrides. This also makes it possible to delete synthesized properties. - -Use one of the `addOverride` methods (Python: `add_override`) methods, as shown in the following example. - -==== -[role="tablist"] -TypeScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -// Get the CloudFormation resource -const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; - -// Use dot notation to address inside the resource template fragment -cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); -cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); - -// use index (0 here) to address an element of a list -cfnBucket.addOverride('Properties.Tags.0.Value', 'NewValue'); -cfnBucket.addDeletionOverride('Properties.Tags.0'); - -// addPropertyOverride is a convenience function for paths starting with "Properties." -cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); -cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); -cfnBucket.addPropertyOverride('Tags.0.Value', 'NewValue'); -cfnBucket.addPropertyDeletionOverride('Tags.0'); ----- - -JavaScript:: -+ -[source,javascript,subs="verbatim,attributes"] ----- -// Get the CloudFormation resource -const cfnBucket = bucket.node.defaultChild ; - -// Use dot notation to address inside the resource template fragment -cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); -cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); - -// use index (0 here) to address an element of a list -cfnBucket.addOverride('Properties.Tags.0.Value', 'NewValue'); -cfnBucket.addDeletionOverride('Properties.Tags.0'); - -// addPropertyOverride is a convenience function for paths starting with "Properties." -cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); -cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); -cfnBucket.addPropertyOverride('Tags.0.Value', 'NewValue'); -cfnBucket.addPropertyDeletionOverride('Tags.0'); ----- - -Python:: -+ -[source,python,subs="verbatim,attributes"] ----- -# Get the CloudFormation resource -cfn_bucket = bucket.node.default_child - -# Use dot notation to address inside the resource template fragment -cfn_bucket.add_override("Properties.VersioningConfiguration.Status", "NewStatus") -cfn_bucket.add_deletion_override("Properties.VersioningConfiguration.Status") - -# use index (0 here) to address an element of a list -cfn_bucket.add_override("Properties.Tags.0.Value", "NewValue") -cfn_bucket.add_deletion_override("Properties.Tags.0") - -# addPropertyOverride is a convenience function for paths starting with "Properties." -cfn_bucket.add_property_override("VersioningConfiguration.Status", "NewStatus") -cfn_bucket.add_property_deletion_override("VersioningConfiguration.Status") -cfn_bucket.add_property_override("Tags.0.Value", "NewValue") -cfn_bucket.add_property_deletion_override("Tags.0") ----- - -Java:: -+ -[source,java,subs="verbatim,attributes"] ----- -// Get the CloudFormation resource -CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); - -// Use dot notation to address inside the resource template fragment -cfnBucket.addOverride("Properties.VersioningConfiguration.Status", "NewStatus"); -cfnBucket.addDeletionOverride("Properties.VersioningConfiguration.Status"); - -// use index (0 here) to address an element of a list -cfnBucket.addOverride("Properties.Tags.0.Value", "NewValue"); -cfnBucket.addDeletionOverride("Properties.Tags.0"); - -// addPropertyOverride is a convenience function for paths starting with "Properties." -cfnBucket.addPropertyOverride("VersioningConfiguration.Status", "NewStatus"); -cfnBucket.addPropertyDeletionOverride("VersioningConfiguration.Status"); -cfnBucket.addPropertyOverride("Tags.0.Value", "NewValue"); -cfnBucket.addPropertyDeletionOverride("Tags.0"); ----- - -C#:: -+ -[source,csharp,subs="verbatim,attributes"] ----- -// Get the CloudFormation resource -var cfnBucket = (CfnBucket)bucket.node.defaultChild; - -// Use dot notation to address inside the resource template fragment -cfnBucket.AddOverride("Properties.VersioningConfiguration.Status", "NewStatus"); -cfnBucket.AddDeletionOverride("Properties.VersioningConfiguration.Status"); - -// use index (0 here) to address an element of a list -cfnBucket.AddOverride("Properties.Tags.0.Value", "NewValue"); -cfnBucket.AddDeletionOverride("Properties.Tags.0"); - -// addPropertyOverride is a convenience function for paths starting with "Properties." -cfnBucket.AddPropertyOverride("VersioningConfiguration.Status", "NewStatus"); -cfnBucket.AddPropertyDeletionOverride("VersioningConfiguration.Status"); -cfnBucket.AddPropertyOverride("Tags.0.Value", "NewValue"); -cfnBucket.AddPropertyDeletionOverride("Tags.0"); ----- -==== - -[#develop-customize-custom] -== Use custom resources - -If the feature isn't available through {aws} CloudFormation, but only through a direct API call, you must write an {aws} CloudFormation Custom Resource to make the API call you need. You can use the {aws} CDK to write custom resources and wrap them into a regular construct interface. From the perspective of a consumer of your construct, the experience will feel 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 https://github.com/awslabs/aws-cdk/tree/master/packages/%40aws-cdk/custom-resources[AwsCustomResource]. 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 cover completely here, but the following links should get you started: - -* https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html[Custom Resources] -* https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/[Custom-Resource Example] -* For a more fully fledged example, see the https://github.com/awslabs/aws-cdk/blob/master/packages/@aws-cdk/aws-certificatemanager/lib/dns-validated-certificate.ts[DnsValidatedCertificate] class in the CDK standard library. This is implemented as a custom resource. \ No newline at end of file diff --git a/v2/guide/chapter-deploy.adoc b/v2/guide/chapter-deploy.adoc deleted file mode 100644 index 6ef008db..00000000 --- a/v2/guide/chapter-deploy.adoc +++ /dev/null @@ -1,234 +0,0 @@ -include::attributes.txt[] - -// Attributes - -:https---docs-aws-amazon-com-cdk-api-v2-docs-aws-cdk-lib-aws-cloudformation-readme-html: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudformation-readme.html -:https---docs-aws-amazon-com-cdk-api-v2-docs-aws-cdk-lib-readme-html-stack-synthesizers: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html#stack-synthesizers -[.topic] -[#deploy] -= Deploy {aws} CDK applications -:keywords: {aws} CDK, IaC, Infrastructure as code, {aws}, {aws} Cloud, serverless, modern applications - -[abstract] --- -An {aws} Cloud Development Kit ({aws} CDK) deployment is the process of provisioning your infrastructure on {aws}. --- - -// Content start - -An {aws} Cloud Development Kit ({aws} CDK) deployment is the process of provisioning your infrastructure on {aws}. - -[#deploy-how] -== How {aws} CDK deployments work - -The {aws} CDK utilizes the {aws} CloudFormation service to perform deployments. Before you deploy, you synthesize your CDK stacks. This creates a CloudFormation template and deployment artifacts for each CDK stack in your app. Deployments are initiated from a local development machine or from a _continuous integration and continuous delivery (CI/CD)_ environment. During deployment, assets are uploaded to the bootstrapped resources and the CloudFormation template is submitted to CloudFormation to provision your {aws} resources. - -For a deployment to be successful, the following is required: - -* The {aws} CDK Command Line Interface ({aws} CDK CLI) must be provided with valid permissions. -* The {aws} environment must be bootstrapped. -* The {aws} CDK must know the bootstrapped resources to upload assets into. - -[#deploy-prerequisites] -== Prerequisites for CDK deployments - -Before you can deploy an {aws} CDK application, you must complete the following: - -* Configure security credentials for the CDK CLI. -* Bootstrap your {aws} environment. -* Configure an {aws} environment for each of your CDK stacks. -* Develop your CDK app. - -[#deploy-prerequisites-creds] -*Configure security credentials*:: -+ -To use the CDK CLI to interact with {aws}, you must configure security credentials on your local machine. For instructions, see xref:configure-access[Configure security credentials for the {aws} CDK CLI]. - -[#deploy-prerequisites-bootstrap] -*Bootstrap your {aws} environment*:: -+ -A deployment is always associated with one or more {aws} xref:environments[environments]. Before you can deploy, the environment must first be xref:bootstrapping[bootstrapped]. Bootstrapping provisions resources in your environment that the CDK uses to perform and manage deployments. These resources include an Amazon Simple Storage Service (Amazon S3) bucket and Amazon Elastic Container Registry (Amazon ECR) repository to store and manage xref:assets[assets]. These resources also include {aws} Identity and Access Management (IAM) roles that are used to provide permissions during development and deployment. -+ -We recommend that you use the {aws} CDK Command Line Interface ({aws} CDK CLI) `cdk bootstrap` command to bootstrap your environment. You can customize bootstrapping or manually create these resources in your environment if necessary. For instructions, see xref:bootstrapping-env[Bootstrap your environment for use with the {aws} CDK]. - -[#deploy-prerequisites-env] -*Configure {aws} environments*:: -+ -Each CDK stack must be associated with an environment to determine where the stack is deployed to. For instructions, see xref:configure-env[Configure environments to use with the {aws} CDK]. - -[#deploy-prerequisites-develop] -*Develop your CDK app*:: -+ -Within a CDK xref:projects[project], you create and develop your CDK app. Within your app, you create one or more CDK xref:stacks[stacks]. Within your stacks, you import and use xref:constructs[constructs] from the {aws} Construct Library to define your infrastructure. Before you can deploy, your CDK app must contain at least one stack. - -[#deploy-how-synth] -== CDK app synthesis - -To perform synthesis, we recommend that you use the CDK CLI `cdk synth` command. The `cdk deploy` command will also perform synthesis before initiating deployment. However, by using `cdk synth`, you can validate your CDK app and catch errors before initiating deployment. - -Synthesis behavior is determined by the link:https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html#stack-synthesizers[stack synthesizer] that you configure for your CDK stack. If you don`'t configure a synthesizer, `https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.DefaultStackSynthesizer.html[DefaultStackSynthesizer]` will be used. You can also configure and customize synthesis to meet your needs. For instructions, see xref:configure-synth[Configure and perform CDK stack synthesis]. - -For your synthesized CloudFormation template to deploy successfully into your environment, it must be compatible with how your environment was bootstrapped. For example, your CloudFormation template must specify the correct Amazon S3 bucket to deploy assets into. If you use the default method of bootstrapping your environment, the default stack synthesizer will work. If you customize CDK behavior, such as customizing bootstrapping or synthesis, CDK deployment behavior may vary. - -[#deploy-how-synth-app] -*The app lifecycle*:: -+ -When you perform synthesis, your CDK app is run through the following phases, known as the __app lifecycle__: -+ -*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 run. Most of your app code is run in this stage. -+ -*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. Be very careful when mutating the construct tree during this phase, because the order of operations could impact behavior. -+ -During this phase, once the construct tree has been built, any xref:aspects[aspects] that you have configured are applied as well. -+ -*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 performing validation as soon as possible (usually as soon as you get some input) and throwing exceptions as early as possible. Performing validation early improves reliability as stack traces will be more accurate, and ensures that your code can continue to execute safely. -+ -*Synthesis*::: -+ -This is the final stage of running your 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 produce deployment artifacts to the resulting cloud assembly. These artifacts include CloudFormation templates, {aws} Lambda application bundles, file and Docker image assets, and other deployment artifacts. In most cases, you won't need to implement the `synthesize` method. - -[#deploy-how-synth-run] -*Running your app*:: -+ -The CDK CLI needs to know how to run your CDK app. If you created the project from a template using the `cdk init` command, your app's `cdk.json` file includes an `app` key. This key specifies the necessary command for the language that the app is written in. If your language requires compilation, the command line performs this step before running the app automatically. -+ -==== -[role="tablist"] -TypeScript:: -+ -[source,json,subs="verbatim,attributes"] ----- -{ - "app": "npx ts-node --prefer-ts-exts bin/my-app.ts" -} ----- - -JavaScript:: -+ -[source,json,subs="verbatim,attributes"] ----- -{ - "app": "node bin/my-app.js" -} ----- - -Python:: -+ -[source,json,subs="verbatim,attributes"] ----- -{ - "app": "python app.py" -} ----- - -Java:: -+ -[source,json,subs="verbatim,attributes"] ----- -{ - "app": "mvn -e -q compile exec:java" -} ----- - -C#:: -+ -[source,json,subs="verbatim,attributes"] ----- -{ - "app": "dotnet run -p src/MyApp/MyApp.csproj" -} ----- - -Go:: -+ -[source,json,subs="verbatim,attributes"] ----- -{ - "app": "go mod download && go run my-app.go" -} ----- -==== -+ -If you didn't create your project using the CDK CLI, or if you want to override the command line given in `cdk.json`, you can provide the `xref:ref-cli-cmd-options-app[--app]` option when running the `cdk` command. - -[source,none,subs="verbatim,attributes"] ----- -$ cdk --app '' ... ----- - -The `` part of the command indicates the command that should be run to execute your CDK application. Use quotation marks as shown, since such commands contain spaces. The `` is a subcommand like `synth` or `deploy` that tells the CDK CLI what you want to do with your app. Follow this with any additional options needed for that subcommand. - -The CDK CLI can also interact directly with an already-synthesized cloud assembly. To do that, pass the directory in which the cloud assembly is stored in `--app`. The following example lists the stacks defined in the cloud assembly stored under `./my-cloud-assembly`. - -[source,none,subs="verbatim,attributes"] ----- -$ cdk --app <./my-cloud-assembly> ls ----- - -[#deploy-how-synth-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. It also includes a copy of any file assets or Docker images that you reference in your app. -+ -See the https://github.com/aws/aws-cdk/blob/master/design/cloud-assembly.md[cloud assembly specification] 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. However, any tool that can read the cloud assembly format can be used to deploy your app. - -[#deploy-how-deploy] -== Deploy your application - -To deploy your application, we recommend that you use the CDK CLI `cdk deploy` command to initiate deployments or to configure automated deployments. - -When you run `cdk deploy`, the CDK CLI initiates `cdk synth` to prepare for deployment. The following diagram illustrates the app lifecycle in the context of a deployment: - -image::./images/app-lifecycle_cdk-flowchart.png[Flowchart of the {aws} CDK app lifecycle.,scaledwidth=100%] - -During deployment, the CDK CLI takes the cloud assembly produced by synthesis and deploys it to an {aws} environment. Assets are uploaded to Amazon S3 and Amazon ECR and the CloudFormation template is submitted to {aws} CloudFormation for deployment. - -By the time the {aws} CloudFormation deployment phase starts, your CDK app has already finished running and exited. This has the following implications: - -* The CDK app can't respond to events that happen during deployment, such as a resource being created or the whole deployment finishing. To run code during the deployment phase, you must inject it into the {aws} CloudFormation template as a xref:develop-customize-custom[custom resource]. For more information about adding a custom resource to your app, see the link:https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudformation-readme.html[{aws} CloudFormation module], or the link:https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-resource/[custom-resource] example. You can also configure the link:https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.triggers-readme.html[Triggers] module to run code during deployments. -* The CDK app might have to work with values that can't be known at the time it runs. For example, if the {aws} CDK app defines an Amazon S3 bucket with an automatically generated name, and you retrieve the `bucket.bucketName` (Python: `bucket_name`) attribute, that value is not the name of the deployed bucket. Instead, you get a `Token` value. To determine whether a particular value is available, call `cdk.isUnresolved(value)` (Python: `is_unresolved`). See xref:tokens[Tokens and the {aws} CDK] for details. - -[#deploy-how-deploy-permissions] -*Deployment permissions*:: -+ -Before deployment can be performed, permissions must be established. The following diagram illustrates the permissions that are used during a default deployment, when using the default bootstrapping process and stack synthesizer: -+ -image::./images/default-deploy-process_cdk_flowchart.png[Flowchart of the default {aws} CDK deployment process.,scaledwidth=100%] -+ -*Actor initiates deployment*::: -+ -Deployments are initiated by an _actor_, using the CDK CLI. An actor can either be a person, or a service such as {aws} CodePipeline. -+ -If necessary, the CDK CLI runs `cdk synth` when you run `cdk deploy`. During synthesis, the {aws} identity assumes the `LookupRole` to perform context lookups in the {aws} environment. -+ -*Permissions are established*::: -+ -First, the actor's security credentials are used to authenticate to {aws} and obtain the first IAM identity in the process. For human actors, how security credentials are configured and obtained depends on how you or your organization manages users. For more information, see xref:configure-access[Configure security credentials for the {aws} CDK CLI]. For service actors, such as CodePipeline, an IAM execution role is assumed and used. -+ -Next, the IAM roles created in your {aws} environment during bootstrapping are used to establish permissions to perform the actions needed for deployment. For more information about these roles and what they grant permissions for, see xref:bootstrapping-env-roles[IAM roles created during bootstrapping]. This process includes the following: -+ --- -* The {aws} identity assumes the `DeploymentActionRole` role and passes the `CloudFormationExecutionRole` role to CloudFormation, ensuring that CloudFormation assumes the role when it performs any actions in your {aws} environment. `DeploymentActionRole` grants permission to perform deployments into your environment and `CloudFormationExecutionRole` determines what actions CloudFormation can perform. -* The {aws} identity assumes the `FilePublishingRole`, which determines the actions that can be performed on the Amazon S3 bucket created during bootstrapping. -* The {aws} identity assumes the `ImagePublishingRole`, which determines the actions that can be performed on the Amazon ECR repository created during bootstrapping. -* If necessary, the {aws} identity assumes the `LookupRole` to perform context lookups in the {aws} environment. This action may also be performed during template synthesis. --- -+ -*Deployment is performed*::: -+ -During deployment, the CDK CLI reads the bootstrap version parameter to confirm the bootstrap version number. {aws} CloudFormation also reads this parameter at deployment time to confirm. If permissions across the deployment workflow are valid, deployment is performed. Assets are uploaded to the bootstrapped resources and the CloudFormation template produced at synthesis is deployed using the CloudFormation service as a CloudFormation stack to provision your resources. - -include::policy-validation-synthesis.adoc[leveloffset=+1] - -include::create-cdk-pipeline.adoc[leveloffset=+1] - -include::build-containers.adoc[leveloffset=+1] - -include::deploy-troubleshoot.adoc[leveloffset=+1] \ No newline at end of file diff --git a/v2/guide/chapter-develop.adoc b/v2/guide/chapter-develop.adoc deleted file mode 100644 index 43b294dc..00000000 --- a/v2/guide/chapter-develop.adoc +++ /dev/null @@ -1,68 +0,0 @@ -include::attributes.txt[] - -// Attributes -[.topic] -[#develop] -= Develop {aws} CDK applications -:keywords: {aws} CDK, IaC, Infrastructure as code, {aws}, {aws} Cloud, serverless, modern applications - -[abstract] --- -Manage your infrastructure on {aws} by developing applications using the {aws} Cloud Development Kit ({aws} CDK). --- - -// Content start - -Manage your infrastructure on {aws} by developing applications using the {aws} Cloud Development Kit ({aws} CDK). - -[#develop-prerequisites] -== Prerequisites - -Before you can start developing applications, complete all set up steps in xref:getting-started[Getting started with the {aws} CDK]. - -[#develop-overview] -== Developing {aws} CDK applications overview - -At a high-level, developing CDK applications involves the following steps: - -. *Create a CDK project* – A CDK xref:projects[project] consists of the files and folders that store and organize your CDK code. -. *Create a CDK app* – Within a CDK project, you use the `App` construct to define a CDK xref:apps[application]. -. *Create a CDK stack* – Within the scope of your CDK app, you define one or more CDK xref:stacks[stacks]. -. *Define your infrastructure* – Within the scope of a CDK stack, you use xref:constructs[constructs] from the {aws} Construct Library to define the {aws} resources and properties that will become your infrastructure. Using a general-purpose programming xref:languages[language] of your choice, you can use logic, such as conditional statements and loops, to define your infrastructure based on certain conditions. - -[#develop-gs] -== Get started with developing CDK applications - -To get started, you can use the {aws} CDK Command Line Interface ({aws} CDK CLI) `cdk init` command. Provide the `--language` option to specify the programming language to use. This command creates a starting CDK project and imports the main {aws} Construct Library and core modules. - -[#develop-library] -== Import and use the {aws} CDK Library - -After you create a CDK project, import and use constructs from the {aws} CDK Library to begin defining your infrastructure. For instructions, see xref:work-with[Work with the {aws} CDK library]. - -[#develop-next] -== Next steps - -When ready to deploy your application, use the CDK CLI `cdk deploy` command. For instructions, see xref:deploy[Deploy {aws} CDK applications]. - -include::usage-data.adoc[leveloffset=+1] - -include::cfn-layer.adoc[leveloffset=+1] - -include::get-env-var.adoc[leveloffset=+1] - -include::get-cfn-val.adoc[leveloffset=+1] - -include::use-cfn-template.adoc[leveloffset=+1] - -include::get-ssm-val.adoc[leveloffset=+1] - -include::get-sm-val.adoc[leveloffset=+1] - -include::set-cw-alarm.adoc[leveloffset=+1] - -include::get-context-var.adoc[leveloffset=+1] - -include::use-cfn-public-registry.adoc[leveloffset=+1] - -include::define-iam-l2.adoc[leveloffset=+1] \ No newline at end of file diff --git a/v2/guide/cli.adoc b/v2/guide/cli.adoc deleted file mode 100644 index 81cf29ff..00000000 --- a/v2/guide/cli.adoc +++ /dev/null @@ -1,785 +0,0 @@ -include::attributes.txt[] - -// Attributes - -[.topic] -[#cli] -= {aws} CDK CLI reference - -// Content start - -The {aws} Cloud Development Kit ({aws} CDK) Command Line Interface ({aws} CDK CLI), also known as the CDK Toolkit, 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 CLI. - -The CDK CLI is installed with the Node Package Manager. In most cases, we recommend installing it globally. - -[source,none,subs="verbatim,attributes"] ----- -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, consider installing a matching version of the CDK CLI in individual CDK projects. To do this, omit `-g` from the `npm install` command. Then use `npx aws-cdk` to invoke it. This runs the local version if one exists, falling back to a global version if not. - -==== - -[#cli-commands] -== CDK CLI commands - -All CDK CLI 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. - -For a description of all subcommands, options, and arguments, see xref:ref-cli-cmd[{aws} CDK CLI command reference]. - -[#cli-options] -== Specify options and their values - -Command line options begin with two hyphens (`--`). Some frequently used options have single-letter synonyms that begin with a single hyphen (for example, `--app` has a synonym `-a`). The order of options in an CDK CLI command is not important. - -All options accept a value, which must follow the option name. The value may be separated from the name by white space or by an equals sign `=`. The following two options are equivalent. - -[source,none,subs="verbatim,attributes"] ----- ---toolkit-stack-name MyBootstrapStack ---toolkit-stack-name=MyBootstrapStack ----- - -Some options are flags (Booleans). You may specify `true` or `false` as their value. If you do not provide a value, the value is taken to be `true`. You may also prefix the option name with `no-` to imply `false`. - -[source,none,subs="verbatim,attributes"] ----- -# sets staging flag to true ---staging ---staging=true ---staging true - -# sets staging flag to false ---no-staging ---staging=false ---staging false ----- - -A few options, namely `--context`, `--parameters`, `--plugin`, `--tags`, and `--trust`, may be specified more than once to specify multiple values. These are noted as having `[array]` type in the CDK CLI help. For example: - -[source,none,subs="verbatim,attributes"] ----- -cdk bootstrap --tags costCenter=0123 --tags responsibleParty=jdoe ----- - -[#cli-help] -== Built-in help - -The CDK CLI has integrated help. You can see general help about the utility and a list of the provided subcommands by issuing: - -[source,none,subs="verbatim,attributes"] ----- -cdk --help ----- - -To see help for a particular subcommand, for example `deploy`, specify it before the `--help` flag. - -[source,none,subs="verbatim,attributes"] ----- -cdk deploy --help ----- - -Issue `cdk version` to display the version of the CDK CLI. Provide this information when requesting support. - -[#version-reporting] -== Version reporting - -To gain insight into how the {aws} CDK is used, the constructs used by {aws} CDK applications are collected and reported by using a resource identified as `{aws}::CDK::Metadata`. To learn more, see xref:usage-data[Configure {aws} CDK usage data reporting]. - -[#cli-auth] -== Authentication with {aws} - -There are different ways in which you can configure programmatic access to {aws} resources, depending on the environment and the {aws} access available to you. - -To choose your method of authentication and configure it for the CDK CLI, see xref:configure-access[Configure security credentials for the {aws} CDK CLI]. - -The recommended approach for new users developing locally, who are not given a method of authentication by their employer, is to set up {aws} IAM Identity Center. This method includes installing the {aws} CLI for ease of configuration and for regularly signing in to the {aws} access portal. If you choose this method, your environment should contain the following elements after you complete the procedure for https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html[IAM Identity Center authentication] in the _{aws} SDKs and Tools Reference Guide_: - -* The {aws} CLI, which you use to start an {aws} access portal session before you run your application. -* A https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html[shared {aws} config file] having a `[default]` profile with a set of configuration values that can be referenced from the {aws} CDK. To find the location of this file, see https://docs.aws.amazon.com/sdkref/latest/guide/file-location.html[Location of the shared files] in the _{aws} SDKs and Tools Reference Guide_. -* The shared `config` file sets the https://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html[region] setting. This sets the default {aws} Region the {aws} CDK and CDK CLI use for {aws} requests. -* The CDK CLI uses the profile's link:https://docs.aws.amazon.com/sdkref/latest/guide/feature-sso-credentials.html#feature-sso-credentials-profile[SSO token provider configuration] to acquire credentials before sending requests to {aws}. The `sso_role_name` value, which is an IAM role connected to an IAM Identity Center permission set, should allow access to the {aws} services used in your application. -+ -The following sample `config` file shows a default profile set up with SSO token provider configuration. The profile's `sso_session` setting refers to the named link:https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html#section-session[`sso-session` section]. The `sso-session` section contains settings to initiate an {aws} access portal session. -+ -[source,none,subs="verbatim,attributes"] ----- -[default] -sso_session = -sso_account_id = \<111122223333> -sso_role_name = -region = -output = - -[sso-session ] -sso_region = -sso_start_url = -sso_registration_scopes = sso:account:access ----- - -[#accessportal] -=== Start an {aws} access portal session - -Before accessing {aws} services, you need an active {aws} access portal session for the CDK CLI to use IAM Identity Center authentication to resolve credentials. Depending on your configured session lengths, your access will eventually expire and the CDK CLI will encounter an authentication error. Run the following command in the {aws} CLI to sign in to the {aws} access portal. - -[source,bash,subs="verbatim,attributes"] ----- -aws sso login ----- - -If your SSO token provider configuration is using a named profile instead of the default profile, the command is `aws sso login --profile `. Also specify this profile when issuing `cdk` commands using the `--profile` option or the `AWS_PROFILE` environment variable. - -To test if you already have an active session, run the following {aws} CLI command. - -[source,bash,subs="verbatim,attributes"] ----- -aws sts get-caller-identity ----- - -The response to this command should report the IAM Identity Center account and permission set configured in the shared `config` file. - -[NOTE] -==== - -If you already have an active {aws} access portal session and run `aws sso login`, you will not be required to provide credentials. - -The sign in process may prompt you to allow the {aws} CLI access to your data. Since the {aws} CLI is built on top of the SDK for Python, permission messages may contain variations of the `botocore` name. - -==== - -[#cli-environment] -== Specify Region and other configuration - -The CDK CLI needs to know the {aws} Region that you're deploying into and how to authenticate with {aws}. This is needed for deployment operations and to retrieve context values during synthesis. Together, your account and Region make up the _environment_. - -Region may be specified using environment variables or in configuration files. These are the same variables and files used by other {aws} tools such as the {aws} CLI and the various {aws} SDKs. The CDK CLI looks for this information in the following order. - -* The `AWS_DEFAULT_REGION` environment variable. -* A named profile defined in the standard {aws} `config` file and specified using the `--profile` option on `cdk` commands. -* The `[default]` section of the standard {aws} `config` file. - -Besides specifying {aws} authentication and a Region in the `[default]` section, you can also add one or more `[profile ]` sections, where `` is the name of the profile. For more information about named profiles, see https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html[Shared config and credentials files] in the _{aws} SDKs and Tools Reference Guide_. - -The standard {aws} `config` file is located at `~/.aws/config` (macOS/Linux) or `%USERPROFILE%\.aws\config` (Windows). For details and alternate locations, see https://docs.aws.amazon.com/sdkref/latest/guide/file-location.html[Location of the shared config and credentials files] in the _{aws} SDKs and Tools Reference Guide_ - -The environment that you specify in your {aws} CDK app by using the stack's `env` property is used during synthesis. It's used to generate an environment-specific {aws} CloudFormation template, and during deployment, it overrides the account or Region specified by one of the preceding methods. For more information, see xref:environments[Environments for the {aws} CDK]. - -[NOTE] -==== - -The {aws} CDK uses credentials from the same source files as other {aws} tools and SDKs, including the https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html[{aws} Command Line Interface]. However, the {aws} CDK might behave somewhat differently from these tools. It uses the {aws} SDK for JavaScript under the hood. For complete details on setting up credentials for the {aws} SDK for JavaScript, see https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html[Setting credentials]. - -==== - -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. - -[#cli-app-command] -== Specify the app command - -Many features of the CDK CLI require one or more {aws} CloudFormation templates be synthesized, which in turn requires running your application. The {aws} CDK supports programs written in a variety of languages. Therefore, it uses a configuration option to specify the exact command necessary to run your app. This option can be specified in two ways. - -First, and most commonly, it can be specified using the `app` key inside the file `cdk.json`. This is in the main directory of your {aws} CDK project. The CDK CLI provides an appropriate command when creating a new project with `cdk init`. Here is the `cdk.json` from a fresh TypeScript project, for instance. - -[source,json,subs="verbatim,attributes"] ----- -{ - "app": "npx ts-node bin/hello-cdk.ts" -} ----- - -The CDK CLI looks for `cdk.json` in the current working directory when attempting to run your app. Because of this, you might keep a shell open in your project's main directory for issuing CDK CLI commands. - -The CDK CLI also looks for the app key in `~/.cdk.json` (that is, in your home directory) if it can't find it in `./cdk.json`. Adding the app command here can be useful if you usually work with CDK code in the same language. - -If you are in some other directory, or to run your app using a command other than the one in `cdk.json`, use the `--app` (or `-a`) option to specify it. - -[source,none,subs="verbatim,attributes"] ----- -cdk --app "npx ts-node bin/hello-cdk.ts" ls ----- - -When deploying, you may also specify a directory containing synthesized cloud assemblies, such as `cdk.out`, as the value of `--app`. The specified stacks are deployed from this directory; the app is not synthesized. - -[#cli-stacks] -== Specify stacks - -Many CDK CLI commands (for example, `cdk deploy`) work on stacks defined in your app. If your app contains only one stack, the CDK CLI 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. - -[source,none,subs="verbatim,attributes"] ----- -cdk synth PipelineStack LambdaStack ----- - -You may also use wildcards to specify IDs that match a pattern. - -* `?` matches any single character -* `\*` matches any number of characters (`*` alone matches all stacks) -* `**` matches everything in a hierarchy - -You may also use the `--all` option to specify all stacks. - -If your app uses xref:cdk-pipeline[CDK Pipelines], the CDK CLI understands your stacks and stages as a hierarchy. Also, the `--all` option and the `\*` wildcard only match top-level stacks. To match all the stacks, use ``\**``. Also use `**` to indicate all the stacks under a particular hierarchy. - -When using wildcards, enclose the pattern in quotes, or escape the wildcards with `\`. If you don't, your shell may try to expand the pattern to the names of files in the current directory. At best, this won't do what you expect; at worst, you could deploy stacks you didn't intend to. This isn't strictly necessary on Windows because `cmd.exe` does not expand wildcards, but is good practice nonetheless. - -[source,none,subs="verbatim,attributes"] ----- -cdk synth "*Stack" # PipelineStack, LambdaStack, etc. -cdk synth 'Stack?' # StackA, StackB, Stack1, etc. -cdk synth \* # All stacks in the app, or all top-level stacks in a CDK Pipelines app -cdk synth '**' # All stacks in a CDK Pipelines app -cdk synth 'PipelineStack/Prod/**' # All stacks in Prod stage in a CDK Pipelines app ----- - -[NOTE] -==== - -The order in which you specify the stacks is not necessarily the order in which they will be processed. The CDK CLI accounts for dependencies between stacks when deciding the order in which to process them. For example, let's say that one stack uses a value produced by another (such as the ARN of a resource defined in the second stack). In this case, the second stack is synthesized before the first one because of this dependency. You can add dependencies between stacks manually using the stack's `link:https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html#addwbrdependencytarget-reason[addDependency()]` method. - -==== - -[#cli-bootstrap] -== Bootstrap your {aws} environment - -Deploying stacks with the CDK requires special dedicated {aws} CDK resources to be provisioned. The `cdk bootstrap` command creates the necessary resources for you. You only need to bootstrap if you are deploying a stack that requires these dedicated resources. See xref:bootstrapping[{aws} CDK bootstrapping] for details. - -[source,none,subs="verbatim,attributes"] ----- -cdk bootstrap ----- - -If issued with no arguments, as shown here, the `cdk bootstrap` command synthesizes the current app and bootstraps the environments its stacks will be deployed to. If the app contains environment-agnostic stacks, which don't explicitly specify an environment, the default account and Region are bootstrapped, or the environment specified using `--profile`. - -Outside of an app, you must explicitly specify the environment to be bootstrapped. You may also do so to bootstrap an environment that's not specified in your app or local {aws} profile. Credentials must be configured (e.g. in `~/.aws/credentials`) for the specified account and Region. You may specify a profile that contains the required credentials. - -[source,none,subs="verbatim,attributes"] ----- -cdk bootstrap / # e.g. -cdk bootstrap 1111111111/us-east-1 -cdk bootstrap --profile test 1111111111/us-east-1 ----- - -[IMPORTANT] -==== - -Each environment (account/region combination) to which you deploy such a stack must be bootstrapped separately. - -==== - -You may incur {aws} charges for what the {aws} CDK stores in the bootstrapped resources. Additionally, if you use `--bootstrap-customer-key`, an {aws} KMS key will be created, which also incurs charges per environment. - -[NOTE] -==== - -Earlier versions of the bootstrap template created a KMS key by default. To avoid charges, re-bootstrap using `--no-bootstrap-customer-key`. - -==== - -[NOTE] -==== - -CDK CLI v2 does not support the original bootstrap template, dubbed the legacy template, used by default with CDK v1. - -==== - -[IMPORTANT] -==== - -The modern bootstrap template effectively grants the permissions implied by the `--cloudformation-execution-policies` to any {aws} account in the `--trust` list. By default, this extends permissions to read and write to any resource in the bootstrapped account. Make sure to xref:bootstrapping-customizing[configure the bootstrapping stack] with policies and trusted accounts that you are comfortable with. - -==== - -[#cli-init] -== Create a new app - -To create a new app, create a directory for it, then, inside the directory, issue `cdk init`. - -[source,none,subs="verbatim,attributes"] ----- -mkdir my-cdk-app -cd my-cdk-app -cdk init