Create an ECS instance by using ecctl
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
ClientTokenidempotency key automatically.Waits for the instance to enter the
Runningstate 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:
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.
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 ecctlWindows
Windows:
Download a Windows archive from the GitHub release page:
windows_amd64.zip(x86 architecture) orwindows_arm64.zip(ARM architecture).Extract the archive and confirm that the extracted files include
ecctl.exe.Add that directory to the
PATHenvironment variable.Right-click Start, go to System > About > Advanced system settings, and open Environment Variables.
On the Environment Variables pane, find Path, then add the extracted path to Path.
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@latestIf 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 ~/.bashrcVerify the installation
Open a new terminal and run the following command:
ecctl --versionConfigure credentials and region
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 --helpschema: Outputs structured JSON for easy parsing by Agents. Theparamsfield describes each parameter and indicates whether it is required, and thecontractfield 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*.schemasupports hierarchical queries, such asecctl schema ecsand thenecctl 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.largeAfter 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_essdIf 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>"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-bp1234567890exampleThis command:
Sends a
RunInstancescreation request, with an idempotentClientTokenattached automatically.Polls
DescribeInstancesand waits until the instance status becomesRunning.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 theRunningstate.--timeout: Changes the waiting limit. By default,ecctlwaits for the instance to enter theRunningstate 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 |
| string | instance name |
| string | Image ID or name. If you pass a name, it is automatically resolved to the image ID before creation |
| string | Zone ID. If not specified, the system assigns one in the zone where the vSwitch resides |
| integer | Number of instances to create |
| key_value, repeatable | Adds tags, for example, |
| string | Billing method: |
| string | Logon password of the instance |
| string | key pair name. Choose either a key pair or a password; the key pair is recommended |
| object(JSON) | system disk configuration. For an example, see Disk configuration examples below |
| object(JSON) | data disk configuration. For an example, see Disk configuration examples below |
| string | Billing method for network usage, for example, |
| 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 itsrequest_id. You can use them for troubleshooting or for submitting a ticket. Because the waiting phase pollsDescribeInstancesmultiple times, the array usually contains multiple records.ecctl_capabilities_used: The built-inecctlcapabilities used by this command, such asauto_wait(automatically waiting for the instance to be ready).instance: The complete view of the instance after creation. It contains fields such asid,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=prodComplete 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-bp1234567890exampleConnect 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
ecctlto 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-ipGet the public IP address
Filter the target instance by using --filter id=<instance ID>:
ecctl ecs instance list --region cn-hangzhou --filter id=i-bp1234567890exampleThe 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 runssh -i <private key file> root@<public IP address>.Password (
--password): Runssh 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 --forceAfter the deletion, use list to confirm that the instance no longer exists:
ecctl ecs instance list --region cn-hangzhou --filter id=i-bp1234567890exampleError 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 |
|
| Region (required) |
|
| instance type (required) |
|
| Image ID or name (required) |
|
| security group ID (required) |
|
| vSwitch ID (required) |
|
| instance name |
|
| Zone |
|
| Number of instances to create |
|
| Billing method |
|
| key pair |
|
| Password |
|
| Hostname |
|
| Tag |
|
| system disk |
|
| data disk |
|
| Billing method for network usage |
|
| outbound public bandwidth |
|
| Idempotency key |
|
| Validation |
|
| User data |