@@ -39,8 +39,13 @@ func (b *defaultBuilder) buildLBSecurityGroups(ctx context.Context, stack *LoadB
39
39
}
40
40
41
41
if len (externalSGs ) != 0 {
42
- sgRefs := make ([]api.SecurityGroupReference , 0 , len (externalSGs ))
43
- for sg := range externalSGs {
42
+ sgIDs , err := b .buildExternalSecurityGroups (ctx , externalSGs .List ())
43
+ if err != nil {
44
+ return nil , err
45
+ }
46
+
47
+ sgRefs := make ([]api.SecurityGroupReference , 0 , len (sgIDs ))
48
+ for _ , sg := range sgIDs {
44
49
sgRefs = append (sgRefs , api.SecurityGroupReference {
45
50
SecurityGroupID : sg ,
46
51
})
@@ -55,6 +60,66 @@ func (b *defaultBuilder) buildLBSecurityGroups(ctx context.Context, stack *LoadB
55
60
return []api.SecurityGroupReference {{SecurityGroupRef : k8s .LocalObjectReference (lbSG )}}, nil
56
61
}
57
62
63
+ func (b * defaultBuilder ) buildExternalSecurityGroups (ctx context.Context , sgIDOrNames []string ) ([]string , error ) {
64
+ sgIDs := sets .NewString ()
65
+
66
+ var sgNames []string
67
+ for _ , idOrName := range sgIDOrNames {
68
+ if strings .HasPrefix (idOrName , "sg-" ) {
69
+ sgIDs .Insert (idOrName )
70
+ continue
71
+ }
72
+ sgNames = append (sgNames , idOrName )
73
+ }
74
+
75
+ if len (sgNames ) > 0 {
76
+ vpcID := b .cloud .VpcID ()
77
+ instancesByGroupName , err := b .cloud .EC2 ().DescribeSecurityGroupsAsList (ctx , & ec2.DescribeSecurityGroupsInput {
78
+ Filters : []* ec2.Filter {
79
+ {
80
+ Name : aws .String ("group-name" ),
81
+ Values : aws .StringSlice (sgNames ),
82
+ },
83
+ {
84
+ Name : aws .String ("vpc-id" ),
85
+ Values : aws .StringSlice ([]string {vpcID }),
86
+ },
87
+ },
88
+ })
89
+ if err != nil {
90
+ return nil , err
91
+ }
92
+ for _ , instance := range instancesByGroupName {
93
+ sgIDs .Insert (aws .StringValue (instance .GroupId ))
94
+ }
95
+
96
+ if len (instancesByGroupName ) != len (sgNames ) {
97
+ instancesByTagName , err := b .cloud .EC2 ().DescribeSecurityGroupsAsList (ctx , & ec2.DescribeSecurityGroupsInput {
98
+ Filters : []* ec2.Filter {
99
+ {
100
+ Name : aws .String ("tag:Name" ),
101
+ Values : aws .StringSlice (sgNames ),
102
+ },
103
+ {
104
+ Name : aws .String ("vpc-id" ),
105
+ Values : aws .StringSlice ([]string {vpcID }),
106
+ },
107
+ },
108
+ })
109
+ if err != nil {
110
+ return nil , err
111
+ }
112
+ for _ , instance := range instancesByTagName {
113
+ sgIDs .Insert (aws .StringValue (instance .GroupId ))
114
+ }
115
+ }
116
+ }
117
+ if sgIDs .Len () != len (sgIDOrNames ) {
118
+ return nil , errors .Errorf ("failed to build external securityGroups, desired:%v, resolved:%v" , sgIDOrNames , sgIDs .List ())
119
+ }
120
+ return sgIDs .List (), nil
121
+ }
122
+
58
123
func (b * defaultBuilder ) buildManagedLBSecurityGroup (ctx context.Context , stack * LoadBalancingStack ,
59
124
ingGroup ingress.Group , portsByIngress map [types.NamespacedName ]sets.Int64 , ipAddressType api.IPAddressType ) (* api.SecurityGroup , error ) {
60
125
0 commit comments