我有一个具有两个堆栈的应用程序,它们都位于同一地区/帐户内。这些堆栈中的一个需要另一个堆栈中存在的lambda的ARN。我该如何引用?
// within stackA constructor
public StackA(Construct scope, String id, StackProps props) {
SingletonFunction myLambda = SingletonFunction.Builder.create(this, "myLambda")
// some code here
.build()
CfnOutput myLambdaArn = CfnOutput.Builder.create(this, "myLambdaArn")
.exportName("myLambdaArn")
.description("ARN of the lambda that I want to use in StackB")
.value(myLambda.getFunctionArn())
.build();
}
App app = new App();
Stack stackA = new StackA(app, "stackA", someAProps);
Stack stackB = new StackB(app, "stackB", someBProps);
stackB.dependsOn(stackA);
如何将ARN传递到StackB?
答案 0 :(得分:5)
您可以访问不同堆栈中的资源,只要它们位于同一帐户和AWS区域中即可。以下示例定义了堆栈stack1,该堆栈定义了Amazon S3存储桶。然后,它定义第二个堆栈stack2,它将来自stack1的存储桶作为构造函数属性。
// Helper method to build an environment
static Environment makeEnv(String account, String region) {
return Environment.builder().account(account).region(region)
.build();
}
App app = new App();
Environment prod = makeEnv("123456789012", "us-east-1");
StackThatProvidesABucket stack1 = new StackThatProvidesABucket(app, "Stack1",
StackProps.builder().env(prod).build());
// stack2 will take an argument "bucket"
StackThatExpectsABucket stack2 = new StackThatExpectsABucket(app, "Stack,",
StackProps.builder().env(prod).build(), stack1.getBucket());
答案 1 :(得分:4)
选项1:
使用构造函数将数据从堆栈A传递到堆栈B:
您可以扩展cdk.stack
并创建一个包含stackA的新类。
在该堆栈中,使用public XXX: string\number (etc)
公开所需的相关数据(请参见示例中的第2行)。
稍后,只需将此数据传递到StackB构造函数中(您也可以使用props传递它)。
工作代码段:
堆栈A:
export class StackA extends cdk.Stack {
public YourKey: KEY_TYPE;
constructor(scope: cdk.Construct, id: string, props: cdk.StackProps ) {
super(scope, id, props);
Code goes here...
// Output the key
new cdk.CfnOutput(this, 'KEY', { value: this.YourKey });
}
}
堆栈B:
export class StackB extends cdk.Stack {
constructor(scope: cdk.Construct, id: string,importedKey: KEY_TYPE, props: cdk.props) {
super(scope, id, props)
Code goes here...
console.log(importedKey)
}
}
bin ts:
const importedKey = new StackA(app, 'id',props).YourKey;
new StackB(app, 'id',importedKey,props);
选项2:
有时候最好将这种东西保存在参数存储中,然后从那里读取。
更多信息here。
答案 2 :(得分:4)
CDK 的官方文档有一个完整的 sharing a S3 bucket between stacks 示例。我把它复制在下面以便更快地参考。
/**
* Stack that defines the bucket
*/
class Producer extends cdk.Stack {
public readonly myBucket: s3.Bucket;
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const bucket = new s3.Bucket(this, 'MyBucket', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
this.myBucket = bucket;
}
}
interface ConsumerProps extends cdk.StackProps {
userBucket: s3.IBucket;
}
/**
* Stack that consumes the bucket
*/
class Consumer extends cdk.Stack {
constructor(scope: cdk.App, id: string, props: ConsumerProps) {
super(scope, id, props);
const user = new iam.User(this, 'MyUser');
props.userBucket.grantReadWrite(user);
}
}
const producer = new Producer(app, 'ProducerStack');
new Consumer(app, 'ConsumerStack', { userBucket: producer.myBucket });