@@ -949,32 +949,49 @@ func (l *loadbalancers) addTLSCert(ctx context.Context, service *v1.Service, nbC
949949 return nil
950950}
951951
952- // getSubnetIDForSVC returns the subnet ID for the service's VPC and subnet.
953- // By default, first VPCName and SubnetName are used to calculate subnet id for the service.
954- // If the service has annotations specifying VPCName and SubnetName, they are used instead.
952+ // getSubnetIDForSVC returns the subnet ID for the service when running within VPC.
953+ // Following precedence rules are applied:
954+ // 1. If the service has an annotation for NodeBalancerBackendSubnetID, use that.
955+ // 2. If the service has annotations specifying VPCName or SubnetName, use them.
956+ // 3. If CCM is configured with --nodebalancer-backend-ipv4-subnet-id, it will be used as the subnet ID.
957+ // 4. Else, use first VPCName and SubnetName to calculate subnet id for the service.
955958func (l * loadbalancers ) getSubnetIDForSVC (ctx context.Context , service * v1.Service ) (int , error ) {
956959 if Options .VPCNames == "" {
957960 return 0 , fmt .Errorf ("CCM not configured with VPC, cannot create NodeBalancer with specified annotation" )
958961 }
962+ // Check if the service has an annotation for NodeBalancerBackendSubnetID
959963 if specifiedSubnetID , ok := service .GetAnnotations ()[annotations .NodeBalancerBackendSubnetID ]; ok {
960964 subnetID , err := strconv .Atoi (specifiedSubnetID )
961965 if err != nil {
962966 return 0 , err
963967 }
964968 return subnetID , nil
965969 }
970+
971+ specifiedVPCName , vpcOk := service .GetAnnotations ()[annotations .NodeBalancerBackendVPCName ]
972+ specifiedSubnetName , subnetOk := service .GetAnnotations ()[annotations .NodeBalancerBackendSubnetName ]
973+
974+ // If no VPCName or SubnetName is specified in annotations, but NodeBalancerBackendIPv4SubnetID is set,
975+ // use the NodeBalancerBackendIPv4SubnetID as the subnet ID.
976+ if ! vpcOk && ! subnetOk && Options .NodeBalancerBackendIPv4SubnetID != 0 {
977+ return Options .NodeBalancerBackendIPv4SubnetID , nil
978+ }
979+
966980 vpcName := strings .Split (Options .VPCNames , "," )[0 ]
967- if specifiedVPCName , ok := service . GetAnnotations ()[ annotations . NodeBalancerBackendVPCName ]; ok {
981+ if vpcOk {
968982 vpcName = specifiedVPCName
969983 }
970984 vpcID , err := GetVPCID (ctx , l .client , vpcName )
971985 if err != nil {
972986 return 0 , err
973987 }
988+
974989 subnetName := strings .Split (Options .SubnetNames , "," )[0 ]
975- if specifiedSubnetName , ok := service . GetAnnotations ()[ annotations . NodeBalancerBackendSubnetName ]; ok {
990+ if subnetOk {
976991 subnetName = specifiedSubnetName
977992 }
993+
994+ // Use the VPC ID and Subnet Name to get the subnet ID
978995 return GetSubnetID (ctx , l .client , vpcID , subnetName )
979996}
980997
0 commit comments