简体   繁体   中英

Get all the resources defined in one stack to another stack using aws cdk

I am creating two stacks and want to reference first stacks resources like Lambda, API Gateway, DyanamoDb into the second stack either using the name of reference to object to the first stack. Note: I do not want to use Stack Props to hard code all the resources into second stack. Eg File 1

export class StackOne extends cdk.Stack {
    constructor(scope: Construct, id: string, props: StackOneProps) {
    super(scope, id, { env: props.env });
    
    const lambda1 = new lambda.Function();
    const lambda2 = new lambda.Function();
    const api = new apigateway.RestApi()
    new apigateway.LambdaIntegration(
      lambda1
    );
    new apigateway.LambdaIntegration(
      lambda2
    );

    }
}

File 2

export class StackTwo extends cdk.Stack {
    constructor(scope: Construct, id: string, props: StackTwoProps) {
    super(scope, id, { env: props.env });
    
    const StackOne = //Get the StackOne Reference
    StackOne.Resourcs.forEach(rsourcs ==> {} )

    }
}

If you assign the resources as the public readonly properties, you can iterate over the properties of the stack object and detect those of IResource (or other that interests you) type.

export class StackOne extends cdk.Stack {
    public readonly lambda1: Function;
    public readonly lambda2: Function;
    // etc.

    constructor(scope: Construct, id: string, props: StackOneProps) {
    super(scope, id, { env: props.env });
    
    this.lambda1 = new lambda.Function();
    this.lambda2 = new lambda.Function();
    // etc.
    }
}
export interface StackTwoProps { 
    stackOne: Stack
}

export class StackTwo extends cdk.Stack {
    constructor(scope: Construct, id: string, props: StackTwoProps) {
    super(scope, id, { env: props.env });
    
    const getResource = (r: any) => r instanceof IResource
        ? r
        : undefined;
    const keys = Object.keys(props.stackOne);
    const resources = keys
        .map(x => getResource(props.stackOne[x]))
        .filter(x => x !== undefined) as IResource);

    }
}

In theory you can access a Stack's synth-ed children (the processed resources, not the original constructs you defined) with escape hatch syntax: myStack.node.children .

This is probably a bad idea unless your use case is unusual.

Passing resource dependencies as props is the standard solution. If you find yourself having to pass lots and lots of resources between stacks, it may be a sign that you should keep the resources in a single stack .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM