[英]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.我正在创建两个堆栈,并想将第一个堆栈资源(如 Lambda、API Gateway、DyanamoDb)引用到第二个堆栈中,或者使用对第一个堆栈的引用名称 object。 Note: I do not want to use Stack Props to hard code all the resources into second stack.注意:我不想使用 Stack Props 将所有资源硬编码到第二个堆栈中。 Eg File 1例如文件 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文件 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.如果将资源分配为公共只读属性,则可以迭代堆栈 object 的属性并检测IResource
(或您感兴趣的其他)类型的属性。
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
.理论上,您可以使用转义舱口语法访问 Stack 的合成子项(已处理的资源,而不是您定义的原始构造): myStack.node.children
。
This is probably a bad idea unless your use case is unusual.除非您的用例不寻常,否则这可能是个坏主意。
Passing resource dependencies as props is the standard solution.将资源依赖项作为 props 传递是标准解决方案。 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 .如果您发现自己必须在堆栈之间传递大量资源,这可能表明您应该将资源保留在一个堆栈中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.