MCPcopy Index your code
hub / github.com/cdklabs/cdk-enterprise-iac

github.com/cdklabs/cdk-enterprise-iac @v0.1.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v0.1.0 ↗ · + Follow
110 symbols 238 edges 37 files 33 documented · 30%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

CDK Enterprise IaC

Utilities for using CDK within enterprise constraints.

Install

Typescript

npm install @cdklabs/cdk-enterprise-iac

Python

pip install cdklabs.cdk-enterprise-iac

Who this project is for

Within large enterprises, builders can come up against enterprise imposed constraints when deploying on AWS.

This could be simple things such as "All IAM roles must have a specific Permissions Boundary attached".

This could also be more restrictive such as strict separation of duties, only allowing certain teams the ability to deploy specific AWS resources (e.g. Networking team can deploy VPCs, Subnets, and route tables. Security team can deploy IAM resources. Developers can deploy Compute. DBAs can deploy Databases, etc.)

Enterprises with very restrictive environments like these would benefit from taking a closer look at their policies to see how they can allow builders to safely deploy resources with less friction. However in many enterprises this is easier said than done, and builders are still expected to deliver.

This project is meant to reduce friction for builders working within these enterprise constraints while the enterprise determines what policies make the most sense for their organization, and is in no way prescriptive.

Usage

There are many tools available, all detailed in API.md.

A few examples of these tools below:

Adding permissions boundaries to all generated IAM roles

Example for AddPermissionBoundary in Typescript project.

import * as cdk from 'aws-cdk-lib';
import { MyStack } from '../lib/my-project-stack';
import { Aspects } from 'aws-cdk-lib';
import { AddPermissionBoundary } from '@cdklabs/cdk-enterprise-iac';

const app = new cdk.App();
new MyStack(app, 'MyStack');

Aspects.of(app).add(
  new AddPermissionBoundary({
    permissionsBoundaryPolicyName: 'MyPermissionBoundaryName',
    instanceProfilePrefix: 'MY_PREFIX_', // optional, Defaults to ''
    policyPrefix: 'MY_POLICY_PREFIX_', // optional, Defaults to ''
    rolePrefix: 'MY_ROLE_PREFIX_', // optional, Defaults to ''
  })
);

Example for AddPermissionBoundary in Python project.

import aws_cdk as cdk
from cdklabs.cdk_enterprise_iac import AddPermissionBoundary
from test_py.test_py_stack import TestPyStack


app = cdk.App()
TestPyStack(app, "TestPyStack")

cdk.Aspects.of(app).add(AddPermissionBoundary(
    permissions_boundary_policy_name="MyPermissionBoundaryName",
    instance_profile_prefix="MY_PREFIX_",  # optional, Defaults to ""
    policy_prefix="MY_POLICY_PREFIX_",  # optional, Defaults to ""
    role_prefix="MY_ROLE_PREFIX_"  # optional, Defaults to ""
))

app.synth()

Resource extraction

:warning: Resource extraction is in an experimental phase. Test and validate before using in production. Please open any issues found here.

NOTE: You must have the AWS CLI installed and available for the Resource Extractor to work.

In many enterprises, there are separate teams with different IAM permissions than developers deploying CDK applications.

For example there might be a networking team with permissions to deploy AWS::EC2::SecurityGroup and AWS::EC2::EIP, or a security team with permissions to deploy AWS::IAM::Role and AWS::IAM::Policy, but the developers deploying the CDK don't have those permissions.

When a developer doesn't have permissions to deploy necessary resources in their CDK application, writing good code becomes difficult to manage when a cdk deploy will quickly error due to not being able to deploy something like an AWS::IAM::Role which is foundational to any project deployed into AWS.

An enterprise should allow builders to deploy these resources via CDK for many reasons, and can use Permissions Boundaries to prevent privilege escalation. For enterprises that haven't yet utilized Permissions Boundaries, the ResourceExtractor can make it easier for builders to write good CDK while complying with enterprise policies.

