Scenario
This document describes how to terminate a prepaid CVM instance and the prepaid cloud disks mounted to it by using the Tencent Cloud Developer Kit (SDK) 3.0 and cloud APIs. This document also provides sample code in Python for your reference.
Note
Preparations
You have purchased a prepaid CVM instance and mounted a cloud disk to the instance.
You have obtained the SecretId and SecretKey on the Manage API Key page.
Instructions
Install the dependencies and SDK
Perform the following steps to install the dependencies and SDK based on your actual development language:
1. Install Python of a version from 3.6 to 3.9. For more information, see the official website of Python.
2. Run the following command to install Python SDK: For more information, see Tencent Cloud SDK 3.0 for Python.
pip install --upgrade tencentcloud-sdk-python
Run the sample code
The following sample code is provided for your reference.
The sample code of the main program:
-- coding: utf-8 --import sysfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKExceptionfrom TerminateTotalInstance import TerminateTotalInstanceif __name__ == '__main__':try:region = "ap-beijing"ins = "ins-irmer45l"TerminateTotalInstance(region=region).process(instance_id=instance_id)print("done!")except TencentCloudSDKException as e:print(e)except Exception as e:print("failed")
The sample code for terminating CVM instances and cloud disks
# -*- coding: utf-8 -*-import loggingimport timefrom tencentcloud.common import credentialfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKExceptionfrom tencentcloud.common.profile.client_profile import ClientProfilefrom tencentcloud.common.profile.http_profile import HttpProfilefrom tencentcloud.cvm.v20170312 import cvm_client, models as cvm_modelsfrom tencentcloud.cbs.v20170312 import cbs_client, models as cbs_modelsclass TerminateTotalInstance(object):def __init__(self, region):Retrieve secretId and secretKey from environment variables TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY by defaultFor more credential management methods, please refer to: https://github.com/TencentCloud/tencentcloud-sdk-python#credential-managementself.cred = credential.EnvironmentVariableCredential().get_credential()self.cbs_client = self.__create_cbs_client(region)self.cvm_client = self.__create_cvm_client(region)def get_cred(self):# If the identity is obtained based on the token, you need to check if the token is valid here.# If invalid, reacquire the credentialif not self.cred:self.cred = credential.EnvironmentVariableCredential().get_credential()return self.creddef process(self, instance_id):# Retrieve cloud diskcbs_ids = self.describe_disks_for_instance(instance_id)# Return instancecvm_resp, cvm_api_errors = self.terminate_instance(instance_id)if cvm_api_errors:raise Exception(cvm_api_errors)# Confirm the successful return of the instanceis_succ, cvm_api_errors = self.check_terminate_instance_success(instance_id)if not is_succ:raise Exception(cvm_api_errors)# Unmount and batch return cloud disksif not cbs_ids:returncbs_resp, cbs_api_errors = self.detach_disks(cbs_ids)if cbs_api_errors:raise Exception(cbs_api_errors)cbs_resp, cbs_api_errors = self.terminate_disks_for_instance(cbs_ids)if cbs_api_errors:raise Exception(cbs_api_errors)def terminate_instance(self, instance_id):# Call failure historycvm_api_errors = []for i in range(0, 5):try:req = cvm_models.TerminateInstancesRequest()params = '{"InstanceIds":["%s"]}' % instance_idreq.from_json_string(params)resp = self.cvm_client.TerminateInstances(req)cvm_api_errors.clear()return resp, cvm_api_errorsexcept TencentCloudSDKException as e:# Retry on failure and log errorscvm_api_errors.append(e)logging.error(e)time.sleep(3)return None, cvm_api_errorsdef check_terminate_instance_success(self, instance_id):# Call failure historycvm_api_errors = []for _ in range(0, 30):try:req = cvm_models.DescribeInstancesStatusRequest()params = '{"InstanceIds":["%s"]}' % instance_idreq.from_json_string(params)resp = self.cvm_client.DescribeInstancesStatus(req)cvm_api_errors.clear()if resp.TotalCount > 0:if resp.InstanceStatusSet[0].InstanceState == "SHUTDOWN":return True, cvm_api_errorselse:logging.error(resp)except TencentCloudSDKException as e:# Retry on failure and log errorscvm_api_errors.append(e)logging.error(e)time.sleep(6)return False, cvm_api_errorsdef describe_disks_for_instance(self, instance_id):# Retrieve the data disks attached to the instancereq = cbs_models.DescribeDisksRequest()params = '{"Filters": [ { "Name": "instance-id", "Values": [ "%s" ]}]}' % instance_idreq.from_json_string(params)disks = self.cbs_client.DescribeDisks(req)if hasattr(disks, "DiskSet"):cbs_ids = [disk.DiskId for disk in disks.DiskSet if disk.DiskUsage == "DATA_DISK"]else:cbs_ids = list()return cbs_idsdef detach_disks(self, cbs_ids):# Unmount data diskcbs_api_errors = []for _ in range(0, 5):try:req = cbs_models.DetachDisksRequest()req.DiskIds = cbs_idsresp = self.cbs_client.DetachDisks(req)cbs_api_errors.clear()return resp, cbs_api_errorsexcept TencentCloudSDKException as e:# Retry on failure and log errorscbs_api_errors.append(e)logging.error(e)time.sleep(3)return None, cbs_api_errorsdef terminate_disks_for_instance(self, cbs_ids):# Return data diskcbs_api_errors = []for _ in range(0, 10):try:req = cbs_models.TerminateDisksRequest()req.DiskIds = cbs_idsresp = self.cbs_client.TerminateDisks(req)cbs_api_errors.clear()return resp, cbs_api_errorsexcept TencentCloudSDKException as e:# Retry on failure and log errorscbs_api_errors.append(e)logging.error(e)time.sleep(6)return None, cbs_api_errorsdef __create_cbs_client(self, region):http_profile = HttpProfile()http_profile.endpoint = "cbs.tencentcloudapi.com"client_profile = ClientProfile()client_profile.httpProfile = http_profilereturn cbs_client.CbsClient(self.get_cred(), region, client_profile)def __create_cvm_client(self, region):http_profile = HttpProfile()http_profile.endpoint = "cvm.tencentcloudapi.com"client_profile = ClientProfile()client_profile.httpProfile = http_profilereturn cvm_client.CvmClient(self.get_cred(), region, client_profile)