All Products
Search
Document Center

Auto Scaling:Use Alibaba Cloud SDK for Python to execute rolling update tasks

Last Updated:Sep 09, 2024

Alibaba Cloud SDK for Python allows you to access Alibaba Cloud services without the need to perform complex coding. This topic describes how to use Alibaba Cloud SDK for Python to call API operations provided by CloudOps Orchestration Service (OOS) to execute rolling update tasks on Linux computers.

Background information

Rolling update tasks can be used to update the configurations of multiple Elastic Compute Service (ECS) instances at the same time. You can use rolling update tasks to batch update images, execute scripts, and install OOS packages on multiple ECS instances that are in the In Service state. The ECS instances must belong to the same scaling group.

Prerequisites

  • A Resource Access Management (RAM) user is created and an AccessKey pair is obtained. For more information, see Create an AccessKey pair for a RAM user. When you call an API operation, you must use an AccessKey pair to complete identity authentication.

    Important
    • To protect the AccessKey pair of your Alibaba Cloud account, we recommend that you create a RAM user, grant the RAM user the permissions to access Auto Scaling, and then use the AccessKey pair of the RAM user to call Auto Scaling SDK for Python. For more information, see System policies for Auto Scaling.

    • The AccessKey secret of a RAM user is displayed only when you create the AccessKey pair. You cannot view the AccessKey secret after the AccessKey pair is created. After you create the AccessKey pair, store the AccessKey secret in a secure location.

  • Environment variables are configured. For more information, see Configure environment variables in Linux, macOS, and Windows. 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.

  • A scaling group is created and ECS instances are added to the scaling group. For more information, see Create a scaling group based on an existing ECS instance.

  • Python 3.6 or later is installed on your on-premises computer.

Step 1: Install Alibaba Cloud SDK for Python

  1. Run the following command to check whether Alibaba Cloud SDK for Python is installed:

    python --version

    If Alibaba Cloud SDK for Python is installed, the following output is displayed. 2024-07-08_13-37-07.png

  2. Run the following command to install the dependencies of OOS:

    pip install alibabacloud_oos20190601==3.2.1

Step 2: Execute a rolling update task

  1. Create a Python script and enter the following sample code to execute a rolling update task:

    For information about the OOS template parameters in the code, see Template parameters.

    # -*- coding: utf-8 -*-
    import os
    import sys
    
    from typing import List
    
    from alibabacloud_oos20190601.client import Client as oos20190601Client
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_oos20190601 import models as oos_20190601_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() -> oos20190601Client:
            """
            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'oos.cn-hangzhou.aliyuncs.com'
            return oos20190601Client(config)
    
        @staticmethod
        def main(
                args: List[str],
        ) -> None:
            client = Sample.create_client()
            tags = {
                'scaling_group': 'asg-bp1******'
            }
            start_execution_request = oos_20190601_models.StartExecutionRequest(
                region_id='cn-hangzhou',
                template_name='ACS-ESS-RollingUpdateByRunCommandInScalingGroup',
                parameters='''{"invokeType": "invoke",
                            "scalingGroupId": "asg-bp1******",
                            "commandType": "RunShellScript",
                            "invokeScript": "df -h;ifconfig",
                            "rollbackScript": "df -h;ifconfig",
                            "OOSAssumeRole": "",
                            "exitProcess": [
                                "ScaleIn",
                                "ScaleOut",
                                "HealthCheck",
                                "AlarmNotification",
                                "ScheduledAction"
                            ],
                            "enterProcess": [
                                "ScaleIn",
                                "ScaleOut",
                                "HealthCheck",
                                "AlarmNotification",
                                "ScheduledAction"
                            ],
                            "batchNumber": 2,
                            "batchPauseOption": "Automatic"}''',
                tags=tags
            )
            runtime = util_models.RuntimeOptions()
            try:
                # Write code to print the response of the API operation based on your business requirements.
                resp = client.start_execution_with_options(start_execution_request, runtime)
                print(resp.body)
            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:])
    
  2. Run the Python script and view the response.

    Note

    When you execute a rollback task, enter the execution ID of the source rolling update task. You can obtain information such as the execution ID of the source rolling update task in the command output, as shown in the following figure.

    image

Step 3: (Optional) Execute a rollback task

If exceptions occur when rolling update tasks are executed or you want to use previous configurations after rolling update tasks are executed, you can execute rollback tasks to restore the configurations of ECS instances.

  1. Create a Python script and enter the following sample code to execute a rollback task:

    For information about the OOS template parameters in the code, see Template parameters. Sample code:

    # -*- coding: utf-8 -*-
    import os
    import sys
    
    from typing import List
    
    from alibabacloud_oos20190601.client import Client as oos20190601Client
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_oos20190601 import models as oos_20190601_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() -> oos20190601Client:
            """
            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'oos.cn-hangzhou.aliyuncs.com'
            return oos20190601Client(config)
    
        @staticmethod
        def main(
                args: List[str],
        ) -> None:
            client = Sample.create_client()
            tags = {
                'scaling_group': 'asg-bp1******'
            }
            start_execution_request = oos_20190601_models.StartExecutionRequest(
                region_id='cn-hangzhou',
                template_name='ACS-ESS-RollingUpdateByRunCommandInScalingGroup',
                parameters='''{"invokeType": "rollback",
                            "scalingGroupId": "asg-bp1******",
                            "commandType": "RunShellScript",
                            "rollbackScript": "df -h;ifconfig",
                            "OOSAssumeRole": "",
                            "sourceExecutionId": "exec-c1******",
                            "batchNumber": 2,
                            "batchPauseOption": "Automatic"}''',
                tags=tags
            )
            runtime = util_models.RuntimeOptions()
            try:
                # Write code to print the response of the API operation based on your business requirements.
                resp = client.start_execution_with_options(start_execution_request, runtime)
                print(resp.body)
            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:])
    
  2. Run the Python script and view the response.

    The following figure shows an example.image

Template parameters

The following table describes the parameters of the ACS-ESS-RollingUpdateByRunCommandInScalingGroup public template used in this topic.

Parameter

Description

invokeType

The type of the task. Valid values:

  • invoke: rolling update task.

  • rollback: rollback task.

scalingGroupId

The scaling group in which you want to execute the task.

commandType

The type of the script that you want to execute. A value of RunShellScript specifies a shell script.

invokeScript

The script that you want to execute on ECS instances during a rolling update task.

rollbackScript

The script that you want to execute on ECS instances during a rollback task.

OOSAssumeRole

The RAM role that you want to use to execute the task. Default value: OOSServiceRole.

enterProcess

The scaling process that you want to suspend before the task is executed.

exitProcess

The scaling process that you want to resume after the task is executed.

batchNumber

The number of batches into which the ECS instances in the scaling group are divided for task execution. Each batch contains at least one ECS instance.

batchPauseOption

Specifies whether and how to suspend the task. Valid values:

  • Automatic: The task is executed without interruptions.

  • FirstBatchPause: The task is suspended when the first batch of executions is complete.

  • EveryBatchPause: The task is suspended when each batch of executions is complete.

sourceExecutionId

The execution ID of the source rolling update task when the rollback task is executed.