Using the ResourceExtractor Aspect, developers can write their CDK code as though they had sufficient IAM permissions, but extract those resources into a separate stack for an external team to deploy on their behalf.

Take the following example stack:

import { App, Aspects, RemovalPolicy, Stack } from 'aws-cdk-lib';
import { Code, Function, Runtime } from 'aws-cdk-lib/aws-lambda';
import { Bucket } from 'aws-cdk-lib/aws-s3';

const app = new App();
const appStack = new Stack(app, 'MyAppStack');

const func = new Function(appStack, 'TestLambda', {
  code: Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  handler: 'index.handler',
  runtime: Runtime.PYTHON_3_11,
});
const bucket = new Bucket(appStack, 'TestBucket', {
  autoDeleteObjects: true,
  removalPolicy: RemovalPolicy.DESTROY,
});
bucket.grantReadWrite(func);

app.synth()

The synthesized Cloudformation would include all AWS resources required, including resources a developer might not have permissions to deploy

The above example would include the following snippet in the synthesized Cloudformation

TestLambdaServiceRoleC28C2D9C:
  Type: 'AWS::IAM::Role'
  Properties:
    AssumeRolePolicyDocument:
      Statement:
        - Action: 'sts:AssumeRole'
          Effect: Allow
          Principal:
            Service: lambda.amazonaws.com
      Version: 2012-10-17
    # excluding remaining properties
  TestLambda2F70C45E:
    Type: 'AWS::Lambda::Function'
    Properties:
      Role: !GetAtt
        - TestLambdaServiceRoleC28C2D9C
        - Arn
      # excluding remaining properties

While including bucket.grantReadWrite(func) in the CDK application ensures an IAM role with least privilege IAM policies for the application, the creation of IAM resources such as Roles and Policies may be restricted to a security team, resulting in the synthesized Cloudformation template not being deployable by a developer.

Using the ResourceExtractor, we can pull out an arbitrary list of Cloudformation resources that a developer doesn't have permissions to provision, and create a separate stack that can be sent to a security team.

import { App, Aspects, RemovalPolicy, Stack } from 'aws-cdk-lib';
import { Code, Function, Runtime } from 'aws-cdk-lib/aws-lambda';
import { Bucket } from 'aws-cdk-lib/aws-s3';
// Import ResourceExtractor
import { ResourceExtractor } from '@cdklabs/cdk-enterprise-iac';

const app = new App();
const appStack = new Stack(app, 'MyAppStack');
// Set up a destination stack to extract resources to
const extractedStack = new Stack(app, 'ExtractedStack');

const func = new Function(appStack, 'TestLambda', {
  code: Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  handler: 'index.handler',
  runtime: Runtime.PYTHON_3_11,
});
const bucket = new Bucket(appStack, 'TestBucket', {
  autoDeleteObjects: true,
  removalPolicy: RemovalPolicy.DESTROY,
});
bucket.grantReadWrite(func);

// Capture the output of app.synth()
const synthedApp = app.synth();
// Apply the ResourceExtractor Aspect
Aspects.of(app).add(
  new ResourceExtractor({
    // synthesized stacks to examine
    stackArtifacts: synthedApp.stacks,
    // Array of Cloudformation resources to extract
    resourceTypesToExtract: [
      'AWS::IAM::Role',
      'AWS::IAM::Policy',
      'AWS::IAM::ManagedPolicy',
      'AWS::IAM::InstanceProfile',
    ],
    // Destination stack for extracted resources
    extractDestinationStack: extractedStack,
  })
);
// Resynthing since ResourceExtractor has modified the app
app.synth({ force: true });

In the example above, all resources are created in the appStack, and an empty extractedStack is also created.

We apply the ResourceExtractor Aspect, specifying the Cloudformation resource types the developer is unable to deploy due to insufficient IAM permissions.

Now when we list stacks in the CDK project, we can see an added stack

$ cdk ls
MyAppStack
ExtractedStack

Taking a look at these synthesized stacks, in the ExtractedStack we'll find:

