

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.

# Bootstrap your environment for use with the AWS CDK
<a name="bootstrapping-env"></a>

Bootstrap your AWS environment to prepare it for AWS Cloud Development Kit (AWS CDK) stack deployments.
+ For an introduction to environments, see [Environments for the AWS CDK](environments.md).
+ For an introduction to bootstrapping, see [AWS CDK bootstrapping](bootstrapping.md).

## How to bootstrap your environment
<a name="bootstrapping-howto"></a>

You can use the AWS CDK Command Line Interface (AWS CDK CLI) or your preferred AWS CloudFormation deployment tool to bootstrap your environment.<a name="bootstrapping-howto-cli"></a>

 **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:  

```
$ cdk bootstrap <aws://123456789012/us-east-1>
```
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:  

```
$ 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:  

```
$ aws sts get-caller-identity --profile <prod>
```
To display the default Region, use the `aws configure get` command:  

```
$ aws configure get region
$ aws configure get region --profile <prod>
```
When providing an argument, the `aws://` prefix is optional. The following is valid:  

```
$ cdk bootstrap <123456789012/us-east-1>
```
To bootstrap multiple environments at the same time, provide multiple arguments:  

```
$ cdk bootstrap <aws://123456789012/us-east-1> <aws://123456789012/us-east-2>
```  
 **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:  

```
$ cdk bootstrap --profile <prod>
```
For more information on the `cdk bootstrap` command and supported options, see [cdk bootstrap](ref-cli-cmd-bootstrap.md).<a name="bootstrapping-howto-cfn"></a>

 **Use any AWS CloudFormation tool**   
