This topic describes how to run the echo 123 command on multiple ECS instances at a time by using Cloud Assistant. You can use Cloud Assistant to configure routine maintenance tasks to be automatically executed in batches. This saves time and effort for instance O&M and ensues high troubleshooting efficiency.

Prerequisites

Before using Cloud Assistant, you must ensure that the target ECS instances meet the following requirements:
  • The target ECS instances have been equipped with the Cloud Assistant client. For more information about how to install the Cloud Assistant client, see Configure the Cloud Assistant client.
  • The target ECS instances are in the Running state.
  • The network type of the target ECS instances are Virtual Private Cloud (VPC).
  • Before running the PowerShell scripts, you have configured the PowerShell module for your Windows instances. For more information, see the Microsoft documentation Installing Windows PowerShell.

Usage

Method 1: Use Alibaba Cloud CLI to call API operations

Before calling API operations in Alibaba Cloud CLI, you must complete the following operations:
  • You have installed Alibaba Cloud CLI. For more information about how to obtain and install Alibaba Cloud CLI, see Overview.
  • You have obtained the region ID. For more information about region IDs, see Regions and zones.

In this example, only the required parameters are set to their default values to call API operations. You can customize scripts as needed.

  1. Optional: Check the status of the target instances. If the instances are not in the Running state, call StartInstance to run the instances.
    aliyun ecs StartInstance --InstanceId i-bp1g6zv0ce8og******p
  2. Optional: Call DescribeCloudAssistantStatus to query whether the Cloud Assistant client is installed on the target instances.
    If CloudAssistantStatus=true is returned, the Cloud Assistant client is installed on the target instances. If CloudAssistantStatus=true is not returned, call InstallCloudAssistant to install the Cloud Assistant client on the target instances.
  3. Call CreateCommand to create a Cloud Assistant script named test. The script content is echo 123 and is in the form of Base64-encoded plain text.
    aliyun ecs CreateCommand --RegionId TheRegionId --CommandContent ZWNobyAxMjM= --Type RunShellScript --Name test --Description test --output cols=CommandId

    If the target instances are Windows instances, change Type to RunBatScript or RunPowershellScript.

  4. Call InvokeCommand to run the Cloud Assistant script that you created on the target instances and obtain the response parameter InvokeId.
    aliyun ecs InvokeCommand --RegionId TheRegionId --InstanceId.1 i-bp1g6zv0ce8og******p --InstanceId.2 i-bp1g6zv0ce8og******p --CommandId your-command-id --Timed false --output cols=InvokeId
    You can specify the execution cycles of recurring tasks by setting Timed=true and by specifying the Frequency parameter. For example, 0 */20 * * * * indicates that the cycle is 20 minutes. For more information about cron expressions, seeConfigure scheduled commands.
  5. Call DescribeInvocations to query the running status of the script.
    aliyun ecs DescribeInvocations --RegionId TheRegionId --InvokeId your-invoke-id
  6. Call DescribeInvocationResults to query the running results of the script on specified instances.
    aliyun ecs DescribeInvocationResults --RegionId TheRegionId --InstanceId i-bp1g6zv0ce8og******p --InvokeId your-invoke-id

Method 2: Use the ECS Python SDK to call API operations

Before calling API operations by using the ECS Python SDK, you must complete the following operations:
  • You have installed the Python SDK V2.1.2 or later. For the latest ECS Python SDK version, visit GitHub Repo Alibaba Cloud.
  • You have obtained the AccessKey ID and the region ID, which are required in the SDK example. For more information about how to obtain AccessKey IDs and region IDs, see Create an AccessKey and Regions and zones.
Example code
# coding=utf-8
# If the Python sdk is not installed, run 'sudo pip install aliyun-python-sdk-ecs'.
# Make sure you're using the latest sdk version.
# Run 'sudo pip install --upgrade aliyun-python-sdk-ecs' to upgrade.

import json
import logging
import os
import time
import datetime
import base64
from aliyunsdkcore import client

from aliyunsdkecs.request.v20140526.CreateCommandRequest import CreateCommandRequest
from aliyunsdkecs.request.v20140526.InvokeCommandRequest import InvokeCommandRequest
from aliyunsdkecs.request.v20140526.DescribeInvocationResultsRequest import DescribeInvocationResultsRequest

# configuration the log output formatter, if you want to save the output to file,
# append ",filename='ecs_invoke.log'" after datefmt.
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',filename='aliyun_assist_openapi_test.log', filemode='w')
#access_key = 'Your Access Key Id'
#acess_key_secrect = 'Your Access Key Secrect'
#region_name = 'cn-shanghai'
#zone_id = 'cn-shanghai-b'

access_key = 'LTAIXXXXXXXXXXXX'  # Enter the actual AccessKey.
acess_key_secrect = '4dZXXXXXXXXXXXXXXXXXXXXXXXX'  # Enter the actual AccessKey secret.
region_name = 'cn-hangzhou'  # Enter the actual region name.
zone_id = 'cn-hangzhou-f'  # Enter the actual zone ID.

clt = client.AcsClient(access_key, acess_key_secrect, region_name)

def create_command(command_content, type, name, description):
    request = CreateCommandRequest()
    request.set_CommandContent(command_content)
    request.set_Type(type)
    request.set_Name(name)
    request.set_Description(description)
    response = _send_request(request)
    if response is None:
        return None
    command_id = response.get('CommandId')
    return command_id;

def invoke_command(instance_id, command_id, timed, cronat):
    request = InvokeCommandRequest()
    request.set_Timed(timed)
    InstanceIds = [instance_id]
    request.set_InstanceIds(InstanceIds)
    request.set_CommandId(command_id)
    request.set_Frequency(cronat)
    response = _send_request(request)
    invoke_id = response.get('InvokeId')
    return invoke_id;

def get_task_output_by_id(instance_id, invoke_id):
    logging.info("Check instance %s invoke_id is %s", instance_id, invoke_id)
    request = DescribeInvocationResultsRequest()
    request.set_InstanceId(instance_id)
    request.set_InvokeId(invoke_id)
    response = _send_request(request)
    invoke_detail = None
    output = None
    if response is not None:
        result_list = response.get('Invocation').get('InvocationResults').get('InvocationResult')
        for item in result_list:
            invoke_detail = item
            output = base64.b64decode(item.get('Output'))
            break;
        return output;

def execute_command(instance_id):
    command_str = 'yum check-update'
    command_id = create_command(base64.b64encode(command_str), 'RunShellScript', 'test', 'test')
    if(command_id is None):
        logging.info('create command failed')
        return

    invoke_id = invoke_command(instance_id, command_id, 'false', '')
    if(invoke_id is None):
        logging.info('invoke command failed')
        return

    time.sleep(15)

    output = get_task_output_by_id(instance_id, invoke_id)
    if(output is None):
        logging.info('get result failed')
        return

    logging.info("output: %s is \n", output)

# send open api request
def _send_request(request):
    request.set_accept_format('json')
    try:
        response_str = clt.do_action(request)
        logging.info(response_str)
        response_detail = json.loads(response_str)
        return response_detail
    except Exception as e:
        logging.error(e)

if __name__ == '__main__':
    execute_command('i-bp17zhpbXXXXXXXXXXXXX')
				

Method 3: Use Cloud Assistant in the ECS console

For more information about how to use Cloud Assistant in the ECS console, see Create scripts.