
Alibabacloud Polardb Ai Assistant
- 175 installs
- 208 repo stars
- Updated August 4, 2026
- aliyun/alibabacloud-aiops-skills
Tune PolarDB clusters, explain slow queries, and automate routine DBA tasks via Alibaba Cloud AI assistant workflows inside Claude Code.
About
alibabacloud-polardb-ai-assistant equips Claude Code to operate Alibaba Cloud PolarDB using AI-guided diagnostics, SQL optimization, and maintenance playbooks. It targets production DBA workflows—index advice, parameter tuning, and health checks—through the alibabacloud-aiops-skills repo.
- PolarDB-specific AI guidance
- Slow-query analysis and tuning
- Capacity and scaling recommendations
- Routine DBA task automation
- Alibaba Cloud console-aligned ops
Alibabacloud Polardb Ai Assistant by the numbers
- 175 all-time installs (skills.sh)
- Ranked #242 of 911 Databases 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-polardb-ai-assistantAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 175 |
|---|---|
| repo stars | ★ 208 |
| Last updated | August 4, 2026 |
| Repository | aliyun/alibabacloud-aiops-skills ↗ |
What it does
Tune PolarDB clusters, explain slow queries, and automate routine DBA tasks via Alibaba Cloud AI assistant workflows inside Claude Code.
Files
PolarDB Database AI Assistant
This Skill focuses on Alibaba Cloud PolarDB MySQL/PostgreSQL database intelligent O&M, invoking the get-yao-chi-agent API through the aliyun CLI DAS plugin for diagnostics and analysis.
Architecture: Aliyun CLI → DAS Plugin (Signature V3) → get-yao-chi-agent API → PolarDB Intelligent Diagnostics
Supported Capabilities
| Capability | Description |
|---|---|
| PolarDB Primary-Standby Switchover Analysis | Failover cause investigation, switchover log analysis, unexpected Failover diagnostics |
| PolarDB Kernel Parameter Change Assessment | Impact assessment before parameter modification, change risk analysis |
| PolarDB Kernel Parameter Explanation | Parameter meaning explanation, configuration suggestions, performance impact analysis |
| PolarDB Kernel Parameter Explanation (IMCI) | IMCI columnar engine related parameter explanation |
| PolarDB Kernel Version Proxy Diagnostics | Proxy layer troubleshooting, version compatibility diagnostics |
| PolarDB Kernel Version Instance Diagnostics | Instance layer version issue diagnostics, upgrade suggestions |
| Instance Query Filter | PolarDB instance search and filtering |
| Proxy Performance Monitoring | Proxy layer performance metrics analysis, connection routing diagnostics |
| Serverless Configuration | Serverless instance parameters and elastic scaling configuration |
| SQL Optimization Analysis | Slow SQL analysis, index suggestions, execution plan interpretation |
| Expiring Instance Query | Subscription instance expiration reminder |
| Backup Status Check | Backup completion, retention policy, recovery point in time |
| Storage Usage Diagnostics | Storage consumption analysis, growth trends, space optimization suggestions |
| Security Configuration Audit | Whitelist, SSL, security policy audit |
| Instance Status Check | Instance health status, running status verification |
| Log Diagnostics | Error log analysis, slow log troubleshooting |
| Auto-Increment ID Overflow Detection | Auto-increment ID exhaustion risk detection, primary key overflow warning |
| Connection and Session Analysis | Connection count monitoring, session issue troubleshooting, connection pool optimization |
| Cluster Performance Monitoring | QPS/TPS/connections/throughput and other core metrics analysis |
| High Availability and Disaster Recovery | HA configuration assessment, disaster recovery architecture diagnostics |
Installation
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 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.[MUST] CLI User-Agent — Every aliyun CLI command invocation must include: --user-agent AlibabaCloud-Agent-Skills/alibabacloud-polardb-ai-assistant
[MUST] Enable AI-Mode — AI-mode is required for Agent Skill execution. Run the following commands before any CLI invocation:
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-polardb-ai-assistant"[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.
aliyun configure ai-mode disable# Install aliyun CLI
curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash
aliyun version # Verify >= 3.3.3
# Enable automatic plugin installation
aliyun configure set --auto-plugin-install true
# Install DAS plugin (get-yao-chi-agent requires plugin for Signature V3 support)
aliyun plugin install --names aliyun-cli-das
# Install jq (for JSON response parsing)
# macOS:
brew install jq
# Ubuntu/Debian:
# sudo apt-get install jqParameter 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 or use default values without explicit user approval.
| Parameter | Required/Optional | Description | Default |
|---|---|---|---|
query | Required | Natural language query content (including region, cluster info) | - |
--session-id | Optional | Session ID for multi-turn conversation | - |
--profile | Optional | aliyun CLI profile name | default |
Authentication
Credentials use existing aliyun CLI configuration, no additional AK/SK setup required:
# Recommended: OAuth mode
aliyun configure --mode OAuth
# Or: AK mode
aliyun configure set \
--mode AK \
--access-key-id <your-access-key-id> \
--access-key-secret <your-access-key-secret> \
--region cn-hangzhou
# Cross-account access: RamRoleArn mode
aliyun configure set \
--mode RamRoleArn \
--access-key-id <your-access-key-id> \
--access-key-secret <your-access-key-secret> \
--ram-role-arn acs:ram::<account-id>:role/<role-name> \
--role-session-name yaochi-agent-session \
--region cn-hangzhouRAM Policy
See references/ram-policies.md
Core Workflow
All intelligent O&M operations are invoked through scripts/call_yaochi_agent.sh, which wraps aliyun das get-yao-chi-agent (DAS plugin kebab-case command, supports Signature V3) with streaming response parsing.
# Cluster management
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "List PolarDB clusters in Hangzhou region"
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "Show detailed configuration of cluster pc-xxx"
# Performance diagnostics
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "Analyze cluster pc-xxx performance in the last hour"
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "Show slow SQL of cluster pc-xxx"
# Parameter tuning
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "How to tune innodb_buffer_pool_size for cluster pc-xxx"
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "Explain loose_polar_log_bin parameter"
# Primary-standby switchover diagnostics
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "Analyze recent primary-standby switchover cause for cluster pc-xxx"
# Connection and session
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "How to troubleshoot high connection count in cluster pc-xxx"
# Backup recovery
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "Show backup status of cluster pc-xxx"
# Multi-turn conversation (use session ID from previous response)
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "Continue analysis" --session-id "<session-id>"
# Specify profile
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "List clusters" --profile myprofile
# Read from stdin
echo "List clusters" | bash $SKILL_DIR/scripts/call_yaochi_agent.sh -Example Questions
| Scenario | Example Question |
|---|---|
| Cluster Management | List nodes of cluster pc-xxx |
| Performance Diagnostics | How to troubleshoot high CPU usage in cluster pc-xxx |
| Slow SQL Analysis | Show slow SQL in cluster pc-xxx in the last hour |
| Parameter Tuning | What does loose_polar_log_bin parameter mean |
| IMCI Parameters | How to configure IMCI related parameters for cluster pc-xxx |
| Primary-Standby | How to handle high primary-standby delay in cluster pc-xxx |
| Backup Recovery | When was the latest backup of cluster pc-xxx |
| Storage Optimization | What to do if storage usage of cluster pc-xxx grows too fast |
| Connection Troubleshooting | Cluster pc-xxx connections are full |
| Security Audit | Check security configuration of cluster pc-xxx |
Success Verification
See references/verification-method.md
Cleanup
This Skill focuses on query and diagnostics capabilities, does not create any resources, no cleanup required.
The following operations are NOT within the scope of this Skill:
- Create/delete PolarDB clusters
- Change instance specifications
- Purchase/renew instances
API and Command Tables
See references/related-apis.md
Best Practices
1. Cluster ID Format: PolarDB cluster IDs typically start with pc-, include the full cluster ID in queries 2. Region Specification: Explicitly specify region in natural language queries (e.g., "Hangzhou region", "Beijing region") to improve query accuracy 3. Multi-turn Conversation: Use --session-id for complex diagnostic scenarios to maintain context continuity 4. Concurrency Limit: Maximum 2 concurrent sessions per account, avoid initiating multiple parallel calls 5. High-risk Operations: For operations involving parameter changes, primary-standby switchover, always remind users to verify in test environment first 6. Throttling Handling: If encountering Throttling.UserConcurrentLimit error, wait for previous query to complete and retry 7. Credential Security: Use aliyun configure to manage credentials, never hardcode AK/SK in scripts
Reference Links
| Reference | Description |
|---|---|
| references/cli-installation-guide.md | Aliyun CLI installation and configuration guide |
| references/related-apis.md | Related API and CLI command list |
| references/ram-policies.md | RAM permission policy list |
| references/verification-method.md | Success verification methods |
| references/acceptance-criteria.md | Acceptance criteria |
Acceptance Criteria: alibabacloud-polardb-ai-assistant
Scenario: PolarDB Database AI Assistant Purpose: Skill testing acceptance criteria
---
Correct CLI Command Patterns
1. Product — DAS (Database Autonomy Service)
CORRECT
aliyun das GetYaoChiAgent --Query "List clusters" --Source "polardb-console" --endpoint das.cn-shanghai.aliyuncs.com --user-agent AlibabaCloud-Agent-SkillsINCORRECT
# Error: Product name spelling error
aliyun DAS GetYaoChiAgent --Query "List clusters"
# Error: Using non-existent plugin mode command
aliyun das get-yao-chi-agent --query "List clusters"Note: DAS product uses traditional API format (PascalCase), not plugin mode (kebab-case).
2. Command — GetYaoChiAgent
CORRECT
aliyun das GetYaoChiAgent --Query "Hello" --endpoint das.cn-shanghai.aliyuncs.com --user-agent AlibabaCloud-Agent-SkillsINCORRECT
# Error: API name spelling error
aliyun das GetYaochiAgent --Query "Hello"
# Error: Using non-existent API
aliyun das YaoChiAgent --Query "Hello"3. Parameters — Parameter Validation
GetYaoChiAgent Parameters
CORRECT
# Required parameter --Query
aliyun das GetYaoChiAgent --Query "List PolarDB clusters in Hangzhou region" --endpoint das.cn-shanghai.aliyuncs.com --user-agent AlibabaCloud-Agent-Skills
# Optional parameter --Source
aliyun das GetYaoChiAgent --Query "List clusters" --Source "polardb-console" --endpoint das.cn-shanghai.aliyuncs.com --user-agent AlibabaCloud-Agent-Skills
# Optional parameter --SessionId (multi-turn conversation)
aliyun das GetYaoChiAgent --Query "Continue analysis" --SessionId "sess-xxx" --Source "polardb-console" --endpoint das.cn-shanghai.aliyuncs.com --user-agent AlibabaCloud-Agent-Skills
# Optional parameter --ExtraInfo
aliyun das GetYaoChiAgent --Query "Show cluster" --ExtraInfo "{}" --endpoint das.cn-shanghai.aliyuncs.com --user-agent AlibabaCloud-Agent-SkillsINCORRECT
# Error: Missing required parameter --Query
aliyun das GetYaoChiAgent --Source "polardb-console"
# Error: Parameter name in lowercase (CLI parameter names are case-sensitive)
aliyun das GetYaoChiAgent --query "List clusters"
# Error: Parameter name spelling error
aliyun das GetYaoChiAgent --Query "List clusters" --Session-Id "sess-xxx"
# Error: Using non-existent parameter
aliyun das GetYaoChiAgent --Query "List clusters" --RegionId "cn-hangzhou"4. Endpoint — Endpoint Validation
CORRECT
# GetYaoChiAgent uses cn-shanghai endpoint uniformly
aliyun das GetYaoChiAgent --Query "List clusters" --endpoint das.cn-shanghai.aliyuncs.com --user-agent AlibabaCloud-Agent-SkillsINCORRECT
# Error: Using wrong endpoint
aliyun das GetYaoChiAgent --Query "List clusters" --endpoint das.cn-beijing.aliyuncs.com
# Error: Endpoint not specified, may use wrong default endpoint
aliyun das GetYaoChiAgent --Query "List clusters"5. --user-agent Flag — Must Include
CORRECT
aliyun das GetYaoChiAgent --Query "List clusters" --endpoint das.cn-shanghai.aliyuncs.com --user-agent AlibabaCloud-Agent-SkillsINCORRECT
# Error: Missing --user-agent flag
aliyun das GetYaoChiAgent --Query "List clusters" --endpoint das.cn-shanghai.aliyuncs.com6. Timeout — Timeout Settings
CORRECT
# SSE streaming API requires longer read timeout (180 seconds)
aliyun das GetYaoChiAgent --Query "List clusters" --endpoint das.cn-shanghai.aliyuncs.com --read-timeout 180 --connect-timeout 30 --user-agent AlibabaCloud-Agent-SkillsINCORRECT
# Error: Read timeout too short, streaming API may timeout
aliyun das GetYaoChiAgent --Query "List clusters" --endpoint das.cn-shanghai.aliyuncs.com --read-timeout 10 --user-agent AlibabaCloud-Agent-Skills---
Correct Bash Script Patterns
1. Script Invocation
CORRECT
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "List PolarDB clusters in Hangzhou region"
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "Analyze cluster pc-xxx performance" --session-id "sess-xxx"
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "List clusters" --profile myprofile
echo "List clusters" | bash $SKILL_DIR/scripts/call_yaochi_agent.sh -INCORRECT
# Error: Using old Python script
uv run $SKILL_DIR/scripts/call_yaochi_agent.py "List clusters"
# Error: Using Python interpreter to run bash script
python $SKILL_DIR/scripts/call_yaochi_agent.sh "List clusters"
# Error: Parameter name using old format
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "List clusters" --role-arn acs:ram::xxx:role/xxx2. SSE Response Parsing
CORRECT — Script automatically parses SSE response
# Input: SSE format response body
data: {"Content":"PolarDB cluster list:","SessionId":"sess-abc123","ReasoningContent":""}
data: {"Content":"\n1. pc-xxx (cn-hangzhou)","SessionId":"sess-abc123","ReasoningContent":""}
data: [DONE]
# Output: Concatenated Content
PolarDB cluster list:
1. pc-xxx (cn-hangzhou)3. Credential Management
CORRECT
# Use existing aliyun CLI configuration
aliyun configure --mode OAuth
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "List clusters"
# Use specified profile
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "List clusters" --profile myprofileINCORRECT
# Error: Hardcoding AK/SK in script
export ALIBABA_CLOUD_ACCESS_KEY_ID="LTAI5tXXXXXXXX"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="8dXXXXXXXXXXXX"
# Error: Using custom credential variables from old script
export YAOCHI_ACCESS_KEY_ID="xxx"
export YAOCHI_ACCESS_KEY_SECRET="xxx"---
Authentication Patterns
CORRECT — Use aliyun CLI configuration
# OAuth mode (Recommended)
aliyun configure --mode OAuth
# AK mode
aliyun configure set --mode AK --access-key-id <AK> --access-key-secret <SK> --region cn-hangzhou
# Cross-account RamRoleArn mode
aliyun configure set --mode RamRoleArn --access-key-id <AK> --access-key-secret <SK> --ram-role-arn <ARN> --role-session-name yaochi-session --region cn-hangzhouINCORRECT — Managing credentials in script
# Error: Using Python SDK to manage credentials
from alibabacloud_das20200116.client import Client as DAS20200116Client
# Error: Parsing credentials from .env file
# Error: Parsing credentials from ~/.alibabacloud/credentialsAliyun 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": "China East 1 (Hangzhou)"
},
...
]
},
"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
RAM Policies
Required Permissions
PolarDB AI Assistant (YaoChi Agent) requires the following RAM permissions.
Standard Edition
RAM sub-accounts must have:
- AliyunPolardbReadOnlyAccess - PolarDB read-only access
- AliyunYaoChiAgentAccess - YaoChi Agent access
For authorization instructions, see Grant permissions to RAM users.
Professional Edition
RAM sub-accounts must have the service-linked role created:
- AliyunServiceRolePolicyForPolarDBAgent - PolarDB Agent service-linked role
Custom Policy (Minimum Permissions)
If you need to create a custom policy with minimum required permissions:
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"das:GetYaoChiAgent",
"das:GetDasAgentSSE"
],
"Resource": "*"
}
]
}Cross-Account Access - STS AssumeRole
For cross-account access, configure trust policy on the target account's RAM role:
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Principal": {
"RAM": [
"acs:ram::<caller-account-id>:root"
]
}
}
]
}System Policy Reference
| Policy Name | Description | Use Case |
|---|---|---|
AliyunPolardbReadOnlyAccess | PolarDB read-only access | Required for Standard Edition |
AliyunYaoChiAgentAccess | YaoChi Agent access | Required for Standard Edition |
Permission Mapping
| Operation | Required RAM Action |
|---|---|
| Invoke YaoChi Agent | das:GetYaoChiAgent |
| Invoke DAS Agent SSE | das:GetDasAgentSSE |
Related APIs
DAS (Database Autonomy Service) - Core API
| Product | CLI Command | API Action | Description |
|---|---|---|---|
| DAS | aliyun das GetYaoChiAgent --Query "<query>" --Source "polardb-console" --endpoint das.cn-shanghai.aliyuncs.com --user-agent AlibabaCloud-Agent-Skills | GetYaoChiAgent | YaoChi Intelligent Diagnostic Agent (SSE streaming response) |
| DAS | aliyun das GetDasAgentSSE --Query "<query>" --endpoint das.cn-shanghai.aliyuncs.com --user-agent AlibabaCloud-Agent-Skills | GetDasAgentSSE | DAS Agent SSE interface |
GetYaoChiAgent API Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
--Query | String | Yes | Natural language query content |
--Source | String | No | Call source identifier, recommended to set as polardb-console |
--SessionId | String | No | Session ID for multi-turn conversation context preservation |
--ExtraInfo | String | No | Extra information |
GetDasAgentSSE API Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
--Query | String | Yes | Natural language query content |
--AgentId | String | No | Agent ID |
--InstanceId | String | No | Database instance ID |
--SessionId | String | No | Session ID for multi-turn conversation context preservation |
SSE Response Format
GetYaoChiAgent returns SSE (Server-Sent Events) streaming response in the following format:
data: {"Content":"Response text chunk 1","SessionId":"sess-xxx","ReasoningContent":""}
data: {"Content":"Response text chunk 2","SessionId":"sess-xxx","ReasoningContent":""}
...
data: [DONE]Response Fields
| Field | Type | Description |
|---|---|---|
Content | String | Text content of current chunk |
SessionId | String | Session ID for multi-turn conversation |
ReasoningContent | String | Reasoning process content (for debugging) |
API Endpoint
| Environment | Endpoint |
|---|---|
| Production | das.cn-shanghai.aliyuncs.com |
Note: GetYaoChiAgent API uses das.cn-shanghai.aliyuncs.com endpoint uniformly, regardless of the region where the user's PolarDB cluster is located.Verification Method
How to Verify Skill Execution Success
Step 1: Verify aliyun CLI Installation and Configuration
# Check CLI version
aliyun version
# Expected output: 3.3.3 or higher
# Check authentication configuration
aliyun configure get
# Expected output: Display current profile configuration
# Test basic connectivity
aliyun das describe-instance-das-pro --instance-id "pc-test" --endpoint das.cn-shanghai.aliyuncs.com --user-agent AlibabaCloud-Agent-Skills/alibabacloud-polardb-ai-assistant 2>&1
# Expected: Return JSON response (even if instance doesn't exist, should return API error not connection error)Step 2: Verify jq Installation
echo '{"Content":"test"}' | jq -r '.Content'
# Expected output: testStep 3: Verify call_yaochi_agent.sh Script
# Verify script is executable
bash $SKILL_DIR/scripts/call_yaochi_agent.sh --help
# Expected: Display help information
# Verify error prompt without parameters
bash $SKILL_DIR/scripts/call_yaochi_agent.sh
# Expected: Display usage prompt and exitStep 4: Verify Actual Invocation (requires valid credentials)
# Simple query test
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "Hello"
# Expected: Return YaoChi Agent response content
# With debug mode
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "Hello" --debug
# Expected: Return response content, also output debug info to stderrStep 5: Verify Multi-turn Conversation
# First round query - note the session ID output to stderr
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "List PolarDB clusters in Hangzhou region"
# Expected: Return cluster list, stderr outputs [SessionID] sess-xxx
# Second round query - use session ID from previous round
bash $SKILL_DIR/scripts/call_yaochi_agent.sh "Continue analyzing the first cluster" --session-id "sess-xxx"
# Expected: Continue analysis based on contextCommon Errors and Solutions
| Error | Cause | Solution |
|---|---|---|
command not found: aliyun | aliyun CLI not installed | Refer to cli-installation-guide.md for installation |
command not found: jq | jq not installed | brew install jq or apt install jq |
InvalidAccessKeyId | Invalid AK/SK | Check aliyun configure get configuration |
Throttling.UserConcurrentLimit | Concurrency limit exceeded | Wait for previous query to complete and retry |
Forbidden.RAM | Insufficient permissions | Refer to ram-policies.md for permission configuration |
#!/usr/bin/env bash
# =============================================================================
# call_yaochi_agent.sh - Alibaba Cloud YaoChi Agent CLI Script
# =============================================================================
# Invokes get-yao-chi-agent API via aliyun CLI DAS plugin with streaming response.
# Requires DAS plugin: aliyun plugin install --names aliyun-cli-das
# Uses existing aliyun CLI credentials (aliyun configure), no extra setup needed.
#
# Usage:
# bash call_yaochi_agent.sh "List PolarDB clusters in Hangzhou region"
# bash call_yaochi_agent.sh "Analyze cluster pc-xxx performance" --session-id <session-id>
# echo "List clusters" | bash call_yaochi_agent.sh -
# =============================================================================
set -euo pipefail
# --- Configuration ---
ENDPOINT="das.cn-shanghai.aliyuncs.com"
SOURCE="polardb-console"
READ_TIMEOUT=180
CONNECT_TIMEOUT=30
# --- Variables ---
QUERY=""
SESSION_ID=""
PROFILE=""
DEBUG=false
# --- Functions ---
usage() {
cat >&2 <<EOF
Alibaba Cloud YaoChi Agent CLI Tool (based on aliyun CLI)
Usage:
$(basename "$0") <query> [options]
Arguments:
<query> Query content (natural language), use '-' to read from stdin
Options:
--session-id <id> Session ID for multi-turn conversation
--profile <name> Specify aliyun CLI profile
--debug, -d Enable debug mode
--help, -h Show help information
Examples:
$(basename "$0") "List PolarDB clusters in Hangzhou region"
$(basename "$0") "Analyze cluster pc-xxx performance" --session-id "sess-xxx"
echo "List clusters" | $(basename "$0") -
EOF
}
debug_log() {
if [[ "$DEBUG" == "true" ]]; then
echo "[DEBUG] $*" >&2
fi
}
# Check dependencies
check_dependencies() {
if ! command -v aliyun &>/dev/null; then
echo "Error: aliyun CLI not found, please install (>= 3.3.3)" >&2
echo "Install: curl -fsSL https://aliyuncli.alicdn.com/install.sh | bash" >&2
echo "See: references/cli-installation-guide.md" >&2
exit 1
fi
if ! command -v jq &>/dev/null; then
echo "Error: jq is required to parse JSON response" >&2
echo "Install:" >&2
echo " macOS: brew install jq" >&2
echo " Ubuntu: sudo apt-get install jq" >&2
echo " CentOS: sudo yum install jq" >&2
exit 1
fi
local version
version=$(aliyun version 2>/dev/null || echo "0.0.0")
debug_log "aliyun CLI version: $version"
# Ensure DAS plugin is installed (get-yao-chi-agent requires plugin for Signature V3)
if ! aliyun das get-yao-chi-agent --help &>/dev/null 2>&1; then
echo "Error: DAS plugin not installed" >&2
echo "Please install manually: aliyun plugin install --names aliyun-cli-das" >&2
exit 1
fi
}
# Stream parse response (read from stdin line by line, output in real-time)
# DAS plugin returns streaming JSON (one {"data": {...}} per line) or SSE format
parse_sse_streaming() {
local session_id=""
local format_detected=false
local is_sse=false
local is_json_stream=false
local error_buffer=""
while IFS= read -r line; do
line="${line%$'\r'}"
[[ -z "$line" ]] && continue
# Detect response format on first line
if [[ "$format_detected" == false ]]; then
if [[ "$line" =~ ^data: ]]; then
is_sse=true
debug_log "Detected SSE format response"
elif echo "$line" | jq -e '.data' &>/dev/null 2>&1; then
is_json_stream=true
debug_log "Detected streaming JSON format response (DAS plugin)"
else
# Might be error response or plain JSON, buffer first
error_buffer="$line"
# Check if error response
local error_code
error_code=$(echo "$line" | jq -r '.Code // empty' 2>/dev/null) || true
if [[ -n "$error_code" ]]; then
local error_msg
error_msg=$(echo "$line" | jq -r '.Message // empty' 2>/dev/null) || true
echo "Error: ${error_msg:-Unknown error} (${error_code})" >&2
if [[ "$error_code" == *"Throttling"* ]] || [[ "$error_code" == *"ConcurrentLimit"* ]]; then
echo "Max 2 concurrent sessions per account. Please wait for previous query to complete." >&2
fi
return 1
fi
# Try to handle as plain JSON response
local content
content=$(echo "$line" | jq -r '.Content // .Data // empty' 2>/dev/null) || true
if [[ -n "$content" ]]; then
printf "%s" "$content"
session_id=$(echo "$line" | jq -r '.SessionId // empty' 2>/dev/null) || true
else
# Cannot parse, output as-is
echo "$line"
fi
format_detected=true
continue
fi
format_detected=true
fi
# Process SSE format
if [[ "$is_sse" == true ]]; then
if [[ "$line" =~ ^data:\ ?(.*) ]]; then
local data="${BASH_REMATCH[1]}"
[[ "$data" == "[DONE]" || -z "$data" ]] && continue
local chunk_content
chunk_content=$(echo "$data" | jq -r '.Content // empty' 2>/dev/null) || true
[[ -n "$chunk_content" ]] && printf "%s" "$chunk_content"
local chunk_session
chunk_session=$(echo "$data" | jq -r '.SessionId // empty' 2>/dev/null) || true
[[ -n "$chunk_session" ]] && session_id="$chunk_session"
if [[ "$DEBUG" == "true" ]]; then
local reasoning
reasoning=$(echo "$data" | jq -r '.ReasoningContent // empty' 2>/dev/null) || true
[[ -n "$reasoning" ]] && debug_log "Reasoning: $reasoning"
fi
fi
fi
# Process streaming JSON format
if [[ "$is_json_stream" == true ]]; then
local chunk_content
chunk_content=$(echo "$line" | jq -r '.data.Content // empty' 2>/dev/null) || true
[[ -n "$chunk_content" ]] && printf "%s" "$chunk_content"
local chunk_session
chunk_session=$(echo "$line" | jq -r '.data.SessionId // empty' 2>/dev/null) || true
[[ -n "$chunk_session" ]] && session_id="$chunk_session"
if [[ "$DEBUG" == "true" ]]; then
local reasoning
reasoning=$(echo "$line" | jq -r '.data.ReasoningContent // empty' 2>/dev/null) || true
[[ -n "$reasoning" ]] && debug_log "Reasoning: $reasoning"
fi
fi
done
# Output newline (end of content)
echo ""
# Output session ID (to stderr for multi-turn conversation)
if [[ -n "$session_id" ]]; then
echo "" >&2
echo "[SessionID] $session_id" >&2
fi
}
# --- Argument parsing ---
while [[ $# -gt 0 ]]; do
case "$1" in
--session-id)
SESSION_ID="$2"
shift 2
;;
--profile)
PROFILE="$2"
shift 2
;;
--debug|-d)
DEBUG=true
shift
;;
--help|-h)
usage
exit 0
;;
-)
QUERY=$(cat)
shift
;;
-*)
echo "Unknown option: $1" >&2
usage
exit 1
;;
*)
QUERY="$1"
shift
;;
esac
done
# --- Input validation ---
# Max query length (reasonable limit for natural language queries)
MAX_QUERY_LENGTH=4000
# Max session ID length
MAX_SESSION_ID_LENGTH=128
# Session ID format: alphanumeric, hyphens, underscores only
SESSION_ID_PATTERN='^[a-zA-Z0-9_-]+$'
validate_input() {
# Validate QUERY
if [[ -z "$QUERY" ]]; then
usage
exit 1
fi
local query_length=${#QUERY}
if [[ $query_length -gt $MAX_QUERY_LENGTH ]]; then
echo "Error: Query too long ($query_length chars). Maximum allowed: $MAX_QUERY_LENGTH" >&2
exit 1
fi
# Validate SESSION_ID if provided
if [[ -n "$SESSION_ID" ]]; then
local session_id_length=${#SESSION_ID}
if [[ $session_id_length -gt $MAX_SESSION_ID_LENGTH ]]; then
echo "Error: Session ID too long ($session_id_length chars). Maximum allowed: $MAX_SESSION_ID_LENGTH" >&2
exit 1
fi
if [[ ! "$SESSION_ID" =~ $SESSION_ID_PATTERN ]]; then
echo "Error: Invalid session ID format. Only alphanumeric, hyphens, and underscores allowed." >&2
exit 1
fi
fi
# Validate PROFILE if provided (alphanumeric, hyphens, underscores, dots)
if [[ -n "$PROFILE" ]]; then
if [[ ! "$PROFILE" =~ ^[a-zA-Z0-9._-]+$ ]]; then
echo "Error: Invalid profile name format." >&2
exit 1
fi
fi
}
# --- Validation ---
validate_input
check_dependencies
# --- Build CLI command arguments ---
# Use DAS plugin's kebab-case command, supports Signature V3
cli_args=(das get-yao-chi-agent
--query "$QUERY"
--source "$SOURCE"
--endpoint "$ENDPOINT"
--read-timeout "$READ_TIMEOUT"
--connect-timeout "$CONNECT_TIMEOUT"
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-polardb-ai-assistant
)
if [[ -n "$SESSION_ID" ]]; then
cli_args+=(--session-id "$SESSION_ID")
fi
if [[ -n "$PROFILE" ]]; then
cli_args+=(--profile "$PROFILE")
fi
# --- Output query info ---
echo "[Query] $QUERY" >&2
if [[ -n "$SESSION_ID" ]]; then
echo "[SessionID] $SESSION_ID" >&2
fi
echo "============================================================" >&2
echo "[YaoChi Agent Response]" >&2
debug_log "Executing: aliyun ${cli_args[*]}"
# --- Execute and stream parse ---
# Use pipe for real streaming output, avoid command substitution blocking
aliyun "${cli_args[@]}" 2>&1 | parse_sse_streaming
exit_code=${PIPESTATUS[0]}
if [[ $exit_code -ne 0 ]]; then
# Non-zero exit but content already output via pipe, just log debug info
debug_log "aliyun CLI exit code: $exit_code (streaming response may return non-zero)"
fi