全部產品
Search
文件中心

Elastic Compute Service:通過SDK建立並使用ECS執行個體

更新時間:Oct 25, 2024

阿里雲ECS提供多種API和SDK,讓您可以通過編程建立和管理ECS執行個體,提高業務效率,實現系統自動化。本文介紹了如何利用V2.0 Java SDK建立ECS執行個體,藉助雲助手API執行指令碼以及釋放資源等操作。

準備工作

  1. 由於阿里雲帳號(主帳號)擁有資源的所有許可權,其AccessKey一旦泄露風險巨大,所以建議您使用滿足最小化許可權需求的RAM使用者的AccessKey。擷取方法請參見建立AccessKey

  2. 給RAM使用者授予操作Elastic Compute Service和Virtual Private Cloud相關資源的許可權。本文提供的範例程式碼需要建立執行個體、VPC、交換器等資源,建議授予以下許可權:

    雲產品

    授予許可權

    Virtual Private Cloud

    本樣本選擇系統策略:AliyunVPCFullAccess

    Elastic Compute Service

    本樣本選擇系統策略:AliyunECSFullAccess

  3. 本文範例程式碼會在系統內容變數中讀取AccessKey作為訪問雲端服務的憑證,具體操作步驟請參見在Linux、macOS和Windows系統配置環境變數

  4. 擷取ECS SDK和VPC SDK,本文通過添加Maven依賴的方式來安裝。更多安裝方式,請參見安裝ECS Java SDK安裝VPC Java SDK

    添加Maven依賴的樣本如下:

    <dependencies>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>ecs20140526</artifactId>
            <version>5.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>vpc20160428</artifactId>
            <version>7.12.0</version>
        </dependency>
    </dependencies>

建立ECS執行個體

建立ECS執行個體時有很多必填參數,包括交換器ID、安全性群組、鏡像等。您可以傳入已經準備好的資源ID,或者調用以下OpenAPI建立對應資源。

  1. 建立VPC

    VPC是一種專有的雲上私人網路,允許使用者在公用雲上配置和管理一個邏輯隔離的網路地區。

    API

    參數

    樣本取值

    CreateVpc

    RegionId

    地區:cn-hangzhou

    CidrBlock

    VPC網段:192.168.0.0/16

  2. 查詢VPC資訊

    在調用CreateVpc之後,VPC需要一段配置時間,您可以調用該OpenAPI查詢VPC的狀態。當VPC的狀態處於Available(可用)時,請再調用後續OpenAPI。

    API

    參數

    樣本取值

    DescribeVpcs

    RegionId

    地區:cn-hangzhou

    VpcId

    VPC的ID:vpc-bp1aag0sb9s4i92i3****

  3. 建立交換器

    交換器是一種在虛擬化環境中使用的網路交換裝置,它類比了物理交換器的功能,使虛擬機器(VMs)之間以及虛擬機器與物理網路之間可以進行通訊。

    API

    參數

    樣本取值

    RegionId

    地區:cn-hangzhou

    CreateVSwitch

    ZoneId

    可用性區域:cn-hangzhou-i

    VpcId

    VPC ID:vpc-bp1aag0sb9s4i92i3****

    CidrBlock

    交換器網段:192.168.0.0/24

  4. 建立安全性群組

    安全性群組是一種虛擬防火牆,能夠控制ECS執行個體的出入方向流量。

    API

    參數

    樣本取值

    CreateSecurityGroup

    RegionId

    地區:cn-hangzhou

    VpcId

    VPC ID:vpc-bp1aag0sb9s4i92i3****

  5. 給安全性群組添加防護規則

    API

    參數

    樣本取值

    AuthorizeSecurityGroup

    RegionId

    地區:cn-hangzhou

    SecurityGroupId

    安全性群組ID:sg-bp1esyhwfbqeyudt****

    IpProtocol

    協議:tcp

    SourceCidrIp

    源CIDR:0.0.0.0/0

    PortRange

    連接埠範圍:

    • Linux執行個體:22/22

    • Windows執行個體:3389/3389

  6. 建立SSH金鑰組

    阿里雲SSH金鑰組是一種安全便捷的登入認證方式,用於在SSH協議中進行身分識別驗證和加密通訊。通過SSH金鑰組,您可以實現免密碼遠程登入。

    API

    參數

    樣本取值

    CreateKeyPair

    RegionId

    地區:cn-hangzhou

    KeyPairName

    金鑰組名稱:sdk-key-pair

  7. 建立ECS執行個體

    使用ECS您可以快速部署和運行應用程式,靈活調整資源以應對業務變化,同時享受高效能、高安全性和低成本的計算能力,適用於網站託管、應用開發、資料處理等多種情境。

    API

    參數

    樣本取值

    RunInstances

    RegionId

    地區:cn-hangzhou

    ImageId

    鏡像:推薦使用Alibaba Cloud Linux鏡像aliyun_3_x64_20G_scc_alibase_20220225.vhd

    InstanceType

    執行個體規格: ecs.e-c1m2.xlarge

    SecurityGroupId

    安全性群組ID:sg-bp1esyhwfbqeyudt****

    VSwitchId

    交換器ID:vsw-bp1nzprm8h7mmnl8t****

    InstanceName

    執行個體名稱:sdk-test

    InstanceChargeType

    付費方式:執行個體按照隨用隨付的方式PostPaid

    說明

    您需要確保帳號餘額能夠完成支付。

    KeyPairName

    金鑰組名稱:sdk-key-pair

    SystemDisk.Category

    系統硬碟的雲端硬碟種類:cloud_essd

  8. 查詢ECS執行個體狀態

    在調用RunInstances後,ECS執行個體需要一定的啟動時間。僅當ECS執行個體狀態達到Running時,才能通過遠端連線等方式登入到執行個體,以進行各種操作和應用程式的部署。您可以調用該OpenAPI查詢ECS執行個體的狀態。

    API

    參數

    樣本取值

    DescribeInstanceStatus

    RegionId

    地區:cn-hangzhou

    InstanceId

    執行個體ID集合:["i-bp17f3kzgtzzj91r****"]

