
Alibabacloud Resourcecenter Search
- 293 installs
- 208 repo stars
- Updated August 4, 2026
- aliyun/alibabacloud-aiops-skills
Search and inventory Alibaba Cloud resources across accounts and regions when agents need asset discovery, cost reviews, or incident context before changes.
About
alibabacloud-resourcecenter-search lets agents query Alibaba Cloud Resource Center to find instances, databases, networks, and tagged assets across regions, giving fast inventory visibility for monitoring, audits, and safer operational changes.
- Cross-region unified resource lookup
- Filters by service, tag, and resource type
- Speeds incident scoping and change impact analysis
- Reduces manual console hopping for agents
- Supports inventory audits and cleanup workflows
Alibabacloud Resourcecenter Search by the numbers
- 293 all-time installs (skills.sh)
- Ranked #409 of 1,039 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/aliyun/alibabacloud-aiops-skills --skill alibabacloud-resourcecenter-searchAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 293 |
|---|---|
| repo stars | ★ 208 |
| Last updated | August 4, 2026 |
| Repository | aliyun/alibabacloud-aiops-skills ↗ |
What it does
Search and inventory Alibaba Cloud resources across accounts and regions when agents need asset discovery, cost reviews, or incident context before changes.
Files
1. Prerequisites
[MUST] CLI User-Agent — Every aliyun CLI command invocation must include:--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search[MUST] Enable AI-Mode — AI-mode is required for Agent Skill execution.
Run the following commands before any other aliyun CLI invocation:```bash
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search"
```
Pre-check: Aliyun CLI >= 3.3.3 required
Run aliyun version to verify >= 3.3.3. If not installed or version too low,run curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash to install/update,or see references/cli-installation-guide.md for installation instructions.Then [MUST] run aliyun configure set --auto-plugin-install true to enable automatic plugin installation.Then [MUST] run aliyun plugin update to ensure that any existing plugins on your local machine are always up-to-date.Pre-check: Alibaba Cloud Credentials Required
>
Security Rules:
>
- NEVER read, echo, or print AK/SK values (e.g., echo $ALIBABA_CLOUD_ACCESS_KEY_ID is FORBIDDEN)- NEVER ask the user to input AK/SK directly in the conversation or command line
- NEVER use aliyun configure set with literal credential values- ONLY use aliyun configure list to check credential status>
```bash
aliyun configure list
```
>
Check the output for a valid profile (AK, STS, or OAuth identity).
>
If no valid profile exists, STOP here.
>
1. Obtain credentials from Alibaba Cloud Console
2. Configure credentials outside of this session (via aliyun configure in terminal or environment variables in shell profile)3. Return and re-run after aliyun configure list shows a valid profile[MUST] Disable AI-Mode at EVERY exit point — Before delivering the final response for ANY reason, always disable AI-mode first. This applies to ALL exit paths: workflow success, workflow failure, error/exception, user cancellation, session end, or any other scenario where no further CLI commands will be executed.
AI-mode is only used for Agent Skill invocation scenarios and MUST NOT remain enabled after the skill stops running.
```bash
aliyun configure ai-mode disable
```
---
2. Parameter Confirmation
IMPORTANT: Parameter Confirmation — Before executing any command or API call,
ALL user-customizable parameters (e.g., RegionId, instance names, CIDR blocks,
passwords, domain names, resource specifications, etc.) MUST be confirmed with the
user. Do NOT assume and use default values without explicit user approval.
| Parameter | Required/Optional | Description | Default Value |
|---|---|---|---|
Scope | Required (cross-account) | Cross-account search scope: Resource Directory ID, Root Folder ID, Folder ID, or Member ID | None |
ResourceType | Optional | Resource type (e.g., ACS::ECS::Instance) | None (all types) |
RegionId | Optional | Resource Region ID (e.g., cn-hangzhou) | None (all regions) |
ResourceId | Optional | Resource ID | None |
ResourceName | Optional | Resource name | None |
VpcId | Optional | VPC ID (e.g., vpc-xxx) | None |
VSwitchId | Optional | VSwitch (e.g., vsw-xxx) | None |
IpAddress | Optional | IP address | None |
GroupByKey | Optional | Statistics grouping dimension: ResourceType, RegionId, ResourceGroupId | None |
MaxResults | Optional | Page size for paginated APIs. | 20 |
---
3. RAM Policy
See references/ram-policies.md for full permission lists.
Recommended system policies:
- Read-only:
AliyunResourceCenterReadOnlyAccess - Full access:
AliyunResourceCenterFullAccess
Opening Resource Center will auto-create the service-linked role AliyunServiceRoleForResourceMetaCenter.Resource Visibility Scope
RAM policies (defined in ram-policies.md) control whether a user can call a Resource Center API. However, for search APIs (SearchResources, GetResourceCounts, GetResourceConfiguration, SearchMultiAccountResources, GetMultiAccountResourceCounts, GetMultiAccountResourceConfiguration), the scope of resources visible in results is determined by each cloud product's own permissions:
Single Account
- Cloud resource read permissions: A RAM user can only see resources in Resource Center for which they have read-only access on the corresponding cloud product. For example, granting
ReadOnlyAccesslets the user see all resources they have access to; granting onlyAliyunVPCReadOnlyAccesslimits visibility to VPC resources. - Resource group scoped permissions: If resources are organized by resource groups, you can grant a RAM user read access scoped to a specific resource group. The user will only see resources within that group, achieving resource isolation.
Cross-Account
- Grant the system policy
AliyunResourceCenterFullAccessto the RAM user of the Resource Directory management account to enable cross-account resource search.
---
4. Core Workflow
Step 1: Identify APIs Based on User Requirements
Determine which APIs are needed based on the user's specific scenario. Refer to the scenario cards below.
Step 2: [MUST] Read API Documentation Before Every CLI Call
CRITICAL WARNING: DO NOT execute anyaliyun resourcecentercommand without first reading the exact parameter format inreferences/related-apis.md.
>
Failure Pattern: Guessing parameters like --filter format will cause errors. The correct JSON structure MUST be copied from the documentation.>
Mandatory Action: Open and read the specific API section in references/related-apis.md BEFORE constructing any CLI command.
---
Scenario Cards
Scenario 1: Service Activation
| Requirement | Account Type | API | Description |
|---|---|---|---|
| Check if enabled | Single-account | get-resource-center-service-status | Returns service status |
| Enable service | Single-account | enable-resource-center | Required for first-time use |
| Check cross-account status | Resource Directory | get-multi-account-resource-center-service-status | Multi-account scenario |
| Enable cross-account service | Resource Directory | enable-multi-account-resource-center | Requires management account or delegated admin |
---
Scenario 2: ResourceType Discovery
| Requirement | Account Type | Script | Description |
|---|---|---|---|
| Find resource type codes by keyword | Single-account | scripts/query-resource-types.py | Search across ResourceType, ProductName, and ResourceTypeName fields |
Decision Logic:
- When you needs to filter by resource type but doesn't know the exact code -> Use this script first
- After discovering the correct
ResourceTypecode -> Use it in search or count API with--filterparameter
---
Scenario 3: Resource Search
| Requirement | Account Scope | API | Key Parameters |
|---|---|---|---|
| Search resources by criteria | Current account | search-resources | --filter |
| Cross-account resource search | Resource Directory | search-multi-account-resources | --scope + --filter |
| Search including deleted resources | Current account | search-resources | --include-deleted-resources=true |
---
Scenario 4: View Resource Details
| Requirement | Account Scope | API | Use Case |
|---|---|---|---|
| Get single resource configuration | Current account | get-resource-configuration | Get complete configuration details |
| Batch get multiple resource configurations | Current account | batch-get-resource-configurations | Get multiple resources at once |
| Get resource configuration from another account | Resource Directory | get-multi-account-resource-configuration | Cross-account view |
---
Scenario 5: Statistics and Analysis
| Requirement | Account Scope | API | Grouping Dimensions |
|---|---|---|---|
| Count resources | Current account | get-resource-counts | ResourceType, RegionId, ResourceGroupId |
| Cross-account statistics | Resource Directory | get-multi-account-resource-counts | ResourceType, RegionId, ResourceGroupId |
---
Scenario 6: Tag Discovery
| Requirement | Account Scope | API | Description |
|---|---|---|---|
| List all tag keys | Current account | list-tag-keys | Browse tag catalog |
| List values for a specific tag key | Current account | list-tag-values | e.g., list all values for env |
| Cross-account tag keys | Resource Directory | list-multi-account-tag-keys | Multi-account scenario |
| Cross-account tag values | Resource Directory | list-multi-account-tag-values | Multi-account scenario |
---
5. Success Verification
See references/verification-method.md for detailed verification steps and commands for each workflow step.
---
6. Precautions
[MUST] High-Risk Operation Confirmation — Before executingdisable-resource-centerordisable-multi-account-resource-center:
>
1. MUST explicitly inform the user of the impacts:
- Disable Impact
- After disabling Resource Center, resource data will no longer be viewable in Resource Center. Specifically:
- For a single Alibaba Cloud account, after disabling Resource Center, resource data in the current account will no longer be viewable.
- For the management account of a Resource Directory and the delegated administrator account of Resource Center, disabling Resource Center will also disable the cross-account resource search feature. Resource data in the current account and members of the Resource Directory will no longer be viewable. Additionally, members will not be able to view resource data in their own accounts.
- After disabling Resource Center, the resource management module on the console homepage, Config Audit service, and other related scenarios will also be unable to view resource data.
- Disable Restrictions
- If the management account of a Resource Directory or the delegated administrator account of Resource Center has cross-account resource features enabled by another account, Resource Center cannot be disabled.
- If there are cloud products or features that have strong dependencies on Resource Center, such as Config Audit and associated resource transfer, you must first disable those cloud products or features before you can disable Resource Center.
2. MUST obtain explicit user confirmation (e.g., user types "confirm disable" or similar clear affirmation)
3. DO NOT proceed without user's explicit acknowledgment
Disable Resource Center
Warning: Disabling will remove all resource data and affect dependent services (e.g., Config Audit). Must first disable cross-account if enabled.
aliyun resourcecenter disable-resource-center \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-searchDisable Cross-Account Resource Center
Must be done before disabling single-account resource center (if cross-account is enabled). Requires management account or delegated admin.
aliyun resourcecenter disable-multi-account-resource-center \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
7. Best Practices
1. `--user-agent` on every Resource Center CLI call — All aliyun resourcecenter examples in this skill include --user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search. When executing commands for this skill, always pass the same flag so usage is consistent with verification, maintainers’ expectations, and any automated checks. 2. Use filters for targeted search — Combining ResourceType, RegionId, and Tag filters improves search efficiency 3. Use `GroupByKey` for quick statistics — Get resource distribution by type, region, or resource group without iterating 4. Cross-account scope selection — Use the most specific scope (member ID > folder ID > root folder ID > directory ID) to narrow search results 5. Wait after enabling — Resource Center needs a few minutes to build data after activation; large accounts may take longer 6. Prefer read-only policies — For daily search and statistics operations, use AliyunResourceCenterReadOnlyAccess for security 7. ResourceType discovery — When the exact resource type code is unknown, use the helper script documented in Section 8 (run from the skill root directory). 8. Tag discovery vs tag-filtered search — For “what tag keys/values exist”, use list-tag-keys / list-tag-values (and multi-account variants with --scope). Reserve search-resources for finding resources that match tag conditions.
---
8. Available scripts
| Script | Purpose | Usage |
|---|---|---|
scripts/query-resource-types.py | Queries resource types by keyword from Alibaba Cloud Resource Center; stdout is JSON (resourceTypes, count, keyword, language; failures use success: false and error) | python3 scripts/query-resource-types.py <keyword> [--language LANGUAGE] |
---
9. Troubleshooting
When a Resource Center API call or aliyun resourcecenter command fails, read the response’s HTTP status, Code (error code), and Message, then match them against the catalog.
Full error list: references/error-codes.md
---
10. Reference Links
| Reference | Description |
|---|---|
| references/related-apis.md | All CLI commands list |
| references/ram-policies.md | RAM permission policies |
| references/verification-method.md | Verification steps for each workflow |
| references/error-codes.md | Deduplicated Resource Center API error code catalog (HTTP, Code, Message) and lookup hints |
| references/cli-installation-guide.md | Aliyun CLI installation guide |
| references/acceptance-criteria.md | For maintainers/CI only: Skill testing acceptance criteria, correct CLI command patterns, parameter validation rules. Note: This document is intended for human maintainers and automated testing, not required reading for end users. |
Acceptance Criteria: alibabacloud-resourcecenter-search
Scenario: Cross-region, Cross-product, Cross-account Global Resource Inventory, Search & Statistics Purpose: Skill testing acceptance criteria
---
Correct CLI Command Patterns
1. Product — resourcecenter
CORRECT
aliyun resourcecenter search-resources ...
aliyun resourcecenter enable-resource-center ...INCORRECT
aliyun resource-center search-resources ... # Wrong: product name has no hyphen
aliyun ResourceCenter SearchResources ... # Wrong: not plugin mode2. Commands — All verified via --help
| Command | Verified |
|---|---|
enable-resource-center | Yes |
disable-resource-center | Yes |
get-resource-center-service-status | Yes |
search-resources | Yes |
get-resource-counts | Yes |
get-resource-configuration | Yes |
batch-get-resource-configurations | Yes |
list-tag-keys | Yes |
list-tag-values | Yes |
enable-multi-account-resource-center | Yes |
disable-multi-account-resource-center | Yes |
get-multi-account-resource-center-service-status | Yes |
search-multi-account-resources | Yes |
get-multi-account-resource-counts | Yes |
get-multi-account-resource-configuration | Yes |
list-multi-account-tag-keys | Yes |
list-multi-account-tag-values | Yes |
3. Parameters — All verified via --help
search-resources
| Parameter | Verified | Notes |
|---|---|---|
--filter | Yes | list, JSON array format: [{"Key":"...","MatchType":"...","Value":["..."]}] |
--max-results | Yes | int, range 1~500, default 20 |
--next-token | Yes | string |
--sort-criterion | Yes | object, format: Key=xxx Order=xxx |
--resource-group-id | Yes | string |
--include-deleted-resources | Yes | bool |
search-multi-account-resources
| Parameter | Verified | Notes |
|---|---|---|
--scope | Yes | Required. Resource Directory ID / Root Folder ID / Folder ID / Member ID |
--filter | Yes | list, JSON array format |
--max-results | Yes | int, range 1~100, default 20 |
--next-token | Yes | string |
--sort-criterion | Yes | object |
get-resource-counts
| Parameter | Verified | Notes |
|---|---|---|
--group-by-key | Yes | Enum: ResourceType, RegionId, ResourceGroupId |
--filter | Yes | list, JSON array format |
--include-deleted-resources | Yes | bool |
get-multi-account-resource-counts
| Parameter | Verified | Notes |
|---|---|---|
--scope | Yes | string, Resource Directory/Folder/Member ID |
--group-by-key | Yes | Enum: ResourceType, RegionId, ResourceGroupId |
--filter | Yes | list, JSON array format |
get-resource-configuration
| Parameter | Verified | Notes |
|---|---|---|
--resource-id | Yes | Required |
--resource-region-id | Yes | Required |
--resource-type | Yes | Required |
list-tag-values
| Parameter | Verified | Notes |
|---|---|---|
--tag-key | Yes | Required |
--match-type | Yes | Enum: Equals, Prefix |
--max-results | Yes | int, range 1~100, default 20 |
4. Enum Values Verified
| Parameter | Command | Valid Values |
|---|---|---|
--group-by-key | get-resource-counts | ResourceType, RegionId, ResourceGroupId |
--group-by-key | get-multi-account-resource-counts | ResourceType, RegionId, ResourceGroupId |
--match-type | list-tag-keys, list-tag-values | Equals, Prefix |
5. Filter Value Format Verified
The --filter parameter accepts a JSON array string:
CORRECT
--filter '[{"Key":"ResourceType","MatchType":"Equals","Value":["ACS::ECS::Instance"]}]'INCORRECT
--filter Key=ResourceType MatchType=Equals Value=ACS::ECS::Instance # Wrong: not JSON format
--filter '{"Key":"ResourceType","MatchType":"Equals","Value":["ACS::ECS::Instance"]}' # Wrong: not array6. --user-agent Flag
CORRECT
aliyun resourcecenter search-resources --max-results 50 --user-agent AlibabaCloud-Agent-SkillsINCORRECT
aliyun resourcecenter search-resources --max-results 50 # Missing --user-agentAll aliyun commands in the skill include --user-agent AlibabaCloud-Agent-Skills.
Aliyun CLI Installation & Configuration Guide
Complete guide for installing and configuring Aliyun CLI.
Aliyun CLI 3.3.3+: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.3 or later for full plugin ecosystem coverage.
Installation
macOS
Using Homebrew (Recommended)
brew install aliyun-cli
# Upgrade to latest
brew upgrade aliyun-cli
# Verify version (>= 3.3.3)
aliyun versionUsing Binary
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-macosx-latest-amd64.tgz
# Extract
tar -xzf aliyun-cli-macosx-latest-amd64.tgz
# Move to PATH
sudo mv aliyun /usr/local/bin/
# Verify
aliyun versionLinux
Debian/Ubuntu
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun versionCentOS/RHEL
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun versionARM64 Architecture
# Download ARM64 version
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-arm64.tgz
sudo mv aliyun /usr/local/bin/Windows
Using Binary 1. Download from: https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip 2. Extract the ZIP file 3. Add the directory to your PATH environment variable 4. Open new Command Prompt or PowerShell 5. Verify: aliyun version
Using PowerShell
# Download
Invoke-WebRequest -Uri "https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip" -OutFile "aliyun-cli.zip"
# Extract
Expand-Archive -Path aliyun-cli.zip -DestinationPath C:\aliyun-cli
# Add to PATH (requires admin privileges)
$env:Path += ";C:\aliyun-cli"
[Environment]::SetEnvironmentVariable("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)
# Verify
aliyun versionConfiguration
Quick Start
aliyun configure set \
--mode AK \
--access-key-id <your-access-key-id> \
--access-key-secret <your-access-key-secret> \
--region cn-hangzhouAll aliyun configure commands support non-interactive flags, which is the recommended approach — it works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.
Where to Get Access Keys
1. Log in to Aliyun Console: https://ram.console.aliyun.com/ 2. Navigate to: AccessKey Management 3. Create a new AccessKey pair 4. Save the secret immediately — it's only shown once
Configuration Modes
Aliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.
1. AK Mode (Access Key)
Most common mode for personal accounts and scripts.
aliyun configure set \
--mode AK \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--region cn-hangzhouConfiguration is stored in ~/.aliyun/config.json:
{
"current": "default",
"profiles": [
{
"name": "default",
"mode": "AK",
"access_key_id": "LTAI5tXXXXXXXX",
"access_key_secret": "8dXXXXXXXXXXXXXXXXXXXXXXXX",
"region_id": "cn-hangzhou",
"output_format": "json",
"language": "en"
}
]
}2. StsToken Mode (Temporary Credentials)
For short-lived access (tokens expire in 1-12 hours).
aliyun configure set \
--mode StsToken \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--sts-token v1.0:XXXXXXXXXXXXXXXX \
--region cn-hangzhouUse cases: CI/CD pipelines, temporary access for external contractors, cross-account access.
3. RamRoleArn Mode (Assume RAM Role)
Assume a RAM role for elevated or cross-account access.
aliyun configure set \
--mode RamRoleArn \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--ram-role-arn acs:ram::123456789012:role/AdminRole \
--role-session-name my-session \
--region cn-hangzhouUse cases: cross-account resource access, temporary elevated privileges, role-based access control.
4. EcsRamRole Mode (ECS Instance RAM Role)
Use the RAM role attached to an ECS instance — no credentials needed.
aliyun configure set \
--mode EcsRamRole \
--ram-role-name MyEcsRole \
--region cn-hangzhouRequirements: must be running on an ECS instance with a RAM role attached.
Use cases: scripts and automation running on ECS instances.
5. RsaKeyPair Mode (RSA Key Pair)
Use RSA key pair for authentication (generate key pair in Aliyun Console first).
aliyun configure set \
--mode RsaKeyPair \
--private-key /path/to/private-key.pem \
--key-pair-name my-key-pair \
--region cn-hangzhou6. RamRoleArnWithEcs Mode (ECS + RAM Role)
Combine ECS instance role with RAM role assumption for cross-account access from ECS.
aliyun configure set \
--mode RamRoleArnWithEcs \
--ram-role-name MyEcsRole \
--ram-role-arn acs:ram::123456789012:role/TargetRole \
--role-session-name my-session \
--region cn-hangzhouEnvironment Variables
Highest priority - overrides config file
Access Key Mode
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_REGION_ID=cn-hangzhouSTS Token Mode
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token
export ALIBABA_CLOUD_REGION_ID=cn-hangzhouECS RAM Role Mode
export ALIBABA_CLOUD_ECS_METADATA=role_nameUse Case:
- CI/CD pipelines
- Docker containers
- Temporary credential override
Managing Multiple Profiles
Create Named Profiles
aliyun configure set --profile projectA \
--mode AK \
--access-key-id LTAI5tAAAAAAAA \
--access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \
--region cn-hangzhou
aliyun configure set --profile projectB \
--mode AK \
--access-key-id LTAI5tBBBBBBBB \
--access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \
--region cn-shanghaiUse Specific Profile
aliyun ecs describe-instances --profile projectA
export ALIBABA_CLOUD_PROFILE=projectA
aliyun ecs describe-instances # Uses projectAList and Switch Profiles
aliyun configure list # List all profiles
aliyun configure set --current projectA # Switch default profileCredential Priority
Credentials are loaded in this order (first found wins):
1. Command-line flag: --profile <name> 2. Environment variable: ALIBABA_CLOUD_PROFILE 3. Environment credentials: ALIBABA_CLOUD_ACCESS_KEY_ID, etc. 4. Configuration file: ~/.aliyun/config.json (current profile) 5. ECS Instance RAM Role: If running on ECS with attached role
Verification
Test Authentication
# Basic test - list regions
aliyun ecs describe-regions
# Expected output: JSON array of regionsIf successful, you'll see:
{
"Regions": {
"Region": [
{
"RegionId": "cn-hangzhou",
"RegionEndpoint": "ecs.cn-hangzhou.aliyuncs.com",
"LocalName": "华东 1(杭州)"
},
...
]
},
"RequestId": "..."
}If failed, you'll see error messages:
InvalidAccessKeyId.NotFound- Wrong Access Key IDSignatureDoesNotMatch- Wrong Access Key SecretInvalidSecurityToken.Expired- STS token expired (for StsToken mode)Forbidden.RAM- Insufficient permissions
Debug Configuration
# Show current configuration
aliyun configure get
# Test with debug logging
aliyun ecs describe-regions --log-level=debug
# Check credential provider
aliyun configure get modeSecurity Best Practices
1. Use RAM Users (Not Root Account)
❌ Don't: Use Aliyun root account credentials ✅ Do: Create RAM users with specific permissions
# Create RAM user in console
# Attach only necessary policies
# Use RAM user's access keys2. Principle of Least Privilege
Grant only the minimum permissions needed:
# Example: Read-only ECS access
# Attach policy: AliyunECSReadOnlyAccess3. Rotate Access Keys Regularly
# Create new access key in RAM Console, then update configuration
aliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET
# Delete old access key from console4. Use STS Tokens for Temporary Access
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token XXXX --region cn-hangzhou5. Use ECS RAM Roles When Possible
aliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou6. Never Commit Credentials
# Add to .gitignore
echo "~/.aliyun/config.json" >> .gitignore
# Use environment variables in CI/CD instead7. Secure Config File
# Restrict permissions
chmod 600 ~/.aliyun/config.jsonTroubleshooting
Issue: Command Not Found
# Check installation
which aliyun
# Check PATH
echo $PATH
# Reinstall or add to PATHIssue: Authentication Failed
# Verify configuration
aliyun configure get
# Test with debug
aliyun ecs describe-regions --log-level=debug
# Check credentials in console
# Verify access key is activeIssue: Permission Denied
# Error: Forbidden.RAM
# Check RAM user permissions
# Attach necessary policies in RAM console
# Example: AliyunECSFullAccess for ECS operationsIssue: STS Token Expired
# Error: InvalidSecurityToken.Expired
# Reconfigure with new token
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token NEW_TOKEN --region cn-hangzhouIssue: Wrong Region
# Some resources may not exist in the specified region
# Check available regions
aliyun ecs describe-regions
# Update default region
aliyun configure set region cn-shanghaiAdvanced Configuration
Custom Endpoint
# Use custom or private endpoint
export ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.comProxy Settings
# HTTP proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
# No proxy for specific domains
export NO_PROXY=localhost,127.0.0.1,.aliyuncs.comTimeout Settings
# Connection timeout (default: 10s)
export ALIBABA_CLOUD_CONNECT_TIMEOUT=30
# Read timeout (default: 10s)
export ALIBABA_CLOUD_READ_TIMEOUT=30Next Steps
After installation and configuration:
1. Install plugins for services you need (v3.3.3+ supports all published product plugins):
aliyun plugin install --names ecs vpc rds
# List all available plugins
aliyun plugin list-remote2. Explore commands:
aliyun ecs --help
aliyun fc --help3. Read documentation:
- Command Syntax Guide
- Global Flags Reference
- Common Scenarios
References
- Official Documentation: https://help.aliyun.com/zh/cli/
- RAM Console: https://ram.console.aliyun.com/
- Access Key Management: https://ram.console.aliyun.com/manage/ak
- Plugin Repository: https://github.com/aliyun/aliyun-cli
Resource Center API error codes
| StatusCode | Code | Message |
|---|---|---|
| 400 | DependencyViolation.Config | ResourceCenter cannot be disabled, because the Config has been enabled. |
| 400 | DependencyViolation.ResourceGroup | Unable to disable resource center while associate transfer is enabled. |
| 400 | DiscoveryInProgress | A discovery task is in progress. Please wait for a while and check the result again. |
| 400 | InvalidParameter.AccountId | The specified parameter AccountId is not valid. |
| 400 | InvalidParameter.Filter.CreateTime | The specified parameter Filter.n.CreateTime is not valid. |
| 400 | InvalidParameter.Filter.IpAddress | The specified parameter Filter.n.IpAddress is not valid. |
| 400 | InvalidParameter.Filter.ResourceType | The specified parameter value of Filter.ResourceType is not valid. |
| 400 | InvalidParameter.Filter.Tag | The specified parameter Filter.n.Tag is not valid. |
| 400 | InvalidParameter.MaxResults | The specified parameter MaxResults is not valid. |
| 400 | MissingParameter.AccountScope | The specified parameter AccountScope is missing. |
| 400 | MultiAccountServiceNotEnabled | Multi account ResourceCenter service is not enabled. |
| 400 | NoPermission | You are not authorized to perform this operation. |
| 400 | NoPermission.ServiceLinkedRole | The current user does not have permission to create servicelinkedrole. Please contact the Alibaba Cloud account or administrator to authorize custom policy: Service Name: rmc.resourcemanager.aliyuncs.com, Action: ram:CreateServiceLinkedRole. |
| 400 | ServiceNotEnabled | ResourceCenter Service is not enabled. |
| 403 | NoPermission.AccountScope | The operator is not permitted for this account scope. |
| 404 | NotExists.Account | The specified account does not exist. |
| 404 | NotExists.Resource | The specified resource does not exist. |
| 404 | NotExists.ResourceDirectory | The resource directory for the account is not enabled. |
| 404 | NotExists.ResourceDirectory.FolderId | The specified folder does not exist. |
| 409 | Conflict.ServiceStatus | The service status conflict occurred due to frequent service enabled and disabled. |
| 409 | DisableConflict.DeliveryChannel | ResourceCenter cannot be disabled because there are active delivery channels. |
| 409 | DisableConflict.MultiAccount | ResourceDirectory management account or delegated administrator account has enabled multi account ResourceCenter, you cannot disable ResourceCenter. |
| 409 | ExceedLimit.Filter | The maximum length of Filters is exceeded. |
| 409 | InvalidParameter.AccountId | The specified parameter AccountId is not valid. |
| 409 | InvalidParameter.MatchType | The specified parameter MatchType is not valid. |
| 409 | InvalidParameter.ResourceType | The specified parameter ResourceType is not valid. |
| 409 | InvalidParameter.Scope | The Scope is invalid. |
| 409 | InvalidParameter.SortCriterion.Key | The specified parameter SortCriterion.Key is not valid. |
| 409 | NoPermission.ResourceDirectory.MemberAccount | ResourceDirectory Member Account is not authorized to perform this operation. For more detail, see Manage a delegated administrator account of Resource Center |
| 409 | NotSupport.Account.Site | The caller is not a current site account, which is not supported. |
| 409 | ServiceNotEnabled.SpecifiedAccount | ResourceCenter service of the specified account is not enabled. |
RAM Policies - Resource Center
Required Permissions
Single Account Operations
The following are the minimum RAM permissions required for single-account resource search and inventory:
resourcecenter:EnableResourceCenter resourcecenter:DisableResourceCenter resourcecenter:GetResourceConfiguration tag:ListTagKeys tag:ListTagValues
Cross-Account Operations (Requires Resource Directory Management Account or Delegated Admin)
The following are the RAM permissions required for cross-account resource search and inventory (must be executed by the Resource Directory management account or delegated admin account):
resourcecenter:EnableMultiAccountResourceCenter resourcecenter:DisableMultiAccountResourceCenter resourcecenter:GetMultiAccountResourceCenterServiceStatus resourcecenter:SearchMultiAccountResources resourcecenter:GetMultiAccountResourceCounts resourcecenter:GetMultiAccountResourceConfiguration
Read-Only Policy (Recommended for Search & Statistics Only)
If only search and statistics functionality is needed, the following read-only permissions can be used:
resourcecenter:GetResourceConfiguration resourcecenter:GetMultiAccountResourceCenterServiceStatus resourcecenter:SearchMultiAccountResources resourcecenter:GetMultiAccountResourceCounts resourcecenter:GetMultiAccountResourceConfiguration tag:ListTagKeys tag:ListTagValues
System Role
When enabling Resource Center, the system automatically creates the service-linked role AliyunServiceRoleForResourceMetaCenter. This role is used by Resource Center to call resource query or list APIs from cloud services to obtain resource metadata information.
Notes
- Enabling/disabling the Resource Center service requires an Alibaba Cloud account or a RAM user with
EnableResourceCenter/DisableResourceCenterpermissions - Cross-account operations must use the Resource Directory management account or Resource Center delegated admin account
- It is recommended to use the system policy
AliyunResourceCenterReadOnlyAccessfor read-only access - It is recommended to use the system policy
AliyunResourceCenterFullAccessfor full access
Related APIs - Resource Center
Single Account Operations
enable-resource-center
Enable Resource Center service.
Usage
# Enable Resource Center service
aliyun resourcecenter enable-resource-center \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
disable-resource-center
Disable Resource Center service.
Usage
# Disable Resource Center service
aliyun resourcecenter disable-resource-center \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
get-resource-center-service-status
Query Resource Center service status.
Usage
# Check if Resource Center is enabled
aliyun resourcecenter get-resource-center-service-status \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
search-resources
Search resources under the current account.
| Parameter | Required | Default Value | Description |
|---|---|---|---|
--filter | No | None | Filter conditions. Structure: [{Key: string, MatchType: string, Value: [string, ...]}, ...]. See Filter Parameter Definition below for supported Key and MatchType combinations |
--include-deleted-resources | No | false | Whether to include deleted resources |
--max-results | No | 20 | Maximum number of entries per page. Valid values: 1~500 |
--next-token | No | None | Token for querying the next page of results |
--resource-group-id | No | None | Resource group ID |
--sort-criterion | No | None | Sorting parameters. Structure: {Key: string, Order: string} |
Usage
# Search all resources (paginated)
aliyun resourcecenter search-resources \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search
# Search by resource type (ECS instances)
aliyun resourcecenter search-resources \
--filter '[{"Key":"ResourceType","MatchType":"Equals","Value":["ACS::ECS::Instance"]}]' \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search
# Combined search: ECS + Hangzhou region
aliyun resourcecenter search-resources \
--filter '[{"Key":"ResourceType","MatchType":"Equals","Value":["ACS::ECS::Instance"]},{"Key":"RegionId","MatchType":"Equals","Value":["cn-hangzhou"]}]' \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search
# Search by tag (Environment=Production)
aliyun resourcecenter search-resources \
--filter '[{"Key":"Tag","MatchType":"Contains","Value":["{\"key\":\"env\",\"value\":\"prod\"}"]}]' \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search
# Find untagged resources
aliyun resourcecenter search-resources \
--filter '[{"Key":"Tag","MatchType":"NotExists"}]' \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search
# Search including deleted resources (for auditing or recovery)
aliyun resourcecenter search-resources \
--include-deleted-resources=true \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
get-resource-counts
Query resource count statistics for the current account.
| Parameter | Required | Default Value | Description |
|---|---|---|---|
--filter | No | None | Filter conditions. Structure: [{Key: string, MatchType: string, Value: [string, ...]}, ...]. See Filter Parameter Definition below for supported Key and MatchType combinations |
--group-by-key | No | None | Grouping dimension for resource count statistics. Valid values: ResourceType, RegionId, ResourceGroupId |
--include-deleted-resources | No | false | Whether to include deleted resources |
Usage
# Count by resource type
aliyun resourcecenter get-resource-counts \
--group-by-key ResourceType \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search
# Count by region
aliyun resourcecenter get-resource-counts \
--group-by-key RegionId \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search
# Count ECS instance distribution by region
aliyun resourcecenter get-resource-counts \
--group-by-key RegionId \
--filter '[{"Key":"ResourceType","MatchType":"Equals","Value":["ACS::ECS::Instance"]}]' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
get-resource-configuration
Query single resource configuration details for the current account.
| Parameter | Required | Default Value | Description |
|---|---|---|---|
--resource-id | Yes | None | Resource ID |
--resource-region-id | Yes | None | Region ID. (e.g., cn-hangzhou) |
--resource-type | Yes | None | Resource type. You can use the scripts/query-resource-types.py script to query accurate resource type codes. (e.g., ACS::ECS::Instance) |
Usage
# Get single ECS instance configuration
aliyun resourcecenter get-resource-configuration \
--resource-type ACS::ECS::Instance \
--resource-region-id cn-hangzhou \
--resource-id i-bp1xxx \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
batch-get-resource-configurations
Batch query resource configurations for the current account.
| Parameter | Required | Default Value | Description |
|---|---|---|---|
--resources | No | None | List of resources. Structure: {RegionId: string, ResourceId: string, ResourceType: string}. Format: --resources RegionId=a ResourceId=b ResourceType=c |
Usage
# Batch get multiple instance configurations
aliyun resourcecenter batch-get-resource-configurations \
--resources RegionId=cn-hangzhou ResourceId=vtb-xxx ResourceType=ACS::VPC::RouteTable \
--resources RegionId=cn-shanghai ResourceId=sg-xxx ResourceType=ACS::ECS::SecurityGroup \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
list-tag-keys
Query tag keys under the current account.
| Parameter | Required | Default Value | Description |
|---|---|---|---|
--match-type | No | None | Match type. Valid values: Equals, Prefix |
--max-results | No | 20 | Maximum number of entries per page. Valid values: 1~100 |
--next-token | No | None | Token for querying the next page of results |
--tag-key | No | None | Tag key |
Usage
# List all tag keys
aliyun resourcecenter list-tag-keys \
--max-results 100 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
list-tag-values
Query tag values under the current account.
| Parameter | Required | Default Value | Description |
|---|---|---|---|
--tag-key | Yes | None | Tag key |
--match-type | No | None | Match type. Valid values: Equals, Prefix |
--max-results | No | 20 | Maximum number of entries per page. Valid values: 1~100 |
--next-token | No | None | Token for querying the next page of results |
--tag-value | No | None | Tag value |
Usage
# List all values for env tag
aliyun resourcecenter list-tag-values \
--tag-key env \
--max-results 100 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
Cross-Account Operations (Requires Resource Directory)
enable-multi-account-resource-center
Enable cross-account resource search.
Usage
# Enable cross-account resource search
aliyun resourcecenter enable-multi-account-resource-center \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
disable-multi-account-resource-center
Disable cross-account resource search.
Usage
# Disable cross-account resource search
aliyun resourcecenter disable-multi-account-resource-center \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
get-multi-account-resource-center-service-status
Query cross-account resource search service status.
Usage
# Check cross-account Resource Center status
aliyun resourcecenter get-multi-account-resource-center-service-status \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
search-multi-account-resources
Search resources across accounts.
| Parameter | Required | Default Value | Description |
|---|---|---|---|
--scope | Yes | None | Search scope. Valid values: Resource Directory ID, Root Folder ID, Folder ID, or Member ID |
--filter | No | None | Filter conditions. Structure: [{Key: string, MatchType: string, Value: [string, ...]}, ...]. See Filter Parameter Definition below for supported Key and MatchType combinations |
--max-results | No | 20 | Maximum number of entries per page. Valid values: 1~100 |
--next-token | No | None | Token for querying the next page of results |
--sort-criterion | No | None | Sorting parameters. Structure: {Key: string, Order: string} |
Usage
# Cross-account resource search
aliyun resourcecenter search-multi-account-resources \
--scope <ResourceDirectoryId> \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
get-multi-account-resource-counts
Query resource count statistics across accounts.
| Parameter | Required | Default Value | Description |
|---|---|---|---|
--scope | No | None | Search scope. Valid values: Resource Directory ID, Root Folder ID, Folder ID, or Member ID |
--filter | No | None | Filter conditions. Structure: [{Key: string, MatchType: string, Value: [string, ...]}, ...]. See Filter Parameter Definition below for supported Key and MatchType combinations |
--group-by-key | No | None | Grouping dimension for resource count statistics. Valid values: ResourceType, RegionId, ResourceGroupId |
Usage
# Cross-account count by resource type
aliyun resourcecenter get-multi-account-resource-counts \
--scope <ResourceDirectoryId> \
--group-by-key ResourceType \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
get-multi-account-resource-configuration
Query single resource configuration across accounts.
| Parameter | Required | Default Value | Description |
|---|---|---|---|
--account-id | Yes | None | Resource Directory management account ID or member ID |
--resource-id | Yes | None | Resource ID |
--resource-region-id | Yes | None | Region ID. (e.g., cn-hangzhou) |
--resource-type | Yes | None | Resource type. You can use the scripts/query-resource-types.py script to query accurate resource type codes. (e.g., ACS::ECS::Instance) |
Usage
# Get cross-account resource configuration
aliyun resourcecenter get-multi-account-resource-configuration \
--account-id <AccountId> \
--resource-type ACS::ECS::Instance \
--resource-region-id cn-hangzhou \
--resource-id i-bp1xxx \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
list-multi-account-tag-keys
Query tag keys across accounts.
| Parameter | Required | Default Value | Description |
|---|---|---|---|
--scope | Yes | None | Search scope. Valid values: Resource Directory ID, Root Folder ID, Folder ID, or Member ID |
--match-type | No | None | Match type. Valid values: Equals, Prefix |
--max-results | No | 20 | Maximum number of entries per page. Valid values: 1~100 |
--next-token | No | None | Token for querying the next page of results |
--tag-key | No | None | Tag key |
Usage
# Cross-account list tag keys
aliyun resourcecenter list-multi-account-tag-keys \
--scope <ResourceDirectoryId> \
--max-results 100 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
list-multi-account-tag-values
Query tag values across accounts.
| Parameter | Required | Default Value | Description |
|---|---|---|---|
--tag-key | Yes | None | Tag key |
--scope | No | None | Search scope. Valid values: Resource Directory ID, Root Folder ID, Folder ID, or Member ID |
--match-type | No | None | Match type. Valid values: Equals, Prefix |
--max-results | No | 20 | Maximum number of entries per page. Valid values: 1~100 |
--next-token | No | None | Token for querying the next page of results |
--tag-value | No | None | Tag value |
Usage
# Cross-account list tag values
aliyun resourcecenter list-multi-account-tag-values \
--scope <ResourceDirectoryId> \
--tag-key env \
--max-results 100 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search---
Filter Parameter Definition
Multiple array elements are combined with logical AND
Filter Parameter Validation Rules — The--filterparameter usesKey+MatchType+Valuestructure. MUST follow the allowed combinations below. Using unsupportedMatchTypefor aKeywill cause API errors.
| Filter Key | Supported MatchType | Description |
|---|---|---|
ResourceType | Equals | Exact match on resource type code (e.g., ACS::ECS::Instance) |
RegionId | Equals | Exact match on region ID (e.g., cn-hangzhou) |
ResourceId | Equals, Prefix | Exact or prefix match on resource ID |
ResourceGroupId | Equals, Exists, NotExists | Exact match or existence check on resource group ID |
ResourceName | Equals, Contains | Exact match or substring match (Contains) on resource name |
Tag | Contains, NotContains, NotExists | Tag-based filtering: contains specific tag, excludes tag, or untagged resources |
VpcId | Equals | Exact match on VPC ID |
VSwitchId | Equals | Exact match on VSwitch ID |
IpAddress | Equals, Contains | Exact match or substring match (Contains) on IP address |
Tag filter examples (JSON array for --filter):
1. `Contains` and `NotContains` — Use the same Value shape: a JSON string for the tag (key-only or key+value).
# key-only
[{"Key":"Tag","MatchType":"Contains","Value":["{\"key\":\"env\"}"]}]
# key+value
[{"Key":"Tag","MatchType":"NotContains","Value":["{\"key\":\"env\",\"value\":\"prod\"}"]}]2. `NotExists` — resources that have no user tags (untagged). Use only Key and MatchType; do not pass Value.
[{"Key":"Tag","MatchType":"NotExists"}]Verification Method - Resource Center
Step 1: Verify Resource Center is Enabled
aliyun resourcecenter get-resource-center-service-status \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-searchExpected Output:
{
"ServiceStatus": "Enabled",
"InitialStatus": "Finished",
"RequestId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}ServiceStatusbeingEnabledindicates that Resource Center is activated.InitialStatusbeingFinishedindicates that Resource index is completed.
Response fields (per API definition):
| Field | Meaning | Values |
|---|---|---|
ServiceStatus | Whether Resource Center is turned on for the account. | Enabled — service is enabled. Disabled — service is disabled. |
InitialStatus | Whether initial resource metadata indexing is complete (only relevant when the service is enabled). | Pending — still preparing. Finished — ready (indexing complete). |
RequestId | Request identifier for tracing. | Opaque string. |
How to interpret results:
- `ServiceStatus: Enabled` — Resource Center is activated; you may call search and statistics APIs.
- `InitialStatus: Pending` — Data is still being built after enablement (or a large inventory is catching up). Search or counts may be empty or incomplete; poll this API until
InitialStatusbecomesFinishedbefore treating failures as permission or configuration issues. Allow several minutes (large accounts may take longer), consistent with the main skill workflow. - `InitialStatus: Finished` — Metadata is ready; search and
GetResourceCountsresults should reflect inventory within normal service behavior. - `ServiceStatus: Disabled` — Enable Resource Center first (
enable-resource-center);InitialStatusis not applicable for operational search until the service is enabled.
Step 2: Verify Resource Search is Working
aliyun resourcecenter search-resources \
--max-results 5 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-searchExpected Output: Returns JSON containing a Resources array, where each resource includes fields such as ResourceId, ResourceType, RegionId, etc.
Step 3: Verify Resource Count Statistics
aliyun resourcecenter get-resource-counts \
--group-by-key ResourceType \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-searchExpected Output: Returns JSON containing a Filters array, where each item includes FilterKey (resource type) and FilterValue (count).
Step 4: Verify Cross-Account Resource Center Status (If Applicable)
This step is only applicable for management accounts that have set up a Resource Directory.
aliyun resourcecenter get-multi-account-resource-center-service-status \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-searchExpected Output:
{
"ServiceStatus": "Enabled",
"RequestId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}Step 5: Verify Cross-Account Resource Search (If Applicable)
The --scope parameter is required (Resource Directory ID, Root Folder ID, Folder ID, or Member ID).aliyun resourcecenter search-multi-account-resources \
--scope <ResourceDirectoryId> \
--max-results 5 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-searchExpected Output: Returns JSON containing a Resources array with resources from multiple member accounts.
Step 6: Verify Cross-Account Resource Count Statistics (If Applicable)
aliyun resourcecenter get-multi-account-resource-counts \
--scope <ResourceDirectoryId> \
--group-by-key ResourceType \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-searchExpected Output: Returns resource count statistics aggregated across multiple member accounts.
Common Failure Scenarios
| Symptom | Cause | Fix |
|---|---|---|
ServiceStatus: Disabled | Resource Center not enabled | Execute enable-resource-center |
ResourceNotFound | Resource Center service not activated | Enable Resource Center first |
NoPermission | Insufficient RAM permissions | Add corresponding RAM policies |
ForbiddenMultiAccountResourceCenter | Non-management account performing cross-account operations | Use Resource Directory management account |
Empty Resources array | Resource Center data is still building (InitialStatus may be Pending) or filters exclude all resources | Re-run Step 1; if InitialStatus is Pending, wait and poll until Finished, then retry search |
#!/usr/bin/env python3
"""
Script to query resource types by keyword from Alibaba Cloud Resource Center.
This script helps you find resource type codes by searching across ResourceType,
ProductName, and ResourceTypeName fields. Results are printed as JSON on stdout.
Usage:
python3 scripts/query-resource-types.py [keyword] [--language LANGUAGE]
Examples:
# Query all resource types
python3 scripts/query-resource-types.py
# Query with keyword (case-insensitive)
python3 scripts/query-resource-types.py ecs
python3 scripts/query-resource-types.py vpc --language en-US
# Example success output:
# {"success":true,"language":"zh-CN","keyword":"ecs","count":1,"resourceTypes":[...]}
JSON output (stdout, UTF-8):
success (bool): true on API success; false on fetch/CLI failure (then also ``error``).
language (str): Same as ``--language`` (only when success).
keyword (str|null): Search keyword, or null when listing all types (only when success).
count (int): Length of ``resourceTypes`` (only when success).
resourceTypes (list[object]): Sorted matches; each object has:
resourceType (str): Resource type code, e.g. ``ACS::ECS::Instance`` (maps to API ``ResourceType``).
productName (str): Product display name (maps to API ``ProductName``).
resourceTypeName (str): Resource type display name (maps to API ``ResourceTypeName``).
hints (list[str], optional): Present when ``success`` and ``count == 0``; search tips.
On failure: ``error`` (str) and optional ``checks`` (list[str]) for common fixes.
Note: Run from the skill's root directory.
"""
import sys
import json
import subprocess
import argparse
from typing import Optional, List, Dict, Tuple, Any
def fetch_resource_types(language: str = "zh-CN") -> Tuple[Optional[dict], Optional[str]]:
"""
Run Aliyun CLI list-resource-types and return parsed JSON.
Filtering by keyword is done in Python so all three fields
(ResourceType, ProductName, ResourceTypeName) stay searchable.
Args:
language: Language for resource labels (e.g. 'zh-CN', 'en-US').
Returns:
(parsed JSON dict, None) on success, or (None, error message) on failure.
"""
cmd = [
"aliyun", "resourcecenter", "list-resource-types",
"--accept-language", language,
"--user-agent", "AlibabaCloud-Agent-Skills/alibabacloud-resourcecenter-search",
"--query", "ProductName", "ResourceTypeName", "ResourceType",
]
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=60,
)
if result.returncode != 0:
msg = result.stderr.strip() or f"aliyun CLI exited with code {result.returncode}"
return None, f"CLI error: {msg}"
return json.loads(result.stdout), None
except FileNotFoundError:
return None, (
"'aliyun' CLI not found. Install Alibaba Cloud CLI and ensure it is on PATH."
)
except subprocess.TimeoutExpired:
return None, "Command timed out after 60 seconds"
except json.JSONDecodeError as e:
return None, f"JSON decode error: {e}"
except Exception as e:
return None, str(e)
def filter_resource_types(data: dict, keyword: str) -> List[Dict[str, str]]:
"""
Filter resource types by keyword.
Args:
data: The API response containing resource types
keyword: Search keyword (case-insensitive)
Returns:
List of dicts with keys resourceType, productName, resourceTypeName
"""
keyword_lower = keyword.lower()
matched: List[Dict[str, str]] = []
resource_types = data.get("ResourceTypes", [])
for rt in resource_types:
resource_type = rt.get("ResourceType", "")
product_name = rt.get("ProductName", "")
type_name = rt.get("ResourceTypeName", "")
if (
keyword_lower in resource_type.lower()
or keyword_lower in product_name.lower()
or keyword_lower in type_name.lower()
):
matched.append(
{
"resourceType": resource_type,
"productName": product_name,
"resourceTypeName": type_name,
}
)
return matched
def all_resource_types_as_records(data: dict) -> List[Dict[str, str]]:
"""Build resource type records from full API response (no keyword filter)."""
return [
{
"resourceType": rt.get("ResourceType", ""),
"productName": rt.get("ProductName", ""),
"resourceTypeName": rt.get("ResourceTypeName", ""),
}
for rt in data.get("ResourceTypes", [])
]
def empty_result_hints(keyword: Optional[str]) -> List[str]:
"""Human-oriented hints when the result set is empty."""
if keyword is None:
return [
"Retry with a different --language if needed",
]
return [
"Try different keywords (e.g., product abbreviations like ECS, VPC, OSS)",
"Use English keywords for better matching",
"Run with a broader keyword or omit keyword to list all types",
]
def emit_json(payload: dict) -> None:
"""Print JSON to stdout with UTF-8 support."""
print(json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
def main():
parser = argparse.ArgumentParser(
description="Query resource types by keyword from Alibaba Cloud Resource Center (JSON output)"
)
parser.add_argument(
"keyword",
type=str,
nargs="?",
default=None,
help="Search keyword for filtering resource types (optional, omit to query all types)",
)
parser.add_argument(
"--language",
type=str,
default="zh-CN",
choices=["zh-CN", "en-US"],
help="Language for resource information (default: zh-CN, options: zh-CN, en-US)",
)
args = parser.parse_args()
data, err = fetch_resource_types(args.language)
if err is not None:
emit_json(
{
"success": False,
"error": err,
"checks": [
"Aliyun CLI is installed and configured",
"Resource Center service is enabled",
"Caller has proper permissions",
],
},
)
sys.exit(1)
if args.keyword:
matched = filter_resource_types(data, args.keyword)
else:
matched = all_resource_types_as_records(data)
matched.sort(key=lambda r: (r["resourceType"], r["productName"], r["resourceTypeName"]))
payload: Dict[str, Any] = {
"success": True,
"language": args.language,
"keyword": args.keyword,
"count": len(matched),
"resourceTypes": matched,
}
if not matched:
payload["hints"] = empty_result_hints(args.keyword)
emit_json(payload)
if __name__ == "__main__":
main()