GTS学苑:利用接口批量创建CVM

背景

当前GTS学苑,TCS、TBDS、TSF、TDSQL以及TBASE等腾讯云自研产品的培训都需要学员自带环境,在培训过程中使用学员自己的环境进行实操演练。每个产品的培训环境对CVM的数量以及配置都有不同要求。一套产品培训的实操环境少则4台,多则接近20台,而且CVM的配置有差异。学员在环境准备的时候如果使用人工购买的方式,就需要花费较多时间进行环境的准备工作,效率低且繁琐。本文将基于GTS学苑当前环境使用情况,介绍自动化创建CVM的功能,并附录主要的培训产品相关创建机器的代码,供学员自行下载并运行。

解决方案

通过本文的介绍,即使对编程不了解的用户也可以通过代码实现创建CVM的功能。

获取创建CVM程序

针对编程零基础的同学来说,不需要自己写程序,在腾讯云网站就有对应的程序生成界面可以自动获取自动创建CVM的代码。

新建服务器的购买页面,按照自己的需求选择需要购买CVM的信息(包含计费模式、地域、机型、网络、配置等信息),在第三阶段“3.确认配置信息”,即可看到“生成API Explorer最佳实践脚本”的选项。点击后即可获取创建CVM的程序。

获取创建CVM的程序代码

在左侧就会展示出当前机器的一下关键配置信息,右侧选择API脚本的语言后,即可看到自动生成的程序。

获取所需代码

运行代码

通过获取的代码,补充”$secretId”, “$secretKey”以及服务器登陆密码信息,就可以直接在安装了tencentcloud-sdk-python的机器上直接运行程序进行CVM的创建。

密钥信息获取

secretId和secretKey信息的获取方式可以直接访问:https://console.cloud.tencent.com/cam/capi 即可获取

SDK安装

安装tencentcloud-sdk-python的方式参考连接:https://cloud.tencent.com/document/sdk/Python 按照安装SDK的方式直接安装腾讯云SDK。

由于获取的代码仅能够创建统一配置的机器,所以还需要进行修改来创建多台不同配置的实验环境。

代码修改

根据要求进行基础配置,即可实现自动化创建不同配置的多台CVM

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# coding: utf8
# author: johnnyxsu
# Create: 2022-2-17

import sys
import json
import time
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.cvm.v20170312 import cvm_client, models

# https://console.cloud.tencent.com/cam/capi 即可获取
SecretId = ""
SecretKey = ""

#按照要求填写机型信息,需要多少台就依次填写多少台
InstanceType = [
    {"InstanceType": "SA3.2XLARGE16"},
    {"InstanceType": "SA3.2XLARGE16"},
    {"InstanceType": "SA3.2XLARGE16"},
    {"InstanceType": "SA3.2XLARGE16"},
]

#机器的数据盘信息,和InstanceType是一一对应的
DataDisks = [
    [{"DiskSize": 100, "DiskType": "CLOUD_PREMIUM"}],
    [{"DiskSize": 100, "DiskType": "CLOUD_PREMIUM"}],
    [{"DiskSize": 100, "DiskType": "CLOUD_PREMIUM"}],
    [{"DiskSize": 100, "DiskType": "CLOUD_PREMIUM"}, {"DiskSize": 200, "DiskType": "CLOUD_PREMIUM"}],

]

def loopCreateCVM(datas):
    cvms = list()
    print("开始创建CVM:")
    for data in datas:
        inData = dict()
        inData['projectId'] = data['projectId']
        inData['VpcId'] = data['VpcId']
        inData['SubnetId'] = data['SubnetId']
        for i in range(len(InstanceType)):
            inData['InstanceType'] = InstanceType[i]['InstanceType']
            inData['InstanceName'] = data['groupId'] + '-'+ InstanceType[i]['InstanceType'].split('.')[-1] + "-{}".format(i+1)
            inData['DataDisks'] = DataDisks[i]

            #print(inData)
            #inData = {"InstanceName": "", "projectId": 1222686, "VpcId": "vpc-ay2tio8z", "SubnetId": "subnet-1tgw7cos","InstanceType": "SA2.8XLARGE64", "DataDisks": []}
            msg = createCVM(inData)
            print(msg)

            retD = json.loads(msg)
            if 'InstanceIdSet' in retD and retD['InstanceIdSet']:
                cvms = cvms + retD['InstanceIdSet']
    return cvms

