简体   繁体   中英

How to create security group in aws cdk in python?

Hi I am trying to write seurity group using aws cdk. I know how to write it in using cloud formation. Below is my cloud formation template.

MerchWebServicesSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      Tags:
        - Key: "Name"
          Value: !Ref "AWS::StackName"
      GroupDescription: "EC2 Services Security Group"
      VpcId:
        Fn::ImportValue: "infra-vpc-base::VpcId"
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: "80"
          ToPort: "80"
          SourceSecurityGroupId: !Ref MerchWebServicesLoadBalancerSecurityGroup
        - IpProtocol: tcp
          FromPort: "443"
          ToPort: "443"
          SourceSecurityGroupId: !Ref MerchWebServicesLoadBalancerSecurityGroup
        - IpProtocol: tcp
          FromPort: 31000
          ToPort: 65535
          SourceSecurityGroupId: !Ref MerchWebServicesLoadBalancerSecurityGroup

I tried to write security group as below in python cdk.

  mws_vpc_sg  = ec2.SecurityGroup(stack, "MerchWebServicesSecurityGroup",
        description= "Allow ssh access to ec2 instances",
        security_group_name= "MerchWebServicesSecurityGroup",
        vpc= vpc
    );

 mws_vpc_sg.add_ingress_rule(?, Port.tcp(80));

Above I want to add sourceSecurityGroupId and port. Can someone help me to write this? Any help would be appreciated. Thanks

If you have created the other security group in CDK as well, you can just pass the security group as peer.

mws_vpc_sg.add_ingress_rule(load_balancer_sg, Port.tcp(80));

If you have created the security group somewhere else you need to obtain a ISecurityGroup from it using the static method:

var load_balancer_sg = ec2.SecurityGroup.fromSecurityGroupId(this, 'loadbalancer_sg', THE_ID_OF_THE_SG)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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