如何在没有循环依赖的情况下,将安全组添加到具有CDK的现有RDS中



我有一个多堆栈应用程序,我想在一个堆栈中部署RDS,然后在稍后的堆栈中部署连接到RDS的Fargate集群。

以下是如何定义rds:

this.rdsSG = new ec2.SecurityGroup(this, `ecsSG`, {
vpc: props.vpc,
allowAllOutbound: true,
});
this.rdsSG.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(5432), 'Ingress 5432');
this.aurora = new rds.ServerlessCluster(this, `rds`, {
engine: rds.DatabaseClusterEngine.AURORA_POSTGRESQL,
parameterGroup: rds.ParameterGroup.fromParameterGroupName(this, 'ParameterGroup', 'default.aurora-postgresql10'),
vpc: props.vpc,
securityGroups: [this.rdsSG],
// more properties below
});

有了这个addingress规则,一切都很好,因为RDS和Fargate都在同一个VPC中,所以我可以很好地通信。它让我担心,即使它在自己的专有网络中,也会让世界变得开放。

const ecsSG = new ec2.SecurityGroup(this, `ecsSG`, {
vpc: props.vpc,
allowAllOutbound: true,
});
const service = new ecs.FargateService(this, `service`, {
cluster,
desiredCount: 1,
taskDefinition,
securityGroups: [ecsSG],
assignPublicIp: true,
});

由于ecsSG稍后部署,我如何删除入口规则并允许从该ecsSG到RDS的入站连接?如果我试图从部署堆栈调用以下命令,我会得到一个循环依赖性错误:

props.rdsSG.connections.allowFrom(ecsSG, ec2.Port.allTcp(), 'Aurora RDS');

谢谢你的帮助!

这比我想象的要容易——你可以翻转连接,这样就不用试图修改rds来接受ecs的安全组,而是使用allowTo来建立与rds实例的连接。

ecsSG.connections.allowTo(props.rds, ec2.Port.tcp(5432), 'RDS Instance');

此外,也许RDS安全组的另一种方式可能由aws_RDS模块而不是aws_ec2模块更好地描述https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_rds/CfnDBSecurityGroup.html(由于代表率低,无法发表评论(

这里还有一种可能性。对我有用的是,我不需要定义任何安全组。只有服务和数据库,并连接两者:

const service = new ecsPatterns.ApplicationLoadBalancedEc2Service(
this,
'app-service',
{
cluster,
...
},
);

const dbCluster = new ServerlessCluster(this, 'DbCluster', {
engine: dbEngine,
...
});
dbCluster.connections.allowDefaultPortFrom(service.service);

最新更新