You can copy the [bootstrap template](https://github.com/aws/aws-cdk-cli/blob/main/packages/aws-cdk/lib/api/bootstrap/bootstrap-template.yaml) 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:  

**Example**  

```
$ cdk bootstrap --show-template > bootstrap-template.yaml
```
On Windows, PowerShell must be used to preserve the encoding of the template.  

```
powershell "cdk bootstrap --show-template | Out-File -encoding utf8 bootstrap-template.yaml"
```
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:  

```
$ cdk bootstrap --template <bootstrap-template.yaml>
```
The following is an example of using the AWS CLI to deploy the template:  

**Example**  

```
aws cloudformation create-stack \
  --stack-name CDKToolkit \
  --template-body file://<path/to/>bootstrap-template.yaml \
  --capabilities CAPABILITY_NAMED_IAM \
  --region <us-west-1>
```

```
aws cloudformation create-stack ^
  --stack-name CDKToolkit ^
  --template-body file://<path/to/>bootstrap-template.yaml ^
  --capabilities CAPABILITY_NAMED_IAM ^
  --region <us-west-1>
```
For information on using CloudFormation StackSets to bootstrap multiple environments, see [Bootstrapping multiple AWS accounts for AWS CDK using CloudFormation StackSets](https://aws.amazon.com/blogs/mt/bootstrapping-multiple-aws-accounts-for-aws-cdk-using-cloudformation-stacksets/) in the * AWS Cloud Operations & Migrations Blog*.

## When to bootstrap your environment
<a name="bootstrapping-env-when"></a>

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:

```
$ 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)
```<a name="bootstrapping-env-when-update"></a>

 **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 [Bootstrap template version history](#bootstrap-template-history).

## Default resources created during bootstrapping
<a name="bootstrapping-env-default"></a><a name="bootstrapping-env-roles"></a>

 **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` <a name="bootstrapping-env-roles-cfn"></a>  
 `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.  
 `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.  
 `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.  
 `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.  
 `LookupRole`   
This IAM role grants `readOnly` permission to look up [context values](context.md) from the AWS environment. It is assumed by the CDK CLI when performing tasks such as template synthesis and deployments.<a name="bootstrapping-env-default-id"></a>

 **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>-<description>-<account-ID>-<Region>`.  
+  **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`.

## Permissions to use when bootstrapping your environment
<a name="bootstrapping-env-permissions"></a>

When bootstrapping an AWS environment, the IAM identity performing the bootstrapping must have at least the following permissions:

```
{
    "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.

## Customize bootstrapping
<a name="bootstrapping-env-customize"></a>

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 [Customize AWS CDK bootstrapping](bootstrapping-customizing.md).

## Bootstrapping with CDK Pipelines
<a name="bootstrapping-env-pipelines"></a>

If you are using CDK Pipelines to deploy into another account’s environment, and you receive a message like the following:

```
Policy contains a statement with one or more invalid principals
```

This error message means that the appropriate IAM roles do not exist in the other environment. The most likely cause is that the environment has not been bootstrapped. Bootstrap the environment and try again.<a name="bootstrapping-env-pipelines-protect"></a>

 **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 [Enable termination protection for the bootstrap stack](bootstrapping-customizing.md#bootstrapping-customizing-cli-protection).

## Bootstrap template version history
<a name="bootstrap-template-history"></a>

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.


| 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 [KMS.2](https://docs.aws.amazon.com/securityhub/latest/userguide/kms-controls.html#kms-2).  | 
|   **17**   |  2.72.0  |  Addresses Security Hub finding [ECR.3](https://docs.aws.amazon.com/securityhub/latest/userguide/ecr-controls.html#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. ([\$127964](https://github.com/aws/aws-cdk/issues/27964))  | 
|   **20**   |  2.119.0  |  Add `ssm:GetParameters` action to the AWS CloudFormation deploy IAM role. For more information, see [\$128336](https://github.com/aws/aws-cdk/pull/28336/files#diff-4fdac38426c4747aa17d515b01af4994d3d2f12c34f7b6655f24328259beb7bf).  | 
|   **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 [\$131949](https://github.com/aws/aws-cdk/pull/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 [\$131956](https://github.com/aws/aws-cdk/pull/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 [\$1100](https://github.com/aws/aws-cdk-cli/pull/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 [\$1112](https://github.com/aws/aws-cdk-cli/pull/112).  | 
|   **28**   |  2.1015.0  |  Add permissions to perform Stack Refactoring actions to the deployment role, and TagSession permissions to all roles. For more information on this change, see `aws-cdk-cli` PR [\$1471](https://github.com/aws/aws-cdk-cli/pull/471).  | 
|   **29**   |  2.1026.0  |  All AssumeRole calls that provide an ExternalId will be rejected by default, unless disabled. For more information on this change, see `aws-cdk-cli` PR [\$1811](https://github.com/aws/aws-cdk-cli/pull/811).  | 
|   **30**   |  2.1034.0  |  Add permissions to describe stack events to the deployment role, to be able to show CloudFormation Early Validation errors accurately. For more information on this change, see `aws-cdk-cli` PR [\$1970](https://github.com/aws/aws-cdk-cli/pull/970).  | 

## Upgrade from legacy to modern bootstrap template
<a name="bootstrapping-template"></a>

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.


| 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\$1**   |  Amazon S3 bucket  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cdk/v2/guide/bootstrapping-env.html)  | 
|   ** AWS KMS key**   |  IAM roles  |  Amazon ECR repository  | 
|   **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.

## Address Security Hub Findings
<a name="bootstrapping-securityhub"></a>

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.<a name="bootstrapping-securityhub-kms2"></a>

 **[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:  

```
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
              ...
```<a name="bootstrapping-securityhub-kms2-why"></a>  
 **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.  
 **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.  
 **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**   

1. If you have not done so, deploy the CDK bootstrap stack using the `cdk bootstrap` command.

1. If you have not done so, create and deploy your CDK Pipeline. For instructions, see [Continuous integration and delivery (CI/CD) using CDK Pipelines](cdk-pipeline.md).

1. Obtain the AWS KMS key ARN of the CodePipeline artifact bucket. This resource is created during pipeline creation.

1. Obtain a copy of the CDK bootstrap template to modify it. The following is an example, using the AWS CDK CLI:

   ```
   $ cdk bootstrap --show-template > bootstrap-template.yaml
   ```

1. Modify the template by replacing `Resource: *` of the `PipelineCrossAccountArtifactsKey` statement with your ARN value.

1. Deploy the template to update your bootstrap stack. The following is an example, using the CDK CLI:

   ```
   $ cdk bootstrap aws://<account-id>/<region> --template bootstrap-template.yaml
   ```  
 **To fix the Security Hub finding if you’re not using CDK Pipelines for cross-account deployments**   

1. Obtain a copy of the CDK bootstrap template to modify it. The following is an example, using the CDK CLI:

   ```
   $ cdk bootstrap --show-template > bootstrap-template.yaml
   ```

1. Delete the `PipelineCrossAccountArtifactsBucket` and `PipelineCrossAccountArtifactsKey` statements from the template.

1. Deploy the template to update your bootstrap stack. The following is an example, using the CDK CLI:

   ```
   $ cdk bootstrap aws://<account-id>/<region> --template bootstrap-template.yaml
   ```

## Considerations
<a name="bootstrapping-env-considerations"></a>

Since bootstrapping provisions resources in your environment, you may incur AWS charges when those resources are used with the AWS CDK.

# Customize AWS CDK bootstrapping
<a name="bootstrapping-customizing"></a>

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 [AWS CDK bootstrapping](bootstrapping.md).

## Use the CDK CLI to customize bootstrapping
<a name="bootstrapping-customizing-cli"></a>

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 [cdk bootstrap](ref-cli-cmd-bootstrap.md).<a name="bootstrapping-customizing-cli-s3-name"></a>

 **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 [Customize CDK stack synthesis](configure-synth.md#bootstrapping-custom-synth).<a name="bootstrapping-customizing-keys"></a>

 **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.<a name="bootstrapping-customizing-cli-deploy-role"></a>

 **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:  

```
$ 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.

 **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 [Customize CDK stack synthesis](configure-synth.md#bootstrapping-custom-synth).

 **Add tags to the bootstrap stack**   
Use the `--tags` option in the format of `KEY=VALUE` to add CloudFormation tags to your bootstrap stack.

 **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 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:  

```
$ 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.
```<a name="bootstrapping-customizing-cli-accounts-lookup"></a>

 **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.<a name="bootstrapping-customizing-cli-protection"></a>

 **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 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**   

1. Run the following command to enable termination protection on a new or existing bootstrap stack:

   ```
   $ cdk bootstrap --termination-protection
   ```

1. 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:

   ```
   $ aws cloudformation describe-stacks --stack-name <CDKToolkit> --query "Stacks[0].EnableTerminationProtection"
   true
   ```

## Modify the default bootstrap template
<a name="bootstrapping-customizing-template"></a>

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**   

1. 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:

   ```
   $ cdk bootstrap --show-template > <my-bootstrap-template.yaml>
   ```

1. 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 [Follow the bootstrap contract](#bootstrapping-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.

1. Deploy your modified template using your preferred AWS CloudFormation deployment method. The following is an example that uses the CDK CLI:

   ```
   $ cdk bootstrap --template <my-bootstrap-template.yaml>
   ```

## Follow the bootstrap contract
<a name="bootstrapping-contract"></a>

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 [Customize CDK stack synthesis](configure-synth.md#bootstrapping-custom-synth). 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 ` [IStackSynthesizer](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.IStackSynthesizer.html) ` (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.

### Versioning
<a name="bootstrapping-contract-versioning"></a>

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:

```
Resources:
  CdkBootstrapVersion:
    Type: AWS::SSM::Parameter
    Properties:
      Type: String
      Name:
        Fn::Sub: '/cdk-bootstrap/${Qualifier}/version'
      Value: 4
Outputs:
  BootstrapVersion:
    Value:
      Fn::GetAtt: [CdkBootstrapVersion, Value]
```

### Roles
<a name="bootstrapping-contract-roles"></a>

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.

### Outputs
<a name="bootstrapping-contract-outputs"></a>

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.

### Template history
<a name="bootstrapping-contract-history"></a>

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 [Bootstrap template version history](bootstrapping-env.md#bootstrap-template-history).

# Create and apply permissions boundaries for the AWS CDK
<a name="customize-permissions-boundaries"></a>

A *permissions boundary* is an AWS Identity and Access Management (IAM) advanced feature that you can use to set the maximum permissions that an IAM entity, such as a user or role, can have. You can use permissions boundaries to restrict the actions that IAM entities can perform when using the AWS Cloud Development Kit (AWS CDK).

To learn more about permissions boundaries, see [Permissions boundaries for IAM entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) in the *IAM User Guide*.

## When to use permissions boundaries with the AWS CDK
<a name="customize-permissions-boundaries-when"></a>

Consider applying permissions boundaries when you need to restrict developers in your organization from performing certain actions with the AWS CDK. For example, if there are specific resources in your AWS environment that you don’t want developers to modify, you can create and apply a permissions boundary.

## How to apply permissions boundaries with the AWS CDK
<a name="customize-permissions-boundaries-how"></a>

### Create the permissions boundary
<a name="customize-permissions-boundaries-how-create"></a>

First, you create the permissions boundary, using an AWS managed policy or a customer managed policy to set the boundary for an IAM entity (user or role). This policy limits the maximum permissions for the user or role. For instructions on creating permissions boundaries, see [Permissions boundaries for IAM entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) in the *IAM User Guide*.

Permissions boundaries set the maximum permissions that an IAM entity can have, but don’t grant permissions on their own. You must use permissions boundaries with IAM policies to effectively limit and grant the proper permissions for your organization. You must also prevent IAM entities from being able to escape the boundaries that you set. For an example, see [Delegating responsibility to others using permissions boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html#access_policies_boundaries-delegate) in the *IAM User Guide*.

### Apply the permissions boundary during bootstrapping
<a name="customize-permissions-boundaries-how-apply"></a>

After creating the permissions boundary, you can enforce it for the AWS CDK by applying it during bootstrapping.

Use the [`--custom-permissions-boundary`](ref-cli-cmd-bootstrap.md#ref-cli-cmd-bootstrap-options-custom-permissions-boundary) option and specify the name of the permissions boundary to apply. The following is an example that applies a permissions boundary named `cdk-permissions-boundary`:

```
$ cdk bootstrap --custom-permissions-boundary <cdk-permissions-boundary>
```

By default, the CDK uses the `CloudFormationExecutionRole` IAM role, defined in the bootstrap template, to receive permissions for performing deployments. By applying the custom permissions boundary during bootstrapping, the permissions boundary gets attached to this role. The permissions boundary will then set the maximum permissions that can be performed by developers in your organization when using the AWS CDK. To learn more about this role, see [IAM roles created during bootstrapping](bootstrapping-env.md#bootstrapping-env-roles).

When you apply permissions boundaries in this way, they are applied to the specific environment that you bootstrap. To use the same permissions boundary across multiple environments, you must apply the permissions boundary for each environment during bootstrapping. You can also apply different permissions boundaries for different environments.

## Learn more
<a name="customize-permissions-boundaries-learn"></a>

For more information on permissions boundaries, see [When and where to use IAM permissions boundaries](https://aws.amazon.com/blogs/security/when-and-where-to-use-iam-permissions-boundaries/) in the * AWS Security Blog*.

# Troubleshoot AWS CDK bootstrapping issues
<a name="bootstrapping-troubleshoot"></a>

Troubleshoot common issues when bootstrapping your environment with the AWS Cloud Development Kit (AWS CDK).
+ For an introduction to bootstrapping, see [AWS CDK bootstrapping](bootstrapping.md).
+ For instructions on bootstrapping, see [Bootstrap your environment for use with the AWS CDK](bootstrapping-env.md).

## When bootstrapping using the default template, you get a 'CREATE\$1FAILED' error for the Amazon S3 bucket
<a name="bootstrapping-troubleshoot-s3-bucket-name"></a>

When bootstrapping using the AWS CDK Command Line Interface (CDK CLI) `cdk bootstrap` command with the default bootstrap template, you receive the following error:

```
CREATE_FAILED | AWS::S3::Bucket | <BucketName> 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.

### Common causes
<a name="bootstrapping-troubleshoot-s3-bucket-name-causes"></a>

When you bootstrap your environment, the AWS CDK generates physical IDs for your bootstrap resources. For more information, see [Resource IDs created during bootstrapping](bootstrapping-env.md#bootstrapping-env-default-id).

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 [Buckets overview](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucket.html) 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.

### Resolution
<a name="bootstrapping-troubleshoot-s3-bucket-name-resolution"></a>

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 [Amazon S3 console](https://console.aws.amazon.com/s3).

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 <CDKToolkit> --region <Region>` command to view the resources in your bootstrap stack and check if the bucket is listed.
+ In the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation), 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 [Customize AWS CDK bootstrapping](bootstrapping-customizing.md).

If you customize bootstrapping, you will need to apply the same changes to synthesis before you can properly deploy an application. For instructions, see [Customize CDK stack synthesis](configure-synth.md#bootstrapping-custom-synth).

For example, you can provide a new qualifier with `cdk bootstrap`:

```
$ cdk bootstrap --qualifier <abcde0123>
```

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:

**Example**  

```
new MyStack(this, 'MyStack', {
  synthesizer: new DefaultStackSynthesizer({
    qualifier: 'abcde0123',
  }),
});
```

```
new MyStack(this, 'MyStack', {
  synthesizer: new DefaultStackSynthesizer({
    qualifier: 'abcde0123',
  }),
})
```

```
MyStack(self, "MyStack",
    synthesizer=DefaultStackSynthesizer(
        qualifier="abcde0123"
))
```

```
new MyStack(app, "MyStack", StackProps.builder()
  .synthesizer(DefaultStackSynthesizer.Builder.create()
    .qualifier("abcde0123")
    .build())
  .build();
)
```

```
new MyStack(app, "MyStack", new StackProps
{
    Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps
    {
        Qualifier = "abcde0123"
    })
});
```

```
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:  

```
{
  "app": "...",
  "context": {
    "@aws-cdk/core:bootstrapQualifier": "abcde0123"
  }
}
```
To modify only the Amazon S3 bucket name, you can use the ` --bootstrap-bucket-name ` option. The following is an example:  

```
$ cdk bootstrap --bootstrap-bucket-name '<my-new-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:

**Example**  

```
new MyStack(this, 'MyStack', {
  synthesizer: new DefaultStackSynthesizer({
    fileAssetsBucketName: 'my-new-bucket-name',
  }),
});
```

```
new MyStack(this, 'MyStack', {
  synthesizer: new DefaultStackSynthesizer({
    fileAssetsBucketName: 'my-new-bucket-name',
  }),
})
```

```
MyStack(self, "MyStack",
    synthesizer=DefaultStackSynthesizer(
        file_assets_bucket_name='my-new-bucket-name'
))
```

```
new MyStack(app, "MyStack", StackProps.builder()
  .synthesizer(DefaultStackSynthesizer.Builder.create()
    .fileAssetsBucketName("my-new-bucket-name")
    .build())
  .build();
)
```

```
new MyStack(app, "MyStack", new StackProps
{
    Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps
    {
        FileAssetsBucketName = "my-new-bucket-name"
    })
});
```

```
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
}
```

### Prevention
<a name="bootstrapping-troubleshoot-s3-bucket-name-prevention"></a>

We recommend that you proactively bootstrap each AWS environment that you plan to use. For more information, see [When to bootstrap your environment](bootstrapping-env.md#bootstrapping-env-when). 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.