All Products
Search
Document Center

Elastic Compute Service:Create and use an ECS instance by using Alibaba Cloud CLI

Last Updated:Nov 07, 2024

Alibaba Cloud CLI is a command-line tool that allows you to call Alibaba Cloud API operations in a terminal or a command-line interface to create, configure, and manage Alibaba Cloud resources. This topic describes how to call Elastic Compute Service (ECS) API operations by using Alibaba Cloud CLI to create and manage ECS instances and provides examples.

Note

For more information about Alibaba Cloud CLI, see What is Alibaba Cloud CLI?

Preparations

  1. Create an AccessKey pair for a Resource Access Management (RAM) user. An Alibaba Cloud account has all permissions on resources. If the AccessKey pair of your Alibaba Cloud account is leaked, your resources are exposed to great risks. We recommend that you use the AccessKey pair of a RAM user. For information about how to create an AccessKey pair, see Create an AccessKey pair.

  2. Grant the required permissions on ECS and Virtual Private Cloud (VPC) resources to the RAM user that you want to use. The sample code provided in this topic creates resources, such as an ECS instance, a VPC, and a vSwitch. To grant the permissions required to run the sample code, we recommend that you attach the policies described in the following table to the RAM user.

    Cloud service

    Policy

    VPC

    AliyunVPCFullAccess

    ECS

    AliyunECSFullAccess

  3. Install and configure Alibaba Cloud CLI. You must install Alibaba Cloud CLI before you can use Alibaba Cloud CLI. You can install Alibaba Cloud CLI on Windows, Linux, and macOS. Download an installation package that is suitable for the operating system that runs on your computer.

    1. Install Alibaba Cloud CLI. For information about how to install Alibaba Cloud CLI in different operating systems, see the following topics:

    2. Configure Alibaba Cloud CLI.

      Configure parameters, such as credentials and regions, that are required to use Alibaba Cloud resources. For information about how to configure credentials, go to the AK tab of the Credential types section of the "Configure profiles" topic.

    If you only need to perform temporary debugging operations, you do not need to install Alibaba Cloud CLI. You can use Cloud Shell provided by Alibaba Cloud to perform the debugging operations. For more information, see What is Cloud Shell? image

Create an ECS instance

Multiple parameters, such as vSwitch ID, security group ID, and image ID, are required to create an ECS instance. You can pass in the IDs of existing resources or call API operations to create new resources.

  1. Create a VPC.

    A VPC is a dedicated private network in the cloud. You can configure and manage VPCs as logically isolated networks in the public cloud.

    API operation

    Parameter

    Description and example

    CreateVpc

    RegionId

    The ID of the region in which to create the VPC. Example: ap-northeast-1.

    CidrBlock

    The CIDR block of the VPC. Example: 192.168.0.0/16.

  2. Create a vSwitch.

    A vSwitch is a network switching device in a VPC, which supports the functionality of a physical switch. It serves to enable communication between virtual machines (VMs) and between VMs and physical networks.

    API operation

    Parameter

    Description and example

    RegionId

    The ID of the region in which to create the vSwitch. Example: ap-northeast-1.

    CreateVSwitch

    ZoneId

    The ID of the zone in which to create the vSwitch. Example: ap-northeast-1a.

    VpcId

    The ID of the VPC in which to create the vSwitch. Example: vpc-bp1aag0sb9s4i92i3****.

    CidrBlock

    The CIDR block of the vSwitch. Example: 192.168.0.0/24.

  3. Create a security group.

    A security group acts as a virtual firewall that controls inbound and outbound traffic for ECS instances.

    API operation

    Parameter

    Description and example

    CreateSecurityGroup

    RegionId

    The ID of the region in which to create the security group. Example: ap-northeast-1.

    VpcId

    The ID of the VPC in which to create the security group. Example: vpc-bp1aag0sb9s4i92i3****.

  4. Create an inbound rule in the security group.

    API operation

    Parameter

    Description and example

    AuthorizeSecurityGroup

    RegionId

    The region ID of the security group. Example: ap-northeast-1.

    SecurityGroupId

    The ID of the security group. Example: sg-bp1esyhwfbqeyudt****.

    IpProtocol

    The protocol. Example: tcp.

    SourceCidrIp

    The source CIDR block. Example: 0.0.0.0/0.

    PortRange

    The port range. Examples:

    • Linux instances: 22/22.

    • Windows instances: 3389/3389.

  5. Create an ECS instance.

    ECS provides high-performance, secure, and low-cost compute capacity and is suitable for various scenarios such as website hosting, application development, and data processing. With ECS, you can quickly deploy and run applications and flexibly adjust resources in response to business changes.

    API operation

    Parameter

    Description and example

    RunInstances

    RegionId

    The ID of the region in which to create the ECS instance. Example: ap-northeast-1.

    ImageId

    The ID of the image from which to create the ECS instance. We recommend that you select the Alibaba Cloud Linux image whose ID is aliyun_3_x64_20G_alibase_20240819.vhd.

    InstanceType

    The instance type of the ECS instance. Example: ecs.e-c1m1.large.

    SecurityGroupId

    The ID of the security group in which to create the ECS instance. Example: sg-bp1esyhwfbqeyudt****.

    VSwitchId

    The ID of the vSwitch to which to connect the ECS instance. Example: vsw-bp1nzprm8h7mmnl8t****.

    InstanceName

    The name of the ECS instance. Example: ecs_cli_demo.

    InstanceChargeType

    The billing method of the ECS instance. To create a pay-as-you-go instance, set this parameter to PostPaid.

    Note

    Make sure that your account balance is sufficient.

    PASSWORD

    The logon password. Example: ******.

    InternetMaxBandwidthOut

    The maximum outbound public bandwidth. If the value of this parameter is greater than 0, a public IP address is automatically assigned to the instance.

    SystemDisk.Category

    The disk category of the system disk. Example: cloud_essd.

    SystemDisk.Size

    The size of the system disk. Example: 40 GiB.

