Tüm Ürünler
Search
Belge Merkezi

Elastic Compute Service:Create and use an ECS instance by using an SDK

Son Güncelleme:Sep 30, 2026

Alibaba Cloud Elastic Compute Service (ECS), ECS örneklerini programlı olarak oluşturmanıza ve yönetmenize olanak tanıyan çeşitli API'ler ve yazılım geliştirme kitleri (SDK) sunar. Bu yaklaşım iş verimliliğini artırır ve sistem otomasyonunu mümkün kılar. Bu konuda, V2.0 Java SDK'yı kullanarak bir ECS örneğinin nasıl oluşturulacağı, Cloud Assistant ile bir betiğin nasıl çalıştırılacağı ve kaynakların nasıl serbest bırakılacağı açıklanmaktadır.

Hazırlıklar

  1. Bir Alibaba Cloud hesabının AccessKey'i tüm kaynaklar için tam yetki sağlar. Sızdırılan bir AccessKey yüksek güvenlik riski oluşturur. Minimum gerekli izinlere sahip bir Resource Access Management (RAM) kullanıcısının AccessKey'ini kullanmanızı öneririz. Daha fazla bilgi için bkz. AccessKey oluşturma.

  2. RAM kullanıcısına Elastic Compute Service (ECS) ve sanal özel cloud (VPC) kaynaklarını yönetme izni verin. Bu konudaki örnek kod; örnekler, VPC'ler ve vSwitch'ler gibi kaynaklar oluşturur. Aşağıdaki izinleri verin:


    Cloud Ürünleri


    İzinleri verin


    Virtual Private Cloud (VPC)


    Bu örnekte sistem ilkesi AliyunVPCFullAccess kullanılır


    Elastic Compute Service (ECS)


    Bu örnekte sistem ilkesi AliyunECSFullAccess kullanılır

  3. Bu konudaki örnek kod, Alibaba Cloud hizmetlerine erişmek için kimlik bilgisi olarak kullanılmak üzere AccessKey'i sistem ortam değişkenlerinden okur. Daha fazla bilgi için bkz. Linux, macOS ve Windows'ta ortam değişkenlerini yapılandırma.

  4. ECS SDK ve VPC SDK'yı edinin. Bu konuda, Maven bağımlılıkları eklenerek SDK'ların nasıl yükleneceği açıklanmaktadır. Diğer yükleme yöntemleri hakkında daha fazla bilgi için bkz. ECS Java SDK'yı yükleme ve VPC Java SDK'yı yükleme.

    Aşağıdaki kod, Maven bağımlılıklarının nasıl ekleneceğine ilişkin bir örnek sunar:

    <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>

Bir ECS örneği oluşturma

