Home > Software design >  CDK: How to use/import s3 defined in one stack to another stack (in a different file)?
CDK: How to use/import s3 defined in one stack to another stack (in a different file)?

Time:12-13

I am trying to define s3 bucket in one stack and use that bucket in another stack. Both the stack are in different files. How to access bucket.ts's s3 bucket in pipeline.ts bucket.

I am looking for an answer which explains the concept so that I repeat it for other stacks too.

bucket.ts

    import * as cdk from 'aws-cdk-lib';
    import * as s3 from 'aws-cdk-lib/aws-s3';
    import { Construct } from 'constructs';
    
    export class PipelineSourceBucket extends cdk.Stack {
        constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    
            super(scope, id, props);
    
            const sourceBucket = new s3.Bucket(this, 'pipelineSourceBucket', {
                versioned: true, // a Bucket used as a source in CodePipeline must be versioned
            });
        }
    }

pipeline.ts

    import * as cdk from 'aws-cdk-lib';
    import { Construct } from 'constructs';
    import * as codepipeline from 'aws-cdk-lib/aws-codepipeline';
    import * as codepipeline_actions from 'aws-cdk-lib/aws-codepipeline-actions';
    
    
    export class PipelineStack extends cdk.Stack {
      constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    
        super(scope, id, props);
    
        const pipeline = new codepipeline.Pipeline(this, 'CodePipeline', {
          pipelineName: 'jatin-ci-cd',
          crossAccountKeys: false, // not required as it wont be cross account deployment
        })
        const sourceAction = new codepipeline_actions.S3SourceAction({
          actionName: 'S3Source',
          bucket: sourceBucket,  //how to access the bucket from other stack?
          bucketKey: 'path/to/file.zip',
          output: sourceOutput,
        });
      }
    }

CodePudding user response:

The aws-cdk-examples repo has several multi-stack examples demonstrating the pattern of passing variables from one construct class to another. The steps are:

The dependency producer declares a public field to export a reference.

export class PipelineSourceBucket extends cdk.Stack {
    readonly sourceBucket: s3.Bucket

    constructor(scope: Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);
        this.sourceBucket = new s3.Bucket(this, 'pipelineSourceBucket');
    }
}

The dependency consumer requires a bucket in its props.

interface PipelineStackProps extends cdk.StackProps {
    bucket: s3.Bucket
}

Instantiate both in app.ts and pass the bucket variable from the produer to the consumer:

const { sourceBucket } = new PipelineSourceBucket(app, "SourceStack", {...etc})

new PipelieStack(app, "PipelineStack", {bucket: sourceBucket, ...etc})

Behind the scenes, the CDK will synth this dependency as CloudFormation import and export cross-stack references.

  • Related