### Quick Start Example
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/index.md
This snippet demonstrates how to define and deploy a CloudFormation StackSet across specified AWS accounts and regions using the CDK StackSets library. It includes setting up a basic IAM role within the StackSet's template.
```typescript
import { Stack, App } from 'aws-cdk-lib';
import { StackSet, StackSetStack, StackSetTarget, StackSetTemplate } from 'cdk-stacksets';
import * as iam from 'aws-cdk-lib/aws-iam';
const app = new App();
const parentStack = new Stack(app, 'ParentStack');
// Define what to deploy
const stackSetStack = new StackSetStack(parentStack, 'MyStackSet');
new iam.Role(stackSetStack, 'MyRole', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});
// Create the StackSet
new StackSet(parentStack, 'StackSet', {
template: StackSetTemplate.fromStackSetStack(stackSetStack),
target: StackSetTarget.fromAccounts({
accounts: ['111111111111', '222222222222'],
regions: ['us-east-1', 'eu-west-1'],
}),
});
```
--------------------------------
### Install cdk-stacksets-go
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/README.md
Install the cdk-stacksets-go package for Go projects.
```bash
go get cdk-stacksets-go
```
--------------------------------
### Full StackSetProps Configuration Example
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/configuration.md
This example demonstrates the complete configuration of the StackSet construct, including template, targeting, permissions, execution, operation controls, parameters, and capabilities. It shows how to import necessary components and instantiate the StackSet with various options.
```typescript
import { Stack, App } from 'aws-cdk-lib';
import {
StackSet,
StackSetStack,
StackSetTarget,
StackSetTemplate,
DeploymentType,
RegionConcurrencyType,
Capability,
OperationPreferences,
} from 'cdk-stacksets';
const app = new App();
const parentStack = new Stack(app, 'Parent');
const stackSetStack = new StackSetStack(parentStack, 'SSTemplate');
const stackSet = new StackSet(parentStack, 'StackSet', {
// Template (required)
template: StackSetTemplate.fromStackSetStack(stackSetStack),
// Naming
stackSetName: 'MyStackSet',
description: 'Deploys infrastructure across accounts and regions',
// Targeting
target: StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'eu-west-1'],
organizationalUnits: ['ou-prod-xxxxx'],
}),
// Permissions
deploymentType: DeploymentType.serviceManaged({
autoDeployEnabled: true,
autoDeployRetainStacks: true,
delegatedAdmin: true,
}),
// Execution
managedExecution: true,
// Operation Control
operationPreferences: {
regionConcurrencyType: RegionConcurrencyType.PARALLEL,
maxConcurrentPercentage: 100,
failureTolerancePercentage: 10,
},
// Parameters
parameters: {
Environment: 'production',
InstanceType: 't3.large',
},
// Capabilities
capabilities: [Capability.NAMED_IAM],
});
```
--------------------------------
### StackSetStack Example with File Assets
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stackset-stack.md
Example demonstrating how to configure StackSetStack with file asset support. It shows creating an S3 bucket and passing it along with a prefix to the StackSetStack props.
```typescript
import { Bucket } from 'aws-cdk-lib/aws-s3';
const parentStack = new Stack(app, 'ParentStack');
const assetBucket = new Bucket(parentStack, 'AssetBucket', {
bucketName: 'my-assets-us-east-1',
});
const stackSetStack = new StackSetStack(parentStack, 'MyStackSetStack', {
assetBuckets: [assetBucket],
assetBucketPrefix: 'my-assets',
});
```
--------------------------------
### Example OperationPreferences Configuration
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/types.md
An example of how to configure operation preferences for parallel deployment with specific concurrency and failure tolerance percentages.
```typescript
operationPreferences: {
regionConcurrencyType: RegionConcurrencyType.PARALLEL,
maxConcurrentPercentage: 100,
failureTolerancePercentage: 10,
}
```
--------------------------------
### StackSet Constructor Example
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stackset.md
Creates a new StackSet instance. This example shows how to configure a self-managed StackSet targeting specific accounts and regions, using a StackSetStack for the template.
```typescript
const stackSet = new StackSet(stack, 'MyStackSet', {
deploymentType: DeploymentType.selfManaged(),
target: StackSetTarget.fromAccounts({
accounts: ['111111111111'],
regions: ['us-east-1'],
}),
template: StackSetTemplate.fromStackSetStack(stackSetStack),
});
```
--------------------------------
### StackSetTarget Deployment Examples
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Demonstrates how to deploy a StackSet to specific accounts or organizational units using StackSetTarget. Includes options for additional accounts and exclusions.
```typescript
StackSetTarget.fromAccounts({
accounts: ['11111111111', '22222222222'],
regions: ['us-east-1', 'us-east-2'],
});
```
```typescript
StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'us-east-2'],
organizationalUnits: ['ou-1111111', 'ou-2222222'],
additionalAccounts: ['33333333333'],
});
```
```typescript
StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'us-east-2'],
organizationalUnits: ['ou-1111111', 'ou-2222222'],
excludeAccounts: ['11111111111'],
});
```
--------------------------------
### Example StackSetParameter Usage
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/types.md
Illustrates how to create a StackSetParameter object with environment and instance type configurations.
```typescript
const params: StackSetParameter = {
Environment: 'production',
InstanceType: 't3.large',
EnableMonitoring: 'true',
};
```
--------------------------------
### Install cdk-stacksets via npm
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/README.md
Install the cdk-stacksets package using npm for TypeScript/JavaScript projects.
```bash
npm install cdk-stacksets
```
--------------------------------
### SelfManagedOptions Example
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/types.md
Example of configuring self-managed deployment with a custom admin role and execution role name. This requires pre-creating IAM roles with specific trust policies and permissions.
```typescript
import * as iam from 'aws-cdk-lib/aws-iam';
const adminRole = new iam.Role(stack, 'AdminRole', {
assumedBy: new iam.ServicePrincipal('cloudformation.amazonaws.com'),
});
DeploymentType.selfManaged({
adminRole,
executionRoleName: 'CustomExecutionRole',
})
```
--------------------------------
### Install cdk-stacksets via pip
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/README.md
Install the cdk-stacksets package using pip for Python projects.
```bash
pip install cdk-stacksets
```
--------------------------------
### Initialize OperationPreferences
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Demonstrates how to import and initialize an OperationPreferences object. This is the starting point for configuring operation preferences.
```typescript
import { OperationPreferences } from 'cdk-stacksets'
const operationPreferences: OperationPreferences = { ... }
```
--------------------------------
### with
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Applies one or more mixins to this construct. Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple `with()` calls if subsequent mixins should apply to added constructs.
```APIDOC
## with
### Description
Applies one or more mixins to this construct. Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple `with()` calls if subsequent mixins should apply to added constructs.
### Method
public with(mixins: ...IMixin[]): IConstruct
### Parameters
#### Path Parameters
- **mixins** (IMixin[]) - Required - The mixins to apply.
```
--------------------------------
### Stack ID Example
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
An example of a resolved stack ID, which is an ARN for a CloudFormation stack.
```typescript
// After resolving, looks like
'arn:aws:cloudformation:us-west-2:123456789012:stack/teststack/51af3dc0-da77-11e4-872e-1234567db123'
```
--------------------------------
### Synthesized Template Asset Reference
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stacksettemplate.md
Example of how a synthesized CloudFormation template references an uploaded file asset for a Lambda function.
```json
{
"MyFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Code": {
"S3Bucket": "assets-{region}",
"S3Key": "asset123.zip"
}
}
}
}
```
--------------------------------
### Complex OU Filtering for StackSet Targets
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stacksettarget.md
Configures StackSet targets using organizational units with exclusion and inclusion rules. This example deploys to the finance OU excluding the audit account, and to core infrastructure OUs plus a specific security tooling account.
```typescript
// Deploy to finance OU except for audit account
const financeTarget = StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'us-west-2'],
organizationalUnits: ['ou-finance-xxxxx'],
excludeAccounts: ['999999999999'], // Audit account
});
// Deploy to core infrastructure OUs plus security tooling account
const infraTarget = StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'eu-west-1'],
organizationalUnits: ['ou-core-platform-xxxxx', 'ou-shared-services-xxxxx'],
additionalAccounts: ['888888888888'], // Security tooling account
});
stackSet.addTarget(financeTarget);
stackSet.addTarget(infraTarget);
```
--------------------------------
### StackSet toString Method
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Returns a string representation of the StackSet construct. No specific setup required.
```typescript
public toString(): string
```
--------------------------------
### Initialize SelfManagedOptions
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Demonstrates how to initialize SelfManagedOptions. Ensure you have imported the necessary type.
```typescript
import { SelfManagedOptions } from 'cdk-stacksets'
const selfManagedOptions: SelfManagedOptions = { ... }
```
--------------------------------
### StackSetStack Initializer
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Explains how to initialize a StackSetStack construct, including its parameters.
```APIDOC
## StackSetStack Initializer
### Description
Initializes a new instance of the StackSetStack class.
### Method
```typescript
new StackSetStack(scope: Construct, id: string, props?: StackSetStackProps)
```
### Parameters
#### scope
- **Type:** constructs.Construct - Required
The scope in which to define this StackSet.
#### id
- **Type:** string - Required
The ID of the StackSet.
#### props
- **Type:** StackSetStackProps - Optional
The properties of the StackSet.
```
--------------------------------
### Template File Property
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
The name of the CloudFormation template file generated during synthesis. Example: MyStack.template.json.
```typescript
public readonly templateFile: string;
```
--------------------------------
### Basic StackSetStack Creation
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stackset-stack.md
Demonstrates how to create a basic StackSetStack and define resources within it. This is useful for defining a reusable CloudFormation template for AWS StackSets.
```typescript
import { Stack, App } from 'aws-cdk-lib';
import { StackSetStack, StackSet, StackSetTarget, StackSetTemplate } from 'cdk-stacksets';
import * as iam from 'aws-cdk-lib/aws-iam';
const app = new App();
const parentStack = new Stack(app, 'StackSetParent');
// Create a StackSetStack and define resources
const stackSetStack = new StackSetStack(parentStack, 'MyStackSet');
new iam.Role(stackSetStack, 'MyRole', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});
// Create a StackSet that references the template
new StackSet(parentStack, 'StackSet', {
template: StackSetTemplate.fromStackSetStack(stackSetStack),
target: StackSetTarget.fromAccounts({
regions: ['us-east-1', 'eu-west-1'],
accounts: ['111111111111', '222222222222'],
}),
});
```
--------------------------------
### TargetOptions Initializer
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Shows the basic structure for initializing TargetOptions. This configuration is used for specifying deployment targets within a stack set.
```typescript
import { TargetOptions } from 'cdk-stacksets'
const targetOptions: TargetOptions = { ... }
```
--------------------------------
### StackSetTarget fromAccounts Method
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Use this method to deploy a StackSet to a specified list of AWS accounts. Requires account IDs and target regions.
```typescript
import { StackSetTarget } from 'cdk-stacksets'
StackSetTarget.fromAccounts({
accounts: ['11111111111', '22222222222'],
regions: ['us-east-1', 'us-east-2'],
});
```
--------------------------------
### Create StackSet Target from Accounts
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/types.md
Demonstrates creating a StackSet target configuration using specific AWS account IDs, regions, and parameter overrides.
```typescript
StackSetTarget.fromAccounts({
accounts: ['111111111111', '222222222222', '333333333333'],
regions: ['us-east-1', 'eu-west-1'],
parameterOverrides: {
Environment: 'production',
},
})
```
--------------------------------
### addMetadata
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Adds an arbitary key-value pair, with information you want to record about the stack. These get translated to the Metadata section of the generated template.
```APIDOC
## addMetadata
### Description
Adds an arbitary key-value pair, with information you want to record about the stack. These get translated to the Metadata section of the generated template.
### Method
public addMetadata(key: string, value: any): void
### Parameters
#### Path Parameters
- **key** (string) - Required -
- **value** (any) - Required -
```
--------------------------------
### addFileAsset
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Registers a File Asset and returns parameters for referencing the asset in the template. The synthesizer must ensure the asset is available before deployment.
```APIDOC
## addFileAsset
### Description
Register a File Asset. Returns the parameters that can be used to refer to the asset inside the template. The synthesizer must rely on some out-of-band mechanism to make sure the given files are actually placed in the returned location before the deployment happens.
### Method
```typescript
public addFileAsset(asset: FileAssetSource): FileAssetLocation
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
#### asset
- *Type:* aws-cdk-lib.FileAssetSource - Required - The file asset to register.
```
--------------------------------
### DeploymentType Service Managed
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Use for StackSets deployed with service-managed permissions within an AWS Organization. AWS handles IAM role creation and permissions setup.
```typescript
import { DeploymentType } from 'cdk-stacksets'
DeploymentType.serviceManaged(options?: ServiceManagedOptions)
```
--------------------------------
### Accessing StackSetTemplate templateUrl
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stacksettemplate.md
Demonstrates how to get the S3 URL of a CloudFormation template from a StackSetStack object. The URL is used by CloudFormation to retrieve the template during stack instance deployment.
```typescript
const template = StackSetTemplate.fromStackSetStack(stackSetStack);
console.log(template.templateUrl);
// Output: https://s3.cdk-assets-111111111111-us-east-1/abc123def456.zip
```
--------------------------------
### DeploymentType.selfManaged
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/deploymenttype.md
Creates a self-managed StackSet deployment where users must pre-create IAM roles in source and target accounts. This model offers granular permission control but requires manual setup and maintenance of roles.
```APIDOC
## DeploymentType.selfManaged
### Description
Creates a self-managed StackSet deployment. You must pre-create IAM roles in source and target accounts with appropriate permissions. This model provides more granular permission control but requires manual setup and maintenance.
### Method
`static selfManaged(options?: SelfManagedOptions): DeploymentType`
### Parameters
#### Query Parameters
- **options** (SelfManagedOptions) - Optional - Configuration for self-managed permissions.
- **adminRole** (iam.IRole) - Optional - The admin role in the source account.
- **executionRoleName** (string) - Optional - The name for the execution role in target accounts.
### Response
#### Success Response
- **DeploymentType** - An instance of DeploymentType configured for self-managed deployment.
### Request Example
```typescript
import { DeploymentType } from 'cdk-stacksets';
import * as iam from 'aws-cdk-lib/aws-iam';
// Basic self-managed with defaults
const deployment = DeploymentType.selfManaged();
// With custom execution role name
const deploymentCustom = DeploymentType.selfManaged({
executionRoleName: 'MyCustomExecutionRole',
});
// With externally-managed admin role
const adminRole = iam.Role.fromRoleArn(
stack,
'AdminRole',
'arn:aws:iam::111111111111:role/StackSetAdminRole'
);
const deploymentExternal = DeploymentType.selfManaged({
adminRole,
executionRoleName: 'StackSetExecutionRole',
});
// Creating a new admin role
const newAdminRole = new iam.Role(stack, 'StackSetAdminRole', {
assumedBy: new iam.ServicePrincipal('cloudformation.amazonaws.com'),
});
const deploymentNew = DeploymentType.selfManaged({
adminRole: newAdminRole,
});
```
```
--------------------------------
### StackSetTarget Initialization
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Initializes a new StackSetTarget instance. No specific configuration is shown in this basic initializer.
```typescript
import { StackSetTarget } from 'cdk-stacksets'
new StackSetTarget()
```
--------------------------------
### addDockerImageAsset Method - Unsupported
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stackset-stack.md
This method is not supported for StackSets due to the multi-region deployment model. Attempting to use it will throw an error.
```typescript
public addDockerImageAsset(_asset: DockerImageAssetSource): DockerImageAssetLocation
```
--------------------------------
### Getting a Logical ID for a CloudFormation Element
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Allocates a unique CloudFormation-compatible logical identity for a given resource element. This method is essential for rendering initial logical identities and can be overridden to customize the naming scheme.
```typescript
public getLogicalId(element: CfnElement): string
```
--------------------------------
### StackSetTarget.fromAccounts
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stacksettarget.md
Creates a StackSetTarget for deploying to a specific list of AWS accounts across specified regions. This method is suitable for known, fixed account lists.
```APIDOC
## StackSetTarget.fromAccounts
### Description
Creates a StackSetTarget that deploys to a specific list of AWS accounts across specified regions. This is the simplest form of targeting when you have a known, fixed set of accounts.
### Method
`static fromAccounts(options: AccountsTargetOptions): StackSetTarget`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
`options` (`AccountsTargetOptions`) - Required - Configuration for account-based deployment.
### Request Example
```typescript
import { StackSetTarget } from 'cdk-stacksets';
// Basic account targeting
const target = StackSetTarget.fromAccounts({
accounts: ['111111111111', '222222222222', '333333333333'],
regions: ['us-east-1', 'eu-west-1'],
});
// With parameter overrides
const targetWithParams = StackSetTarget.fromAccounts({
accounts: ['111111111111', '222222222222'],
regions: ['us-east-1', 'eu-west-1'],
parameterOverrides: {
Environment: 'production',
InstanceType: 't3.large',
},
});
```
### Response
#### Success Response (200)
`StackSetTarget`
#### Response Example
None provided in source.
```
--------------------------------
### formatArn
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Creates an ARN from components.
```APIDOC
## formatArn
### Description
Creates an ARN from components.
### Method
public formatArn(options: ArnComponents): string
```
--------------------------------
### Create StackSetTarget from Accounts
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stacksettarget.md
Use `StackSetTarget.fromAccounts` to deploy to a fixed list of AWS accounts across specified regions. Supports optional parameter overrides for StackSet deployments.
```typescript
import { StackSetTarget } from 'cdk-stacksets';
// Basic account targeting
const target = StackSetTarget.fromAccounts({
accounts: ['111111111111', '222222222222', '333333333333'],
regions: ['us-east-1', 'eu-west-1'],
});
// With parameter overrides
const targetWithParams = StackSetTarget.fromAccounts({
accounts: ['111111111111', '222222222222'],
regions: ['us-east-1', 'eu-west-1'],
parameterOverrides: {
Environment: 'production',
InstanceType: 't3.large',
},
});
```
--------------------------------
### Add cdk-stacksets package for .NET
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/README.md
Add the cdk-stacksets package to your .NET project using the dotnet CLI. Replace 'X.X.X' with the desired version.
```bash
dotnet add package CdklabsCdkStacksets --version X.X.X
```
--------------------------------
### StackSetStack with CloudFormation Parameters
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stackset-stack.md
Shows how to add CloudFormation parameters to a StackSetStack for environment-specific configurations. This allows for dynamic deployment of resources based on parameter values.
```typescript
import { Stack, App } from 'aws-cdk-lib';
import { StackSetStack } from 'cdk-stacksets';
const app = new App();
const parentStack = new Stack(app, 'StackSetParent');
const stackSetStack = new StackSetStack(parentStack, 'MyStackSet');
// Add CloudFormation parameters for environment variation
new CfnParameter(stackSetStack, 'Environment', {
type: 'String',
default: 'prod',
allowedValues: ['dev', 'staging', 'prod'],
});
new CfnParameter(stackSetStack, 'InstanceCount', {
type: 'Number',
default: 2,
});
```
--------------------------------
### Initialize StackSetStackSynthesizer
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Initializes a StackSetStackSynthesizer for deployment environment. It interoperates with the parent stack's StackSynthesizer.
```typescript
import { StackSetStackSynthesizer } from 'cdk-stacksets'
new StackSetStackSynthesizer(assetBuckets?: IBucket[], assetBucketPrefix?: string)
```
--------------------------------
### Adding Multiple Deployment Targets to StackSet
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stackset.md
Demonstrates how to add multiple deployment targets to a StackSet using the `addTarget` method. This allows for deploying to different sets of accounts and regions, including specifying parameter overrides for specific targets.
```typescript
const stackSet = new StackSet(stack, 'MyStackSet', {
template: StackSetTemplate.fromStackSetStack(stackSetStack),
});
// Add target for production accounts
stackSet.addTarget(
StackSetTarget.fromAccounts({
accounts: ['111111111111', '222222222222'],
regions: ['us-east-1', 'eu-west-1'],
})
);
// Add another target for development accounts
stackSet.addTarget(
StackSetTarget.fromAccounts({
accounts: ['333333333333'],
regions: ['us-east-1'],
parameterOverrides: {
Environment: 'development',
},
})
);
```
--------------------------------
### StackSet.with
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Applies one or more mixins to the StackSet construct. Mixins are applied in the order they are provided.
```APIDOC
## StackSet.with
### Description
Applies one or more mixins to this construct. Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple `with()` calls if subsequent mixins should apply to added constructs.
### Method
```typescript
public with(mixins: ...IMixin[]): IConstruct
```
### Parameters
#### Mixins
- **mixins** (...constructs.IMixin[]) - Required - The mixins to apply.
```
--------------------------------
### Service-Managed StackSet with Auto-Deployment
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/README.md
Sets up a service-managed StackSet with auto-deployment enabled and configured to retain stacks.
```typescript
new StackSet(parentStack, 'StackSet', {
template: StackSetTemplate.fromStackSetStack(stackSetStack),
deploymentType: DeploymentType.serviceManaged({
autoDeployEnabled: true,
autoDeployRetainStacks: true,
}),
target: StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1'],
organizationalUnits: ['ou-prod-xxxxx'],
}),
});
```
--------------------------------
### Configure CDK Pipeline for StackSet Deployments
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/README.md
Sets up a CDK CodePipeline to automate the synthesis and deployment of infrastructure. It defines the source repository, connection details, and the synth step commands.
```typescript
const pipeline = new pipelines.CodePipeline(this, 'BootstrapPipeline', {
synth: new pipelines.ShellStep('Synth', {
commands: [
'yarn install --frozen-lockfile',
'npx cdk synth',
],
input: pipelines.CodePipelineSource.connection('myorg/myrepo', 'main', {
connectionArn: 'arn:aws:codestar-connections:us-east-2:111111111111:connection/ca65d487-ca6e-41cc-aab2-645db37fdb2b',
}),
}),
selfMutation: true,
});
const regions = [
'us-east-1',
'us-east-2',
'us-west-2',
'eu-west-2',
'eu-west-1',
'ap-south-1',
'ap-southeast-1',
];
pipeline.addStage(
new BootstrapStage(app, 'DevBootstrap', {
env: {
region: 'us-east-1',
account: '111111111111',
},
stacksetName: 'CDKToolkit-dev',
initialBootstrapTarget: StackSetTarget.fromOrganizationalUnits({
regions,
organizationalUnits: ['ou-hrza-ar333427'],
}),
}),
);
pipeline.addStage(
new BootstrapStage(app, 'ProdBootstrap', {
env: {
region: 'us-east-1',
account: '111111111111',
},
stacksetName: 'CDKToolkit-prd',
initialBootstrapTarget: StackSetTarget.fromOrganizationalUnits({
regions,
organizationalUnits: ['ou-hrza-bb999427', 'ou-hraa-ar111127'],
}),
}),
);
```
--------------------------------
### addFileAsset Method
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stackset-stack.md
Processes file assets for the StackSetStack, returning S3 location details. The bucket name is dynamically constructed from the prefix and the stack's region.
```typescript
public addFileAsset(asset: FileAssetSource): FileAssetLocation
```
--------------------------------
### No Concurrency (Safest Option)
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/configuration.md
Deploy one region at a time, stopping on any failure, and updating only one stack at a time. This is the safest option for maximum control and minimal risk.
```typescript
const operationPreferences: OperationPreferences = {
// One region at a time
regionConcurrencyType: RegionConcurrencyType.SEQUENTIAL,
regionOrder: ['us-east-1', 'eu-west-1'],
// Stop on any failure
failureToleranceCount: 0,
// Update 1 stack at a time
maxConcurrentCount: 1,
};
```
--------------------------------
### StackSetStackProps Initializer
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Demonstrates how to initialize StackSetStackProps. This is used for configuring stack set stacks.
```typescript
import { StackSetStackProps } from 'cdk-stacksets'
const stackSetStackProps: StackSetStackProps = { ... }
```
--------------------------------
### bind
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Binds the synthesizer to the stack environment it will be used on. This method must be called before any other methods.
```APIDOC
## bind
### Description
Bind to the stack this environment is going to be used on. Must be called before any of the other methods are called.
### Method
```typescript
public bind(stack: Stack): void
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
#### stack
- *Type:* aws-cdk-lib.Stack - Required - The stack to bind to.
```
--------------------------------
### Full Service-Managed Configuration
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/configuration.md
Specify all available options for service-managed StackSets, including auto-deployment, stack retention, and delegated administration.
```typescript
DeploymentType.serviceManaged({
autoDeployEnabled: true,
autoDeployRetainStacks: false,
delegatedAdmin: true,
})
```
--------------------------------
### Initialize DeploymentType
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Instantiates a new DeploymentType object. This is the base class for defining deployment types.
```typescript
import { DeploymentType } from 'cdk-stacksets'
new DeploymentType()
```
--------------------------------
### OrganizationsTargetOptions
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Options for deploying a StackSet to a set of Organizational Units (OUs).
```APIDOC
## OrganizationsTargetOptions
### Description
Options for deploying a StackSet to a set of Organizational Units (OUs).
### Initializer
```typescript
import { OrganizationsTargetOptions } from 'cdk-stacksets'
const organizationsTargetOptions: OrganizationsTargetOptions = { ... }
```
### Properties
#### `regions`
- **Type:** `string[]`
- **Required:** Yes
- **Description:** A list of regions the Stack should be deployed to. If `StackSetProps.operationPreferences.regionOrder` is specified then the StackSet will be deployed sequentially otherwise it will be deployed to all regions in parallel.
#### `parameterOverrides`
- **Type:** `{[ key: string ]: string}`
- **Optional:** Yes
- **Default:** use parameter overrides specified in `StackSetProps.parameterOverrides`
- **Description:** Parameter overrides that should be applied to only this target.
#### `organizationalUnits`
- **Type:** `string[]`
- **Required:** Yes
- **Description:** A list of organizational unit ids to deploy to. The StackSet will deploy the provided Stack template to all accounts in the OU. This can be further filtered by specifying either `additionalAccounts` or `excludeAccounts`. If the `deploymentType` is specified with `autoDeployEnabled` then the StackSet will automatically deploy the Stack to new accounts as they are added to the specified `organizationalUnits`.
#### `additionalAccounts`
- **Type:** `string[]`
- **Optional:** Yes
- **Default:** Stacks will only be deployed to accounts that exist in the specified organizationalUnits
- **Description:** A list of additional AWS accounts to deploy the StackSet to. This can be used to deploy the StackSet to additional AWS accounts that exist in a different OU than what has been provided in `organizationalUnits`.
#### `excludeAccounts`
- **Type:** `string[]`
- **Optional:** Yes
- **Default:** Stacks will be deployed to all accounts that exist in the OUs specified in the organizationUnits property
- **Description:** A list of AWS accounts to exclude from deploying the StackSet to. This can be useful if there are accounts that exist in an OU that is provided in `organizationalUnits`, but you do not want the StackSet to be deployed.
#### `intersectionAccounts`
- **Type:** `string[]`
- **Optional:** Yes
- **Default:** Stacks will be deployed to all accounts in the specified OUs
- **Description:** A list of AWS accounts to intersect with the organizational units. Only accounts that are BOTH in the specified OUs AND in this list will have the StackSet deployed.
```
--------------------------------
### AccountsTargetOptions Initializer
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Initialize an AccountsTargetOptions object. This is used to specify deployment targets for a StackSet.
```typescript
import { AccountsTargetOptions } from 'cdk-stacksets'
const accountsTargetOptions: AccountsTargetOptions = { ... }
```
--------------------------------
### StackSetTemplate Initialization
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
Initializes a new StackSetTemplate instance. This is a basic initializer and does not take arguments.
```typescript
import { StackSetTemplate } from 'cdk-stacksets'
new StackSetTemplate()
```
--------------------------------
### Minimal StackSet Deployment
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/README.md
Creates a basic StackSet targeting a specific AWS account and region.
```typescript
new StackSet(parentStack, 'StackSet', {
template: StackSetTemplate.fromStackSetStack(stackSetStack),
target: StackSetTarget.fromAccounts({
accounts: ['111111111111'],
regions: ['us-east-1'],
}),
});
```
--------------------------------
### StackSet with Multiple Targets and Parameters
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/README.md
Configures a StackSet with initial parameters and adds a new target with parameter overrides.
```typescript
const stackSet = new StackSet(parentStack, 'StackSet', {
template: StackSetTemplate.fromStackSetStack(stackSetStack),
parameters: { Environment: 'production' },
});
stackset.addTarget(
StackSetTarget.fromAccounts({
accounts: ['dev-account'],
regions: ['us-east-1'],
parameterOverrides: { Environment: 'dev' },
})
);
```
--------------------------------
### Formatting an ARN from Components
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
This method constructs an AWS ARN using provided components. It intelligently uses the stack's partition, region, and account if these are not specified in the components. Handles empty string components by inserting an empty string into the ARN.
```typescript
public formatArn(components: ArnComponents): string
```
--------------------------------
### Phased Rollout with Multiple Targets
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stacksettarget.md
Defines targets for a StackSet in phases: first testing in a dev account, then deploying to a staging OU, and finally to all production accounts. Each target can specify accounts, regions, and parameter overrides.
```typescript
import { Stack, App } from 'aws-cdk-lib';
import { StackSet, StackSetTarget, StackSetTemplate, StackSetStack } from 'cdk-stacksets';
const app = new App();
const parentStack = new Stack(app, 'RolloutStack');
const stackSetStack = new StackSetStack(parentStack, 'MyApp');
const stackSet = new StackSet(parentStack, 'StackSet', {
template: StackSetTemplate.fromStackSetStack(stackSetStack),
});
// Phase 1: Test in dev account
stackSet.addTarget(StackSetTarget.fromAccounts({
accounts: ['111111111111'],
regions: ['us-east-1'],
parameterOverrides: { Environment: 'dev' },
}));
// Phase 2: Deploy to staging OU
stackSet.addTarget(StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'eu-west-1'],
organizationalUnits: ['ou-staging-xxxxx'],
parameterOverrides: { Environment: 'staging' },
}));
// Phase 3: Deploy to all production accounts
stackSet.addTarget(StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'eu-west-1', 'ap-southeast-1'],
organizationalUnits: ['ou-prod-xxxxx'],
parameterOverrides: { Environment: 'production' },
}));
```
--------------------------------
### StackSetTarget.fromOrganizationalUnits
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stacksettarget.md
Creates a StackSetTarget for deploying to AWS Organizations organizational units. The StackSet deploys to all accounts within specified OUs, with options for filtering accounts.
```APIDOC
## StackSetTarget.fromOrganizationalUnits
### Description
Creates a StackSetTarget that deploys to AWS Organizations organizational units. The StackSet automatically deploys to all accounts within the specified OUs, including nested OUs. Optionally filter accounts with `additionalAccounts`, `excludeAccounts`, or `intersectionAccounts`.
### Method
`static fromOrganizationalUnits(options: OrganizationsTargetOptions): StackSetTarget`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
`options` (`OrganizationsTargetOptions`) - Required - Configuration for OU-based deployment with optional account filtering.
### Request Example
```typescript
import { StackSetTarget } from 'cdk-stacksets';
// Deploy to all accounts in an OU
const target = StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'eu-west-1'],
organizationalUnits: ['ou-prod-12345678'],
});
// Deploy to OU but exclude specific accounts
const targetExclude = StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1'],
organizationalUnits: ['ou-prod-12345678'],
excludeAccounts: ['111111111111', '222222222222'],
});
// Deploy to OU plus additional accounts from other OUs
const targetAdd = StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'eu-west-1'],
organizationalUnits: ['ou-prod-12345678'],
additionalAccounts: ['999999999999'],
});
// Deploy only to accounts in both the OU and the list
const targetIntersect = StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1'],
organizationalUnits: ['ou-prod-12345678', 'ou-staging-87654321'],
intersectionAccounts: ['111111111111', '222222222222', '333333333333'],
});
```
### Response
#### Success Response (200)
`StackSetTarget`
#### Response Example
None provided in source.
```
--------------------------------
### Sequential Regional Deployment with Failure Tolerance
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/configuration.md
Deploy one region at a time in order, allowing one stack failure per region and updating 10% of stacks concurrently. Use for controlled rollouts with specific regional ordering.
```typescript
const operationPreferences: OperationPreferences = {
// Deploy one region at a time in order
regionConcurrencyType: RegionConcurrencyType.SEQUENTIAL,
regionOrder: ['us-east-1', 'eu-west-1', 'ap-southeast-1'],
// Allow 1 stack to fail per region
failureToleranceCount: 1,
// Update 10% of stacks at a time (minimum 1)
maxConcurrentPercentage: 10,
};
```
--------------------------------
### CDK StackSets Project File Structure
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/index.md
This snippet shows the directory structure of the CDK StackSets project. It highlights the main source files and the test directory.
```tree
cdk-stacksets/
├── src/
│ ├── index.ts # Public exports
│ ├── stackset.ts # StackSet, StackSetTarget, DeploymentType classes
│ └── stackset-stack.ts # StackSetStack, StackSetStackSynthesizer classes
└── test/ # Integration tests
```
--------------------------------
### Multi-Target Phased Rollout for StackSets
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/index.md
Define a phased rollout strategy for StackSets by adding targets sequentially. Each target can specify accounts, OUs, regions, and parameter overrides for different deployment phases.
```typescript
const stackSet = new StackSet(parentStack, 'StackSet', {
template,
});
// Phase 1: Dev
stackSet.addTarget(
StackSetTarget.fromAccounts({
accounts: ['dev-account-id'],
regions: ['us-east-1'],
parameterOverrides: { Environment: 'dev' },
})
);
// Phase 2: Staging
stackSet.addTarget(
StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'eu-west-1'],
organizationalUnits: ['ou-staging-xxxxx'],
parameterOverrides: { Environment: 'staging' },
})
);
// Phase 3: Production
stackSet.addTarget(
StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'eu-west-1', 'ap-southeast-1'],
organizationalUnits: ['ou-prod-xxxxx'],
parameterOverrides: { Environment: 'prod' },
})
);
```
--------------------------------
### Migrate from Manual CloudFormation StackSets
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/index.md
Use the StackSet construct with a StackSetTemplate and target accounts to replace manual AWS CLI commands for creating StackSets.
```bash
aws cloudformation create-stack-set --stack-set-name MyStackSet ...
aws cloudformation create-stack-instances --stack-set-name MyStackSet ...
```
```typescript
new StackSet(stack, 'MyStackSet', {
template: StackSetTemplate.fromStackSetStack(stackSetStack),
target: StackSetTarget.fromAccounts({...}),
});
```
--------------------------------
### Using StackSetTemplate in StackSet Constructor
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stacksettemplate.md
Illustrates how to provide a StackSetTemplate to the StackSet constructor. This is a common pattern for deploying stacks across multiple AWS accounts and regions using AWS CDK StackSets.
```typescript
new StackSet(stack, 'StackSet', {
template: StackSetTemplate.fromStackSetStack(stackSetStack),
target: StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'eu-west-1'],
organizationalUnits: ['ou-prod-xxxxx'],
}),
});
```
--------------------------------
### Create StackSetTarget from Organizational Units
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stacksettarget.md
Use `StackSetTarget.fromOrganizationalUnits` to deploy to AWS Organizations OUs. This method supports deploying to all accounts within specified OUs and allows for optional account filtering using `additionalAccounts`, `excludeAccounts`, or `intersectionAccounts`.
```typescript
import { StackSetTarget } from 'cdk-stacksets';
// Deploy to all accounts in an OU
const target = StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'eu-west-1'],
organizationalUnits: ['ou-prod-12345678'],
});
// Deploy to OU but exclude specific accounts
const targetExclude = StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1'],
organizationalUnits: ['ou-prod-12345678'],
excludeAccounts: ['111111111111', '222222222222'],
});
// Deploy to OU plus additional accounts from other OUs
const targetAdd = StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1', 'eu-west-1'],
organizationalUnits: ['ou-prod-12345678'],
additionalAccounts: ['999999999999'],
});
// Deploy only to accounts in both the OU and the list
const targetIntersect = StackSetTarget.fromOrganizationalUnits({
regions: ['us-east-1'],
organizationalUnits: ['ou-prod-12345678', 'ou-staging-87654321'],
intersectionAccounts: ['111111111111', '222222222222', '333333333333'],
});
```
--------------------------------
### IStackSet Interface Properties
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/API.md
This section details the properties available on the IStackSet interface, including node, env, stack, and role.
```APIDOC
## IStackSet Interface
Represents a CloudFormation StackSet.
### Properties
#### `node`Required
- *Type:* constructs.Node
The tree node.
#### `env`Required
- *Type:* aws-cdk-lib.ResourceEnvironment
The environment this resource belongs to.
For resources that are created and managed by the CDK
(generally, those created by creating new class instances like Role, Bucket, etc.),
this is always the same as the environment of the stack they belong to;
however, for imported resources
(those obtained from static methods like fromRoleArn, fromBucketName, etc.),
that might be different than the stack they were imported into.
#### `stack`Required
- *Type:* aws-cdk-lib.Stack
The stack in which this resource is defined.
#### `role`Optional
- *Type:* aws-cdk-lib.aws_iam.IRole
Only available on self managed stacksets.
The admin role that CloudFormation will use to perform stackset operations.
This role should only have permissions to be assumed by the CloudFormation service
and to assume the execution role in each individual account.
When you create the execution role it must have an assume role policy statement which
allows `sts:AssumeRole` from this admin role.
To grant specific users/groups access to use this role to deploy stacksets they must have
a policy that allows `iam:GetRole` & `iam:PassRole` on this role resource.
```
--------------------------------
### Create and Configure S3 Bucket for StackSet Assets
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/README.md
Defines an S3 bucket in the parent stack and configures its resource policy to grant read access to an AWS Organization. This bucket can then be used to store assets for StackSet deployments.
```typescript
const bucket = new s3.Bucket(this, "Assets", {
bucketName: "prefix-us-east-1",
});
bucket.addToResourcePolicy(
new iam.PolicyStatement({
actions: ["s3:Get*", "s3:List*"],
resources: [bucket.arnForObjects("*"Подсказка: "), bucket.bucketArn],
principals: [new iam.OrganizationPrincipal("o-xyz")],
})
);
```
--------------------------------
### Self-Managed StackSets with Auto-Created Admin Role
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/deploymenttype.md
Demonstrates self-managed StackSets where the admin role is automatically created by the CDK. The ARN of the auto-created role can be accessed after instantiation.
```typescript
// Using default auto-created role
new StackSet(stack, 'StackSet', {
template: StackSetTemplate.fromStackSetStack(stackSetStack),
deploymentType: DeploymentType.selfManaged(),
target: StackSetTarget.fromAccounts({
regions: ['us-east-1'],
accounts: ['222222222222', '333333333333'],
}),
});
// Accessing the auto-created role
const stackSet = new StackSet(stack, 'StackSet', {
template: StackSetTemplate.fromStackSetStack(stackSetStack),
deploymentType: DeploymentType.selfManaged(),
target: StackSetTarget.fromAccounts({
regions: ['us-east-1'],
accounts: ['222222222222'],
}),
});
console.log(stackSet.role?.roleArn);
```
--------------------------------
### StackSetTemplate.fromStackSetStack
Source: https://github.com/cdklabs/cdk-stacksets/blob/main/_autodocs/stacksettemplate.md
Creates a StackSetTemplate from a StackSetStack. This method bridges infrastructure definitions to the StackSet deployment mechanism by synthesizing the StackSetStack, uploading the template to S3, and capturing its URL for StackSet references.
```APIDOC
## StackSetTemplate.fromStackSetStack
### Description
Creates a StackSetTemplate from a StackSetStack. This is the standard way to bridge your infrastructure definition (in StackSetStack) to the StackSet deployment mechanism.
### Method Signature
```typescript
public static fromStackSetStack(stack: StackSetStack): StackSetTemplate
```
### Parameters
#### Path Parameters
- **stack** (`StackSetStack`) - Required - The StackSetStack to extract the template from.
### Returns
- `StackSetTemplate`
### Example
```typescript
import { Stack, App } from 'aws-cdk-lib';
import { StackSetStack, StackSetTemplate, StackSet, StackSetTarget } from 'cdk-stacksets';
const app = new App();
const parentStack = new Stack(app, 'ParentStack');
// Create the template source
const stackSetStack = new StackSetStack(parentStack, 'MyStackSet');
// Create a template from it
const template = StackSetTemplate.fromStackSetStack(stackSetStack);
// Use the template in a StackSet
new StackSet(parentStack, 'StackSet', {
template,
target: StackSetTarget.fromAccounts({
regions: ['us-east-1'],
accounts: ['111111111111'],
}),
});
```
```