Create an ECS instance by using ecctl

Updated at:

ecctl (Elastic Compute Control CLI) is a command-line controller for Alibaba Cloud elastic computing resources, built for Agents and O&M engineers. It provides a unified product/resource/action syntax, JSON-first output, command documentation that you can query with ecctl schema, and built-in waiting and read-back capabilities. This tutorial walks you through creating an ECS instance with ecctl, from preparation to connection and cleanup. For more information about ecctl, see ecctl documentation.

Differences from Alibaba Cloud CLI

The Alibaba Cloud CLI organizes commands by product + OpenAPI operation. For example, aliyun ecs RunInstances uses raw OpenAPI field names as parameters, such as InstanceType, ImageId, and SecurityGroupId. ecctl uses a resource-action model instead. The equivalent command is ecctl ecs instance create, with shorter resource field parameters such as --type, --image, and --sg. ecctl also provides the following enhancements:

  • Resolves image names to image IDs automatically.

  • Creates instances idempotently by attaching a ClientToken idempotency key automatically.

  • Waits for the instance to enter the Running state and returns the final view of the instance.

  • Returns structured error objects with recovery suggestions.

    For the correspondence between the parameters of the two CLIs, see the parameter mapping table in the FAQ section.

Preparations

Alibaba Cloud account and permissions

An Alibaba Cloud account (root account) has full permissions on all resources, and a leaked AccessKey poses severe risks. As a best practice, call ecctl with the AccessKey of a Resource Access Management (RAM) user that meets the principle of least privilege:

  1. Create a RAM user and obtain an AccessKey pair (AccessKey ID and AccessKey secret). For more information, see Create a RAM user and Create an AccessKey pair.

  2. Grant the RAM user the permissions on Elastic Compute Service (ECS) and Virtual Private Cloud (VPC) resources. For more information, see Grant permissions to a RAM user. The examples in this topic create ECS instances, VPCs, vSwitches, security groups, and key pairs. Attach the following system policies:

Cloud service

Granted policy

Virtual Private Cloud (VPC)

AliyunVPCFullAccess

Elastic Compute Service (ECS)

AliyunECSFullAccess

Install ecctl

For temporary debugging, you can use Cloud Shell provided by Alibaba Cloud instead of installing the CLI locally.

Choose an installation method based on your operating system:

macOS

Install by using Homebrew:

brew tap aliyun/ecctl https://github.com/aliyun/elastic-compute-control-cli
brew install ecctl

Windows

Windows:

  1. Download a Windows archive from the GitHub release page: windows_amd64.zip (x86 architecture) or windows_arm64.zip (ARM architecture).

  2. Extract the archive and confirm that the extracted files include ecctl.exe.

  3. Add that directory to the PATH environment variable.

    1. Right-click Start, go to System > About > Advanced system settings, and open Environment Variables.

    2. On the Environment Variables pane, find Path, then add the extracted path to Path.

    3. Click OK to save, then reopen your terminal for the change to take effect.

Linux

Install by using Go. Go 1.25 or later is required:

go install github.com/aliyun/elastic-compute-control-cli/cmd/ecctl@latest

If you get a message that the ecctl command cannot be found after installation, the installation directory $(go env GOPATH)/bin (default: ~/go/bin) is not in PATH. Run the following command to add it (bash is used as an example):

echo 'export PATH=$PATH:$(go env GOPATH)/bin' >> ~/.bashrc && source ~/.bashrc

Verify the installation

Open a new terminal and run the following command:

ecctl --version

Configure credentials and region

Note

If a local Alibaba Cloud CLI configuration already exists on your machine (that is, you have run aliyun configure), you can use it directly without reconfiguration. ecctl reads the profile, region, and credentials from the same configuration.

Run the following commands to configure the region and the AccessKey of the RAM user. Replace <AccessKeyId> and <AccessKeySecret> with the AccessKey pair obtained earlier:

ecctl configure set region cn-hangzhou
ecctl configure set access-key-id <AccessKeyId>
ecctl configure set access-key-secret <AccessKeySecret>

For more configuration items (output format, language, profile, environment variables, and others), see the ecctl configuration documentation.

View commands (optional)

Before you create an instance, you can view the command documentation:

# View command documentation (JSON format)
ecctl schema ecs.instance.create --brief