完整的範例程式碼如下:

import com.aliyun.ecs20140526.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.vpc20160428.models.CreateVSwitchRequest;
import com.aliyun.vpc20160428.models.CreateVSwitchResponse;
import com.aliyun.vpc20160428.models.CreateVpcRequest;
import com.aliyun.vpc20160428.models.CreateVpcResponse;
import com.aliyun.vpc20160428.models.DescribeVpcsRequest;

import java.util.ArrayList;
import java.util.List;

public class EcsDemo {
    public static void main(String[] args) {
        String vpcId = null;
        String vSwitchId = null;
        String securityGroupId = null;
        String instanceId = null;
        com.aliyun.vpc20160428.Client vpcClient = null;
        com.aliyun.ecs20140526.Client ecsClient = null;
        try {
            vpcClient = createVpcClient();
            ecsClient = createEcsClient();
            // 建立VPC
            vpcId = createVpc(vpcClient);
            System.out.println("VPC create success, vpcId :" + vpcId);
            // 當VPC的狀態為Available時,繼續後續步驟
            while (true) {
                String status = describeVpc(vpcId, vpcClient);
                if ("Available".equals(status)) {
                    break;
                }
            }
            // 建立交換器
            vSwitchId = CreateVSwitch(vpcId, vpcClient);
            System.out.println("VSwitch create success, vSwitchId :" + vSwitchId);
            // 建立安全性群組
            securityGroupId = createSecurityGroup(vpcId, ecsClient);
            System.out.println("SecurityGroup create success, securityGroupId :" + securityGroupId);
            // 添加安全性群組入方向規則
            authorizeSecurityGroup(securityGroupId, ecsClient);
            // 建立金鑰組。注意:儲存金鑰組的資訊,用於登入ECS
            CreateKeyPairResponse keyPair = createKeyPair(ecsClient);
            System.out.println("KeyPair create success, keyPairName :" + keyPair.body.keyPairName);
            // 建立執行個體,當ECS執行個體狀態為Running時,表示ECS已經處於運行中
            instanceId = createInstance(ecsClient, vSwitchId, securityGroupId);
            System.out.println("ECS create success, instanceId :" + instanceId);
            while (true) {
                List<String> instanceIds = new ArrayList<>();
                instanceIds.add(instanceId);
                DescribeInstanceStatusResponse describeInstanceStatus = describeInstanceStatus(instanceIds, ecsClient);
                List<DescribeInstanceStatusResponseBody.DescribeInstanceStatusResponseBodyInstanceStatusesInstanceStatus> instanceStatusList = describeInstanceStatus.body.instanceStatuses.instanceStatus;
                if (instanceStatusList != null && !instanceStatusList.isEmpty()) {
                    String status = instanceStatusList.get(0).status;
                    if ("Running".equals(status)) {
                        break;
                    }
                }
            }
        } catch (Exception e) {
            // 當面對部分資源建立成功而其他資源建立失敗的情況時,需要增加合理的處理機制,例如記錄日誌、復原機制、補償機制等。
            System.out.println(e.getMessage());
        }
    }

