All Products
Search
Document Center

Auto Scaling:Use Auto Scaling SDKs to create multi-zone scaling groups

Last Updated:Sep 20, 2024

This topic describes how to use Auto Scaling SDKs for Java and Python to create multi-zone scaling groups.

Prerequisites

  • An Alibaba Cloud account is created. To create an Alibaba Cloud account, go to the Sign up to Alibaba Cloud page.

  • The Alibaba Cloud Credentials tool is configured.

    In this topic, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are used to configure identity verification for the Alibaba Cloud Credentials tool. This allows you to access Alibaba Cloud OpenAPI Explorer without the need for a hard-coded plaintext AccessKey pair. For more information, see Manage access credentials.

Background information

If you create a scaling group of the virtual private cloud (VPC) network type, you must specify at least one vSwitch for the scaling group. After you create the scaling group, the Elastic Compute Service (ECS) instances that are created in the scaling group use the specified vSwitch. Originally, Auto Scaling allows you to specify only one vSwitch for a scaling group of the VPC network type. Because a vSwitch belongs to only one zone, the scaling group is bound to that specific zone. In this case, if the zone has insufficient instance types, ECS instances cannot be created in the scaling group. The scaling configuration, scaling rules, and event-triggered tasks of the scaling group also become ineffective.

To prevent scale-out failures that are caused by insufficient instance types in a single zone and improve the availability of scaling groups of the VPC network type, Auto Scaling provides the VSwitchIds.N parameter. When you create a scaling group, you can use this parameter to specify multiple vSwitches for the scaling group. If a scale-out event fails in one zone, Auto Scaling triggers a scale-out event in another zone.

Usage notes

Before you use the VSwitchIds.N parameter, take note of the following usage notes:

  • If you use the VSwitchIds.N parameter, Auto Scaling ignores the VSwitchId parameter.

  • You can use the VSwitchIds.N parameter to specify up to five vSwitches for a scaling group. N in the VSwitchIds.N parameter specifies the vSwitch priority. A smaller value of N specifies a higher priority.

    If a scale-out event fails in the zone where the vSwitch that has the highest priority resides, Auto Scaling triggers a scale-out event in the zone where the vSwitch that has the next highest priority resides. We recommend that you use the VSwitchIds.N parameter to specify vSwitches of different zones. This helps prevent creation failures of ECS instances in a single zone due to insufficient resources.

  • The vSwitches that are specified by the VSwitchIds.N parameter must belong to the same VPC.

Use Auto Scaling SDK for Java to create a multi-zone scaling group

  1. Import Auto Scaling SDK for Java.

    Use Maven to manage the dependency libraries of your Java project and add the following dependencies to the pom.xml file of the project:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>tea-openapi</artifactId>
      <version>0.2.8</version>
    </dependency>
     <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>ess20220222</artifactId>
          <version>1.0.5</version>
        </dependency>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>credentials-java</artifactId>
          <version>0.2.11</version>
        </dependency>
  2. Use Auto Scaling SDK for Java to create a multi-zone scaling group.

    After you import Auto Scaling SDK for Java into your Java project, you can use Auto Scaling SDK for Java to compile code to create a multi-zone scaling group. Sample code:

    import com.aliyun.teaopenapi.models.Config;
    import java.util.Arrays;
    import java.util.List;
    
    public class EssSdkDemo {
        public static final String       REGION_ID          = "cn-hangzhou";
        public static final Integer      MAX_SIZE           = 10;
        public static final Integer      MIN_SIZE           = 1;
        public static final String       SCALING_GROUP_NAME = "TestScalingGroup";
    
        // The list of vSwitches. The vSwitches are listed in descending order of priority. 
        public static final String[]     vswitchIdArray     = { "vsw-id1", "vsw-id2" };
        public static final List<String> vswitchIds         = Arrays.asList(vswitchIdArray);
    
        public static void main(String[] args) throws Exception {
            com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
            com.aliyun.teaopenapi.models.Config config = new Config();
            config.setCredential(credentialClient);
            config.setEndpoint("ess.aliyuncs.com");
            com.aliyun.ess20220222.Client client = new com.aliyun.ess20220222.Client(config);
            createScalingGroup(client);
    
        }
    
        public static String createScalingGroup(com.aliyun.ess20220222.Client client) throws Exception {
            com.aliyun.ess20220222.models.CreateScalingGroupRequest request = new com.aliyun.ess20220222.models.CreateScalingGroupRequest();
            request.setRegionId(REGION_ID);
            request.setMaxSize(MAX_SIZE);
            request.setMinSize(MIN_SIZE);
            request.setScalingGroupName(SCALING_GROUP_NAME);
            request.setVSwitchIds(vswitchIds);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            com.aliyun.ess20220222.models.CreateScalingGroupResponse scalingGroupWithOptions = client.createScalingGroupWithOptions(request, runtime);
            return scalingGroupWithOptions.getBody().toMap().toString();
        }
    
    }       

    In the preceding code, the vSwitches are listed in descending order of priority. The first vSwitch has the highest priority.

Use Auto Scaling SDK for Python to create a multi-zone scaling group

  1. Install Auto Scaling SDK for Python.

    Run the following command to install the dependencies:

    pip install alibabacloud_ess20220222==1.7.4
  2. Use Auto Scaling SDK for Python to create a multi-zone scaling group.

    After you install the dependency libraries, you can use Auto Scaling SDK for Python to compile code to create a multi-zone scaling group. Sample code:

    # -*- coding: utf-8 -*-
    import os
    import sys
    
    from typing import List
    
    from alibabacloud_ess20220222.client import Client as Ess20220222Client
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_ess20220222 import models as ess_20220222_models
    from alibabacloud_tea_util import models as util_models
    from alibabacloud_tea_util.client import Client as UtilClient
    
    
    class Sample:
        def __init__(self):
            pass
    
        @staticmethod
        def create_client() -> Ess20220222Client:
            """
            Use your AccessKey ID and AccessKey secret to initialize the client.
            @return: Client
            @throws Exception
            """
            # If the project code is leaked, the AccessKey pair may be leaked and the security of all resources in your Alibaba Cloud account may be compromised. The following sample code is provided only for reference. 
            config = open_api_models.Config(
                # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. ,
                access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. ,
                access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
            )
            config.endpoint = f'ess.aliyuncs.com'
            return Ess20220222Client(config)
    
        @staticmethod
        def main(
                args: List[str],
        ) -> None:
            client = Sample.create_client()
            create_scaling_group_request = ess_20220222_models.CreateScalingGroupRequest(
                region_id='cn-hangzhou',
                scaling_group_name='py-sdk-create-scaling-group-sample',
                min_size=1,
                max_size=1,
                v_switch_ids=[
                    'vsw-bp******g',
                    'vsw-bp******y'
                ]
            )
            runtime = util_models.RuntimeOptions()
            try:
                # Write your code to print the response of the API operation based on your business requirements.
                client.create_scaling_group_with_options(create_scaling_group_request, runtime)
            except Exception as error:
                # Exercise caution when you handle exceptions in actual business scenarios, and do not ignore exceptions in your project. In this example, error messages are printed only for reference. 
                # Print error messages.
                print(error.message)
                # Provide the URL for troubleshooting.
                print(error.data.get("Recommend"))
                UtilClient.assert_as_string(error.message)
    
    
    if __name__ == '__main__':
        Sample.main(sys.argv[1:])
    

    In the preceding code, Python 3.9 is used. The vSwitches are listed in descending order of priority.