Resources:
  TestLambdaServiceRoleC28C2D9C:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: 'sts:AssumeRole'
            Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
        Version: 2012-10-17
      # excluding remaining properties
Outputs:
  ExportAppStackTestLambdaServiceRoleC28C2D9C:
    Value:
      'Fn::GetAtt':
        - TestLambdaServiceRoleC28C2D9C
        - Arn
    Export:
      Name: 'AppStack:TestLambdaServiceRoleC28C2D9C'  # Exported name

And inside the synthesized MyAppStack template:

Resources:
  TestLambda2F70C45E:
    Type: 'AWS::Lambda::Function'
    Properties:
      Role: !ImportValue 'AppStack:TestLambdaServiceRoleC28C2D9C'  # Using ImportValue instrinsic function to use pre-created IAM role
      # excluding remaining properties

In this scenario, a developer is able to provide an external security team with sufficient IAM privileges to deploy the ExtractedStack.

Once deployed, a developer can run cdk deploy MyAppStack without errors due to insufficient IAM privileges

Value Sharing methods

When resources are extracted from a stack, there must be a method to reference the resources that have been extracted.

There are three methods (see ResourceExtractorShareMethod enum)

  • CFN_OUTPUT
  • SSM_PARAMETER
  • API_LOOKUP
CFN_OUTPUT

The default sharing method is CFN_OUTPUT, which uses Cloudformation Export/Import to Export values in the extracted stack (see Outputs), and use the Fn::ImportValue intrinsic function to reference those values.

This works fine, but some teams may prefer a looser coupling between the extracted stack deployed by an external team and the rest of the CDK infrastructure.

SSM_PARAMETER

In this method, the extracted stack generates Parameters in AWS Systems Manager Parameter Store, and modifies the CDK application to look up the generated parameter using aws_ssm.StringParameter.valueFromLookup() at synthesis time.

Example on using this method:

import { ResourceExtractor, ResourceExtractorShareMethod } from '@cdklabs/cdk-enterprise-iac';

Aspects.of(app).add(
  new ResourceExtractor({
    stackArtifacts: synthedApp.stacks,
    resourceTypesToExtract: [
      'AWS::IAM::Role',
      'AWS::IAM::Policy',
      'AWS::IAM::ManagedPolicy',
      'AWS::IAM::InstanceProfile',
    ],
    extractDestinationStack: extractedStack,
    valueShareMethod: ResourceExtractorShareMethod.SSM_PARAMETER,  // Specify SSM_PARAMETER Method
  });
);
API_LOOKUP

The API_LOOKUP sharing method is a work in progress, and not yet supported

Resource Partials

Some resources that get extracted might reference resources that aren't yet created.

In our example CDK application we include the line

bucket.grantReadWrite(func);

This creates an AWS::IAM::Policy that includes the necessary Actions scoped down to the S3 bucket.

When the AWS::IAM::Policy is extracted, it's unable to use Ref or Fn::GetAtt to reference the S3 bucket since the S3 bucket wasn't extracted.

In this case we substitute the reference with a "partial ARN" that makes a best effort to scope the resources in the IAM policy statement to the ARN of the yet-to-be created S3 bucket.

There are multiple resource types supported out of the box (found in createDefaultTransforms). In the event you have a resource not yet supported, you'll receive a MissingTransformError. In this case you can either open an issue with the resource in question, or you can include the additionalTransforms property.

Consider the following:

const vpc = new Vpc(stack, 'TestVpc');
const db = new DatabaseInstance(stack, 'TestDb', {
  vpc,
  engine: DatabaseInstanceEngine.POSTGRES,
})
const func = new Function(stack, 'TestLambda', {
  code: Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  handler: 'index.handler',
  runtime: Runtime.PYTHON_3_11,
});
db.secret?.grantRead(func)