    public static class Constants {
        // 名稱
        public static final String NAME = "sdk-test";
        // 地區
        public static final String REGION_ID = "cn-hangzhou";
        // 可用性區域
        public static final String ZONE_ID = "cn-hangzhou-i";
        // 建立的VPC網路和交換器網段
        public static final String CIDR_BLOCK_VPC = "192.168.0.0/16";
        public static final String CIDR_BLOCK_VSWITCH = "192.168.0.0/24";
        // 鏡像
        public static final String IMAGE_ID = "aliyun_3_x64_20G_scc_alibase_20220225.vhd";
        // 執行個體規格
        public static final String INSTANCE_TYPE = "ecs.e-c1m2.xlarge";
        // 磁碟類型
        public static final String SYSTEM_DISK_CATEGORY = "cloud_essd";

        // 金鑰組名稱
        public static final String KEY_PAIR_NAME = "sdk-key-pair";

        // 服務存取點
        public static final class ENDPOINT {
            public static final String VPC = "vpc.cn-hangzhou.aliyuncs.com";
            public static final String ECS = "ecs.cn-hangzhou.aliyuncs.com";
        }

        // 付費類型
        public static final class INSTANCE_CHARGE_TYPE {
            // 訂用帳戶
            public static final String PRE_PAID = "PrePaid";
            // 隨用隨付
            public static final String POST_PAID = "PostPaid";
        }
    }

    public static com.aliyun.vpc20160428.Client createVpcClient() throws Exception {
        Config config = new Config();
        config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = Constants.ENDPOINT.VPC;
        return new com.aliyun.vpc20160428.Client(config);
    }

    public static com.aliyun.ecs20140526.Client createEcsClient() throws Exception {
        Config config = new Config();
        config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = Constants.ENDPOINT.ECS;
        return new com.aliyun.ecs20140526.Client(config);
    }

    /**
     * 建立VPC(虛擬私人雲端)網路
     * 該方法通過調用阿里雲VPC服務的API來建立一個VPC網路,並返回新建立VPC的ID
     *
     * @param vpcClient VPC用戶端
     * @return 返回新建立的VPC的ID
     */
    public static String createVpc(com.aliyun.vpc20160428.Client vpcClient) {
        try {
            CreateVpcRequest createVpcRequest = new CreateVpcRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setCidrBlock(Constants.CIDR_BLOCK_VPC)
                    .setVpcName(Constants.NAME);
            CreateVpcResponse vpc = vpcClient.createVpc(createVpcRequest);
            return vpc.body.vpcId;
        } catch (Exception e) {
            throw new RuntimeException("createVpc failed: " + e.getMessage());
        }
    }

    /**
     * 建立VSwitch(虛擬交換器).
     * 該方法負責通過阿里雲VPC用戶端建立一個新的VSwitch. 它配置了必要的請求參數,如地區ID、可用性區域ID、
     * CIDR段、VPC ID和VSwitch名稱,然後發送請求並返回新建立VSwitch的ID.
     *
     * @param vpcId     VPC的ID,標識要在其中建立VSwitch的VPC
     * @param vpcClient VPC用戶端
     * @return 返回新建立的VSwitch的ID
     */
    public static String CreateVSwitch(String vpcId, com.aliyun.vpc20160428.Client vpcClient) {
        try {
            CreateVSwitchRequest createVSwitchRequest = new CreateVSwitchRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setZoneId(Constants.ZONE_ID)
                    .setCidrBlock(Constants.CIDR_BLOCK_VSWITCH)
                    .setVpcId(vpcId)
                    .setVSwitchName(Constants.NAME);
            CreateVSwitchResponse vSwitch = vpcClient.createVSwitch(createVSwitchRequest);
            return vSwitch.body.vSwitchId;
        } catch (Exception e) {
            throw new RuntimeException("CreateVSwitch failed: " + e.getMessage());
        }
    }