# View parameter help
ecctl ecs instance create --help
  • schema: Outputs structured JSON for easy parsing by Agents. The params field describes each parameter and indicates whether it is required, and the contract field declares behavior contracts such as dry-run, idempotency, and waiting.

  • --help: Outputs human-readable help, including usage examples (Examples) and a parameter list (Resource Flags). Required parameters are marked with *.

  • schema supports hierarchical queries, such as ecctl schema ecs and then ecctl schema ecs.instance. You can locate available commands level by level.

Create an ECS instance

Check inventory (optional)

Before you create an instance, you can check whether the target region and zone have inventory for the target instance type and system disk. The following example queries the inventory of the ecs.g7.large instance type in the Hangzhou region. The command returns the zones in Hangzhou that have available inventory.

# Query inventory of an instance type
ecctl call ecs DescribeAvailableResource \
  --region cn-hangzhou \
  --DestinationResource InstanceType \
  --IoOptimized optimized \
  --InstanceType ecs.g7.large

After you confirm the inventory of the target instance type and zone, you can query the inventory of system disks. Use DestinationResource=SystemDisk to specify the system disk as the queried resource, together with InstanceType and ZoneId to specify the instance type and zone:

ecctl call ecs DescribeAvailableResource \
  --region cn-hangzhou \
  --ZoneId cn-hangzhou-b \
  --ResourceType instance \
  --DestinationResource SystemDisk \
  --InstanceType ecs.g7.large \
  --SystemDiskCategory cloud_essd

If creation fails due to insufficient inventory, ecctl automatically provides the corresponding DescribeAvailableResource query command in the error message. For more information, see Error handling.

Create prerequisite resources

Before you create an instance, prepare resources such as the network and security groups. The following commands create the following resources in order:

# 1. Create a VPC
ecctl vpc create --name demo-vpc --cidr 10.0.0.0/16 --region cn-hangzhou
# → Get the VPC ID from the vpc.id field, for example, vpc-bp1234567890example

# 2. Create a vSwitch in the VPC
ecctl vpc vswitch create \
  --vpc vpc-bp1234567890example \
  --zone cn-hangzhou-b \
  --cidr 10.0.1.0/24 \
  --name demo-vsw \
  --region cn-hangzhou
# → Get the vSwitch ID from the vswitch.id field, for example, vsw-bp1234567890example

# 3. Create a security group
ecctl ecs sg create \
  --vpc vpc-bp1234567890example \
  --name demo-sg \
  --region cn-hangzhou
# → Get the security group ID from the security_group.id field, for example, sg-bp1234567890example

# 4. Add an inbound rule to the security group to allow port 22 for SSH logon
ecctl ecs sg authorize sg-bp1234567890example --region cn-hangzhou --rule tcp:22@0.0.0.0/0

# 5. (Optional) Create a key pair for subsequent SSH logon
# Generate a key file
ssh-keygen -t rsa -b 2048 -f <local key file path>
# Import an existing key pair. --public-key must start with @ and point to the public key file (with the .pub suffix).
ecctl ecs keypair create \
  --name web-key \
  --region cn-hangzhou \
  --public-key "@<local public key file path>"
Important

0.0.0.0/0 allows access to port 22 from any IP address and is suitable only for quick verification in test environments. In the production environment, authorize a specified IP address or CIDR block (such as tcp:22@203.0.113.10/32) to avoid brute-force attacks caused by exposing the SSH port to the Internet.

Create the instance

Pass the vSwitch ID and security group ID obtained in the previous step to --vswitch and --sg. To validate the request without creating resources, append --dry-run to the command (only one instance is supported; do not pass --amount):

ecctl ecs instance create \
  --region cn-hangzhou \
  --type ecs.g7.large \
  --image aliyun_3 \
  --sg sg-bp1234567890example \
  --vswitch vsw-bp1234567890example

This command:

  1. Sends a RunInstances creation request, with an idempotent ClientToken attached automatically.

  2. Polls DescribeInstances and waits until the instance status becomes Running.

  3. Returns the final view of the instance.

The preceding idempotency and waiting behaviors are defaults and can be adjusted as needed:

  • --idempotency-key: Explicitly specifies the idempotency key (generated automatically by default).

  • --no-wait: Returns immediately after creation, without waiting for the instance to enter the Running state.

  • --timeout: Changes the waiting limit. By default, ecctl waits for the instance to enter the Running state with a timeout of 300s. Example: --timeout 10m.

