阿里云首页 容器服务 ACK

集群管理

本文介绍ACK集群的基本操作示例,包括创建集群、查集群状态、扩容集群、查集群节点和删除集群。

说明

在操作集群管理SDK示例前,需先安装SDK。具体操作,请参见安装SDK

代码示例

// This file is auto-generated, don't edit it. Thanks.
package aliyun.com.alibabacloud.CS20151215;
import com.aliyun.tea.*;
public class Client {
    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @param regionId
     * @param endpoint
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.cs20151215.Client createClient(String accessKeyId, String accessKeySecret, String regionId) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        // 您的AccessKey ID
        config.accessKeyId = accessKeyId;
        // 您的AccessKey Secret
        config.accessKeySecret = accessKeySecret;
        // 您的可用区ID
        config.regionId = regionId;
        return new com.aliyun.cs20151215.Client(config);
    }
    /**
     * 创建集群
     * @param client
     * @return CreateClusterResponse
     * @throws Exception
     */
    public static com.aliyun.cs20151215.models.CreateClusterResponse createCluster(com.aliyun.cs20151215.Client client) throws Exception {
        com.aliyun.cs20151215.models.CreateClusterRequest createClusterRequest = new com.aliyun.cs20151215.models.CreateClusterRequest()
                .setName("my-test-Kubernetes-cluster")
                .setTimeoutMins(60)
                .setClusterType("ManagedKubernetes")
                .setRegionId("cn-beijing")
                .setVpcid("vpc-2zegvl5etah5requ0****")
                .setContainerCidr("172.20.0.0/16")
                .setServiceCidr("172.21.0.0/20")
                .setLoginPassword("Test_1234")
                .setWorkerInstanceChargeType("PostPaid")
                .setWorkerInstanceTypes(java.util.Arrays.asList(
            "ecs.sn2.3xlarge"
        ))
                .setWorkerVswitchIds(java.util.Arrays.asList(
            "vsw-2ze48rkq464rsdts****"
        ))
                .setWorkerSystemDiskCategory("cloud_efficiency")
                .setWorkerSystemDiskSize(120)
                .setNumOfNodes(3)
                .setOsType("Linux");
        return client.createCluster(createClusterRequest);
    }
    /**
     * 查询集群状态
     * @param client
     * @param clusterId
     * @return DescribeClusterDetailResponse
     * @throws Exception
     */
    public static com.aliyun.cs20151215.models.DescribeClusterDetailResponse describeClusterDetail(com.aliyun.cs20151215.Client client, String clusterId) throws Exception {
        return client.describeClusterDetail(clusterId);
    }
    /**
     * 扩容
     * @param client
     * @param clusterId
     * @return ScaleOutClusterResponse
     * @throws Exception
     */
    public static com.aliyun.cs20151215.models.ScaleOutClusterResponse scaleOutCluster(com.aliyun.cs20151215.Client client, String clusterId) throws Exception {
        com.aliyun.cs20151215.models.ScaleOutClusterRequest scaleOutClusterRequest = new com.aliyun.cs20151215.models.ScaleOutClusterRequest()
                .setLoginPassword("Test_1234")
                .setVswitchIds(java.util.Arrays.asList(
            "vsw-uf684tfrpwup8gcsw****"
        ))
                .setWorkerInstanceTypes(java.util.Arrays.asList(
            "ecs.c5.xlarge"
        ))
                .setWorkerSystemDiskCategory("cloud_efficiency")
                .setWorkerSystemDiskSize(120L)
                .setCount(3L);
        return client.scaleOutCluster(clusterId, scaleOutClusterRequest);
    }
    /**
     * 查询节点
     * @param client
     * @param clusterId
     * @return DescribeClusterNodesResponse
     * @throws Exception
     */
    public static com.aliyun.cs20151215.models.DescribeClusterNodesResponse describeClusterNodes(com.aliyun.cs20151215.Client client, String clusterId) throws Exception {
        com.aliyun.cs20151215.models.DescribeClusterNodesRequest describeClusterNodesRequest = new com.aliyun.cs20151215.models.DescribeClusterNodesRequest()
                .setPageSize("18")
                .setPageNumber("1")
                .setNodepoolId("nodepool_id")
                .setState("running");
        return client.describeClusterNodes(clusterId, describeClusterNodesRequest);
    }
    /**
     * 删除集群
     * @param client
     * @param clusterId
     * @return DescribeClusterDetailResponse
     * @throws Exception
     */
    public static com.aliyun.cs20151215.models.DeleteClusterResponse deleteCluster(com.aliyun.cs20151215.Client client, String clusterId) throws Exception {
        com.aliyun.cs20151215.models.DeleteClusterRequest deleteClusterRequest = new com.aliyun.cs20151215.models.DeleteClusterRequest()
                .setRetainResources(java.util.Arrays.asList(
            "sg-2ze6ess9kho6fdn9****"
        ));
        return client.deleteCluster(clusterId, deleteClusterRequest);
    }
    public static void main(String[] args) throws Exception {
        // 1. 初始化客户端
        com.aliyun.cs20151215.Client client = Client.createClient("accessKeyId", "accessKeySecret", "regionId");
        // 2. 创建集群
        com.aliyun.cs20151215.models.CreateClusterResponse createClusterRes = Client.createCluster(client);
        String clusterId = createClusterRes.body.clusterId;
        // 3. 查询集群状态
        com.aliyun.cs20151215.models.DescribeClusterDetailResponse describeClusterDetailRes = Client.describeClusterDetail(client, clusterId);
        // 4. 当集群状态为“running” 时 进行扩容
        while (true) {
            if (com.aliyun.teautil.Common.equalString(describeClusterDetailRes.body.state, "initial")) {
                // 当集群状态为“initial” 时,创建还未完成,睡眠 3 分钟重试
                com.aliyun.teautil.Common.sleep(180000);
            } else if (com.aliyun.teautil.Common.equalString(describeClusterDetailRes.body.state, "running")) {
                // 创建完成,扩容
                com.aliyun.cs20151215.models.ScaleOutClusterResponse scaleClusterRes = Client.scaleOutCluster(client, clusterId);
                com.aliyun.teaconsole.Client.log(scaleClusterRes.body.requestId);
                break;
            } else {
                // 其他状态直接退出
                return ;
            }
        }
        // 5. 查询节点
        com.aliyun.cs20151215.models.DescribeClusterNodesResponse describeClusterNodesRes = Client.describeClusterNodes(client, clusterId);
        java.util.Map<String, String> describeClusterNodesResHeaders = describeClusterNodesRes.headers;
        com.aliyun.teaconsole.Client.log(describeClusterNodesResHeaders.get("x-acs-request-id"));
        // 6. 删除集群
        com.aliyun.cs20151215.models.DeleteClusterResponse deleteClusterRes = Client.deleteCluster(client, clusterId);
        java.util.Map<String, String> deleteCLusterResHeaders = deleteClusterRes.headers;
        com.aliyun.teaconsole.Client.log(deleteCLusterResHeaders.get("x-acs-request-id"));
    }
}
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import sys
from typing import List
from alibabacloud_cs20151215.client import Client as CSClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_cs20151215 import models as cs_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_tea_console.client import Client as ConsoleClient
class Client:
    def __init__(self):
        pass
    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
        region_id: str,
    ) -> CSClient:
        """
        使用AK&SK初始化账号Client
        @param access_key_id:
        @param access_key_secret:
        @param region_id:
        @param endpoint:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config()
        # 您的AccessKey ID
        config.access_key_id = access_key_id
        # 您的AccessKey Secret
        config.access_key_secret = access_key_secret
        # 您的可用区ID
        config.region_id = region_id
        return CSClient(config)
    @staticmethod
    async def create_client_async(
        access_key_id: str,
        access_key_secret: str,
        region_id: str,
    ) -> CSClient:
        """
        使用AK&SK初始化账号Client
        @param access_key_id:
        @param access_key_secret:
        @param region_id:
        @param endpoint:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config()
        # 您的AccessKey ID。
        config.access_key_id = access_key_id
        # 您的AccessKey Secret
        config.access_key_secret = access_key_secret
        # 您的可用区ID。
        config.region_id = region_id
        return CSClient(config)
    @staticmethod
    def create_cluster(
        client: CSClient,
    ) -> cs_models.CreateClusterResponse:
        """
        创建集群。
        @param client:
        @return: CreateClusterResponse
        @throws Exception
        """
        create_cluster_request = cs_models.CreateClusterRequest(
            name='my-test-Kubernetes-cluster',
            timeout_mins=60,
            cluster_type='ManagedKubernetes',
            region_id='cn-beijing',
            vpcid='vpc-2zegvl5etah5requ0****',
            container_cidr='172.20.0.0/16',
            service_cidr='172.21.0.0/20',
            login_password='Test_1234',
            worker_instance_charge_type='PostPaid',
            worker_instance_types=[
                'ecs.sn2.3xlarge'
            ],
            worker_vswitch_ids=[
                'vsw-2ze48rkq464rsdts****'
            ],
            worker_system_disk_category='cloud_efficiency',
            worker_system_disk_size=120,
            num_of_nodes=3,
            os_type='Linux'
        )
        return client.create_cluster(create_cluster_request)
    @staticmethod
    async def create_cluster_async(
        client: CSClient,
    ) -> cs_models.CreateClusterResponse:
        """
        创建集群
        @param client:
        @return: CreateClusterResponse
        @throws Exception
        """
        create_cluster_request = cs_models.CreateClusterRequest(
            name='my-test-Kubernetes-cluster',
            timeout_mins=60,
            cluster_type='ManagedKubernetes',
            region_id='cn-beijing',
            vpcid='vpc-2zegvl5etah5requ0****',
            container_cidr='172.20.0.0/16',
            service_cidr='172.21.0.0/20',
            login_password='Test_1234',
            worker_instance_charge_type='PostPaid',
            worker_instance_types=[
                'ecs.sn2.3xlarge'
            ],
            worker_vswitch_ids=[
                'vsw-2ze48rkq464rsdts****'
            ],
            worker_system_disk_category='cloud_efficiency',
            worker_system_disk_size=120,
            num_of_nodes=3,
            os_type='Linux'
        )
        return await client.create_cluster_async(create_cluster_request)
    @staticmethod
    def describe_cluster_detail(
        client: CSClient,
        cluster_id: str,
    ) -> cs_models.DescribeClusterDetailResponse:
        """
        查询集群状态
        @param client:
        @param cluster_id:
        @return: DescribeClusterDetailResponse
        @throws Exception
        """
        return client.describe_cluster_detail(cluster_id)
    @staticmethod
    async def describe_cluster_detail_async(
        client: CSClient,
        cluster_id: str,
    ) -> cs_models.DescribeClusterDetailResponse:
        """
        查询集群状态
        @param client:
        @param cluster_id:
        @return: DescribeClusterDetailResponse
        @throws Exception
        """
        return await client.describe_cluster_detail_async(cluster_id)
    @staticmethod
    def scale_out_cluster(
        client: CSClient,
        cluster_id: str,
    ) -> cs_models.ScaleOutClusterResponse:
        """
        扩容
        @param client:
        @param cluster_id:
        @return: ScaleOutClusterResponse
        @throws Exception
        """
        scale_out_cluster_request = cs_models.ScaleOutClusterRequest(
            login_password='Test_1234',
            vswitch_ids=[
                'vsw-uf684tfrpwup8gcsw****'
            ],
            worker_instance_types=[
                'ecs.c5.xlarge'
            ],
            worker_system_disk_category='cloud_efficiency',
            worker_system_disk_size=120,
            count=3
        )
        return client.scale_out_cluster(cluster_id, scale_out_cluster_request)
    @staticmethod
    async def scale_out_cluster_async(
        client: CSClient,
        cluster_id: str,
    ) -> cs_models.ScaleOutClusterResponse:
        """
        扩容
        @param client:
        @param cluster_id:
        @return: ScaleOutClusterResponse
        @throws Exception
        """
        scale_out_cluster_request = cs_models.ScaleOutClusterRequest(
            login_password='Test_1234',
            vswitch_ids=[
                'vsw-uf684tfrpwup8gcsw****'
            ],
            worker_instance_types=[
                'ecs.c5.xlarge'
            ],
            worker_system_disk_category='cloud_efficiency',
            worker_system_disk_size=120,
            count=3
        )
        return await client.scale_out_cluster_async(cluster_id, scale_out_cluster_request)
    @staticmethod
    def describe_cluster_nodes(
        client: CSClient,
        cluster_id: str,
    ) -> cs_models.DescribeClusterNodesResponse:
        """
        查询节点
        @param client:
        @param cluster_id:
        @return: DescribeClusterNodesResponse
        @throws Exception
        """
        describe_cluster_nodes_request = cs_models.DescribeClusterNodesRequest(
            page_size='18',
            page_number='1',
            nodepool_id='nodepool_id',
            state='running'
        )
        return client.describe_cluster_nodes(cluster_id, describe_cluster_nodes_request)
    @staticmethod
    async def describe_cluster_nodes_async(
        client: CSClient,
        cluster_id: str,
    ) -> cs_models.DescribeClusterNodesResponse:
        """
        查询节点
        @param client:
        @param cluster_id:
        @return: DescribeClusterNodesResponse
        @throws Exception
        """
        describe_cluster_nodes_request = cs_models.DescribeClusterNodesRequest(
            page_size='18',
            page_number='1',
            nodepool_id='nodepool_id',
            state='running'
        )
        return await client.describe_cluster_nodes_async(cluster_id, describe_cluster_nodes_request)
    @staticmethod
    def delete_cluster(
        client: CSClient,
        cluster_id: str,
    ) -> cs_models.DeleteClusterResponse:
        """
        删除集群
        @param client:
        @param cluster_id:
        @return: DescribeClusterDetailResponse
        @throws Exception
        """
        delete_cluster_request = cs_models.DeleteClusterRequest(
            retain_resources=[
                'sg-2ze6ess9kho6fdn9****'
            ]
        )
        return client.delete_cluster(cluster_id, delete_cluster_request)
    @staticmethod
    async def delete_cluster_async(
        client: CSClient,
        cluster_id: str,
    ) -> cs_models.DeleteClusterResponse:
        """
        删除集群
        @param client:
        @param cluster_id:
        @return: DescribeClusterDetailResponse
        @throws Exception
        """
        delete_cluster_request = cs_models.DeleteClusterRequest(
            retain_resources=[
                'sg-2ze6ess9kho6fdn9****'
            ]
        )
        return await client.delete_cluster_async(cluster_id, delete_cluster_request)
    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        # 1. 初始化客户端
        client = Client.create_client('accessKeyId', 'accessKeySecret', 'regionId')
        # 2. 创建集群
        create_cluster_res = Client.create_cluster(client)
        cluster_id = create_cluster_res.body.cluster_id
        # 3. 查询集群状态
        describe_cluster_detail_res = Client.describe_cluster_detail(client, cluster_id)
        # 4. 当集群状态为“running” 时 进行扩容
        while True:
            if UtilClient.equal_string(describe_cluster_detail_res.body.state, 'initial'):
                # 当集群状态为“initial” 时,创建还未完成,睡眠 3 分钟重试
                UtilClient.sleep(180000)
            elif UtilClient.equal_string(describe_cluster_detail_res.body.state, 'running'):
                # 创建完成,扩容
                scale_cluster_res = Client.scale_out_cluster(client, cluster_id)
                ConsoleClient.log(scale_cluster_res.body.request_id)
                break
            else:
                # 其他状态直接退出
                return
        # 5. 查询节点
        describe_cluster_nodes_res = Client.describe_cluster_nodes(client, cluster_id)
        describe_cluster_nodes_res_headers = describe_cluster_nodes_res.headers
        ConsoleClient.log(describe_cluster_nodes_res_headers.get('x-acs-request-id'))
        # 6. 删除集群
        delete_cluster_res = Client.delete_cluster(client, cluster_id)
        delete_cluster_res_headers = delete_cluster_res.headers
        ConsoleClient.log(delete_cluster_res_headers.get('x-acs-request-id'))
    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        # 1. 初始化客户端
        client = await Client.create_client_async('accessKeyId', 'accessKeySecret', 'regionId')
        # 2. 创建集群
        create_cluster_res = await Client.create_cluster_async(client)
        cluster_id = create_cluster_res.body.cluster_id
        # 3. 查询集群状态
        describe_cluster_detail_res = await Client.describe_cluster_detail_async(client, cluster_id)
        # 4. 当集群状态为“running” 时 进行扩容
        while True:
            if UtilClient.equal_string(describe_cluster_detail_res.body.state, 'initial'):
                # 当集群状态为“initial” 时,创建还未完成,睡眠 3 分钟重试
                await UtilClient.sleep_async(180000)
            elif UtilClient.equal_string(describe_cluster_detail_res.body.state, 'running'):
                # 创建完成,扩容
                scale_cluster_res = await Client.scale_out_cluster_async(client, cluster_id)
                ConsoleClient.log(scale_cluster_res.body.request_id)
                break
            else:
                # 其他状态直接退出
                return
        # 5. 查询节点
        describe_cluster_nodes_res = await Client.describe_cluster_nodes_async(client, cluster_id)
        describe_cluster_nodes_res_headers = describe_cluster_nodes_res.headers
        ConsoleClient.log(describe_cluster_nodes_res_headers.get('x-acs-request-id'))
        # 6. 删除集群
        delete_cluster_res = await Client.delete_cluster_async(client, cluster_id)
        delete_cluster_res_headers = delete_cluster_res.headers
        ConsoleClient.log(delete_cluster_res_headers.get('x-acs-request-id'))