    /**
     * 建立安全性群組
     *
     * @param vpcId     專用網路的ID
     * @param ecsClient ECS用戶端
     * @return 建立的安全性群組的ID
     */
    public static String createSecurityGroup(String vpcId, com.aliyun.ecs20140526.Client ecsClient) {
        try {
            CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setVpcId(vpcId)
                    .setSecurityGroupName(Constants.NAME);
            CreateSecurityGroupResponse securityGroup = ecsClient.createSecurityGroup(createSecurityGroupRequest);
            return securityGroup.body.securityGroupId;
        } catch (Exception e) {
            throw new RuntimeException("createSecurityGroup failed: " + e.getMessage());
        }
    }

    /**
     * 授權安全性群組規則,以允許特定的入站流量
     * 例如:允許TCP協議的22連接埠(SSH)從任何IP地址(0.0.0.0/0)訪問。
     *
     * @param securityGroupId 安全性群組的ID,用於標識哪個安全性群組的規則需要被授權。
     * @param ecsClient       ECS用戶端
     */
    public static void authorizeSecurityGroup(String securityGroupId, com.aliyun.ecs20140526.Client ecsClient) {
        try {
            AuthorizeSecurityGroupRequest.AuthorizeSecurityGroupRequestPermissions permission = new AuthorizeSecurityGroupRequest.AuthorizeSecurityGroupRequestPermissions()
                    .setIpProtocol("tcp")
                    .setPortRange("22/22")
                    .setSourceCidrIp("0.0.0.0/0");
            List<AuthorizeSecurityGroupRequest.AuthorizeSecurityGroupRequestPermissions> permissions = new ArrayList<>();
            permissions.add(permission);
            AuthorizeSecurityGroupRequest authorizeSecurityGroupRequest = new AuthorizeSecurityGroupRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setSecurityGroupId(securityGroupId)
                    .setPermissions(permissions);

            ecsClient.authorizeSecurityGroup(authorizeSecurityGroupRequest);
        } catch (Exception e) {
            throw new RuntimeException("authorizeSecurityGroup failed: " + e.getMessage());
        }
    }

    /**
     * 建立ECS執行個體
     *
     * @param ecsClient       ECS用戶端
     * @param vSwitchId       交換器ID
     * @param securityGroupId 安全性群組ID
     * @return 新建立的ECS執行個體的ID
     */
    public static String createInstance(com.aliyun.ecs20140526.Client ecsClient, String vSwitchId, String securityGroupId) {
        try {
            RunInstancesRequest.RunInstancesRequestSystemDisk systemDisk = new RunInstancesRequest.RunInstancesRequestSystemDisk()
                    .setCategory(Constants.SYSTEM_DISK_CATEGORY);
            RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setImageId(Constants.IMAGE_ID)
                    .setInstanceType(Constants.INSTANCE_TYPE)
                    .setSecurityGroupId(securityGroupId)
                    .setVSwitchId(vSwitchId)
                    .setInstanceChargeType(Constants.INSTANCE_CHARGE_TYPE.POST_PAID)
                    .setInstanceName(Constants.NAME)
                    .setInternetMaxBandwidthOut(1)
                    .setSystemDisk(systemDisk)
                    .setKeyPairName(Constants.KEY_PAIR_NAME);
            RunInstancesResponse resp = ecsClient.runInstances(runInstancesRequest);
            return resp.body.getInstanceIdSets().getInstanceIdSet().get(0);
        } catch (Exception e) {
            throw new RuntimeException("createInstance failed: " + e.getMessage());
        }
    }

    /**
     * 使用指定的安全性群組ID建立金鑰組
     *
     * @param ecsClient ECS用戶端
     * @return 返回建立金鑰組的響應對象
     */
    public static CreateKeyPairResponse createKeyPair(com.aliyun.ecs20140526.Client ecsClient) {
        try {
            // 建立一個建立金鑰組的請求對象,並設定地區ID、金鑰組名稱和資源群組ID
            CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setKeyPairName(Constants.KEY_PAIR_NAME);
            // 通過ECS用戶端發送建立金鑰組的請求,並返迴響應對象
            return ecsClient.createKeyPair(createKeyPairRequest);
        } catch (Exception e) {
            // 如果建立金鑰組失敗,則拋出運行時異常,包含錯誤資訊
            throw new RuntimeException("createKeyPair failed: " + e.getMessage());
        }
    }