Common parameters

The following table lists the parameters commonly used when you create an instance. To view all parameters, run ecctl ecs instance create --help, or see Full parameters of create. ecctl also provides built-in capabilities such as image name resolution. For more information, see ECS-specific optimizations.

ecctl parameter

Type

Description

--name

string

instance name

--image

string

Image ID or name. If you pass a name, it is automatically resolved to the image ID before creation

--zone

string

Zone ID. If not specified, the system assigns one in the zone where the vSwitch resides

--amount

integer

Number of instances to create

--tag key=value

key_value, repeatable

Adds tags, for example, --tag env=prod --tag app=web

--instance-charge-type

string

Billing method: PostPaid (default) / PrePaid

--password

string

Logon password of the instance

--key-pair

string

key pair name. Choose either a key pair or a password; the key pair is recommended

--system-disk

object(JSON)

system disk configuration. For an example, see Disk configuration examples below

--data-disk

object(JSON)

data disk configuration. For an example, see Disk configuration examples below

--internet-charge-type

string

Billing method for network usage, for example, PayByTraffic

--internet-bandwidth-out

integer

outbound public bandwidth (Mbps). A value greater than 0 assigns a public IP address

Disk configuration examples

Object parameters such as --system-disk and --data-disk support three input methods: key=value, JSON, and @file. This topic uses JSON as an example:

# system disk: disk category, capacity (GiB), and ESSD performance level
--system-disk '{
  "category": "cloud_essd",
  "size": 40,
  "performance_level": "PL1"
}'

# data disk: disk category and capacity (GiB)
--data-disk '{
  "category": "cloud_essd",
  "size": 100
}'

View the creation result

When the creation succeeds, ecctl returns structured JSON (--output json is the default output mode), which contains the following three parts:

  • actions: Each OpenAPI operation that the command actually called, along with its request_id. You can use them for troubleshooting or for submitting a ticket. Because the waiting phase polls DescribeInstances multiple times, the array usually contains multiple records.

  • ecctl_capabilities_used: The built-in ecctl capabilities used by this command, such as auto_wait (automatically waiting for the instance to be ready).

  • instance: The complete view of the instance after creation. It contains fields such as id, status, and network configuration. Get the instance ID required by subsequent operations (connect and release) from this field.

    Example output (only key fields are retained):

{
  "actions": [
    {"action_name": "RunInstances", "request_id": "A1B2C3D4-..."},
    {"action_name": "DescribeInstances", "request_id": "B2C3D4E5-..."}
  ],
  "ecctl_capabilities_used": ["auto_wait"],
  "instance": {
    "id": "i-bp1234567890example",
    "name": "web-01",
    "status": "Running"
    // Other fields are omitted
  }
}

Query instances

After the creation, you can query the instance information at any time. get shows the details of a single instance by instance ID, and list lists instances by page and uses --filter to filter by conditions such as status and tag:

ecctl ecs instance get i-bp1234567890example --region cn-hangzhou

ecctl ecs instance list --region cn-hangzhou \
  --filter status=Running --filter tag.env=prod

Complete example

The following example creates an instance with a public IP address, a key pair, a system disk, a data disk, tags, and a resource group:

ecctl ecs instance create \
  --region cn-hangzhou \
  --zone cn-hangzhou-b \
  --type ecs.g7.large \
  --image aliyun_3 \
  --sg sg-bp1234567890example \
  --vswitch vsw-bp1234567890example \
  --name web-01 \
  --host-name web-01 \
  --key-pair web-key \
  --system-disk '{"category":"cloud_essd","size":40,"performance_level":"PL1"}' \
  --data-disk '{"category":"cloud_essd","size":100}' \
  --internet-charge-type PayByTraffic \
  --internet-bandwidth-out 10 \
  --tag env=prod --tag app=web \
  --resource-group rg-bp1234567890example

Connect to the instance

After the creation, you can connect to the instance in either of the following ways:

  • Log on through SSH over the Internet. This method requires the instance to have a public IP address.

  • Use ecctl to invoke Cloud Assistant to run commands inside the instance. This method does not require a public IP address.

SSH logon