if __name__ == '__main__':
    Client.main(sys.argv[1:])
// This file is auto-generated, don't edit it. Thanks.
package main
import (
  "os"
  cs  "github.com/alibabacloud-go/cs-20151215/v2/client"
  openapi  "github.com/alibabacloud-go/darabonba-openapi/client"
  util  "github.com/alibabacloud-go/tea-utils/service"
  console  "github.com/alibabacloud-go/tea-console/client"
  "github.com/alibabacloud-go/tea/tea"
)
/**
 * 使用AK&SK初始化账号Client。
 * @param accessKeyId
 * @param accessKeySecret
 * @param regionId
 * @param endpoint
 * @return Client
 * @throws Exception
 */
func CreateClient (accessKeyId *string, accessKeySecret *string, regionId *string) (_result *cs.Client, _err error) {
  config := &openapi.Config{}
  // 您的AccessKey ID。
  config.AccessKeyId = accessKeyId
  // 您的AccessKey Secret。
  config.AccessKeySecret = accessKeySecret
  // 您的可用区ID。
  config.RegionId = regionId
  _result = &cs.Client{}
  _result, _err = cs.NewClient(config)
  return _result, _err
}
/**
 * 创建集群。
 * @param client
 * @return CreateClusterResponse
 * @throws Exception
 */
