Alibaba Cloud How-to Guides¶
Task recipes for day-2 operations on Alibaba Cloud (Aliyun): setting up credentials, building a Resource Directory and landing zone, wiring CEN, running common CLI tasks, monitoring, identity and security setup, and troubleshooting. Why these patterns exist is in Explanation. Region IDs, limits, and name mappings are in Reference.
Command syntax and versions
Commands target Alibaba Cloud CLI v3.5.x and Terraform provider aliyun/alicloud 1.29x (September 2026).
RPC APIs take flat parameters (--Name value). Arrays and objects use numbered keys
(--ZoneMappings.1.ZoneId ...) or a JSON string where the API defines one. Since v3.5.0 the CLI also accepts
kebab-case (aliyun ecs describe-instances). IDs such as i-bp1xxxx are placeholders. Always pass
--RegionId for regional APIs.
Set Up Credentials¶
Install and Configure the CLI¶
# Install (macOS/Linux)
brew install aliyun-cli
# or the official installer script
/bin/bash -c "$(curl -fsSL https://aliyuncli.alicdn.com/install.sh)"
aliyun version
# Preferred for humans: OAuth or CloudSSO, no stored long-lived AccessKey
aliyun configure --mode OAuth --profile default
aliyun configure --mode CloudSSO --profile cloud-sso # prompts for the CloudSSO sign-in URL
# CI on Alibaba Cloud or ACK: use EcsRamRole or OIDC instead of AK
# Last resort: static AccessKey (keep it out of shell history, rotate it)
aliyun configure set \
--profile ci \
--mode AK \
--region ap-southeast-5 \
--access-key-id "$ALIBABA_CLOUD_ACCESS_KEY_ID" \
--access-key-secret "$ALIBABA_CLOUD_ACCESS_KEY_SECRET"
aliyun configure list
aliyun configure switch --profile default
Assume a Role in Another Account¶
For a profile that assumes a role through another profile, use ChainableRamRoleArn. This is the usual way to
reach member accounts through ResourceDirectoryAccountAccessRole or a CloudSSO-provisioned role.
aliyun configure set \
--profile a-prod \
--mode ChainableRamRoleArn \
--source-profile default \
--ram-role-arn 'acs:ram::<member-account-id>:role/ResourceDirectoryAccountAccessRole' \
--role-session-name ops-cli
# One-off temporary credentials
aliyun sts AssumeRole \
--RoleArn acs:ram::<account-id>:role/deploy-role \
--RoleSessionName ci-deploy-session \
--DurationSeconds 3600 # 900 up to the role's MaxSessionDuration (max 43200)
Configure the Terraform Provider¶
Keep credentials out of .tf files. Use environment variables, a CLI profile, or assume_role. The legacy
ALICLOUD_* variables are deprecated since provider v1.228.0.
terraform {
required_providers {
alicloud = {
source = "aliyun/alicloud"
version = "~> 1.293"
}
}
}
# Management/network account: credentials from ALIBABA_CLOUD_ACCESS_KEY_ID/SECRET, a profile, or OIDC
provider "alicloud" {
region = "ap-southeast-5"
}
variable "a_prod_account_id" { type = string }
# Member account through the RD access role
provider "alicloud" {
alias = "a_prod"
region = "ap-southeast-5"
assume_role {
role_arn = "acs:ram::${var.a_prod_account_id}:role/ResourceDirectoryAccountAccessRole"
session_name = "terraform"
}
}
resource "alicloud_vpc" "main" {
provider = alicloud.a_prod
vpc_name = "prod-vpc"
cidr_block = "10.0.0.0/16"
}
resource "alicloud_vswitch" "app_a" {
provider = alicloud.a_prod
vpc_id = alicloud_vpc.main.id
cidr_block = "10.0.1.0/24"
zone_id = "ap-southeast-5a" # confirm zone IDs with: aliyun ecs DescribeZones --RegionId ap-southeast-5
vswitch_name = "app-a"
}
In CI (GitHub Actions, GitLab), prefer assume_role_with_oidc { oidc_provider_arn, role_arn, oidc_token_file }
so the pipeline stores no AccessKey.
Build the Resource Directory and Landing Zone¶
Use the Governance Center Wizard (Recommended Start)¶
- In the management account, open Agentic Cloud Governance Center > Landing Zone > Setup and follow the wizard. It enables Resource Directory, creates the core accounts (log archive, security, and so on), and applies the recommended baseline.
- Under Account Factory, define a baseline (password policy, RAM security preferences, subscribed services, CloudSSO access, ActionTrail delivery, networking).
- Enable the guardrails that protect the landing zone resources from modification.
- Vend new accounts from the account factory, or with Terraform as shown below.
Create Folders, Accounts, and Control Policies with the CLI¶
The Root folder ID starts with r-. Get it from GetResourceDirectory. CreateResourceAccount takes
ParentFolderId, not FolderId.
# Enable RD once, from the management account (if the wizard has not done it)
aliyun resourcemanager InitResourceDirectory
aliyun resourcemanager GetResourceDirectory # note RootFolderId (r-xxxx)
# Create a folder under Root
aliyun resourcemanager CreateFolder \
--ParentFolderId r-xxxxxx \
--FolderName "Workloads"
# Create a member (resource account) in that folder
aliyun resourcemanager CreateResourceAccount \
--DisplayName "bu-a-prod" \
--ParentFolderId fd-xxxxxxxx \
--AccountNamePrefix bu-a-prod
# Control policies must be enabled once before they take effect
aliyun resourcemanager EnableControlPolicy
# Create a control policy (EffectScope RAM = applies to RAM users/roles only)
aliyun resourcemanager CreateControlPolicy \
--PolicyName deny-outside-approved-regions \
--EffectScope RAM \
--PolicyDocument '{"Version":"1","Statement":[{"Effect":"Deny","Action":"*","Resource":"*","Condition":{"StringNotEquals":{"acs:RequestedRegion":["ap-southeast-5","ap-southeast-1"]}}}]}'
# Attach it to a folder (or a member account ID)
aliyun resourcemanager AttachControlPolicy \
--PolicyId cp-xxxxxxxx \
--TargetId fd-xxxxxxxx
Test region-deny policies before attaching them widely
Global services (RAM, CloudSSO, ActionTrail, CDN, DNS) are called with a fixed or empty region. A blanket
region deny can break them. Add NotAction exceptions for global services and test on a sandbox folder first.
The condition key name above follows Alibaba's control-policy examples. Verify it against the current
control-policy language docs.
Vend Accounts with Terraform¶
data "alicloud_resource_manager_folders" "workloads" {
name_regex = "^Workloads$"
}
data "alicloud_governance_baselines" "default" {}
# Account factory: creates the member AND applies the Governance Center baseline
resource "alicloud_governance_account" "bu_a_prod" {
account_name_prefix = "bu-a-prod"
display_name = "bu-a-prod"
folder_id = data.alicloud_resource_manager_folders.workloads.ids[0]
baseline_id = data.alicloud_governance_baselines.default.ids[0]
}
# Plain RD member without a baseline (available since provider v1.83.0)
resource "alicloud_resource_manager_account" "sandbox" {
display_name = "sandbox-01"
folder_id = data.alicloud_resource_manager_folders.workloads.ids[0]
}
Destroy behaviour
Terraform cannot delete an alicloud_governance_account. destroy only removes it from state. Removing an RD
member needs the account-deletion checks (abandonable_check_id / force_delete on
alicloud_resource_manager_account, provider v1.249.0+).
Connect VPCs with CEN and Transit Router¶
# List CEN instances and transit routers
aliyun cbn DescribeCens
aliyun cbn ListTransitRouters --CenId cen-xxxxxxxx --RegionId ap-southeast-5
# Attach a VPC (possibly owned by another account) with vSwitches in two zones
aliyun cbn CreateTransitRouterVpcAttachment \
--RegionId ap-southeast-5 \
--CenId cen-xxxxxxxx \
--TransitRouterId tr-xxxxxxxx \
--VpcId vpc-xxxxxxxx \
--VpcOwnerId <workload-account-id> \
--ZoneMappings.1.ZoneId ap-southeast-5a \
--ZoneMappings.1.VSwitchId vsw-aaaaaaaa \
--ZoneMappings.2.ZoneId ap-southeast-5b \
--ZoneMappings.2.VSwitchId vsw-bbbbbbbb \
--TransitRouterAttachmentName a-prod-vpc
# Inspect route tables and their associations
aliyun cbn ListTransitRouterRouteTables --TransitRouterId tr-xxxxxxxx
aliyun cbn ListTransitRouterRouteTableAssociations \
--TransitRouterRouteTableId vtb-xxxxxxxx
For a cross-account attachment, the VPC owner first grants the CEN instance permission to attach its VPC. You can do this in the VPC console or with the CEN cross-account authorization API. Then the network account creates the attachment.
CLI Recipes by Service¶
ECS (Elastic Compute Service)¶
# List instances as a table
aliyun ecs DescribeInstances --RegionId ap-southeast-5 \
--output cols=InstanceId,InstanceName,Status rows=Instances.Instance[]
# Start a stopped instance
aliyun ecs StartInstance --InstanceId i-xxxxxxxxxxxxxxxx
# Snapshot a disk before a deploy
aliyun ecs CreateSnapshot --DiskId d-xxxxxxxxxxxxxxxx --SnapshotName "pre-deploy-2026-09-25"
# List zones in a region (verify AZ IDs before writing IaC)
aliyun ecs DescribeZones --RegionId ap-southeast-5
VPC and Security Groups¶
aliyun vpc DescribeVpcs --RegionId ap-southeast-5
aliyun vpc DescribeRouteTableList --RegionId ap-southeast-5 --VpcId vpc-xxxxxxxx
# Allow HTTPS inbound on a security group (priority 1 = highest)
aliyun ecs AuthorizeSecurityGroup \
--RegionId ap-southeast-5 \
--SecurityGroupId sg-xxxxxxxx \
--IpProtocol tcp \
--PortRange 443/443 \
--SourceCidrIp 0.0.0.0/0 \
--Policy accept \
--Priority 1
Load Balancers (CLB / ALB)¶
# CLB (legacy "SLB" API)
aliyun slb DescribeLoadBalancers --RegionId ap-southeast-5
aliyun slb AddBackendServers \
--LoadBalancerId lb-xxxxxxxx \
--BackendServers '[{"ServerId":"i-xxxxxxxx","Weight":"100"}]'
# ALB
aliyun alb ListLoadBalancers --RegionId ap-southeast-5
RDS (ApsaraDB RDS)¶
aliyun rds DescribeDBInstances --RegionId ap-southeast-5
# Manual physical backup
aliyun rds CreateBackup --DBInstanceId rm-xxxxxxxx --BackupMethod Physical
# Planned primary/standby switchover (HA edition)
aliyun rds SwitchDBInstanceHA --DBInstanceId rm-xxxxxxxx --NodeId <standby-node-id>
Monitoring and Alerting¶
CloudMonitor¶
CloudMonitor collects host-level and service-level metrics automatically. You can push custom metrics through the
PutCustomMetric API.
# Metric definitions for ECS
aliyun cms DescribeMetricMetaList --Namespace acs_ecs_dashboard
# Latest CPU utilization for one instance
aliyun cms DescribeMetricLast \
--Namespace acs_ecs_dashboard \
--MetricName CPUUtilization \
--Dimensions '[{"instanceId":"i-xxxxxxxx"}]' \
--Period 300
# Alarm: CPU > 80% (average) for 3 consecutive periods
aliyun cms PutResourceMetricRule \
--RuleId cpu-high-prod \
--RuleName "CPU > 80%" \
--Namespace acs_ecs_dashboard \
--MetricName CPUUtilization \
--Resources '[{"instanceId":"i-xxxxxxxx"}]' \
--Escalations.Critical.Statistics Average \
--Escalations.Critical.ComparisonOperator GreaterThanThreshold \
--Escalations.Critical.Threshold 80 \
--Escalations.Critical.Times 3 \
--Period 300 \
--ContactGroups ops-team
SLS (Simple Log Service)¶
SLS is Alibaba Cloud's centralized log service. It handles real-time log collection, search, dashboards, and
alerting. The commands below call the SLS OpenAPI (2020-12-30) through the aliyun CLI. Check parameter spelling
with aliyun sls <API> --help on your CLI version.
aliyun sls CreateProject --body '{"projectName":"prod-logs","description":"Production logging"}'
aliyun sls CreateLogStore \
--project prod-logs \
--body '{"logstoreName":"app-logs","ttl":90,"shardCount":2}'
# Query: 5xx count per host over a one-hour window (Unix seconds)
aliyun sls GetLogs \
--project prod-logs \
--logstore app-logs \
--from 1790000000 \
--to 1790003600 \
--query "status >= 500 | SELECT count(*) as error_count, host GROUP BY host"
Centralized logging across accounts
Create one ActionTrail organization trail in the management account that delivers to the Log Archive account's SLS project. Use SLS cross-account collection or log shipping for application logs from member accounts.
Identity and Security Tasks¶
Register a SAML IdP for Role-Based SSO¶
For multi-account tenancies, prefer CloudSSO. For a single account, register the IdP in RAM. The IMS API expects the metadata Base64-encoded.
aliyun ims CreateSAMLProvider \
--SAMLProviderName okta-idp \
--EncodedSAMLMetadataDocument "$(base64 < metadata.xml | tr -d '\n')"
Then create a RAM role whose trust policy trusts acs:ram::<account-id>:saml-provider/okta-idp. Configure the
IdP (Okta, Microsoft Entra ID, and others) to send the role and provider ARNs in the SAML assertion.
Enable an Organization-Wide ActionTrail¶
aliyun actiontrail CreateTrail \
--Name org-audit-trail \
--OssBucketName audit-logs-bucket \
--OssKeyPrefix actiontrail \
--SlsProjectArn acs:log:ap-southeast-5:<log-archive-account-id>:project/audit-logs \
--IsOrganizationTrail true
# A new trail does not record until it is started
aliyun actiontrail StartLogging --Name org-audit-trail
Enable TDE on RDS¶
# Service-managed key
aliyun rds ModifyDBInstanceTDE --RegionId ap-southeast-5 \
--DBInstanceId rm-xxxxxxxx --TDEStatus Enabled
# Customer-managed KMS key (MySQL/PostgreSQL): RDS needs a role that may use the key
aliyun rds ModifyDBInstanceTDE --RegionId ap-southeast-5 \
--DBInstanceId rm-xxxxxxxx --TDEStatus Enabled \
--EncryptionKey <kms-key-id> \
--RoleARN acs:ram::<account-id>:role/aliyunrdsinstanceencryptiondefaultrole
TDE is one-way on many engines
On several RDS engines, TDE cannot be disabled once enabled. Test on a clone first.
Troubleshooting¶
CEN Connectivity Issues¶
| Symptom | Likely cause | Resolution |
|---|---|---|
| VPC-to-VPC ping fails across CEN | Missing route table association or propagation | List TR route tables (aliyun cbn ListTransitRouterRouteTables --TransitRouterId tr-xxx) and associations (ListTransitRouterRouteTableAssociations --TransitRouterRouteTableId vtb-xxx). Check the attachment is associated with the right table and that propagation is enabled. Check the VPC route table has a route to the TR |
| Cross-region traffic drops | Inter-region connection has no bandwidth, or the bandwidth plan is exhausted | Check the inter-region attachment's bandwidth type. For BandwidthPackage, check aliyun cbn DescribeCenBandwidthPackages --Filter.1.Key CenId --Filter.1.Value.1 cen-xxx and increase it. Or switch to pay-by-data-transfer |
| Asymmetric routing through firewall VPC | Custom route tables do not send return traffic through the firewall | Make both directions' route tables point through the firewall VPC's TR attachment. Or use Cloud Firewall VPC border, which handles symmetry |
| Cross-account attachment fails | VPC owner has not authorized the CEN instance | Grant CEN cross-account authorization from the VPC owner account, then retry with --VpcOwnerId |
Cross-Region Replication Failures¶
# DTS (current API): job status and lag
aliyun dts DescribeDtsJobDetail --RegionId ap-southeast-5 --DtsJobId <dts-job-id>
# OSS CRR rules on the source bucket (ossutil-style syntax wrapped by `aliyun oss`; check `aliyun oss --help`)
aliyun oss bucket-replication --method get oss://source-bucket
OSS CRR and versioning
The versioning state of the source and destination buckets must match (both unversioned or both versioning-enabled). Check it on both buckets before enabling CRR. The earlier version of this note said CRR fails silently without versioning. That was not accurate for unversioned pairs.
NAT Gateway Troubleshooting¶
| Symptom | Likely cause | Resolution |
|---|---|---|
| Private instances cannot reach the Internet | No SNAT entry for the vSwitch, or no 0.0.0.0/0 route to the NAT Gateway |
Create an SNAT entry: aliyun vpc CreateSnatEntry --RegionId <region> --SnatTableId stb-xxx --SnatIp <eip-address> --SourceVSwitchId vsw-xxx. Check the VPC route table |
| SNAT port exhaustion / connection failures under load | Too few EIPs for the concurrency | Add EIPs to the SNAT entry (comma-separated SnatIp). Spread high-fan-out workloads across entries |
| DNAT port forwarding not working | Security group blocks the forwarded port | Allow inbound traffic on the DNAT target port in the ECS instance's security group |
General Diagnostic Commands¶
# Network interfaces attached to an instance
aliyun ecs DescribeNetworkInterfaces --RegionId ap-southeast-5 --InstanceId i-xxxxxxxx
# Security group rules
aliyun ecs DescribeSecurityGroupAttribute --RegionId ap-southeast-5 --SecurityGroupId sg-xxxxxxxx
# Flow logs on a VPC
aliyun vpc DescribeFlowLogs --RegionId ap-southeast-5 --ResourceId vpc-xxxxxxxx
Sources¶
- Alibaba Cloud CLI README and configuration docs
- Terraform provider authentication
- Terraform
alicloud_governance_account,alicloud_resource_manager_account,alicloud_resource_manager_control_policy - Set up a landing zone (Governance Center)
- Create a member in a resource directory
- API parameter names cross-checked against the Terraform provider source (
resource_alicloud_resource_manager_account.go,resource_alicloud_cen_transit_router_vpc_attachment.go,resource_alicloud_cms_alarm.go,resource_alicloud_ram_saml_provider.go,resource_alicloud_actiontrail_trail.go)