Bir ECS örneği oluştururken vSwitch ID'si, güvenlik grubu ve görüntü gibi birçok zorunlu parametre belirtmeniz gerekir. Mevcut kaynakların ID'lerini kullanabilir veya aşağıdaki OpenAPI işlemlerini çağırarak kaynakları oluşturabilirsiniz.

  1. Bir VPC oluşturun

    Sanal özel cloud (VPC), mantıksal olarak izole edilmiş bir ağ alanını yapılandırmanıza ve yönetmenize olanak tanıyan cloud üzerinde bir özel ağdır.

    API

    Parametre

    Örnek değer

    CreateVpc

    RegionId

    Bölge: cn-hangzhou

    CidrBlock

    VPC CIDR bloğu: 192.168.0.0/16

  2. VPC bilgilerini sorgulayın

    CreateVpc işlemini çağırdıktan sonra VPC'nin yapılandırılması zaman alır. VPC durumunu sorgulamak için bu OpenAPI işlemini çağırın. VPC durumu Available olarak değişene kadar sonraki OpenAPI işlemlerini çağırmayın.

    API

    Parametre

    Örnek değer

    DescribeVpcs

    RegionId

    Bölge: cn-hangzhou

    VpcId

    VPC ID'si: vpc-bp1aag0sb9s4i92i3****

  3. Bir vSwitch oluşturun

    vSwitch, sanallaştırma ortamında kullanılan bir ağ anahtarı aygıtıdır. Sanal makineler (VM'ler) arasında ve VM'ler ile fiziksel ağ arasında iletişim sağlamak için fiziksel bir anahtarın işlevlerini simüle eder.

    API

    Parametre

    Örnek değer

    RegionId

    Bölge: cn-hangzhou

    CreateVSwitch

    ZoneId

    Alan: cn-hangzhou-i

    VpcId

    VPC ID'si: vpc-bp1aag0sb9s4i92i3****

    CidrBlock

    vSwitch CIDR bloğu: 192.168.0.0/24

  4. Bir güvenlik grubu oluşturun

    Güvenlik grubu, ECS örnekleri için gelen ve giden trafiği kontrol eden sanal bir güvenlik duvarıdır.

    API

    Parametre

    Örnek değer

    CreateSecurityGroup

    RegionId

    Bölge: cn-hangzhou

    VpcId

    VPC ID'si: vpc-bp1aag0sb9s4i92i3****

  5. Güvenlik grubuna bir kural ekleyin

    API

    Parametre

    Örnek değer

    AuthorizeSecurityGroup

    RegionId

    Bölge: cn-hangzhou

    SecurityGroupId

    Güvenlik grubu ID'si: sg-bp1esyhwfbqeyudt****

    IpProtocol

    Protokol: tcp

    SourceCidrIp

    Kaynak CIDR bloğu: 0.0.0.0/0

    PortRange

    Bağlantı noktası aralığı:

    • Linux örneği için: 22/22

    • Windows örneği için: 3389/3389

  6. Bir SSH anahtar çifti oluşturun

    Alibaba Cloud SSH anahtar çifti, Secure Shell Protocol (SSH) içinde kimlik doğrulama ve şifreli iletişim için kullanılan güvenli ve kullanışlı bir oturum açma kimlik doğrulama yöntemidir. Parolasız uzaktan oturum açmak için SSH anahtar çiftini kullanabilirsiniz.

    API

    Parametre

    Örnek değer

    CreateKeyPair

    RegionId

    Bölge: cn-hangzhou

    KeyPairName

    Anahtar çifti adı: sdk-key-pair

  7. Bir ECS örneği oluşturun

    ECS, uygulamaları hızlı bir şekilde dağıtmanıza ve çalıştırmanıza, iş değişikliklerini karşılamak için kaynakları esnek bir şekilde ölçeklendirmenize ve yüksek performanslı, güvenli ve maliyet etkin bilişimden yararlanmanıza olanak tanır. ECS; web sitesi barındırma, uygulama geliştirme ve veri işleme gibi çeşitli senaryolar için uygundur.

    API

    Parametre

    Örnek değer

    RunInstances

    RegionId

    Bölge: cn-hangzhou

    ImageId

    Görüntü: Alibaba Cloud Linux görüntüsü aliyun_3_x64_20G_scc_alibase_20220225.vhd kullanın.

    InstanceType

    Örnek türü: ecs.e-c1m2.xlarge.

    SecurityGroupId

    Güvenlik grubu ID'si: sg-bp1esyhwfbqeyudt****

    VSwitchId

    vSwitch ID'si: vsw-bp1nzprm8h7mmnl8t****

    InstanceName

    Örnek adı: sdk-test

    InstanceChargeType

    Faturalandırma yöntemi: Örnek kullandıkça öde (PostPaid) olarak faturalandırılır.

    Not

    Hesap bakiyenizin ödeme için yeterli olduğundan emin olun.

    KeyPairName

    Anahtar çifti adı: sdk-key-pair

    SystemDisk.Category

    Sistem diski türü: cloud_essd

  8. ECS örneği durumunu sorgulayın

    RunInstances işlemini çağırdıktan sonra ECS örneğinin başlaması zaman alır. Uzaktan bağlantılar ve uygulama dağıtımları gibi işlemleri yalnızca örnek Running durumuna geçtiğinde gerçekleştirebilirsiniz. ECS örneğinin durumunu sorgulamak için bu OpenAPI işlemini çağırabilirsiniz.

    API

    Parametre

    Örnek değer

    DescribeInstanceStatus

    RegionId

    Bölge: cn-hangzhou

    InstanceId

    Örnek ID'leri: ["i-bp17f3kzgtzzj91r****"]

Aşağıdaki kod eksiksiz bir örnek sunar:

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();
            // Create a VPC.
            vpcId = createVpc(vpcClient);
            System.out.println("VPC create success, vpcId :" + vpcId);
            // Proceed to the next step only after the VPC is in the Available state.
            while (true) {
                String status = describeVpc(vpcId, vpcClient);
                if ("Available".equals(status)) {
                    break;
                }
            }
            // Create a vSwitch.
            vSwitchId = CreateVSwitch(vpcId, vpcClient);
            System.out.println("VSwitch create success, vSwitchId :" + vSwitchId);
            // Create a security group.
            securityGroupId = createSecurityGroup(vpcId, ecsClient);
            System.out.println("SecurityGroup create success, securityGroupId :" + securityGroupId);
            // Add an inbound rule to the security group.
            authorizeSecurityGroup(securityGroupId, ecsClient);
            // Create a key pair. Note: Save the key pair information to log on to the ECS instance.
            CreateKeyPairResponse keyPair = createKeyPair(ecsClient);
            System.out.println("KeyPair create success, keyPairName :" + keyPair.body.keyPairName);
            // Create an instance. The instance is running when its status is Running.
            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) {
            // If some resources are created but others fail, add a proper handling mechanism, such as logging, rollback, or compensation.
            System.out.println(e.getMessage());
        }
    }

    public static class Constants {
        // Name
        public static final String NAME = "sdk-test";
        // Region
        public static final String REGION_ID = "cn-hangzhou";
        // Zone
        public static final String ZONE_ID = "cn-hangzhou-i";
        // The CIDR blocks of the VPC and vSwitch to be created
        public static final String CIDR_BLOCK_VPC = "192.168.0.0/16";
        public static final String CIDR_BLOCK_VSWITCH = "192.168.0.0/24";
        // Image
        public static final String IMAGE_ID = "aliyun_3_x64_20G_scc_alibase_20220225.vhd";
        // Instance type
        public static final String INSTANCE_TYPE = "ecs.e-c1m2.xlarge";
        // Disk type
        public static final String SYSTEM_DISK_CATEGORY = "cloud_essd";

        // Key pair name
        public static final String KEY_PAIR_NAME = "sdk-key-pair";

        // Endpoint
        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";
        }

        // Billing method
        public static final class INSTANCE_CHARGE_TYPE {
            // Subscription
            public static final String PRE_PAID = "PrePaid";
            // Pay-as-you-go
            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);
    }

    /**
     * Creates a virtual private cloud (VPC) network.
     * This method calls the API of the VPC service to create a VPC network and returns the ID of the new VPC.
     *
     * @param vpcClient The VPC client.
     * @return Returns the ID of the new VPC.
     */
    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());
        }
    }

    /**
     * Creates a vSwitch.
     * This method creates a new vSwitch using the Alibaba Cloud VPC client. It configures the required request parameters, such as the region ID, zone ID,
     * CIDR block, VPC ID, and vSwitch name, then sends the request and returns the ID of the new vSwitch.
     *
     * @param vpcId     The ID of the VPC in which to create the vSwitch.
     * @param vpcClient The VPC client.
     * @return Returns the ID of the new vSwitch.
     */
    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());
        }
    }

    /**
     * Creates a security group.
     *
     * @param vpcId     The ID of the VPC.
     * @param ecsClient The ECS client.
     * @return The ID of the created security group.
     */
    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());
        }
    }

    /**
     * Authorizes a security group rule to allow specific inbound traffic.
     * For example, allow access from any IP address (0.0.0.0/0) over TCP on port 22 (SSH).
     *
     * @param securityGroupId The ID of the security group for which to authorize the rule.
     * @param ecsClient       The ECS client.
     */
    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());
        }
    }

    /**
     * Creates an ECS instance.
     *
     * @param ecsClient       The ECS client.
     * @param vSwitchId       The vSwitch ID.
     * @param securityGroupId The security group ID.
     * @return The ID of the new ECS instance.
     */
    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());
        }
    }

    /**
     * Creates a key pair using the specified security group ID.
     *
     * @param ecsClient The ECS client.
     * @return Returns the response object for creating the key pair.
     */
    public static CreateKeyPairResponse createKeyPair(com.aliyun.ecs20140526.Client ecsClient) {
        try {
            // Create a request object to create a key pair, and set the region ID and key pair name.
            CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setKeyPairName(Constants.KEY_PAIR_NAME);
            // Send the request to create the key pair using the ECS client and return the response object.
            return ecsClient.createKeyPair(createKeyPairRequest);
        } catch (Exception e) {
            // If the key pair fails to be created, throw a runtime exception that contains the error message.
            throw new RuntimeException("createKeyPair failed: " + e.getMessage());
        }
    }

    /**
     * Queries the VPC status.
     *
     * @param vpcId     The ID of the VPC.
     * @param vpcClient The VPC client.
     * @return Returns the status of the 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) {
            // If an exception occurs, throw a custom exception.
            throw new RuntimeException("describeVpc failed: " + e.getMessage());
        }
    }

    /**
     * Queries ECS instance information based on a list of instance IDs.
     *
     * @param instanceIds A list of instance IDs.
     * @param ecsClient   The ECS client.
     * @return Returns the response object that contains the instance status information.
     */
    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());
        }
    }
}