    /**
     * 查詢VPC狀態
     *
     * @param vpcId     VPC的ID
     * @param vpcClient VPC用戶端
     * @return 返回VPC的狀態資訊
     */
    public static String describeVpc(String vpcId, com.aliyun.vpc20160428.Client vpcClient) {
        try {
            DescribeVpcsRequest request = new DescribeVpcsRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setVpcId(vpcId);
            return vpcClient.describeVpcs(request).body.vpcs.getVpc().get(0).status;
        } catch (Exception e) {
            // 如果發生異常,拋出自訂異常
            throw new RuntimeException("describeVpc failed: " + e.getMessage());
        }
    }

    /**
     * 根據執行個體ID列表查詢ECS執行個體資訊
     *
     * @param instanceIds 執行個體ID列表
     * @param ecsClient   ECS用戶端
     * @return 返回查詢到的執行個體狀態資訊響應對象
     */
    public static DescribeInstanceStatusResponse describeInstanceStatus(List<String> instanceIds, com.aliyun.ecs20140526.Client ecsClient) {
        try {
            DescribeInstanceStatusRequest request = new DescribeInstanceStatusRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setInstanceId(instanceIds);
            return ecsClient.describeInstanceStatus(request);
        } catch (Exception e) {
            throw new RuntimeException("describeInstanceStatus failed: " + e.getMessage());
        }
    }
}

免登入營運

您可以通過Elastic Compute Service提供的原生自動化營運工具雲助手,免密碼、免登入,且無需使用跳板機,即可批量執行命令(Shell、PowerShell、Bat等),從而實現自動化營運指令碼的執行、進程的輪詢、軟體的安裝與卸載、服務的啟動或停止,以及補丁或安全更新的安裝等任務。更多詳細資料,請參見雲助手概述

例如在ECS中安裝Java和Tomcat,您可以調用RunCommand介面執行命令:

API

參數

樣本取值

RunCommand

RegionId

地區:cn-hangzhou

Type

營運命令的語言類型:RunShellScript

CommandContent

命令內容:

#!/bin/bash
if cat /etc/issue|grep -i Ubuntu ; then
	sudo apt-get update
	sudo apt-get install -y default-jdk
	sudo apt-get install -y tomcat9
else
        yum install -y java
	yum install -y tomcat
fi

Timeout

可選,執行命令的逾時時間,單位:秒。 樣本:60

InstanceId

ECS執行個體ID集合:["i-bp17f3kzgtzzj91r****"]

完整的範例程式碼如下

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.RunCommandRequest;
import com.aliyun.ecs20140526.models.RunCommandResponse;
import com.aliyun.teaopenapi.models.Config;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class CloudAssistant {
    public static void main(String[] args) throws Exception {
        Client ecsClient = createEcsClient();
        List<String> instanceIds = new ArrayList<>();
        instanceIds.add("i-bp17f3kzgtzzj91r****");
        String commandContent = "#!/bin/bash\n" +
                "if cat /etc/issue|grep -i Ubuntu ; then\n" +
                "\tsudo apt-get update\n" +
                "\tsudo apt-get install -y default-jdk\n" +
                "\tsudo apt-get install -y tomcat9\n" +
                "else\n" +
                "  yum install -y java\n" +
                "\tyum install -y tomcat\n" +
                "fi";
        System.out.println("commandContent:" + commandContent);
        runCommand(commandContent, instanceIds, ecsClient);
    }

    public static class Constants {
        // 地區
        public static final String REGION_ID = "cn-hangzhou";

        // 服務存取點
        public static final class ENDPOINT {
            public static final String VPC = "vpc.cn-hangzhou.aliyuncs.com";
            public static final String ECS = "ecs.cn-hangzhou.aliyuncs.com";
        }

        // 命令類型
        public static final class COMMAND_TYPE {
            // 適用於Linux執行個體的Shell命令。
            public static final String RUN_SHELL_SCRIPT = "RunShellScript";
            // 適用於Windows執行個體的Bat命令。
            public static final String RUN_BAT_SCRIPT = "RunBatScript";
            // 適用於Windows執行個體的PowerShell命令。
            public static final String RUN_POWERSHELL_SCRIPT = "RunPowerShellScript";
        }
    }

    public static com.aliyun.ecs20140526.Client createEcsClient() throws Exception {
        Config config = new Config();
        config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = Constants.ENDPOINT.ECS;
        return new com.aliyun.ecs20140526.Client(config);
    }

    public static void runCommand(String commandContent, List<String> instanceIds, com.aliyun.ecs20140526.Client ecsClient) {
        try {
            RunCommandRequest request = new RunCommandRequest();
            request.setRegionId(Constants.REGION_ID);
            // RunShellScript適用於Linux執行個體的Shell命令。
            request.setType(Constants.COMMAND_TYPE.RUN_SHELL_SCRIPT);
            request.setCommandContent(commandContent);
            request.setInstanceId(instanceIds);
            request.setTimeout(60L);
            RunCommandResponse runCommandResponse = ecsClient.runCommand(request);
            System.out.println(new Gson().toJson(runCommandResponse));
        } catch (Exception e) {
            throw new RuntimeException("runCommand failed:" + e);
        }
    }
}

