Create and use an ECS instance with the CLI

Updated at:

The Alibaba Cloud Command Line Interface (CLI) is a tool for managing Alibaba Cloud resources from your terminal by calling OpenAPI operations. This topic provides examples of using the Alibaba Cloud CLI to create and manage an ECS instance.

Note

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

Before you begin

  1. Because an Alibaba Cloud account has full permissions over all resources, a leaked AccessKey for the account poses a high security risk. We recommend that you use the AccessKey of a RAM user that is granted only the minimum required permissions. For more information, see Create an AccessKey.

  2. Grant the RAM user the permissions required to manage ECS and VPC resources. The sample code in this topic creates resources such as instances, VPCs, and vSwitches. We recommend that you grant the following permissions:

    Cloud service

    Permission

    VPC

    Attach the system policy: AliyunVPCFullAccess

    ECS

    Attach the system policy: AliyunECSFullAccess

  3. Install and configure the CLI. The Alibaba Cloud CLI is available for Windows, Linux, and macOS. Select the appropriate installation method for your operating system:

    1. Install the CLI.

    2. Configure the CLI.

      Configure the credentials and service request region required to call Alibaba Cloud resources. For more information, see Configure credentials.

    If you only need to debug something temporarily and do not want to install the Alibaba Cloud CLI, you can use Cloud Shell. For more information, see What is Cloud Shell? To start Cloud Shell, log on to the Alibaba Cloud console and click the Cloud Shell icon (a terminal icon) to the right of Tickets in the top navigation bar.

Create an ECS instance

Creating an ECS instance requires parameters such as a vSwitch ID, security group ID, and image ID. You can use existing resource IDs or create new ones by calling the operations in the following steps.

  1. Create a VPC.

    A VPC is a logically isolated private network for your cloud resources.

    API

    Parameter

    Value

    CreateVpc

    RegionId

    Region: cn-hangzhou

    CidrBlock

    VPC CIDR block: 192.168.0.0/16

  2. Create a vSwitch.

    A vSwitch is a basic network device in a VPC that connects different cloud resources.

    API

    Parameter

    Value

    RegionId

    Region: cn-hangzhou

    CreateVSwitch

    ZoneId

    Zone: cn-hangzhou-i

    VpcId

    VPC ID: vpc-bp1aag0sb9s4i92i3****

    CidrBlock

    vSwitch CIDR block: 192.168.0.0/24

  3. Create a security group.

    A security group is a virtual firewall that controls traffic to and from your ECS instances.

    API

    Parameter

    Value

    CreateSecurityGroup

    RegionId

    Region: cn-hangzhou

    VpcId

    VPC ID: vpc-bp1aag0sb9s4i92i3****

  4. Add an inbound rule to the security group.

    API

    Parameter

    Value

    AuthorizeSecurityGroup

    RegionId

    Region: cn-hangzhou

    SecurityGroupId

    Security group ID: sg-bp1esyhwfbqeyudt****

    IpProtocol

    Protocol: tcp

    SourceCidrIp

    Source CIDR block: 0.0.0.0/0

    PortRange

    Port range:

    • For Linux instances: 22/22

    • For Windows instances: 3389/3389

  5. Create an ECS instance.

    API

    Parameter

    Value

    RunInstances

    RegionId

    Region: cn-hangzhou

    ImageId

    Image: Use the Alibaba Cloud Linux image aliyun_3_x64_20G_alibase_20240819.vhd

    InstanceType

    Instance type: ecs.e-c1m1.large

    SecurityGroupId

    Security group ID: sg-bp1esyhwfbqeyudt****

    VSwitchId

    vSwitch ID: vsw-bp1nzprm8h7mmnl8t****

    InstanceName

    Instance name: ecs_cli_demo

    InstanceChargeType

    Set to PostPaid to create a pay-as-you-go instance.

    Note

    Make sure that your account has a sufficient balance.

    Password

    Logon password: ******

    InternetMaxBandwidthOut

    If this value is greater than 0, a public IP address is automatically assigned to the instance.

    SystemDisk.Category

    System disk category: cloud_essd

    SystemDisk.Size

    System disk size: 40 GiB