def createCVM(inData):
    # inData = {"groupId": "", "projectId": 1222686, "VpcId": "vpc-ay2tio8z", "SubnetId": "subnet-1tgw7cos", "InstanceType": "SA2.8XLARGE64", "DataDisks":[]}
    try:
        cred = credential.Credential(SecretId, SecretKey)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cvm.ap-guangzhou.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cvm_client.CvmClient(cred, "ap-guangzhou", clientProfile)

        req = models.RunInstancesRequest()
        params = {
            "InstanceChargeType": "POSTPAID_BY_HOUR", # PREPAID POSTPAID_BY_HOUR
            "InstanceChargePrepaid": {
                "Period": 1,
                "RenewFlag": "NOTIFY_AND_MANUAL_RENEW"
            },
            "Placement": {
                "Zone": "ap-guangzhou-7",  # 可用区
                "ProjectId": inData['projectId']  # 项目ID需要修改
            },
            "VirtualPrivateCloud": {
                "AsVpcGateway": False,
                "VpcId": inData['VpcId'],  # VPC需要修改
                "SubnetId": inData['SubnetId'],  # 子网需要修改
                "Ipv6AddressCount": 0
            },
            "InstanceType": inData['InstanceType'],  # 机型需要修改
            "ImageId": "img-hdt9xxkt",
            "SystemDisk": {
                "DiskSize": 100,  ## 系统盘大小
                "DiskType": "CLOUD_PREMIUM"
            },
            "DataDisks": inData['DataDisks'],  # 磁盘信息需要修改
            "InternetAccessible": {
                "InternetMaxBandwidthOut": 0,
                "PublicIpAssigned": False
            },
            "InstanceName": inData['InstanceName'],  # 实例ID需要修改
            "LoginSettings": {
                "Password": "Tcdn@2007"
            },
            "SecurityGroupIds": ["sg-5etqc5mt"],  # 按照要求配置安全组
            "InstanceCount": 1,  # 创建实例个数
            "EnhancedService": {
                "SecurityService": {"Enabled": True},
                "MonitorService": {"Enabled": True},
                "AutomationService": {"Enabled": True}
            }
        }
        req.from_json_string(json.dumps(params))

        resp = client.RunInstances(req)
        return resp.to_json_string()

    except TencentCloudSDKException as err:
        return err

def batchcreateCVM(data):
    cvmslist = list()
    print("inputData:{}".format(json.dumps(data)))
    print("---------------------------------------------")
    cvms = loopCreateCVM([data])
    cvmslist.append(cvms)
    print("---------------------------------------------")
    print("创建CVM列表信息:{}".format(json.dumps(cvmslist)))
    print("等待120s创建虚拟机后,开始查询CVM IP信息")
    time.sleep(120)
    describeCVM(cvmslist)
    return cvmslist


def describeCVM(cvmslist):
    for cvms in cvmslist:
        try:
            cred = credential.Credential(SecretId, SecretKey)
            httpProfile = HttpProfile()
            httpProfile.endpoint = "cvm.tencentcloudapi.com"

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = cvm_client.CvmClient(cred, "ap-guangzhou", clientProfile)

            req = models.DescribeInstancesRequest()
            params = {
                "InstanceIds": cvms
            }
            req.from_json_string(json.dumps(params))
            #print(json.dumps(cvms))
            resp = client.DescribeInstances(req)
            retD = json.loads(resp.to_json_string())
            #print(resp.to_json_string())
            if 'InstanceSet' in retD and retD['InstanceSet'] and 'TotalCount' in retD and retD['TotalCount'] > 0:
                for cvm in cvms:
                    for ret in retD['InstanceSet']:
                        if ret['InstanceId'] == cvm:
                            print("{data[InstanceId]}  {data[PrivateIpAddresses][0]}".format(data=ret))
                            break

        except TencentCloudSDKException as err:
            print(err)
        print("---------------------------------------------")


if __name__ == '__main__':
    data = {"groupId": "TBASE", "projectId": 1254589, "VpcId": "vpc-lkj4qiln", "SubnetId": "subnet-1ymbb2sw"}
    '''
    groupId: 机器名称
    projectId:项目ID,如果没有修改为0即可
    VpcId:创建CVM对应的VPC ID
    SubnetId:创建CVM对应的子网ID,子网要必须和Zone信息是对应的
    '''
    msg = batchcreateCVM(data)
    #cvmslist = []
    #msg = describeCVM(cvmslist)

正文完