Parolasız İşletme ve Bakım

Elastic Compute Service (ECS) tarafından sunulan yerel otomatik işletme ve bakım aracı Cloud Assistant'ı kullanarak parolalara, oturum açmalara veya atlama sunucularına gerek kalmadan toplu iş komutları (Shell, PowerShell ve Batch gibi) çalıştırabilirsiniz. Bu sayede otomatik işletme ve bakım betikleri çalıştırma, süreçleri yoklama, yazılım yükleme veya kaldırma, hizmetleri başlatma veya durdurma ve yamalar ya da güvenlik güncellemeleri yükleme gibi görevleri gerçekleştirebilirsiniz. Daha fazla bilgi için bkz. Cloud Assistant'a genel bakış.

Örneğin, bir ECS örneğine Java ve Tomcat yüklemek için RunCommand işlemini çağırabilirsiniz:

API

Parametre

Örnek değer

RunCommand

RegionId

Bölge: cn-hangzhou

Type

İşletme ve bakım komutunun dil türü: RunShellScript

CommandContent

Komut içeriği:

#!/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

İsteğe bağlı. Komutu çalıştırmak için zaman aşımı süresi. Birim: saniye. Örnek: 60

InstanceId

ECS örnek ID'leri: ["i-bp17f3kzgtzzj91r****"]