func CreateCluster (client *cs.Client) (_result *cs.CreateClusterResponse, _err error) {
  createClusterRequest := &cs.CreateClusterRequest{
    // 集群名称。
    Name: tea.String("my-test-Kubernetes-cluster"),
    // 集群创建超时时间。
    TimeoutMins: tea.Int64(60),
    // 集群类型,ManagedKubernetes。
    ClusterType: tea.String("ManagedKubernetes"),
    // 地域。
    RegionId: tea.String("cn-beijing"),
    // VPC ID。
    Vpcid: tea.String("vpc-2zegvl5etah5requ0****"),
    // 容器POD CIDR。
    ContainerCidr: tea.String("172.20.0.0/16"),
    // 服务CIDR。
    ServiceCidr: tea.String("172.21.0.0/20"),
    // 节点SSH登录密码,和key_pair二选一。
    LoginPassword: tea.String("Test_1234"),
    // Worker节点付费类型PrePaid|PostPaid。
    WorkerInstanceChargeType: tea.String("PostPaid"),
    // Worker实例规格多实例规格参数。
    WorkerInstanceTypes: []*string{tea.String("ecs.sn2.3xlarge")},
    // 一台或多台虚拟交换机 ID,N 的取值范围为 [1, 5]。
    WorkerVswitchIds: []*string{tea.String("vsw-2ze48rkq464rsdts****")},
    // Worker系统盘类型。
    WorkerSystemDiskCategory: tea.String("cloud_efficiency"),
    // Worker节点系统盘大小。
    WorkerSystemDiskSize: tea.Int64(120),
    // Worker节点数。
    NumOfNodes: tea.Int64(3),
    // 运行pod的主机的操作系统类型,例如:Linux,Windows等。
    OsType: tea.String("Linux"),
  }
  _result = &cs.CreateClusterResponse{}
  _body, _err := client.CreateCluster(createClusterRequest)
  if _err != nil {
    return _result, _err
  }
  _result = _body
  return _result, _err
}
/**
 * 查询集群状态
 * @param client
 * @param clusterId
 * @return DescribeClusterDetailResponse
 * @throws Exception
 */