釋放資源

當您不再需要所建立的資源時,可以調用以下OpenAPI介面以釋放該資源。

說明

根據您的實際需求,選擇相應的OpenAPI釋放資源 。本樣本釋放上述步驟建立的所有資源。

  1. 釋放ECS執行個體

    API

    參數

    樣本取值

    DeleteInstances

    RegionId

    地區:cn-hangzhou

    InstanceId

    執行個體 ID:i-bp17f3kzgtzzj91r****

  2. 刪除SSH金鑰組

    API

    參數

    樣本取值

    DeleteKeyPairs

    RegionId

    地區:cn-hangzhou

    KeyPairNames

    SSH金鑰組名稱:["sdk-key-pair"]

  3. 刪除安全性群組

    API

    參數

    樣本取值

    DeleteSecurityGroup

    RegionId

    地區:cn-hangzhou

    SecurityGroupId

    安全性群組ID:sg-bp1esyhwfbqeyudt****

  4. 刪除交換器

    API

    參數

    樣本取值

    DeleteVSwitch

    RegionId

    地區:cn-hangzhou

    VSwitchId

    交換器ID:vsw-bp1nzprm8h7mmnl8t****

  5. 刪除VPC

    API

    參數

    樣本取值

    DeleteVpc

    RegionId

    地區:cn-hangzhou

    VpcId

    VPC ID:vpc-bp1aag0sb9s4i92i3****

範例程式碼如下:

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.vpc20160428.models.DeleteVSwitchRequest;
import com.aliyun.vpc20160428.models.DeleteVpcRequest;
import com.google.gson.Gson;

