繁体   English   中英

使用 AWS CDK 将入口规则添加到安全组

[英]Add Ingress Rule to Security Groups using AWS CDK

我正在尝试使用 Python 通过 AWS CDK 将入口规则添加到安全组。 根据此处的文档 - 类 aws_cdk.aws_ec2 上有一个方法 add_ingress_rule()。

但是 - 当我尝试部署堆栈时,出现以下错误:

AttributeError: 'method' 对象没有属性 ' jsii__type ' 子进程退出,错误 1

下面的安全组代码片段-

        sg_elb = ec2.SecurityGroup(
            self,
            id = "sg_elb",
            vpc = vpc,
            security_group_name = "sg_elb"
        )

        sg_elb.add_ingress_rule(
            peer = ec2.Peer.any_ipv4,
            connection = ec2.Port.tcp(443)   # This line seems to be a problem.
        )

此处的官方文档中甚至还提供了相同的示例(在 TypeScript 中),因此我不确定自己做错了什么。

任何人都可以建议吗?

提前致谢 !

我使用 TS 获得了以下内容,希望对您有所帮助。

        const mySG = new ec2.SecurityGroup(this, `${stack}-security-group`, {
            vpc: vpc,
            allowAllOutbound: true,
            description: 'CDK Security Group'
        });

        mySG.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(22), 'SSH frm anywhere');
        mySG.addIngressRule(ec2.Peer.ipv4('10.200.0.0/24'), ec2.Port.tcp(5439), 'Redshift Ingress1');
        mySG.addIngressRule(ec2.Peer.ipv4('10.0.0.0/24'), ec2.Port.tcp(5439), 'Redshift Ingress2');

顺便说一句,不建议使用明确的安全组名称: https : //docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.SecurityGroup.html

这对我有用

        sg = ec2.SecurityGroup(
            self,
            id="sg_1",
            vpc=vpc,
            allow_all_outbound=True,
            description="CDK Security Group"
            # security_group_name = "sg_elb"
            # not recommended https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.SecurityGroup.html
        )

        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22),
            description="ssh",
        )

在 SDK 文档中:“可以通过 addIngressRule 和 addEgressRule 直接操作安全组,但建议通过 .connections 对象进行更改。如果以这种方式将两个构造与安全组对等,将在两者中创建适当的规则。”

所以最好添加这样的规则:

sg.connections.allow_from(
  Peer.any_ipv4(),
  Port.tcp(22),
  "ssh" 
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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