func DescribeClusterDetail (client *cs.Client, clusterId *string) (_result *cs.DescribeClusterDetailResponse, _err error) {
  _result = &cs.DescribeClusterDetailResponse{}
  _body, _err := client.DescribeClusterDetail(clusterId)
  if _err != nil {
    return _result, _err
  }
  _result = _body
  return _result, _err
}
/**
 * 扩容
 * @param client
 * @param clusterId
 * @return ScaleOutClusterResponse
 * @throws Exception
 */
func ScaleOutCluster (client *cs.Client, clusterId *string) (_result *cs.ScaleOutClusterResponse, _err error) {
  scaleOutClusterRequest := &cs.ScaleOutClusterRequest{
    // keypair名称,和login_password 二选一
    LoginPassword: tea.String("Test_1234"),
    // 一台或多台虚拟交换机 ID,N 的取值范围为 [1, 3]
    VswitchIds: []*string{tea.String("vsw-uf684tfrpwup8gcsw****")},
    // Worker实例规格多实例规格参数
    WorkerInstanceTypes: []*string{tea.String("ecs.c5.xlarge")},
    // Worker节点系统盘类型
    WorkerSystemDiskCategory: tea.String("cloud_efficiency"),
    // Worker节点系统盘类型
    WorkerSystemDiskSize: tea.Int64(120),
    // 扩容的数量
    Count: tea.Int64(3),
  }
  _result = &cs.ScaleOutClusterResponse{}
  _body, _err := client.ScaleOutCluster(clusterId, scaleOutClusterRequest)
  if _err != nil {
    return _result, _err
  }
  _result = _body
  return _result, _err
}
/**
 * 查询节点
 * @param client
 * @param clusterId
 * @return DescribeClusterNodesResponse
 * @throws Exception
 */