The following is the complete sample script:

Important

Running this sample script multiple times will create duplicate resources and may incur unnecessary costs. Review and adapt the script for your specific needs before execution.

#!/bin/bash
# In a production environment, make sure that your AccessKey ID and AccessKey secret
# are securely set by using environment variables or a configuration file.
# 1. Set variables.
INSTANCE_NAME="ecs_cli_demo"
# 2. Install the jq tool.
echo "Installing the jq dependency tool..."
yum install -y jq
sleep 3
# 3. Create a VPC, vSwitch, and security group.
echo "Creating a VPC..."
VpcId=$(aliyun vpc CreateVpc --RegionId cn-hangzhou --CidrBlock 192.168.0.0/16 | jq -r .VpcId)
aliyun vpc DescribeVpcAttribute --RegionId cn-hangzhou --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=cn-hangzhou-i | jq -r .VSwitchId)
echo "Creating a security group..."
SecurityGroupId=$(aliyun ecs CreateSecurityGroup --RegionId cn-hangzhou --VpcId ${VpcId} | jq -r .SecurityGroupId)
aliyun ecs AuthorizeSecurityGroup --RegionId cn-hangzhou --SecurityGroupId ${SecurityGroupId} --IpProtocol tcp --SourceCidrIp 0.0.0.0/0 --PortRange 22/22 > /dev/null 2>&1
read -s -p "Enter your password:" PASSWORD
echo
echo "PASSWORD OK."
# 4. Run the command to create an ECS instance.
echo "Creating the ECS instance..."
INSTANCE_ID_RAW=$(aliyun ecs RunInstances \
--RegionId cn-hangzhou \
--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. Extract the instance ID for later use.
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 ECS instance status.
echo "Querying the ECS instance status..."
INSTANCE_ID_QUOTED=$(printf '"%s"' "$INSTANCE_ID")
aliyun ecs DescribeInstances \
--RegionId cn-hangzhou \
--InstanceIds "[${INSTANCE_ID_QUOTED}]" \
--output cols=InstanceId,InstanceName,InstanceType,ImageId,Status rows=Instances.Instance[]

Create and run the shell script. The expected output is as follows:

[root@i-xxxxx Z ~]# bash ecs-cli.sh
Installing the jq dependency tool...
Last metadata expiration check: 0:24:56 ago on Tue 22 Oct 2024 09:24:50 AM CST.
Package jq-1.6-15.al8.x86_64 is already installed.
Dependencies resolved.
Nothing to do.
Complete!
Creating a VPC...
Creating a vSwitch...
Creating a security group...
Enter your password:
PASSWORD OK.
Creating the ECS instance...
Waiting for the ECS instance to be created...
Querying the ECS instance status...
InstanceId          | InstanceName | InstanceType     | ImageId                               | Status
----------          | ------------ | ------------     | -------                               | -------
i-bpxxxxxxxxxxxz4   | ecs_cli_demo | ecs.e-c1m1.large | aliyun_3_x64_20G_alibase_20240819.vhd | Running

Connect to the instance

After connecting to the instance with SSH, you can deploy your services and applications.

  1. Get the public IP address of the instance.

    Call DescribeInstances with the <InstanceID> to obtain the public IP address of the instance.

    • Sample request

      aliyun ecs DescribeInstances \
      --RegionId cn-hangzhou \
      --InstanceIds '["<instance-id>"]'
    • Sample response

      The PublicIpAddress parameter indicates the public IP address of the instance.

      "PublicIpAddress": {
          "IpAddress": [
                          "115.29.xxx.xxx"
          ]
      }
  2. Connect to the ECS instance.

    ssh <username>@<public_ip_address>
    [root@i-xxx bfZ ~ ]# ssh root@1xx.xx.xx.xx
    The authenticity of host '1xx.xx.xx.xx (1xx.xx.xx.xx)' can't be established.
    ECDSA key fingerprint is SHA256:PVyhCaxxx4mecykrU.
    Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
    Warning: Permanently added '1xx.xx.xx.xx' (ECDSA) to the list of known hosts.
    root@1xx.xx.xx.xx's password:
    Welcome to Alibaba Cloud Elastic Compute Service !
    Last login: Thu Oct 10 13:31:58 2024 from xxx.67
    [root@iZ xxx ugZ ~]#

Clean up resources

When you no longer need the resources, release them to avoid further charges.

Note

Choose the appropriate OpenAPI operation to release resources. This example releases all resources created in the preceding steps.

  1. Delete the ECS instance.

    API

    Parameter

    Value

    DeleteInstance

    RegionId

    Region: cn-hangzhou

    InstanceId

    Instance ID: i-bp17f3kzgtzzj91r****

  2. Delete the security group.

    API

    Parameter

    Value

    DeleteSecurityGroup

    RegionId

    Region: cn-hangzhou

    SecurityGroupId

    Security group ID: sg-bp1esyhwfbqeyudt****

  3. Delete the vSwitch.

    API

    Parameter

    Value

    DeleteVSwitch

    RegionId

    Region: cn-hangzhou

    VSwitchId

    vSwitch ID: vsw-bp1nzprm8h7mmnl8t****

  4. Delete the VPC.

    API

    Parameter

    Value

    DeleteVpc

    RegionId

    Region: cn-hangzhou

    VpcId

    VPC ID: vpc-bp1aag0sb9s4i92i3****

The following is a sample script:

#!/bin/bash
# Replace the placeholder values with the actual IDs of the resources you want to release.
INSTANCE_ID='i-bpxxxxxxxxxxxz4'
SECURITY_GROUP_ID='sg-bp1esyhwfbqeyudt****'
VSWITCH_ID='vsw-bp1nzprm8h7mmnl8t****'
VPC_ID='vpc-bp1aag0sb9s4i92i3****'
REGION='cn-hangzhou'
echo "Releasing resources..."
# Delete the instance.
aliyun ecs DeleteInstance \
  --region ${REGION} \
  --InstanceId ${INSTANCE_ID}
# Wait for the instance to be deleted before deleting the security group.
# Add a wait logic here in a production script.
# Delete the security group.
aliyun ecs DeleteSecurityGroup \
  --region ${REGION} \
  --SecurityGroupId ${SECURITY_GROUP_ID}
# Delete the vSwitch.
aliyun vpc DeleteVSwitch \
  --region ${REGION} \
  --VSwitchId ${VSWITCH_ID}
# Delete the VPC.
aliyun vpc DeleteVpc \
  --region ${REGION} \
  --VpcId ${VPC_ID}
echo "Cleanup complete."
            

References

You can run the following command to view a list of supported CLI commands for ECS.

aliyun ecs --help

Use the following syntax to call ECS API operations. For detailed parameters, see the documentation for each operation.

aliyun ecs <APIName> --<parameter1 value1> --<parameter2 value2> ...

Generate CLI command

To help developers learn and use cloud service OpenAPI quickly and efficiently, Alibaba Cloud provides the OpenAPI website. It is a comprehensive product that integrates intelligent OpenAPI search, documentation, online debugging, SDK acquisition, code samples, call error diagnosis, and call statistics. You can use the OpenAPI website to automatically generate CLI code for APIs. For more information, see What is OpenAPI.

  1. Log on to the OpenAPI Portal for ECS.

  2. Select the API operation you need and fill in the parameters.

  3. Click the CLI Example tab on the right to generate the command with the specified parameters.

    For example, after selecting the StartInstance API operation and entering parameters, the CLI Example tab generates the corresponding command: aliyun ecs StartInstance --region cn-hangzhou --InstanceId 'i-bp1i79spj7zmoqg****'.