The following sample code provides a complete example on how to create an ECS instance.

Important

Use Alibaba Cloud CLI to run the sample code. If you repeatedly run the code, resources such as VPCs, vSwitches, and security groups are repeatedly created. This may cause resource wastes. Make sure that you carefully review the code and optimize the code based on your business logic.

#!/bin/bash

# Configure the AccessKey ID and AccessKey secret used by Alibaba Cloud CLI.
# Note: Make sure that the AccessKey ID and AccessKey secret are securely configured by configuring environment variables or by using a configuration file.

# 1. Configure variables.
INSTANCE_NAME="ecs_cli_demo"

#2. Install the jq tool.
echo "Installing the jq dependency tool..."
yum install jq
sleep 3

#3. Create a VPC, a vSwitch, and a security group.
echo "Creating a VPC..."
VpcId=$(aliyun vpc CreateVpc --RegionId ap-northeast-1 --CidrBlock 192.168.0.0/16 | jq -r .VpcId)
aliyun vpc DescribeVpcAttribute --RegionId ap-northeast-1 --VpcId ${VpcId} --waiter expr='Status' to=Available > /dev/null 2>&1

echo "Creating a vSwitch..."
VSwitchId=$(aliyun vpc CreateVSwitch --CidrBlock 192.168.0.0/24 --VpcId ${VpcId} --ZoneId=ap-northeast-1a | jq -r .VSwitchId)

echo "Creating a security group..."
SecurityGroupId=$(aliyun ecs CreateSecurityGroup --RegionId ap-northeast-1 --VpcId ${VpcId} | jq -r .SecurityGroupId)
aliyun ecs AuthorizeSecurityGroup --RegionId ap-northeast-1 --SecurityGroupId ${SecurityGroupId} --IpProtocol tcp --SourceCidrIp 0.0.0.0/0 --PortRange 22/22 > /dev/null 2>&1

read -s -P "Input Your Password:" PASSWORD
echo
echo "PASSWORD OK."

# 4. Run the command used to create an ECS instance.
echo "Creating an ECS instance..."
INSTANCE_ID_RAW=$(aliyun ecs RunInstances \
--RegionId ap-northeast-1 \
--ImageId aliyun_3_x64_20G_alibase_20240819.vhd \
--InstanceType ecs.e-c1m1.large \
--SecurityGroupId ${SecurityGroupId} \
--VSwitchId ${VSwitchId} \
--InstanceName $INSTANCE_NAME \
--InstanceChargeType PostPaid \
--InternetMaxBandwidthOut 1 \
--Password $PASSWORD  \
--SystemDisk.Category cloud_essd \
--SystemDisk.Size 40)

# 5. Obtain the InstanceId parameter for subsequently returned information.
INSTANCE_ID=$(echo "$INSTANCE_ID_RAW" | jq -r '.InstanceIdSets.InstanceIdSet[]')

# 6. Wait for 20 seconds for the ECS instance to be created.
echo "Waiting for the ECS instance to be created..."
sleep 20