Aşağıdaki kod eksiksiz bir örnek sunar:

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 {
        // Region
        public static final String REGION_ID = "cn-hangzhou";

        // Endpoint
        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";
        }

        // Command type
        public static final class COMMAND_TYPE {
            // A shell command for a Linux instance.
            public static final String RUN_SHELL_SCRIPT = "RunShellScript";
            // A batch command for a Windows instance.
            public static final String RUN_BAT_SCRIPT = "RunBatScript";
            // A PowerShell command for a Windows instance.
            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 specifies a shell command for a Linux instance.
            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);
        }
    }
}

Kaynakları serbest bırakma

Artık kaynaklara ihtiyacınız olmadığında bunları serbest bırakmak için aşağıdaki OpenAPI işlemlerini çağırabilirsiniz.

Not

Gerektiğinde uygun OpenAPI işlemlerini çağırarak kaynakları serbest bırakın. Bu örnek, önceki adımlarda oluşturulan tüm kaynakları serbest bırakır.

  1. ECS örneğini serbest bırakın

    API

    Parametre

    Örnek değer

    DeleteInstances

    RegionId

    Bölge: cn-hangzhou

    InstanceId

    Örnek ID'si: i-bp17f3kzgtzzj91r****

  2. SSH anahtar çiftini silin

    API

    Parametre

    Örnek değer

    DeleteKeyPairs

    RegionId

    Bölge: cn-hangzhou

    KeyPairNames

    SSH anahtar çifti adı: ["sdk-key-pair"]

  3. Güvenlik grubunu silin

    API

    Parametre

    Örnek değer

    DeleteSecurityGroup

    RegionId

    Bölge: cn-hangzhou

    SecurityGroupId

    Güvenlik grubu ID'si: sg-bp1esyhwfbqeyudt****

  4. vSwitch'i silin

    API

    Parametre

    Örnek değer

    DeleteVSwitch

    RegionId

    Bölge: cn-hangzhou

    VSwitchId

    vSwitch ID'si: vsw-bp1nzprm8h7mmnl8t****

  5. VPC'yi silin

    API

    Parametre

    Örnek değer

    DeleteVpc

    RegionId

    Bölge: cn-hangzhou

    VpcId

    VPC ID'si: vpc-bp1aag0sb9s4i92i3****

