All Products
Search
Document Center

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

Last Updated:Dec 28, 2023

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.

Prerequisites

  • A scaling group is created and Elastic Compute Service (ECS) instances are added to the scaling group.

  • SDK for Python is installed on your computer.

  • A Resource Access Management (RAM) user is created and an AccessKey pair is obtained. For more information, see Create an AccessKey pair.

    Important

    The AccessKey secret of a RAM user is displayed only when the AccessKey pair is created. You cannot view the AccessKey secret after the AccessKey pair is created. Save the AccessKey secret when you create an AccessKey pair and keep the AccessKey secret confidential.

Background information

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

Step 1: Install Alibaba Cloud SDK for Python

  1. Run the following command to check the version of Python:

    python --version

    If the version of Python is returned, Python is installed. The following figure shows a sample command output. python-version

  2. Run the following command to install the SDK core library:

    pip install aliyun-python-sdk-core
  3. Run the following command to install the Alibaba Cloud SDK Credentials tool.

    pip install alibabacloud_credentials
    Note

    You can configure the Alibaba Cloud Credentials tool by specifying the following environment variables: ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. This allows you to access Alibaba Cloud OpenAPI Explorer without using a hard-coded plaintext AccessKey pair. For more information, see Configure environment variables.

  4. Run the following command to install OOS SDK for Python:

    pip install aliyun-python-sdk-oos

Step 2: Execute a rolling update task

Sample code is provided in this step to demonstrate how to execute a script on ECS instances.

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

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

    # -*- coding: UTF-8 -*-
    
    from aliyunsdkcore.client import AcsClient
    from alibabacloud_credentials.client import Client as CredClient
    from aliyunsdkoos.request.v20190601 import StartExecutionRequest
    import json
    cred=CredClient()
    accesskeyid = cred.get_access_key_id()
    accesskeysecret = cred.get_access_key_secret()
    # Create an AcsClient instance.
    client = AcsClient(accesskeyid, accesskeysecret)
    
    # Create a request and set the JSON data format.
    request = StartExecutionRequest.StartExecutionRequest()
    request.set_accept_format('json')
    
    # Replace the template name based on the selected update method.
    request.set_TemplateName("ACS-ESS-RollingUpdateByRunCommandInScalingGroup")
    
    # Associate a rolling update task with a scaling group to query the task execution status in the scaling group.
    request.set_Tags("{\"scaling_group\":\"asg-xxxxxxxx\"}")
    
    # Replace parameters based on the selected template.
    parameters = {"invokeType": "invoke",
                  "scalingGroupId": "asg-xxxxxxxxx",
                  "commandType": "RunShellScript",
                  "invokeScript": "df -h\nifconfig",
                  "rollbackScript": "df -h\nifconfig",
                  "OOSAssumeRole": "",
                  "exitProcess": [
                      "ScaleIn",
                      "ScaleOut",
                      "HealthCheck",
                      "AlarmNotification",
                      "ScheduledAction"
                  ],
                  "enterProcess": [
                      "ScaleIn",
                      "ScaleOut",
                      "HealthCheck",
                      "AlarmNotification",
                      "ScheduledAction"
                  ],
                  "batchNumber": 2,
                  "batchPauseOption": "Automatic"}
    
    request.set_Parameters(json.dumps(parameters))
    
    # Initiate the API request and obtain the response.
    response = client.do_action_with_exception(request)
    print(response)
  2. Execute the Python script and check the command output.

    You can find information such as the execution ID of the rolling update task in the command output. The following figure shows a sample command output.

    Note

    To execute a rollback task, you must enter the execution ID of the source rolling update task.

    rollingupdate-py

(Optional) Execute a rollback task

If exceptions occur during rolling update tasks or if you want to use previous configurations after rolling upgrade tasks are executed, you can execute rollback tasks to restore the configurations of the ECS instances. Sample code is provided in this section to demonstrate how to roll back rolling update tasks that have been executed.

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

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

    # -*- coding: UTF-8 -*-
    
    from aliyunsdkcore.client import AcsClient
    from alibabacloud_credentials.client import Client as CredClient
    from aliyunsdkoos.request.v20190601 import StartExecutionRequest
    import json
    cred=CredClient()
    accesskeyid = cred.get_access_key_id()
    accesskeysecret = cred.get_access_key_secret()
    # Create an AcsClient instance.
    client = AcsClient(accesskeyid, accesskeysecret)
    
    # Create a request and set the JSON data format.
    request = StartExecutionRequest.StartExecutionRequest()
    request.set_accept_format('json')
    
    # Replace the template name based on the selected update method.
    request.set_TemplateName("ACS-ESS-RollingUpdateByRunCommandInScalingGroup")
    
    # Associate a rolling update task with a scaling group to query the task execution status in the scaling group.
    request.set_Tags("{\"scaling_group\":\"asg-xxxxxxxxxx\"}")
    
    # Parameters of the rollback operation
    parameters = {"invokeType": "rollback",
                  "scalingGroupId": "asg-xxxxxxxxx",
                  "commandType": "RunShellScript",
                  "rollbackScript": "df -h\nifconfig",
                  "OOSAssumeRole": "",
                  "sourceExecutionId": "exec-xxxxxxxx",
                  "batchNumber": 2,
                  "batchPauseOption": "Automatic"}
    
    request.set_Parameters(json.dumps(parameters))
    
    # Initiate the API request and obtain the response.
    response = client.do_action_with_exception(request)
    print(response)
  2. Execute the Python script and check the command output.

    The following figure shows a sample command output. rollingupdate-rollback-py

OOS template parameters

This following table describes the parameters of the ACS-ESS-RollingUpdateByRunCommandInScalingGroup public template used in the preceding examples.

Parameter

Description

invokeType

The type of the task. Valid values:

  • invoke: rolling update task

  • rollback: rollback task

scalingGroupId

The ID of the scaling group in which the task is to be executed.

commandType

The type of the script to be executed. The value of RunShellScript indicates a shell script.

invokeScript

The script that is executed on ECS instances during a rolling update task.

rollbackScript

The script that is executed on ECS instances during a rollback task.

OOSAssumeRole

The RAM role used to execute the task. Default value: OOSServiceRole.

enterProcess

The scaling process that is suspended before the task is executed.

exitProcess

The scaling process that is resumed when the task is completed.

batchNumber

The number of batches in which the ECS instances in the scaling group are divided. The task is executed in these batches. 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 are complete.

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

sourceExecutionId

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