edit-icon download-icon

Automatically manage instances

Last Updated: Jul 18, 2018

ECS instances maintenance aims to keep ECS instances in the best state and guarantee the troubleshooting efficiency. However, manual maintenance involves a huge amount of time and effort. To address this issue, you can use cloud assistant for automation and batch processing of daily maintenance tasks. This topic illustrates how to automatically maintain ECS instances by invoking cloud assistant commands on ECS instances.

Command types

Cloud assistant supports the following three command types.

Command type Parameter Description
Shell script RunShellScript A shell script that is running on running Linux instances.
PowerShell script RunPowerShellScript A PowerShell script that is running on running Windows instances.
Bat script RunBatScript A Bat script that is running on running Windows instances.


  • You must make sure that the network type of the target ECS instances is VPC.

  • The target ECS instances must be in the Running status.

  • The target ECS instances must have the Cloud Assistant client installed in advance. For more information, see Cloud assistant client.

  • To perform a PowerShell command, you must make sure that the target Windows instances has the PowerShell feature configured.

  • The following example is completed in the command line tool. You must make sure that you have installed Alibaba Cloud CLI (Command-Line Interface).

  • You must have your SDK upgraded.

  • You must modify the CLI configuration:

    1. Download the file aliyunOpenApiData.py.

    2. Replace the aliyunOpenApiData.py file in the %python_install_path%\Lib\site-packages\aliyuncli path with the downloaded file.


For more information about how to configure Alibaba Cloud CLI, see Alibaba Cloud CLI article For Alibaba Cloud users.

Sample of CLI to use cloud assistant

The following example illustrates how to use APIs in Alibaba Cloud CLI to use Cloud Assistant. For example, we want to run the echo 123 command on Linux instances.

  1. In the CMD, PowerShell, or Shell of a local computer, run aliyuncli ecs CreateCommand --CommandContent ZWNobyAxMjM= --Type RunShellScript --Name test --Description test to create a shell script(CreateCommand). The Command ID information is returned after successful creation.



    • The ZWNobyAxMjM= in CommandContent is the Base64 code of the echo 123 command. For more information about Base64 encoding or decoding, see Wikipedia - Base64.
    • If the operating system of the target ECS instances are Windows, change type to RunBatScript or RunPowershellScript.
  2. Run aliyuncli ecs InvokeCommand --InstanceIds your-vm-instance-id1 instance-id2 --CommandId your-command-id --Timed false to run the command (InvokeCommand).


    • The InstanceIds indicates your ECS instances IDs. Up to 100 ECS instances are supported each time.
    • The Timed indicates whether the task is a periodical one or not. --Timed True indicates that the task is a periodical one, while --Timed False indicates the opposite.
    • When your task is a periodical one and the Timed parameter value is True, you must specify the interval value in the Frequency parameter. For example, 0 */20 * * * * indicates that the interval value is 20 minutes. For more information, see Cron expressions.
    • A shared InvokeId is returned for all target ECS instances. You can use the Invoke ID to check the invocation status of the command.
  3. Optional. Run aliyuncli ecs DescribeInvocations --InstanceId your-vm-instance-id --InvokeId your-invoke-id to query the invocation status (DescribeInvocations). Specifically, the InvokeId is the invocation ID returned in step 2 during command invocation on the ECS instances.

    When the returned InvokeStatus value is Finished, it indicates that the command process is complete, but not necessarily as effective as expected. You must check the Output parameter in DescribeInvocationResults to get the specific invocation result.

  4. (Optional). Run aliyuncli ecs DescribeInvocationResults --InstanceId your-vm-instance-id --InvokeId your-invoke-id to check the results of the invocation (DescribeInvocationResults). Specifically, the InvokeId is the invocation ID returned in step 2 during command invocation on the ECS instances.

During a CreateCommand operation, you can set the following request parameters for the command.

Parameter Description
WorkingDir Specifies the path in an ECS instance where the command is performed. Default value:
  • For Linux instances: /root.
  • For Windows instances: In the path where the cloud assistant client process is located, such as C:\ProgramData\aliyun\assist\$(version).
TimeOut Modifies the invocation timeout value of a command on ECS instances. The unit is seconds. When your command fails for some reason, the invocation may time out, and the cloud assistant client forces to terminate the command process afterwards.
The parameter value must be greater than or equal to 60. If the value is smaller than 60, the timeout value is 60 seconds by default.
Default value: 3600.
  • One-time invocation:
    • After invocation timeout, the command invocation status (InvokeRecordStatus) for the specified ECS instances becomes Failed.
  • Periodical invocation:
    • The timeout value of periodical invocation is effective for every invocation record.
    • After one invocation operation timed out, the status for the invocation record (InvokeRecordStatus) becomes Failed.
    • The timeout status of last invocation does not affect the next invocation.

