How to create SecurityGroupIngress objects?

Viewed 501

.securityGroupIngress() of CfnSecurityGroup.Builder takes a List<Object> securityGroupIngress. I'm trying to add an ingress rule to a security group:

CfnSecurityGroupIngress ingressRule =
    CfnSecurityGroupIngress.Builder.create(this, "IngressRule")
            .ipProtocol("tcp")
            .fromPort(80)
            .toPort(80)
            .cidrIp("0.0.0.0/0")
            .build();

List<Object> ingressRules = new ArrayList<>();
ingressRules.add(ingressRule) 

And then:

CfnSecurityGroup.Builder.create(this, "SecurityGroup")
        .groupName("ALB-SG")
        .groupDescription("Allow traffic from the Internet to the ALB")
        .vpcId(vpc.getRef())
        .securityGroupIngress(ingressRules) // <-- 
        .build();

When I try to compile, I get the following error:

Caused by: software.amazon.jsii.JsiiException: Resolution error: Resolution error: Trying to resolve() a Construct at /Resources/${Token[SGStack.SecurityGroup.LogicalID.39]}/Properties/securityGroupIngress/0/node.

A point of confusion for me is the List<Object> required by .securityGroupIngress() because in CloudFormation, the SecurityGroupIngress (CfnSecurityGroupIngress) property of an AWS::EC2::SecurityGroup (CfnSecurityGroup) takes a list of Ingress objects. Why is it List<Object> and not List<CfnSecurityGroupIngressProps> or List<CfnSecurityGroupIngress>? But most importantly, how do I create this List<Object> that is required?

1 Answers

Use software.amazon.awscdk.services.ec2.CfnSecurityGroup.IngressProperty instead of CfnSecurityGroupIngress:

IngressProperty
    .builder()
    .fromPort(80)
    .toPort(80)
    .ipProtocol("tcp")
    .cidrIp("0.0.0.0/0")
    .build()
Related