All Products
Search
Document Center

Auto Scaling:Use the Alibaba Cloud ESS SDK to quickly create a multi-zone scaling group

Last Updated:Apr 01, 2026

Use the Auto Scaling SDK for Java or Python to create a scaling group that spans multiple zones. When a scale-out event fails in one zone due to insufficient instance types, Auto Scaling automatically tries the next zone, keeping your scaling group available.

Prerequisites

Before you begin, make sure you have:

  • An Alibaba Cloud account. Sign up if you don't have one.

    Before you start, make sure you have an Alibaba Cloud account. If you do not have an account, create one.

  • The Alibaba Cloud Credentials tool configured. This tutorial uses the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to authenticate without hard-coding an AccessKey pair in your code. For setup instructions, see Manage access credentials.

How it works

A virtual private cloud (VPC)-type scaling group requires at least one vSwitch. Because each vSwitch belongs to a single zone, a group with only one vSwitch is bound to that zone. If the zone runs out of the instance type you need, scale-out fails—and the scaling configuration, scaling rules, and event-triggered tasks of that group all become ineffective.

The VSwitchIds.N parameter solves this by letting you attach up to five vSwitches from different zones to a single scaling group. When scale-out fails in the highest-priority zone, Auto Scaling retries in the zone with the next highest priority.

Usage notes

ConstraintDetail
Maximum vSwitches per group5
Priority orderN in VSwitchIds.N sets priority. A smaller value means higher priority.
FailoverOn scale-out failure, Auto Scaling tries vSwitches in ascending order of N.
Zone coverageSpecify vSwitches from different zones to avoid single-zone resource failures.
VPC requirementAll specified vSwitches must belong to the same VPC.
Interaction with VSwitchIdWhen you use VSwitchIds.N, Auto Scaling ignores the VSwitchId parameter.

Create a multi-zone scaling group with Java

Step 1: Add dependencies

Use Maven to manage your Java project dependencies. Add the following to your pom.xml:

<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>

Step 2: Create the scaling group

The following example creates a scaling group with two vSwitches. The first vSwitch (vsw-id1) has higher priority than the second (vsw-id2).

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";

    // vSwitches listed in descending order of priority (first = highest 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 {
        // Initialize credentials from environment variables
        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);  // Sets the multi-zone vSwitches
        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();
    }
}

Replace vsw-id1 and vsw-id2 with your actual vSwitch IDs. The vSwitches are evaluated in list order, so put the preferred zone first.

Create a multi-zone scaling group with Python

Step 1: Install the SDK

pip install alibabacloud_ess20220222==1.7.4

Step 2: Create the scaling group

The following example uses Python 3.9 and creates a scaling group with two vSwitches listed in descending order of priority.

# -*- 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:
        """
        Initialize the Auto Scaling client using credentials from environment variables.

        :return: Ess20220222Client
        :raises Exception: If the environment variables are not set.
        """
        # 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(
            # Read credentials from environment variables to avoid hard-coding secrets
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )
        config.endpoint = 'ess.aliyuncs.com'
        return Ess20220222Client(config)

    @staticmethod
    def main(args: List[str]) -> None:
        client = Sample.create_client()

        # vSwitches listed in descending order of priority (first = highest priority)
        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',  # Higher priority
                'vsw-bp******y'   # Lower priority (fallback zone)
            ]
        )
        runtime = util_models.RuntimeOptions()
        try:
            client.create_scaling_group_with_options(create_scaling_group_request, runtime)
        except Exception as error:
            # Exercise caution when handling exceptions in production scenarios.
            # Do not ignore exceptions in your project. The following prints are for reference only.
            # Print the error message and a link to the troubleshooting guide
            print(error.message)
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)


if __name__ == '__main__':
    Sample.main(sys.argv[1:])

Replace vsw-bp******g and vsw-bp******y with your actual vSwitch IDs.

What's next