我有一个数据库堆栈,然后将其传递给另一个堆栈:
class DbStack extends cdk.Stack {
public dbSocket: string;
public dbReadSocket: string;
constructor(scope: cdk.Construct, id: string, props: { vpc: ec2.Vpc }) {
super(scope, id);
const { vpc } = props;
const db = new DatabaseCluster(this, "Database", {
engine: rds.DatabaseClusterEngine.AuroraPostgresql,
....
});
this.dbSocket = db.clusterEndpoint.socketAddress;
this.dbReadSocket = db.clusterReadEndpoint.socketAddress;
}
}
const dbStack = new DbStack(app, "db", { vpc });
new MyStack(app, "mystack", {
vpc,
dbSocket: dbStack.dbSocket,
dbReadSocket: dbStack.dbReadSocket,
}
在另一个堆栈中,我将这些套接字传递给ECS环境变量:
export class PpfStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props: MyStackProps) {
super(scope, id, props);
const { vpc, dbSocket, dbReadSocket } = props;
new MyService(this, "svc", {
vpc,
...
environment: {
NODE_ENV: "production",
DATABASE_RO_SOCKET: dbReadSocket,
DATABASE_RW_SOCKET: dbSocket,
},
});
不幸的是,环境变量最终显示为:
db-databasec2aad89b-1t1yxzplxjsvu.cluster-cppalohfw5gz.us-east-2.rds.amazonaws.com:{IndirectPort}
答案 0 :(得分:0)
在我看来,最简单,最直接的方法是使用输出。在第一个堆栈中,添加一个输出(假设您在堆栈的类级别上定义了“ databaseOutput:CfnOutput;”):
this.databaseOutput = new CfnOutput(this, 'DatabaseOutput', {
export: 'db-stack-database-cluster',
value: db.clusterIdentifier
});
然后,在另一个Stack中,可以调用'fromDatabaseClusterAttributes'导入方法:
const db = DatabaseCluster.fromDatabaseClusterAttributes(this, 'ImportedDatabase', {
clusterIdentifier: Fn.importValue('db-stack-database-cluster');
});
然后相应地初始化DatabaseCluster对象,您可以访问其所有属性,然后将它们传递给您的环境变量。
如果集群标识符不是唯一的(很抱歉,我对RDS的了解不那么深),则可以定义更多的输出并使用它们来显示更多的值。然后,您可以在“ fromDatabaseClusterAttributes”调用期间使用所有这些参数。