Sample of Python SDK to use cloud assistant

You can also use the cloud assistant by using the Alibaba Cloud SDK. For more information about how to configure Alibaba Cloud SDK, see Alibaba Cloud CLI document For Alibaba Cloud users. The following is the Python SDK code to use cloud assistant.

  1. # coding=utf-8
  2. # if the python sdk is not install using 'sudo pip install aliyun-python-sdk-ecs'
  3. # if the python sdk is install using 'sudo pip install --upgrade aliyun-python-sdk-ecs'
  4. # make sure the sdk version is 2.1.2, you can use command 'pip show aliyun-python-sdk-ecs' to check
  5. import json
  6. import logging
  7. import os
  8. import time
  9. import datetime
  10. import base64
  11. from aliyunsdkcore import client
  12. from aliyunsdkecs.request.v20140526.CreateCommandRequest import CreateCommandRequest
  13. from aliyunsdkecs.request.v20140526.InvokeCommandRequest import InvokeCommandRequest
  14. from aliyunsdkecs.request.v20140526.DescribeInvocationResultsRequest import DescribeInvocationResultsRequest
  15. # configuration the log output formatter, if you want to save the output to file,
  16. # append ",filename='ecs_invoke.log'" after datefmt.
  17. logging.basicConfig(level=logging.INFO,
  18. format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  19. datefmt='%a, %d %b %Y %H:%M:%S',filename='aliyun_assist_openapi_test.log', filemode='w')
  20. #access_key = 'Your Access Key Id'
  21. #acess_key_secrect = 'Your Access Key Secrect'
  22. #region_name = 'cn-shanghai'
  23. #zone_id = 'cn-shanghai-b'
  24. access_key = 'LTAIXXXXXXXXXXXX'
  25. acess_key_secrect = '4dZXXXXXXXXXXXXXXXXXXXXXXXX'
  26. region_name = 'cn-hangzhou'
  27. zone_id = 'cn-hangzhou-f'
  28. clt = client.AcsClient(access_key, acess_key_secrect, region_name)
  29. def create_command(command_content, type, name, description):
  30. request = CreateCommandRequest()
  31. request.set_CommandContent(command_content)
  32. request.set_Type(type)
  33. request.set_Name(name)
  34. request.set_Description(description)
  35. response = _send_request(request)
  36. if response is None:
  37. return None
  38. command_id = response.get('CommandId')
  39. return command_id;
  40. def invoke_command(instance_id, command_id, timed, cronat):
  41. request = InvokeCommandRequest()
  42. request.set_Timed(timed)
  43. InstanceIds = [instance_id]
  44. request.set_InstanceIds(InstanceIds)
  45. request.set_CommandId(command_id)
  46. request.set_Frequency(cronat)
  47. response = _send_request(request)
  48. invoke_id = response.get('InvokeId')
  49. return invoke_id;
  50. def get_task_output_by_id(instance_id, invoke_id):
  51. logging.info("Check instance %s invoke_id is %s", instance_id, invoke_id)
  52. request = DescribeInvocationResultsRequest()
  53. request.set_InstanceId(instance_id)
  54. request.set_InvokeId(invoke_id)
  55. response = _send_request(request)
  56. invoke_detail = None
  57. output = None
  58. if response is not None:
  59. result_list = response.get('Invocation').get('InvocationResults').get('InvocationResult')
  60. for item in result_list:
  61. invoke_detail = item
  62. output = base64.b64decode(item.get('Output'))
  63. break;
  64. return output;
  65. def execute_command(instance_id):
  66. command_str = 'yum check-update'
  67. command_id = create_command(base64.b64encode(command_str), 'RunShellScript', 'test', 'test')
  68. if(command_id is None):
  69. logging.info('create command failed')
  70. return
  71. invoke_id = invoke_command(instance_id, command_id, 'false', '')
  72. if(invoke_id is None):
  73. logging.info('invoke command failed')
  74. return
  75. time.sleep(15)
  76. output = get_task_output_by_id(instance_id, invoke_id)
  77. if(output is None):
  78. logging.info('get result failed')
  79. return
  80. logging.info("output: %s is \n", output)
  81. # send open api request
  82. def _send_request(request):
  83. request.set_accept_format('json')
  84. try:
  85. response_str = clt.do_action(request)
  86. logging.info(response_str)
  87. response_detail = json.loads(response_str)
  88. return response_detail
  89. except Exception as e:
  90. logging.error(e)
  91. if __name__ == '__main__':
  92. execute_command('i-bp17zhpbXXXXXXXXXXXXX')


The preceding examples demonstrate how to auto manage ECS instances maintenance by using Alibaba Cloud CLI and cloud assistant APIs CreateCommand, InvokeCommand, DescribeInvocations, and DescribeInvocationResults. You can also use other APIs of the cloud assistant:

Thank you! We've received your feedback.