Aşağıdaki kod bir örnek sunar:

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();
            // Delete the ECS instance.
            executorService.schedule(() -> deleteInstance(instanceId, ecsClient), 1, TimeUnit.SECONDS);
            // Delete the key pair.
            executorService.schedule(() -> deleteKeyPairs(keyPairName, ecsClient), 1, TimeUnit.SECONDS);
            // Delete the security group.
            executorService.schedule(() -> deleteSecurityGroup(securityGroupId, ecsClient), 60, TimeUnit.SECONDS);
            // Delete the vSwitch.
            executorService.schedule(() -> deleteVSwitch(vSwitchId, vpcClient), 60, TimeUnit.SECONDS);
            // Delete the VPC.
            executorService.schedule(() -> deleteVpc(vpcId, vpcClient), 65, TimeUnit.SECONDS);
        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
            // Handle exceptions. Releasing an instance takes time. Some resources may be deleted while others are not. Add a proper mechanism to handle data for failed deletions.
        } finally {
            executorService.shutdown();
        }
    }

    public static class Constants {
        // Endpoint
        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";
        }

        // Region
        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);
    }

    /**
     * Deletes the specified virtual private cloud (VPC) resource.
     *
     * @param vpcId     The ID of the VPC to delete.
     * @param vpcClient The VPC client.
     */
    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());
        }
    }

    /**
     * Deletes the specified vSwitch.
     *
     * @param vSwitchId The ID of the vSwitch.
     * @param vpcClient The VPC client.
     */
    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());
        }
    }

    /**
     * Deletes the specified security group.
     *
     * @param securityGroupId The ID of the security group to delete.
     * @param ecsClient       The ECS client.
     */
    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());
        }
    }

    /**
     * Deletes the ECS instance.
     *
     * @param instanceId The ID of the ECS instance to delete.
     * @param ecsClient  The ECS client.
     */
    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());
        }
    }

    /**
     * Deletes the key pair using the specified ECS client.
     *
     * @param keyPairName The key pair name.
     * @param ecsClient   The ECS client.
     */
    public static void deleteKeyPairs(String keyPairName, Client ecsClient) {
        System.out.println("KeyPair is deleting, please wait...");
        try {
            // Create a request to delete the key pair, and set the region ID and key pair name.
            DeleteKeyPairsRequest deleteKeyPairsRequest = new DeleteKeyPairsRequest()
                    .setRegionId(Constants.REGION_ID)
                    .setKeyPairNames(new Gson().toJson(Collections.singletonList(keyPairName)));
            ecsClient.deleteKeyPairs(deleteKeyPairsRequest);
        } catch (Exception e) {
            // If the key pair fails to be deleted, throw a runtime exception that contains the error message.
            throw new RuntimeException("DeleteKeyPairs failed: " + e.getMessage());
        }
    }
}