const synthedApp = app.synth();
Aspects.of(app).add(
  new ResourceExtractor({
    extractDestinationStack: extractedStack,
    stackArtifacts: synthedApp.stacks,
    valueShareMethod: ResourceExtractorShareMethod.CFN_OUTPUT,
    resourceTypesToExtract: ['AWS::IAM::Role', 'AWS::IAM::Policy'],
    additionalTransforms: {
      'AWS::SecretsManager::SecretTargetAttachment': `arn:${Aws.PARTITION}:secretsmanager:${Aws.REGION}:${Aws.ACCOUNT_ID}:secret:some-expected-value*`,
    },
  });
);
app.synth({ force: true });

In this case, there is a AWS::SecretsManager::SecretTargetAttachment generated to complete the final link between a Secrets Manager secret and the associated database by adding the database connection information to the secret JSON, which returns the ARN of the generated secret.

In the context of extracting the IAM policy, we want to tell the ResourceExtractor how to handle the resource section of the IAM policy statement so that it is scoped down sufficiently.

In this case rather than using a Ref: LogicalIdForTheSecretTargetAttachment we construct the ARN we want

Extension points exported contracts — how you extend this code

AddPermissionBoundaryProps (Interface)
(no doc)
src/patches/addPermissionsBoundary.ts
EcsIsoServiceAutoscalerProps (Interface)
(no doc)
src/constructs/ecsIsoServiceAutoscaler/ecsIsoServiceAutoscaler.ts
RemoveTagsProps (Interface)
(no doc)
src/patches/removeTags.ts
SubnetConfig (Interface)
(no doc)
src/constructs/populateProvidedVpc/populateProvidedVpc.ts
AddCfnInitProxyProps (Interface)
(no doc)
src/patches/addCfnInitProxy.ts
PopulateWithConfigProps (Interface)
(no doc)
src/constructs/populateProvidedVpc/populateProvidedVpc.ts
SetApiGatewayEndpointConfigurationProps (Interface)
(no doc)
src/patches/setApiGatewayEndpointConfiguration.ts
SplitVpcEvenlyProps (Interface)
(no doc)
src/constructs/populateProvidedVpc/populateProvidedVpc.ts

Core symbols most depended-on inside this repo

generateArnPreamble
called by 13
src/patches/resource-extractor/resourceTransformer.ts
_trigger_scaling_action
called by 8
resources/constructs/ecsIsoServiceAutoscaler/ecs_scaling_manager.py
getResourceId
called by 4
src/utils/utils.ts
checkAndOverride
called by 4
src/patches/addPermissionsBoundary.ts
_get_alarm_states
called by 3
resources/constructs/ecsIsoServiceAutoscaler/ecs_scaling_manager.py
_get_ecs_service
called by 3
resources/constructs/ecsIsoServiceAutoscaler/ecs_scaling_manager.py
rebuildFnJoin
called by 3
src/patches/resource-extractor/cfnStore.ts
_get_time_since_last_ecs_update
called by 2
resources/constructs/ecsIsoServiceAutoscaler/ecs_scaling_manager.py

Shape

Method 42
Class 32
Function 18
Interface 15
Enum 3

Languages

TypeScript85%
Python15%

Modules by API surface

src/patches/resource-extractor/resourceExtractor.ts17 symbols
src/patches/resource-extractor/resourceTransformer.ts11 symbols
src/patches/resource-extractor/cfnStore.ts11 symbols
test/constructs/ecsIsoServiceAutoscaler/resources/test_ecs_scaling_manager.py9 symbols
src/constructs/populateProvidedVpc/populateProvidedVpc.ts9 symbols
src/patches/addCfnInitProxy.ts8 symbols
src/patches/addPermissionsBoundary.ts6 symbols
src/patches/setApiGatewayEndpointConfiguration.ts5 symbols
src/patches/removeTags.ts5 symbols
resources/constructs/ecsIsoServiceAutoscaler/ecs_scaling_manager.py5 symbols
src/patches/addLambdaEnvironmentVariables.ts4 symbols
src/constructs/enterpriseDnsResolver/enterpriseDnsResolver.ts4 symbols

For agents

$ claude mcp add cdk-enterprise-iac \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact