Help & Documentation>Cloud Virtual Machine>Operation Guide>Instance>Terminating/Returning Instances>Using APIs to terminate/return prepaid instances and mounted ‍cloud ‍disks

Using APIs to terminate/return prepaid instances and mounted ‍cloud ‍disks

Last updated: 2024-05-15 10:25:42

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
For ‍more information about the impact of terminating/returning a CVM instance, see Impacts.

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:
Python
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.
Python
The sample code of the main program:
-- coding: utf-8 --
import sys
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from TerminateTotalInstance import TerminateTotalInstance

if __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 logging
import time

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.cvm.v20170312 import cvm_client, models as cvm_models
from tencentcloud.cbs.v20170312 import cbs_client, models as cbs_models


class TerminateTotalInstance(object):
def __init__(self, region):
Retrieve secretId and secretKey from environment variables TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY by default
For more credential management methods, please refer to: https://github.com/TencentCloud/tencentcloud-sdk-python#credential-management
self.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 credential
if not self.cred:
self.cred = credential.EnvironmentVariableCredential().get_credential()
return self.cred
def process(self, instance_id):
# Retrieve cloud disk
cbs_ids = self.describe_disks_for_instance(instance_id)

# Return instance
cvm_resp, cvm_api_errors = self.terminate_instance(instance_id)
if cvm_api_errors:
raise Exception(cvm_api_errors)

# Confirm the successful return of the instance
is_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 disks
if not cbs_ids:
return
cbs_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 history
cvm_api_errors = []

for i in range(0, 5):
try:
req = cvm_models.TerminateInstancesRequest()
params = '{"InstanceIds":["%s"]}' % instance_id
req.from_json_string(params)
resp = self.cvm_client.TerminateInstances(req)
cvm_api_errors.clear()
return resp, cvm_api_errors

except TencentCloudSDKException as e:
# Retry on failure and log errors
cvm_api_errors.append(e)
logging.error(e)
time.sleep(3)

return None, cvm_api_errors

def check_terminate_instance_success(self, instance_id):
# Call failure history
cvm_api_errors = []

for _ in range(0, 30):
try:
req = cvm_models.DescribeInstancesStatusRequest()
params = '{"InstanceIds":["%s"]}' % instance_id
req.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_errors
else:
logging.error(resp)

except TencentCloudSDKException as e:
# Retry on failure and log errors
cvm_api_errors.append(e)
logging.error(e)
time.sleep(6)

return False, cvm_api_errors

def describe_disks_for_instance(self, instance_id):
# Retrieve the data disks attached to the instance
req = cbs_models.DescribeDisksRequest()
params = '{"Filters": [ { "Name": "instance-id", "Values": [ "%s" ]}]}' % instance_id
req.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_ids

def detach_disks(self, cbs_ids):
# Unmount data disk
cbs_api_errors = []
for _ in range(0, 5):
try:
req = cbs_models.DetachDisksRequest()
req.DiskIds = cbs_ids
resp = self.cbs_client.DetachDisks(req)
cbs_api_errors.clear()
return resp, cbs_api_errors

except TencentCloudSDKException as e:
# Retry on failure and log errors
cbs_api_errors.append(e)
logging.error(e)
time.sleep(3)

return None, cbs_api_errors

def terminate_disks_for_instance(self, cbs_ids):
# Return data disk
cbs_api_errors = []
for _ in range(0, 10):
try:
req = cbs_models.TerminateDisksRequest()
req.DiskIds = cbs_ids
resp = self.cbs_client.TerminateDisks(req)
cbs_api_errors.clear()
return resp, cbs_api_errors

except TencentCloudSDKException as e:
# Retry on failure and log errors
cbs_api_errors.append(e)
logging.error(e)
time.sleep(6)
return None, cbs_api_errors

def __create_cbs_client(self, region):
http_profile = HttpProfile()
http_profile.endpoint = "cbs.tencentcloudapi.com"

client_profile = ClientProfile()
client_profile.httpProfile = http_profile
return 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_profile
return cvm_client.CvmClient(self.get_cred(), region, client_profile)