func DescribeClusterNodes (client *cs.Client, clusterId *string) (_result *cs.DescribeClusterNodesResponse, _err error) {
  describeClusterNodesRequest := &cs.DescribeClusterNodesRequest{
    // 可选 每页显示条数
    PageSize: tea.String("18"),
    // 可选 页码数
    PageNumber: tea.String("1"),
    // 可选 nodepool_id
    NodepoolId: tea.String("nodepool_id"),
    // 状态 
    State: tea.String("running"),
  }
  _result = &cs.DescribeClusterNodesResponse{}
  _body, _err := client.DescribeClusterNodes(clusterId, describeClusterNodesRequest)
  if _err != nil {
    return _result, _err
  }
  _result = _body
  return _result, _err
}
/**
 * 删除集群
 * @param client
 * @param clusterId
 * @return DescribeClusterDetailResponse
 * @throws Exception
 */
func DeleteCluster (client *cs.Client, clusterId *string) (_result *cs.DeleteClusterResponse, _err error) {
  deleteClusterRequest := &cs.DeleteClusterRequest{
    // 可选 集群删除时需要保留的资源列表
    RetainResources: []*string{tea.String("sg-2ze6ess9kho6fdn9****")},
  }
  _result = &cs.DeleteClusterResponse{}
  _body, _err := client.DeleteCluster(clusterId, deleteClusterRequest)
  if _err != nil {
    return _result, _err
  }
  _result = _body
  return _result, _err
}
func _main (args []*string) (_err error) {
  // 1. 初始化客户端
  client, _err := CreateClient(tea.String("accessKeyId"), tea.String("accessKeySecret"), tea.String("regionId"))
  if _err != nil {
    return _err
  }
  // 2. 创建集群
  createClusterRes, _err := CreateCluster(client)
  if _err != nil {
    return _err
  }
  clusterId := createClusterRes.Body.ClusterId
  // 3. 查询集群状态
  describeClusterDetailRes, _err := DescribeClusterDetail(client, clusterId)
  if _err != nil {
    return _err
  }
  // 4. 当集群状态为“running” 时 进行扩容
  for true {
    if tea.BoolValue(util.EqualString(describeClusterDetailRes.Body.State, tea.String("initial"))) {
      // 当集群状态为“initial” 时,创建还未完成,睡眠 3 分钟重试
      _err = util.Sleep(tea.Int(180000))
      if _err != nil {
        return _err
      }
    } else if tea.BoolValue(util.EqualString(describeClusterDetailRes.Body.State, tea.String("running"))) {
      // 创建完成,扩容
      scaleClusterRes, _err := ScaleOutCluster(client, clusterId)
      if _err != nil {
        return _err
      }
      console.Log(scaleClusterRes.Body.RequestId)
      break
    } else {
      // 其他状态直接退出
      return _err
    }
  }
  // 5. 查询节点
  describeClusterNodesRes, _err := DescribeClusterNodes(client, clusterId)
  if _err != nil {
    return _err
  }
  describeClusterNodesResHeaders := describeClusterNodesRes.Headers
  console.Log(describeClusterNodesResHeaders["x-acs-request-id"])
  // 6. 删除集群
  deleteClusterRes, _err := DeleteCluster(client, clusterId)
  if _err != nil {
    return _err
  }
  deleteCLusterResHeaders := deleteClusterRes.Headers
  console.Log(deleteCLusterResHeaders["x-acs-request-id"])
  return _err
}
func main() {
  err := _main(tea.StringSlice(os.Args))
  if err != nil {
    panic(err)
  }
}
// This file is auto-generated, don't edit it
import CS, * as $CS from '@alicloud/cs20151215';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util from '@alicloud/tea-util';
import Console from '@alicloud/tea-console';
import * as $tea from '@alicloud/tea-typescript';
export default class Client {
  /**
   * 使用AK&SK初始化账号Client
   * @param accessKeyId
   * @param accessKeySecret
   * @param regionId
   * @param endpoint
   * @return Client
   * @throws Exception
   */
  static async createClient(accessKeyId: string, accessKeySecret: string, regionId: string): Promise<CS> {
    let config = new $OpenApi.Config({ });
    // 您的AccessKey ID
    config.accessKeyId = accessKeyId;
    // 您的AccessKey Secret
    config.accessKeySecret = accessKeySecret;
    // 您的可用区ID
    config.regionId = regionId;
    return new CS(config);
  }
  /**
   * 创建集群
   * @param client
   * @return CreateClusterResponse
   * @throws Exception
   */
  static async createCluster(client: CS): Promise<$CS.CreateClusterResponse> {
    let createClusterRequest = new $CS.CreateClusterRequest({
      // 集群名称
      name: "my-test-Kubernetes-cluster",
      // 集群创建超时时间
      timeoutMins: 60,
      // 集群类型,ManagedKubernetes
      clusterType: "ManagedKubernetes",
      // 地域
      regionId: "cn-beijing",
      // VPC ID
      vpcid: "vpc-2zegvl5etah5requ0****",
      // 容器POD CIDR
      containerCidr: "172.20.0.0/16",
      // 服务CIDR
      serviceCidr: "172.21.0.0/20",
      // 节点SSH登录密码,和key_pair二选一
      loginPassword: "Test_1234",
      // Worker节点付费类型PrePaid|PostPaid
      workerInstanceChargeType: "PostPaid",
      // Worker实例规格多实例规格参数
      workerInstanceTypes: [
        "ecs.sn2.3xlarge"
      ],
      // 一台或多台虚拟交换机 ID,N 的取值范围为 [1, 5]
      workerVswitchIds: [
        "vsw-2ze48rkq464rsdts****"
      ],
      // Worker系统盘类型
      workerSystemDiskCategory: "cloud_efficiency",
      // Worker节点系统盘大小
      workerSystemDiskSize: 120,
      // Worker节点数
      numOfNodes: 3,
      // 运行pod的主机的操作系统类型,例如:linux,Windows等
      osType: "linux",
    });
    return await client.createCluster(createClusterRequest);
  }
  /**
   * 查询集群状态
   * @param client
   * @param clusterId
   * @return DescribeClusterDetailResponse
   * @throws Exception
   */
  static async describeClusterDetail(client: CS, clusterId: string): Promise<$CS.DescribeClusterDetailResponse> {
    return await client.describeClusterDetail(clusterId);
  }
  /**
   * 扩容
   * @param client
   * @param clusterId
   * @return ScaleOutClusterResponse
   * @throws Exception
   */
  static async scaleOutCluster(client: CS, clusterId: string): Promise<$CS.ScaleOutClusterResponse> {
    let scaleOutClusterRequest = new $CS.ScaleOutClusterRequest({
      // keypair名称,和login_password 二选一
      loginPassword: "Test_1234",
      // 一台或多台虚拟交换机 ID,N 的取值范围为 [1, 3]
      vswitchIds: [
        "vsw-uf684tfrpwup8gcsw****"
      ],
      // Worker实例规格多实例规格参数
      workerInstanceTypes: [
        "ecs.c5.xlarge"
      ],
      // Worker节点系统盘类型
      workerSystemDiskCategory: "cloud_efficiency",
      // Worker节点系统盘类型
      workerSystemDiskSize: 120,
      // 扩容的数量
      count: 3,
    });
    return await client.scaleOutCluster(clusterId, scaleOutClusterRequest);
  }
  /**
   * 查询节点
   * @param client
   * @param clusterId
   * @return DescribeClusterNodesResponse
   * @throws Exception
   */
  static async describeClusterNodes(client: CS, clusterId: string): Promise<$CS.DescribeClusterNodesResponse> {
    let describeClusterNodesRequest = new $CS.DescribeClusterNodesRequest({
      // 可选 每页显示条数
      pageSize: "18",
      // 可选 页码数
      pageNumber: "1",
      // 可选 nodepool_id
      nodepoolId: "nodepool_id",
      // 状态 
      state: "running",
    });
    return await client.describeClusterNodes(clusterId, describeClusterNodesRequest);
  }
  /**
   * 删除集群
   * @param client
   * @param clusterId
   * @return DescribeClusterDetailResponse
   * @throws Exception
   */
  static async deleteCluster(client: CS, clusterId: string): Promise<$CS.DeleteClusterResponse> {
    let deleteClusterRequest = new $CS.DeleteClusterRequest({
      // 可选 集群删除时需要保留的资源列表
      retainResources: [
        "sg-2ze6ess9kho6fdn9****"
      ],
    });
    return await client.deleteCluster(clusterId, deleteClusterRequest);
  }
  static async main(args: string[]): Promise<void> {
    // 1. 初始化客户端
    let client = await Client.createClient("accessKeyId", "accessKeySecret", "regionId");
    // 2. 创建集群
    let createClusterRes = await Client.createCluster(client);
    let clusterId = createClusterRes.body.clusterId;
    // 3. 查询集群状态
    let describeClusterDetailRes = await Client.describeClusterDetail(client, clusterId);
    // 4. 当集群状态为“running” 时 进行扩容
    while (true) {
      if (Util.equalString(describeClusterDetailRes.body.state, "initial")) {
        // 当集群状态为“initial” 时,创建还未完成,睡眠 3 分钟重试
        await Util.sleep(180000);
      } else if (Util.equalString(describeClusterDetailRes.body.state, "running")) {
        // 创建完成,扩容
        let scaleClusterRes = await Client.scaleOutCluster(client, clusterId);
        Console.log(scaleClusterRes.body.requestId);
        break;
      } else {
        // 其他状态直接退出
        return ;
      }
    }
    // 5. 查询节点
    let describeClusterNodesRes = await Client.describeClusterNodes(client, clusterId);
    let describeClusterNodesResHeaders = describeClusterNodesRes.headers;
    Console.log(describeClusterNodesResHeaders["x-acs-request-id"]);
    // 6. 删除集群
    let deleteClusterRes = await Client.deleteCluster(client, clusterId);
    let deleteCLusterResHeaders = deleteClusterRes.headers;
    Console.log(deleteCLusterResHeaders["x-acs-request-id"]);
  }
}
Client.main(process.argv.slice(2));