import java.util.Collections;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DeleteResources {
    public static void main(String[] args) {
        String vpcId = "vpc-bp1aag0sb9s4i92i3****";
        String vSwitchId = "vsw-bp1nzprm8h7mmnl8t****";
        String securityGroupId = "sg-bp1esyhwfbqeyudt****";
        String instanceId = "i-bp17f3kzgtzzj91r****";
        String keyPairName = "sdk-key-pair";
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        try {
            com.aliyun.ecs20140526.Client ecsClient = createEcsClient();
            com.aliyun.vpc20160428.Client vpcClient = createVpcClient();
            // 刪除ECS執行個體
            executorService.schedule(() -> deleteInstance(instanceId, ecsClient), 1, TimeUnit.SECONDS);
            // 刪除金鑰組
            executorService.schedule(() -> deleteKeyPairs(keyPairName, ecsClient), 1, TimeUnit.SECONDS);
            // 刪除安全性群組
            executorService.schedule(() -> deleteSecurityGroup(securityGroupId, ecsClient), 60, TimeUnit.SECONDS);
            // 刪除交換器
            executorService.schedule(() -> deleteVSwitch(vSwitchId, vpcClient), 60, TimeUnit.SECONDS);
            // 刪除VPC
            executorService.schedule(() -> deleteVpc(vpcId, vpcClient), 65, TimeUnit.SECONDS);
        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
            // 異常處理,因為釋放執行個體需要一定時間,可能會存在部分刪除成功,部分刪除失敗的情況,請增加合理的刪除失敗資料處理機制。
        } finally {
            executorService.shutdown();
        }
    }

    public static class Constants {
        // 服務存取點
        public static final class ENDPOINT {
            public static final String VPC = "vpc.cn-hangzhou.aliyuncs.com";
            public static final String ECS = "ecs.cn-hangzhou.aliyuncs.com";
        }

        // 地區
        public static final String REGION_ID = "cn-hangzhou";
    }

    public static com.aliyun.vpc20160428.Client createVpcClient() throws Exception {
        Config config = new Config();
        config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = Constants.ENDPOINT.VPC;
        return new com.aliyun.vpc20160428.Client(config);
    }

    public static com.aliyun.ecs20140526.Client createEcsClient() throws Exception {
        Config config = new Config();
        config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = Constants.ENDPOINT.ECS;
        return new com.aliyun.ecs20140526.Client(config);
    }

    /**
     * 刪除指定的VPC(虛擬私人雲端)資源
     *
     * @param vpcId     VPC的ID,標識了要刪除的VPC資源
     * @param vpcClient VPC用戶端
     */
    public static void deleteVpc(String vpcId, com.aliyun.vpc20160428.Client vpcClient) {
        try {
            System.out.println("VPC is deleting, please wait...");
            DeleteVpcRequest deleteVpcRequest = new DeleteVpcRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setVpcId(vpcId);
            vpcClient.deleteVpc(deleteVpcRequest);
        } catch (Exception e) {
            throw new RuntimeException("DeleteVpc failed: " + e.getMessage());
        }
    }

    /**
     * 刪除指定的虛擬交換器(VSwitch)
     *
     * @param vSwitchId 虛擬交換器的ID
     * @param vpcClient VPC用戶端
     */
    public static void deleteVSwitch(String vSwitchId, com.aliyun.vpc20160428.Client vpcClient) {
        System.out.println("VSwitch is deleting, please wait...");
        try {
            DeleteVSwitchRequest deleteVSwitchRequest = new DeleteVSwitchRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setVSwitchId(vSwitchId);
            vpcClient.deleteVSwitch(deleteVSwitchRequest);
        } catch (Exception e) {
            throw new RuntimeException("DeleteVSwitch failed: " + e.getMessage());
        }
    }

    /**
     * 刪除指定的安全性群組
     *
     * @param securityGroupId 安全性群組的ID,標識要刪除的安全性群組
     * @param ecsClient       ECS用戶端
     */
    public static void deleteSecurityGroup(String securityGroupId, Client ecsClient) {
        System.out.println("SecurityGroup is deleting, please wait...");
        try {
            DeleteSecurityGroupRequest deleteSecurityGroupRequest = new DeleteSecurityGroupRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setSecurityGroupId(securityGroupId);
            ecsClient.deleteSecurityGroup(deleteSecurityGroupRequest);
        } catch (Exception e) {
            throw new RuntimeException("DeleteSecurityGroup failed: " + e.getMessage());
        }
    }

    /**
     * 刪除雲端服務器執行個體.
     *
     * @param instanceId 執行個體ID,標識了要刪除的雲端服務器執行個體
     * @param ecsClient  ECS用戶端
     */
    public static void deleteInstance(String instanceId, Client ecsClient) {
        System.out.println("ECS instance is deleting, please wait...");
        try {
            DeleteInstanceRequest request = new DeleteInstanceRequest()
                    .setForce(true)
                    .setInstanceId(instanceId);
            ecsClient.deleteInstance(request);
        } catch (Exception e) {
            throw new RuntimeException("DeleteInstance failed: " + e.getMessage());
        }
    }

    /**
     * 使用指定的ECS用戶端刪除金鑰組
     *
     * @param keyPairName 金鑰組名稱
     * @param ecsClient   ECS用戶端
     */
    public static void deleteKeyPairs(String keyPairName, Client ecsClient) {
        System.out.println("KeyPair is deleting, please wait...");
        try {
            // 建立刪除金鑰組請求,並設定地區ID和金鑰組名稱
            DeleteKeyPairsRequest deleteKeyPairsRequest = new DeleteKeyPairsRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setKeyPairNames(new Gson().toJson(Collections.singletonList(keyPairName)));
            ecsClient.deleteKeyPairs(deleteKeyPairsRequest);
        } catch (Exception e) {
            // 如果刪除金鑰組失敗,拋出運行時異常,包含錯誤資訊
            throw new RuntimeException("DeleteKeyPairs failed: " + e.getMessage());
        }
    }
}