# 7. Query the status of the ECS instance.
echo "Querying the status of the ECS instance..."
INSTANCE_ID_QUOTED=$(printf '"%s"' "$INSTANCE_ID")
aliyun ecs DescribeInstances \
--RegionId ap-northeast-1 \
--InstanceIds "[${INSTANCE_ID_QUOTED}]" \
--output cols=InstanceId,InstanceName,InstanceType,ImageId,Status rows=Instances.Instance[]

Create and run a Shell script. The following figure shows the command output.

image

Connect to the ECS instance

You can use SSH to log on to the ECS instance and then deploy services and build applications on the ECS instance.

  1. Obtain the public IP address of the ECS instance.

    Call the DescribeInstances operation and specify <Instance ID> to query the public IP address of the instance.

    • Sample request

      aliyun ecs DescribeInstances \
      --RegionId ap-northeast-1 \
      -- InstanceIds '["<Instance ID>"]' 
    • Sample response

      The PublicIpAddresses parameter indicates the public IP address of the ECS instance.

      公网IP

  2. Connect to the ECS instance.

    ssh <Username>@<Public IP address>

    image

Release resources

If you no longer require the resources that you created, you can call the following API operations to release the resources.

Note

Select an API operation to release resources based on your business requirements. In the following examples, all resources that are created in the preceding section are released.

  1. Release an ECS instance.

    API operation

    Parameter

    Description and example

    DeleteInstances

    RegionId

    The region ID. Example: ap-northeast-1.

    InstanceId

    The instance ID. Example: i-bp17f3kzgtzzj91r****.

  2. Delete a security group.

    API operation

    Parameter

    Description and example

    DeleteSecurityGroup

    RegionId

    The region ID of the security group. Example: ap-northeast-1.

    SecurityGroupId

    The security group ID. Example: sg-bp1esyhwfbqeyudt****.

  3. Delete a vSwitch.

    API operation

    Parameter

    Description and example

    DeleteVSwitch

    RegionId

    The region ID. Example: ap-northeast-1.

    VSwitchId

    The vSwitch ID. Example: vsw-bp1nzprm8h7mmnl8t****.

  4. Delete a VPC.

    API operation

    Parameter

    Description and example

    DeleteVpc

    RegionId

    The region ID. Example: ap-northeast-1.

    VpcId

    The VPC ID. Example: vpc-bp1aag0sb9s4i92i3****.

Sample code:

#!/bin/bash

# Configure the parameters of the resources that you want to release or delete.
INSTANCE_ID='ecs_cli_demo'  # Specify the ID of the ECS instance that you want to release.
SECURITY_GROUP_ID='sg-bp1esyhwfbqeyudt****' # Specify the ID of the security group that you want to delete.
VSWITCH_ID='vsw-bp1nzprm8h7mmnl8t****'  # Specify the ID of the vSwitch that you want to delete.
VPC_ID='vpc-bp1aag0sb9s4i92i3****'      # Specify the ID of the VPC that you want to delete.
REGION='ap-northeast-1'                    # Specify the region ID.

echo "Releasing or deleting resources..."

# Release the ECS instance.
aliyun ecs DeleteInstance \
  --region ${REGION} \
  --InstanceId ${INSTANCE_ID}

# Delete the security group.
aliyun ecs DeleteSecurityGroup \
  --region ${REGION} \
  --RegionId ${REGION} \
  --SecurityGroupId ${SECURITY_GROUP_ID}

# Delete the vSwitch.
aliyun vpc DeleteVSwitch \
  --region ${REGION} \
  --RegionId ${REGION} \
  --VSwitchId ${VSWITCH_ID}

# Delete the VPC.
aliyun vpc DeleteVpc \
  --region ${REGION} \
  --RegionId ${REGION} \
  --VpcId ${VPC_ID}

echo "Release completed"

References

You can run the following command to query supported commands:

aliyun ecs --help

You can run commands by using the following syntax to call ECS API operations. For information about the request parameters, see the documentation of each API operation.

aliyun ecs <API operation name> --<Parameter 1 Value 1> --<Parameter 2 Value 2> ...

Generate a CLI command

Alibaba Cloud provides OpenAPI Explorer for developers to understand and use the API operations of various Alibaba Cloud services in a quick and efficient manner. OpenAPI Explorer integrates multiple features related to API operations, including intelligent search, documentation, online debugging, SDK download, sample code, error diagnosis, and call statistics. You can use OpenAPI Explorer to generate a CLI command for an API operation. For more information, see What is an API?

  1. Log on to the OpenAPI Portal.

  2. Select the API operation for which you want to generate a CLI command and specify parameters.

  3. Click the CLI Example tab in the right-side pane to view the CLI command that is generated with the specified parameters.

    2024-08-12_10-30-57.png