Logging on through SSH over the Internet requires the instance to have a public IP address. To allocate one when you create the instance, add the following two parameters. --internet-bandwidth-out specifies the outbound public bandwidth (Mbps), which is the outbound bandwidth allocated to the instance:

--internet-charge-type PayByTraffic \
--internet-bandwidth-out <bandwidth (Mbps)>

For an instance created without a public IP address, run the following command to assign one afterwards:

ecctl ecs instance update i-bp1234567890example \
--region cn-hangzhou \
--internet-bandwidth-out 5 \
--allocate-public-ip

Get the public IP address

Filter the target instance by using --filter id=<instance ID>:

ecctl ecs instance list --region cn-hangzhou --filter id=i-bp1234567890example

The public IP address is in the instances[].public_ip_addresses field of the output (an array whose first element is the public IP address of the instance):

{
  "instances": [
    {
      "id": "i-bp1234567890example",
      "public_ip_addresses": [
        "47.xx.xx.xx"
      ]
      // Other fields are omitted
    }
  ]
}

Log on

Based on the logon credentials selected during creation, run the corresponding logon command:

  • Key pair (--key-pair): Use the private key file generated when you created the key pair, and run ssh -i <private key file> root@<public IP address>.

  • Password (--password): Run ssh root@<public IP address>, and enter the password as prompted.

Run commands through Cloud Assistant (no public IP address required)

ecctl runs commands inside the instance through Cloud Assistant, automatically waits for the execution to complete, and returns the result:

ecctl ecs instance exec i-bp1234567890example --region cn-hangzhou --command 'uname -a'

Delete resources

Delete resources promptly after you verify the instance to avoid charges. You must stop the instance before you delete it. A running instance requires an explicit --force to be forcefully released:

# Stop and then delete
ecctl ecs instance stop i-bp1234567890example --region cn-hangzhou
ecctl ecs instance delete i-bp1234567890example --region cn-hangzhou

# Or forcefully release a running instance
ecctl ecs instance delete i-bp1234567890example --region cn-hangzhou --force

After the deletion, use list to confirm that the instance no longer exists:

ecctl ecs instance list --region cn-hangzhou --filter id=i-bp1234567890example

Error handling

ecctl writes failure information to a structured error object on stdout, and keeps the original OpenAPI error code and RequestId in actions. If the instance type has no inventory in the target zone when you create an instance, a recovery suggestion is attached automatically:

{
  "error": {
    "kind": "service",
    "code": "CloudAPIError",
    "field": "type",
    "retryable": false,
    "suggested_action": "ecctl call ecs DescribeAvailableResource --region cn-hangzhou --DestinationResource InstanceType --InstanceType ecs.g7.large"
  },
  "actions": [
    {
      "action_name": "RunInstances",
      "code": "InvalidResourceType.NotSupported",
      "message": "instance type ecs.g7.large not exists in [cn-hangzhou-b]",
      "request_id": "..."
    }
  ]
}

If the image name does not exist, a not_found error is returned with the prompt image not found.

FAQ

Parameter mapping

The following table maps the parameters of aliyun ecs RunInstances (partial) to ecctl ecs instance create. It is intended for readers who are familiar with the Alibaba Cloud CLI. For what each ecctl parameter does, see the Common parameters section:

Alibaba Cloud CLI / OpenAPI

ecctl

Description

--RegionId

--region

Region (required)

--InstanceType

--type

instance type (required)

--ImageId

--image

Image ID or name (required)

--SecurityGroupId

--sg

security group ID (required)

--VSwitchId

--vswitch

vSwitch ID (required)

--InstanceName

--name

instance name

--ZoneId

--zone

Zone

--Amount

--amount

Number of instances to create

--InstanceChargeType

--instance-charge-type

Billing method

--KeyPairName

--key-pair

key pair

--Password

--password

Password

--HostName

--host-name

Hostname

--Tag.N.Key / --Tag.N.Value

--tag key=value

Tag

--SystemDisk.Category

--system-disk (JSON)

system disk

--DataDisk.N.Category and others

--data-disk (JSON)

data disk

--InternetChargeType

--internet-charge-type

Billing method for network usage

--InternetMaxBandwidthOut

--internet-bandwidth-out

outbound public bandwidth

--ClientToken

--idempotency-key

Idempotency key

--DryRun

--dry-run

Validation

--UserData

--user-data

User data