
Alibabacloud Governance Evaluation Report
- 190 installs
- 208 repo stars
- Updated August 4, 2026
- aliyun/alibabacloud-aiops-skills
Generate Alibaba Cloud governance evaluation reports summarizing policy adherence, risk findings, and remediation priorities for audits and executive reviews.
About
alibabacloud-governance-evaluation-report enables agents to produce Alibaba Cloud governance evaluation reports that consolidate compliance posture, misconfigurations, and recommended fixes. Security and platform teams use it for periodic audits, risk committees, and tracking cloud control maturity across accounts and regions.
- Governance score and finding aggregation
- Policy compliance gap identification
- Executive-ready evaluation summaries
- Remediation prioritization hints
- Alibaba Cloud governance API/report flows
Alibabacloud Governance Evaluation Report by the numbers
- 190 all-time installs (skills.sh)
- Ranked #792 of 2,203 Security 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-governance-evaluation-reportAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 190 |
|---|---|
| repo stars | ★ 208 |
| Last updated | August 4, 2026 |
| Repository | aliyun/alibabacloud-aiops-skills ↗ |
What it does
Generate Alibaba Cloud governance evaluation reports summarizing policy adherence, risk findings, and remediation priorities for audits and executive reviews.
Files
Alibaba Cloud Governance Center Evaluation Report
Guide users to discover governance risks, focus on critical issues, and take remediation actions through a progressive drill-down workflow.
Scenario Description
This skill is a problem-discovery and resolution guide — not a comprehensive audit report generator. It operates as a progressive disclosure funnel:
1. Overview (quick diagnosis) — Score + pillar distribution + top critical risks → guide user to choose a direction 2. Pillar analysis (focused drill-down) — All risks in a specific domain, controlled by severity → guide user to specific items 3. Detail (deep dive) — Single check item with full remediation steps → guide user to related items or resources 4. Resources (action) — Non-compliant resource listing for targeted remediation
Each layer focuses on the most important information and guides the user to the next level. Avoid information overload — keep output concise and actionable.
Architecture: Governance Center API → CLI (aliyun governance) → governance_query.py (merge + cache) → JSON output → Agent report
How It Works
Data Sources — Three APIs provide all data: 1. list-evaluation-metadata — Check item definitions (name, description, pillar, level, remediation) 2. list-evaluation-results — Actual results (status, risk, compliance rate, score) 3. list-evaluation-metric-details — Non-compliant resource details for a specific check item
Processing — The script (governance_query.py) merges data sources and caches results for 1 hour. It provides 4 query modes: overview, pillar, detail, resources.
Output — Structured JSON for Agent to generate user-friendly reports. Reports are output directly in the conversation as formatted text, NOT written to files.
---
Prerequisites
Pre-check: Aliyun CLI >= 3.3.0 required
Run aliyun version to verify. If not installed or version too low,see references/cli-installation-guide.md for installation instructions.
Then [MUST] run aliyun configure set --auto-plugin-install true to enable automatic plugin installation.aliyun version # >= 3.3.0
aliyun configure set --auto-plugin-install true # Enable auto plugin install
python3 --version # Python 3.xAuthentication
Configure CLI authentication (OAuth recommended):
# OAuth mode (recommended)
aliyun configure --mode OAuth
## RAM Policy
Requires Governance Center read permissions. See [references/ram-policies.md](references/ram-policies.md) for full policy.
Minimum required permissions:
- `governance:ListEvaluationMetadata`
- `governance:ListEvaluationResults`
Or attach system policy: **AliyunGovernanceReadOnlyAccess**
## Parameter Confirmation
This skill has minimal user-specific parameters. The following may require confirmation:
| Parameter Name | Required/Optional | Description | Default Value |
|----------------|-------------------|-------------|---------------|
| `--profile` | Optional | Aliyun CLI profile name | Default profile |
| `-c, --category` | Required (pillar mode) | Pillar category name | N/A |
| `--id` | Required (detail/resources mode) | Check item metric ID | N/A |
| `--keyword` | Optional (detail mode) | Search keyword for check items | N/A |
| `--max-results` | Optional (resources mode) | Max results per page | 50 |
## Verification
Verify setup before use:
Test CLI connection
aliyun governance list-evaluation-results \ --user-agent AlibabaCloud-Agent-Skills \ --cli-query "Results.TotalScore"
Test script
python3 scripts/governance_query.py overview
See [references/verification-method.md](references/verification-method.md) for detailed steps.
---
## Core Workflow
> **IMPORTANT: Parameter Confirmation** — Before executing any command or API call,
> ALL user-customizable parameters (e.g., `--profile`, `--category`, `--id`, `--keyword`,
> `--max-results`, etc.) MUST be confirmed with the user.
> Do NOT assume or use default values without explicit user approval.
> **IMPORTANT: Output Format** — Reports are format specifications for conversation output only.
> Always output report content directly in the chat message as formatted Markdown.
> Do NOT create or write report files (e.g., `.md`, `.txt`, `.html`). No file generation is needed.
Script location: [scripts/governance_query.py](scripts/governance_query.py)
### Global Options
| Option | Description |
|--------|-------------|
| `--refresh` | Force refresh cache (default: 1-hour TTL) |
---
### Mode 1: `overview` — Overall Maturity Report
**When to use**: User asks about overall account health, maturity score, or wants a summary.
python3 scripts/governance_query.py overview python3 scripts/governance_query.py overview -r Error # Only high-risk items python3 scripts/governance_query.py overview -r Error,Warning # High + medium risk python3 scripts/governance_query.py --refresh overview # Force fresh data
**Options**:
| Option | Description |
|--------|-------------|
| `-r, --risk` | Filter RiskyItems by risk level (comma-separated: `Error`, `Warning`, `Suggestion`). PillarSummary and RiskDistribution are always complete. |
**Output JSON fields**:
- `TotalScore` — Overall maturity score (0.0-1.0)
- `PillarSummary` — Per-pillar statistics (checked/risky counts, always unfiltered)
- `RiskDistribution` — Count by risk level (always unfiltered)
- `RiskyItems` — Items with risk, filtered by `--risk` if specified, sorted by severity
- `RiskFilter` — Applied risk filter values (only present when `--risk` is used)
**Report format**: Read [references/report-format-overview.md](references/report-format-overview.md) for the exact output format.
---
### Mode 2: `pillar` — Pillar-Specific Report
**When to use**: User asks about a specific domain (security, reliability, cost, etc.).
python3 scripts/governance_query.py pillar -c <Category> [options]
**Options**:
| Option | Description |
|--------|-------------|
| `-c, --category` | **Required**. Pillar name (see below) |
| `--risky` | Only show items with risk (exclude compliant) |
| `-l, --level` | Filter by recommendation level (comma-separated) |
| `-r, --risk` | Filter by actual risk level (comma-separated) |
**Category values**:
- `Security` — 安全
- `Reliability` — 稳定
- `CostOptimization` — 成本
- `OperationalExcellence` — 效率
- `Performance` — 性能
**Level values**: `Critical`, `High`, `Medium`, `Suggestion`
**Risk values**: `Error`, `Warning`, `Suggestion`, `None`
**Examples**:安全支柱所有风险项
python3 scripts/governance_query.py pillar -c Security --risky
仅严重和高优先级的错误/警告
python3 scripts/governance_query.py pillar -c Security -l Critical,High -r Error,Warning --risky
**Output JSON fields**:
- `Category`, `CategoryCN` — Pillar name
- `MatchedCount` — Number of matched items
- `Items` — List of check items with status
**Report format**: Read [references/report-format-pillar.md](references/report-format-pillar.md) for the exact output format.
---
### Mode 3: `detail` — Check Item Detail
**When to use**: User asks about a specific check item or how to fix an issue.
python3 scripts/governance_query.py detail --id <metric-id> python3 scripts/governance_query.py detail --keyword <search-term>
**Options**:
| Option | Description |
|--------|-------------|
| `--id` | Check item ID (e.g., `apbxftkv5c`) |
| `--keyword` | Search by name/description (if multiple matches, shows list) |
**Examples**:按 ID 查询
python3 scripts/governance_query.py detail --id apbxftkv5c
按关键字搜索
python3 scripts/governance_query.py detail --keyword "MFA"
**Output JSON fields**:
- Basic info: `Id`, `DisplayName`, `Description`, `Category`
- Status: `Status`, `Risk`, `Compliance`, `NonCompliant`
- `Remediation` — Fix steps (Manual/Analysis/QuickFix)
**Report format**: Read [references/report-format-detail.md](references/report-format-detail.md) for the exact output format. The detail format also covers the resources listing when needed.
---
### Mode 4: `resources` — Non-Compliant Resources
**When to use**: User wants to see which specific resources failed a check item.
python3 scripts/governance_query.py resources --id <metric-id>
**Options**:
| Option | Description |
|--------|-------------|
| `--id` | **Required**. Check item ID |
| `--max-results` | Max results per page (default: 50) |
**Examples**:查询未启用 MFA 的 RAM 用户列表
python3 scripts/governance_query.py resources --id apbxftkv5c
查询开放高危端口的安全组
python3 scripts/governance_query.py resources --id a9g6pv7r5b
**Output JSON fields**:
- `MetricId` — Check item ID
- `TotalCount` — Number of non-compliant resources
- `Resources[]` — List of resources:
- `ResourceId`, `ResourceName`, `ResourceType`
- `RegionId`, `ResourceOwnerId`
- `Classification` — Risk classification
- `Properties` — Resource-specific attributes
---
## Mode Selection Guide
| User says... | Use mode | Command | Report format |
|--------------|----------|---------|---------------|
| "查查我的账号安全吗" / "成熟度得分" / "分析下治理检测结果" | `overview` | `overview` | [overview](references/report-format-overview.md) |
| "有哪些高风险项" / "看下所有高风险" | `overview` | `overview -r Error` | [overview](references/report-format-overview.md) |
| "中风险以上的问题" | `overview` | `overview -r Error,Warning` | [overview](references/report-format-overview.md) |
| "安全方面有哪些问题" / "XX支柱的风险" | `pillar` | `pillar -c Security --risky` | [pillar](references/report-format-pillar.md) |
| "网络安全相关的检测项" / "数据库风险" | `pillar` + keyword filter | `pillar -c Security --risky` then filter by keyword | [pillar](references/report-format-pillar.md) |
| "高优先级的问题" | `pillar` | `pillar -c Security -l Critical,High --risky` | [pillar](references/report-format-pillar.md) |
| "MFA怎么修" / "XX检测项详情" | `detail` | `detail --keyword "MFA"` | [detail](references/report-format-detail.md) |
| "哪些用户没开MFA" / "不合规资源有哪些" | `detail` + `resources` | `detail --id xxx` then `resources --id xxx` | [detail](references/report-format-detail.md) |
**Default**: If user doesn't specify pillar or check item, use `overview`.
**Report format selection**: After determining the query mode, read the corresponding report format reference file before generating output. Only read the format file that matches the user's intent — do not read all format files at once.
## Field Reference
| Field | Values | Note |
|-------|--------|------|
| `Risk` | `Error`(高风险) > `Warning`(中风险) > `Suggestion`(低风险) > `None`(合规) | Actual detected risk |
| `RecommendationLevel` | `Critical` > `High` > `Medium` > `Suggestion` | Recommended priority |
| `Status` | `Finished` / `NotApplicable` / `Failed` | Check execution status |
| `Compliance` | 0.0 - 1.0 | 1.0 = fully compliant |
## Cache & Cleanup
Only metadata (check item definitions) is cached locally — results are always fetched in real-time.
- Cache location: `~/.governance_cache/metadata.json`
- TTL: 24 hours (metadata rarely changes)
- `list-evaluation-results` and `list-evaluation-metric-details` are **never cached**
Force refresh metadata cache
python3 scripts/governance_query.py --refresh overview
Clear cache manually
rm -rf ~/.governance_cache/
## Best Practices
1. **Focus, don't dump** — Each report layer should highlight what matters most, not list everything. Read the corresponding report format reference for quantity control rules
2. **Follow the funnel** — Start with `overview`, guide user to `pillar`, then to `detail`. Don't skip layers unless user explicitly asks for a specific item
3. **Use `--risky` filter for pillar mode** — Reduces noise by hiding compliant items when investigating issues
4. **Prioritize by Risk + Level** — Focus on `Error` risk with `Critical`/`High` recommendation level first
5. **Follow remediation guidance** — Use `detail` mode to get actionable fix steps before modifying resources
6. **Always guide next steps** — Every report must end with follow-up guidance based on actual data, helping users continue exploring
7. **Cache management** — Only metadata is cached (24h TTL); results are always real-time. Use `--refresh` to force metadata refresh
## References
| File | Content |
|------|---------|
| [report-format-overview.md](references/report-format-overview.md) | Report format: overall governance overview |
| [report-format-pillar.md](references/report-format-pillar.md) | Report format: pillar / keyword aggregated analysis |
| [report-format-detail.md](references/report-format-detail.md) | Report format: single check item detail + resources |
| [related-apis.md](references/related-apis.md) | CLI commands and API details |
| [ram-policies.md](references/ram-policies.md) | Required permissions |
| [verification-method.md](references/verification-method.md) | Verification steps |
| [cli-installation-guide.md](references/cli-installation-guide.md) | CLI installation |
Acceptance Criteria: alicloud-it-gov-evaluation-report
Scenario: Alibaba Cloud Governance Center Maturity Evaluation Report Purpose: Skill testing acceptance criteria
---
Correct CLI Command Patterns
1. Correct Product Pattern
✅ CORRECT: governance product
aliyun governance list-evaluation-metadata❌ INCORRECT: Wrong product name
aliyun gov list-evaluation-metadata # Wrong - 'gov' is not a valid product
aliyun cgc list-evaluation-metadata # Wrong - 'cgc' is not a valid product2. Correct Command Pattern
✅ CORRECT: kebab-case subcommands
aliyun governance list-evaluation-metadata
aliyun governance list-evaluation-results
aliyun governance list-evaluation-metric-details
aliyun governance run-evaluation❌ INCORRECT: PascalCase or wrong command
aliyun governance ListEvaluationMetadata # Wrong - should be kebab-case
aliyun governance get-evaluation-metadata # Wrong - command is 'list-evaluation-metadata'
aliyun governance query-results # Wrong - command is 'list-evaluation-results'3. Correct Parameter Patterns
✅ CORRECT: kebab-case parameters
aliyun governance list-evaluation-metadata --language zh
aliyun governance list-evaluation-results --account-id 123456789
aliyun governance list-evaluation-metric-details --id apbxftkv5c❌ INCORRECT: Wrong parameter names
aliyun governance list-evaluation-metadata --Language zh # Wrong - should be --language
aliyun governance list-evaluation-results --accountId 123 # Wrong - should be --account-id
aliyun governance list-evaluation-metric-details --metric-id abc # Wrong - should be --id4. User-Agent Flag
✅ CORRECT: Include user-agent
aliyun governance list-evaluation-results --user-agent AlibabaCloud-Agent-Skills❌ INCORRECT: Missing user-agent
aliyun governance list-evaluation-results # Missing --user-agent flag5. Profile Parameter
✅ CORRECT: Use --profile flag
aliyun governance list-evaluation-metadata --profile myprofile❌ INCORRECT: Wrong profile parameter
aliyun governance list-evaluation-metadata -p myprofile # Wrong - should be --profileCorrect Python Script Patterns
1. Script Invocation
✅ CORRECT: Valid modes
python3 scripts/governance_query.py overview
python3 scripts/governance_query.py overview -r Error
python3 scripts/governance_query.py overview -r Error,Warning
python3 scripts/governance_query.py pillar -c Security --risky
python3 scripts/governance_query.py detail --id apbxftkv5c
python3 scripts/governance_query.py detail --keyword "MFA"❌ INCORRECT: Invalid modes or parameters
python3 scripts/governance_query.py summary # Wrong - mode should be 'overview'
python3 scripts/governance_query.py pillar Security # Wrong - need -c flag
python3 scripts/governance_query.py detail MFA # Wrong - need --id or --keyword flag2. Category Values
✅ CORRECT: Valid category names
python3 scripts/governance_query.py pillar -c Security
python3 scripts/governance_query.py pillar -c Reliability
python3 scripts/governance_query.py pillar -c Performance
python3 scripts/governance_query.py pillar -c OperationalExcellence
python3 scripts/governance_query.py pillar -c CostOptimization❌ INCORRECT: Invalid category names
python3 scripts/governance_query.py pillar -c security # Wrong - case sensitive
python3 scripts/governance_query.py pillar -c 安全 # Wrong - use English name
python3 scripts/governance_query.py pillar -c Cost # Wrong - full name is CostOptimization3. Filter Parameters
✅ CORRECT: Valid filter values
python3 scripts/governance_query.py pillar -c Security -l Critical,High
python3 scripts/governance_query.py pillar -c Security -r Error,Warning
python3 scripts/governance_query.py pillar -c Security --risky❌ INCORRECT: Invalid filter values
python3 scripts/governance_query.py pillar -c Security -l critical # Wrong - case sensitive
python3 scripts/governance_query.py pillar -c Security -r error # Wrong - case sensitiveOutput Format Patterns
1. Overview Mode Output
Expected JSON structure:
{
"TotalScore": 0.85,
"EvaluationTime": "2024-01-15T10:30:00Z",
"TotalMetrics": 150,
"PillarSummary": [...],
"RiskDistribution": {...},
"RiskyItems": [...]
}2. Pillar Mode Output
Expected JSON structure:
{
"TotalScore": 0.85,
"EvaluationTime": "2024-01-15T10:30:00Z",
"Category": "Security",
"CategoryCN": "安全",
"MatchedCount": 10,
"Items": [...]
}3. Detail Mode Output
Expected JSON structure:
{
"Id": "apbxftkv5c",
"DisplayName": "...",
"Description": "...",
"Category": "Security",
"CategoryCN": "安全",
"RecommendationLevel": "Critical",
"Status": "Finished",
"Risk": "Error",
"Compliance": 0.5,
"Remediation": [...]
}4. Resources Mode Output
Expected JSON structure:
{
"MetricId": "apbxftkv5c",
"TotalCount": 3,
"Resources": [
{
"ResourceId": "user-001",
"ResourceName": "test-user",
"ResourceType": "ACS::RAM::User",
"RegionId": "cn-hangzhou",
"ResourceOwnerId": "123456789",
"Classification": "NonCompliant",
"Properties": {
"MFAEnabled": "false"
}
}
]
}5. Resources Mode Invocation
✅ CORRECT: Valid resources query
python3 scripts/governance_query.py resources --id apbxftkv5c
python3 scripts/governance_query.py resources --id apbxftkv5c --max-results 100❌ INCORRECT: Missing required --id
python3 scripts/governance_query.py resources # Wrong - --id is required
python3 scripts/governance_query.py resources --keyword "MFA" # Wrong - resources mode only accepts --idAliyun CLI Installation & Configuration Guide
Complete guide for installing and configuring Aliyun CLI.
Aliyun CLI 3.3.0+: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.0 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.0)
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.0+ 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
The following RAM permissions are required to use the Governance Center evaluation features.
Minimum Required Policy
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"governance:ListEvaluationMetadata",
"governance:ListEvaluationResults",
"governance:ListEvaluationMetricDetails"
],
"Resource": "*"
}
]
}System Policy
Alternatively, attach the system policy:
- AliyunGovernanceReadOnlyAccess - Read-only access to Governance Center
Permission Details
| API Action | Permission | Description |
|---|---|---|
| ListEvaluationMetadata | governance:ListEvaluationMetadata | Query check item definitions |
| ListEvaluationResults | governance:ListEvaluationResults | Query evaluation results |
| ListEvaluationMetricDetails | governance:ListEvaluationMetricDetails | Query non-compliant resource details |
Related APIs
Governance Center CLI Commands
| Product | CLI Command | API Action | Description |
|---|---|---|---|
| governance | aliyun governance list-evaluation-metadata | ListEvaluationMetadata | Query all check items metadata including name, ID, description, stage, resource metadata, and remediation guide |
| governance | aliyun governance list-evaluation-results | ListEvaluationResults | Query governance check results and status |
| governance | aliyun governance list-evaluation-metric-details | ListEvaluationMetricDetails | Query non-compliant resource details for a specific check item |
| governance | aliyun governance list-evaluation-score-history | ListEvaluationScoreHistory | Query historical scores of governance maturity checks |
| governance | aliyun governance run-evaluation | RunEvaluation | Trigger a governance maturity check |
| governance | aliyun governance generate-evaluation-report | GenerateEvaluationReport | Generate governance evaluation report |
Command Details
list-evaluation-metadata
Query all check item metadata.
aliyun governance list-evaluation-metadata \
--user-agent AlibabaCloud-Agent-SkillsResponse fields:
EvaluationMetadata[].Metadata[].Id- Check item IDEvaluationMetadata[].Metadata[].DisplayName- Display nameEvaluationMetadata[].Metadata[].Description- DescriptionEvaluationMetadata[].Metadata[].Category- Category/Pillar (Security, Reliability, Performance, OperationalExcellence, CostOptimization)EvaluationMetadata[].Metadata[].RecommendationLevel- Recommendation level (Critical, High, Medium, Suggestion)EvaluationMetadata[].Metadata[].RemediationMetadata- Remediation guidance
list-evaluation-results
Query governance check results.
aliyun governance list-evaluation-results \
--user-agent AlibabaCloud-Agent-SkillsResponse fields:
Results.TotalScore- Overall maturity score (0.0-1.0)Results.EvaluationTime- Evaluation timestampResults.MetricResults[].Id- Check item IDResults.MetricResults[].Status- Status (Finished, NotApplicable, Failed)Results.MetricResults[].Risk- Risk level (Error, Warning, Suggestion, None)Results.MetricResults[].Result- Compliance rate (0.0-1.0)Results.MetricResults[].ResourcesSummary.NonCompliant- Non-compliant resource count
list-evaluation-metric-details
Query non-compliant resources for a specific check item.
aliyun governance list-evaluation-metric-details \
--id <metric-id> \
--max-results 50 \
--user-agent AlibabaCloud-Agent-SkillsParameters:
--id(required) - Check item ID--max-results(optional) - Max results per page (default: 5)--next-token(optional) - Pagination token
Response fields:
Resources[].ResourceId- Resource IDResources[].ResourceName- Resource nameResources[].ResourceType- Resource type (e.g.,ACS::RAM::User,ACS::ECS::SecurityGroup)Resources[].RegionId- Region IDResources[].ResourceOwnerId- Owner account IDResources[].ResourceClassification- Risk classificationResources[].ResourceProperties[]- Resource-specific attributesNextToken- Pagination token for next page
run-evaluation
Trigger a new governance check.
aliyun governance run-evaluation \
--user-agent AlibabaCloud-Agent-SkillsReferences
报告格式:单项检测详情分析报告
适用场景:
- 用户询问某个具体检测项的详情,如"MFA 那个检测项是什么情况""apbxftkv5c 这个检测项帮我看看"
- 用户询问某个检测项的修复方法,如"MFA 怎么修""如何修复高危端口暴露的问题"
- 用户查看某个检测项的不合规资源列表,如"哪些用户没开 MFA""哪些安全组开放了高危端口"
数据来源:
- 检测项详情:
detail --id <metric-id>或detail --keyword <keyword>模式输出的 JSON - 不合规资源:
resources --id <metric-id>模式输出的 JSON(按需获取)
---
格式模板
仅查看检测项详情(不含资源列表)
## 检测项详情:{DisplayName}
| 属性 | 值 |
| --- | --- |
| 检测项 ID | `{Id}` |
| 所属支柱 | {CategoryCN} |
| 优先级 | {RecommendationLevelCN} |
| 当前状态 | {Risk → 高风险/中风险/低风险/合规} |
| 合规率 | {Compliance*100:.0f}% |
| 不合规资源数 | {NonCompliant, if available, otherwise "N/A"} |
| 修复后预计提分 | +{PotentialScoreIncrease:.1f} 分 {if available, otherwise omit this row} |
### 检测说明
{Description — the full description of what this check item evaluates}
### 当前风险分析
{Agent analyzes:
- Why this check item is in its current risk state
- What the compliance rate means in practical terms
- Potential impact of non-compliance (security, cost, stability implications)
}
### 修复方案
{Parse Remediation array and present each remediation option.
For each remediation:}
#### 方案{N}:{RemediationType → "手动修复"/"分析修复"/"快速修复"}
{For each step in Steps:}
**{Classification, if present}**
{Description — what this step does}
{If Suggestion is present:}
> 建议:{Suggestion}
{If CostDescription is present:}
> 费用说明:{CostDescription}
{If Notice is present:}
> 注意:{Notice}
{If Guidance is present, for each guidance entry:}
**{Title}**
{Content}
{If ButtonRef is present:}
[{ButtonName}]({ButtonRef})
{End of steps}
{Repeat for each remediation option}含不合规资源列表
当用户明确要求查看不合规资源,或 Agent 判断列出具体资源有助于用户理解问题时,在上述报告末尾追加资源列表部分。
需要额外调用 resources --id <metric-id> 获取资源数据。
### 不合规资源列表
共 {TotalCount} 个不合规资源:
| 资源 ID | 资源名称 | 资源类型 | 地域 | 关键属性 |
| --- | --- | --- | --- | --- |
| {ResourceId} | {ResourceName, or "-"} | {ResourceType} | {RegionId} | {Agent: pick 1-2 most relevant properties from Properties} |
| ... | ... | ... | ... | ... |
{If TotalCount > displayed count:}
> 仅展示前 {N} 条,共 {TotalCount} 条。可通过增加 `--max-results` 查看更多。
### 处置建议
{Agent generates specific remediation advice based on the actual non-compliant resources:
- Group similar resources if applicable (e.g., "以下 5 个 RAM 用户均未启用 MFA")
- Provide concrete next steps for remediation
- Highlight any resources that need prioritized attention (e.g., root account, production resources)
}
---
### 相关检测项
{Agent looks through the pillar data (from the same overview/pillar query results already cached)
and picks 2-5 related check items that share the same Category or are topically related.
Only include items that have risk (Risk != "None"). If no related risky items, omit this section.}
该检测项所属的{CategoryCN}支柱下,还有以下相关风险项值得关注:
| 检测项 | 风险等级 | 合规率 |
| --- | --- | --- |
| {DisplayName} | {RiskCN} | {Compliance*100:.0f}% |
| ... | ... | ... |
---
如需进一步了解,可以告诉我:
- 想查看上述某个相关检测项的详情,如"**{pick a related DisplayName} 的详细情况**"
- 想查看该检测项的不合规资源,如"**{current DisplayName} 有哪些不合规资源**" {only if resource list was not already shown}
- 想查看{CategoryCN}支柱的整体情况,如"**分析下{CategoryCN}支柱的所有检测项**"---
格式规则
- 禁止使用任何 emoji,全文保持专业语气
- 检测项属性表使用竖排 key-value 布局,不使用横排表格
- "当前状态"字段将 Risk 枚举值翻译为中文:
Error→ 高风险,Warning→ 中风险,Suggestion→ 低风险,None→ 合规 - 修复方案部分忠实呈现 API 返回的 Remediation 数据,不要编造修复步骤
- 如 Remediation 数据中包含控制台链接(ButtonRef),保留为 markdown 链接格式
- 不合规资源列表中的"关键属性"列:从 Properties 中挑选最能说明问题的 1-2 个属性(如
MFAEnabled: false) - 若资源数量较多(>20),建议只展示前 20 条并提示总数
- 当
detail --keyword匹配到多条结果时,先展示匹配列表让用户选择,不要自动展开所有详情
后续引导规则
- 报告末尾必须附带后续引导,帮助用户继续探索
- 引导内容必须基于报告中的实际数据,从报告中挑选具体的检测项名、支柱名填入引导模板
- 引导以列表形式呈现,提供 2-3 个方向,每个方向用加粗标出建议的提问语句
- 引导方向应根据当前上下文灵活选择:
- 若当前报告未含资源列表,可引导查看不合规资源
- 若已含资源列表,可引导查看所属支柱整体情况或回到概览
- 若有相关检测项,优先引导查看某个相关检测项的详情
- "相关检测项"部分:从同支柱下挑选有风险的检测项(排除当前项),优先选择同主题或高风险的项;若同支柱下无其他风险项则省略该部分
- 禁止使用 emoji
报告格式:整体概览报告
适用场景:用户询问账号整体健康状况、成熟度评分、或要求生成综合报告,且未指定具体支柱或检测项。
数据来源:overview 模式输出的 JSON
设计原则:概览是漏斗入口,职责是快速诊断 + 聚焦重点 + 引导深入,而非穷举所有风险项。
---
格式模板
## 治理检测报告
**最近一次检测时间**:{EvaluationTime, format: YYYY-MM-DD HH:MM:SS}
**整体情况概述**:当前治理检测综合评分为 {TotalScore*100:.1f} 分。
{Agent summarizes: 一两句话概括整体状况,点明问题集中在哪些支柱、最需要优先关注什么}
### 各支柱风险分布
| 支柱 | 高风险 | 中风险 | 建议优化 | 总结 |
| --- | --- | --- | --- | --- |
| 安全 | {Error} | {Warning} | {Suggestion} | {Agent: one sentence summary} |
| 稳定 | {Error} | {Warning} | {Suggestion} | {Agent: one sentence summary} |
| 成本 | {Error} | {Warning} | {Suggestion} | {Agent: one sentence summary} |
| 效率 | {Error} | {Warning} | {Suggestion} | {Agent: one sentence summary} |
| 性能 | {Error} | {Warning} | {Suggestion} | {Agent: one sentence summary} |
### 重点风险项
{Agent selects the most critical risk items to highlight.
Selection criteria — see "数量控制规则" section below.
Group selected items by logical topic/domain (e.g., "身份与访问安全", "网络安全", "数据保护").}
#### {Group Name}
| 风险项 | 风险等级 | 所属支柱 | 说明 |
| --- | --- | --- | --- |
| {DisplayName} | 高风险 | {CategoryCN} | {Agent: brief explanation of risk and impact} |
| ... | ... | ... | ... |
{Repeat for each group}
{After listing, add a summary of unlisted items:}
> 以上为当前最需关注的风险项。此外还有 {remaining_error} 项高风险、{warning_count} 项中风险、{suggestion_count} 项建议优化项未列出,可按支柱深入查看。
{If no high-risk items at all: "当前无高风险项。" and skip grouping.}
### 治理建议
{Agent generates 2-3 focused, actionable recommendations.
Each recommendation must have a title and directly reference the risk items shown above.}
#### 1. {Recommendation title}
{Specific actionable content, referencing the relevant risk items from the report.
Include concrete next step, e.g., "可进一步查看安全支柱的详细分析" or "建议优先处理 {DisplayName}".}
#### 2. {Recommendation title}
{...}
#### 3. {Recommendation title}
{...}
---
如需进一步了解,可以告诉我:
- 想深入了解某个支柱的详情,如"**分析下{pick the pillar with most risks}支柱的具体情况**"
- 想查看某个具体风险项的修复方案,如"**{pick a high-risk DisplayName from report} 怎么修复**"
- 想查看某类风险的不合规资源,如"**哪些资源存在 {pick a risk topic} 问题**"---
数量控制规则
概览报告的核心是聚焦,Agent 根据以下准则灵活控制"重点风险项"展示数量:
- 高风险项 <= 5:全部展示
- 高风险项 6-10:全部展示,但每项的"说明"列保持简短(一句话)
- 高风险项 > 10:展示优先级最高的 Top 10(按 RecommendationLevel: Critical > High > Medium > Suggestion 排序),其余在汇总行中用数字概括
- 中风险 / 建议优化项:不在"重点风险项"中逐条列出,仅在支柱分布表和汇总行中以数字体现
- 若无高风险项但有中风险项,可挑选 Top 3-5 中风险项作为"重点关注项"展示
格式规则
- 禁止使用任何 emoji,全文保持专业语气
- 支柱分布表中数字列直接填数字(如
3),不加前缀 - "总结"列:根据该支柱下检测项的实际结果,用一句话概述;全部合规时注明"全部合规"
- "重点风险项"按逻辑主题分组,跨支柱分组(如安全和效率的 RAM 相关问题可归入同一组)
- 治理建议必须带标题分段,2-3 条即可,每条关联具体风险项,不要泛泛而谈
- 汇总行用 blockquote 格式,准确填写未列出的各等级数量
后续引导规则
- 报告末尾必须附带后续引导,帮助用户继续深入分析
- 引导内容必须基于报告中的实际数据,不要给出泛泛的示例
- 从报告中挑选具体的支柱名、风险项名称、风险主题填入引导模板
- 引导以列表形式呈现,提供 2-3 个方向,每个方向用加粗标出建议的提问语句
- 优先引导用户进入风险最集中的支柱,或查看最严重的风险项
- 禁止使用 emoji
报告格式:支柱 / 关键词聚合分析报告
适用场景:
- 用户按支柱维度分析,如"安全方面有哪些问题""看下成本优化的情况"
- 用户按关键词/主题分析,如"看下网络安全相关的检测项""数据库相关的风险有哪些"
- 用户指定筛选条件,如"高优先级的安全问题""中风险以上的稳定性问题"
数据来源:
- 按支柱分析:
pillar -c <Category>模式输出的 JSON - 按关键词分析:
detail --keyword <keyword>返回多个匹配项时,需逐个使用detail --id获取详情,或使用pillar模式后按关键词在结果中筛选
设计原则:支柱报告是漏斗的第二层,用户已主动选择了方向,报告应聚焦该领域的风险全貌,但仍需控制信息密度,高风险详细、低风险概括。
---
格式模板
## {CategoryCN}支柱 治理检测分析
> 也可根据用户意图调整标题,如"网络安全相关检测分析"、"数据库相关风险分析"
**最近一次检测时间**:{EvaluationTime, format: YYYY-MM-DD HH:MM:SS}
**整体评分**:{TotalScore*100:.1f} 分
**分析范围**:{CategoryCN}支柱,共 {MatchedCount} 项检测
{If filtered: "筛选条件:仅显示有风险项 / 仅显示高优先级 / 等"}
### 概述
{Agent summarizes:
- 该支柱/主题下的整体合规情况
- 风险分布(高 N / 中 N / 建议 N)
- 主要问题集中在哪些方面
}
### 高风险项
{If no Error items: "当前无高风险项。"}
| 检测项 | 优先级 | 合规率 | 不合规资源数 | 说明 |
| --- | --- | --- | --- | --- |
| {DisplayName} | {RecommendationLevelCN} | {Compliance*100:.0f}% | {NonCompliant} | {Agent: brief explanation of risk and impact} |
| ... | ... | ... | ... | ... |
### 中风险项
{If no Warning items: "当前无中风险项。"}
{See "数量控制规则" for display limits.}
| 检测项 | 优先级 | 合规率 | 不合规资源数 | 说明 |
| --- | --- | --- | --- | --- |
| {DisplayName} | {RecommendationLevelCN} | {Compliance*100:.0f}% | {NonCompliant} | {Agent: brief explanation} |
| ... | ... | ... | ... | ... |
{If truncated:}
> 仅展示前 {N} 项,另有 {remaining} 项中风险未列出。如需查看完整列表,请告诉我。
### 建议优化项
{Default: only show count, do not list individual items.}
共 {suggestion_count} 项建议优化项,均为低风险。如需查看详情,请告诉我。
{If user explicitly asked for all items, then list them in a table.}
### 治理建议
{Agent generates targeted recommendations specific to this pillar/topic.
Each recommendation has a title and directly references risk items from above.}
#### 1. {Recommendation title}
{Specific actionable content, referencing the relevant risk items.
Include concrete next step, e.g., "建议优先处理 {DisplayName},可查看其修复方案".}
#### 2. {Recommendation title}
{...}
{2-3 recommendations, prioritized by risk severity.}
---
如需进一步了解,可以告诉我:
- 想查看某个风险项的详情和修复方案,如"**{pick a risky DisplayName from report} 怎么修复**"
- 想查看某个风险项的不合规资源列表,如"**{pick a risky DisplayName} 有哪些不合规资源**"
- 想查看其他支柱的情况,如"**分析下{pick another pillar}支柱**"---
数量控制规则
- 高风险项(Error):全部展示(该支柱下高风险项通常不多,且是用户钻入的核心原因)
- 中风险项(Warning):
- <= 5 项:全部展示
- > 5 项:展示 Top 5(按 RecommendationLevel 排序),其余用汇总行概括
- 建议优化项(Suggestion):默认只展示数量,不逐条列出;用户明确要求时才展开
- 若用户指定了
--risk或--level过滤条件,按过滤后的结果展示,不再额外截断
格式规则
- 禁止使用任何 emoji,全文保持专业语气
- 标题根据实际分析维度灵活调整:
- 按支柱分析时用 "{CategoryCN}支柱 治理检测分析"
- 按关键词分析时用 "{关键词}相关检测分析"
- 风险项按风险等级分段展示(高 → 中 → 建议),每段内按优先级排序
- "合规率"列:
Compliance * 100,取整数百分比 - "不合规资源数"列:取
NonCompliant字段值,若无则显示 "-" - "说明"列:Agent 根据检测项的
Description和实际检测结果,用简练语言说明风险含义 - 若某风险等级下无检测项,保留该段标题并注明"当前无{等级}项"
- 治理建议必须带标题分段,关联具体风险项,避免空泛的通用建议
后续引导规则
- 报告末尾必须附带后续引导,帮助用户继续深入分析
- 引导内容必须基于报告中的实际数据,从报告中挑选具体的检测项名称、支柱名填入引导模板
- 引导以列表形式呈现,提供 2-3 个方向,每个方向用加粗标出建议的提问语句
- 若当前分析的是某个支柱,引导可指向:该支柱下某个具体风险项的修复、不合规资源查看、其他支柱对比
- 禁止使用 emoji
Verification Methods
Step 1: Verify CLI Installation
aliyun version
# Expected: version >= 3.3.0Step 2: Verify Governance Plugin
aliyun governance --help
# Expected: Shows available governance commandsIf plugin not installed:
aliyun plugin install --names governanceStep 3: Verify Authentication
aliyun governance list-evaluation-results \
--user-agent AlibabaCloud-Agent-Skills \
--cli-query "Results.TotalScore"Success indicators:
- Returns a numeric value (0.0-1.0)
- No error messages
Common errors:
InvalidAccessKeyId.NotFound- Wrong Access Key IDSignatureDoesNotMatch- Wrong Access Key SecretForbidden.RAM- Insufficient permissions (see ram-policies.md)
Step 4: Verify Metadata Query
aliyun governance list-evaluation-metadata \
--user-agent AlibabaCloud-Agent-Skills \
--cli-query "EvaluationMetadata | length(@)"Success indicators:
- Returns a number > 0 (typically 5, one per pillar)
Step 5: Verify Python Script
cd /path/to/alicloud-it-gov-evaluation-report
python3 scripts/governance_query.py overviewSuccess indicators:
- Returns JSON with
TotalScore,PillarSummary,RiskDistribution - No Python errors
Step 6: Verify Specific Query Modes
Overview Mode
python3 scripts/governance_query.py overviewExpected: JSON with overall maturity score and pillar summaries
Pillar Mode
python3 scripts/governance_query.py pillar -c Security --riskyExpected: JSON with security-related risky items
Detail Mode
python3 scripts/governance_query.py detail --keyword "MFA"Expected: JSON with detailed check item information
Troubleshooting
Cache Issues
Force refresh cache:
python3 scripts/governance_query.py overview --refreshProfile Issues
Specify profile explicitly:
python3 scripts/governance_query.py overview --profile <your-profile>Permission Denied
Verify RAM policy is attached: 1. Go to RAM Console 2. Check user/role policies 3. Attach AliyunGovernanceReadOnlyAccess or custom policy
#!/usr/bin/env python3
"""
阿里云治理中心查询工具
支持四种模式:
overview - 全局成熟度报告(评分 + 各支柱分布 + 风险分布)
pillar - 指定支柱的风险明细
detail - 指定检测项的完整详情(含修复建议)
resources - 指定检测项的不合规资源列表
"""
import argparse
import json
import os
import subprocess
import sys
import time
from collections import Counter
CATEGORIES = [
"Security", "Reliability", "CostOptimization",
"OperationalExcellence", "Performance",
]
CATEGORY_CN = {
"Security": "安全",
"Reliability": "稳定",
"CostOptimization": "成本",
"OperationalExcellence": "效率",
"Performance": "性能",
}
LEVELS = ["Critical", "High", "Medium", "Suggestion"]
LEVEL_CN = {
"Critical": "严重", "High": "高", "Medium": "中", "Suggestion": "建议",
}
RISKS = ["Error", "Warning", "Suggestion", "None"]
RISK_CN = {
"Error": "高风险", "Warning": "中风险", "Suggestion": "低风险", "None": "合规",
}
CACHE_DIR = os.path.expanduser("~/.governance_cache")
METADATA_CACHE_TTL = 86400
def call_api(command, timeout=60):
cmd = ["aliyun", "governance", command, "--user-agent", "AlibabaCloud-Agent-Skills"]
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
print(f"API 调用超时 (>{timeout}s): {' '.join(cmd)}", file=sys.stderr)
sys.exit(1)
if proc.returncode != 0:
print(f"API 调用失败: {proc.stderr.strip()}", file=sys.stderr)
sys.exit(1)
return json.loads(proc.stdout)
def load_metadata(refresh=False):
"""Load metadata with file cache (rarely changes)."""
os.makedirs(CACHE_DIR, exist_ok=True)
cache_file = os.path.join(CACHE_DIR, "metadata.json")
if not refresh and os.path.exists(cache_file):
age = time.time() - os.path.getmtime(cache_file)
if age < METADATA_CACHE_TTL:
with open(cache_file, "r", encoding="utf-8") as f:
return json.load(f)
data = call_api("list-evaluation-metadata")
with open(cache_file, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)
return data
def load_data(refresh=False):
if refresh and os.path.isdir(CACHE_DIR):
for f in os.listdir(CACHE_DIR):
if f.endswith(".json"):
os.remove(os.path.join(CACHE_DIR, f))
meta_raw = load_metadata(refresh)
result_raw = call_api("list-evaluation-results")
meta_idx = {}
for em in meta_raw.get("EvaluationMetadata", []):
for item in em.get("Metadata", []):
meta_idx[item["Id"]] = item
result_idx = {}
for item in result_raw.get("Results", {}).get("MetricResults", []):
result_idx[item["Id"]] = item
summary = {
"TotalScore": result_raw.get("Results", {}).get("TotalScore"),
"EvaluationTime": result_raw.get("Results", {}).get("EvaluationTime"),
}
return meta_idx, result_idx, summary
def merge_item(mid, meta, result):
risk = result.get("Risk")
compliance = result.get("Result")
item = {
"Id": mid,
"DisplayName": meta.get("DisplayName"),
"Description": meta.get("Description"),
"Category": meta.get("Category"),
"CategoryCN": CATEGORY_CN.get(meta.get("Category"), ""),
"RecommendationLevel": meta.get("RecommendationLevel"),
"RecommendationLevelCN": LEVEL_CN.get(meta.get("RecommendationLevel"), ""),
"Status": result.get("Status", "Unknown"),
"Risk": risk,
"RiskCN": RISK_CN.get(risk, "N/A"),
"Compliance": compliance,
}
summary = result.get("ResourcesSummary")
if summary and summary.get("NonCompliant"):
item["NonCompliant"] = summary["NonCompliant"]
return item
def cmd_overview(meta_idx, result_idx, summary, risk_filter=None):
risk_filters = {r.strip() for r in risk_filter.split(",")} if risk_filter else None
output = {
"TotalScore": summary["TotalScore"],
"EvaluationTime": summary["EvaluationTime"],
"TotalMetrics": len(meta_idx),
"PillarSummary": [],
"RiskDistribution": {},
"RiskyItems": [],
}
if risk_filters:
output["RiskFilter"] = sorted(risk_filters, key=lambda r: RISKS.index(r) if r in RISKS else 99)
risk_order = {r: i for i, r in enumerate(RISKS)}
level_order = {l: i for i, l in enumerate(LEVELS)}
pillar_data = {c: {"total": 0, "finished": 0, "risky": 0, "risk_counts": Counter()} for c in CATEGORIES}
risky_items = []
for mid, meta in meta_idx.items():
result = result_idx.get(mid, {})
cat = meta.get("Category")
status = result.get("Status", "Unknown")
risk = result.get("Risk")
if cat in pillar_data:
pillar_data[cat]["total"] += 1
if status == "Finished":
pillar_data[cat]["finished"] += 1
if risk and risk != "None":
pillar_data[cat]["risky"] += 1
pillar_data[cat]["risk_counts"][risk] += 1
if not risk_filters or risk in risk_filters:
risky_items.append(merge_item(mid, meta, result))
for cat in CATEGORIES:
d = pillar_data[cat]
output["PillarSummary"].append({
"Category": cat,
"CategoryCN": CATEGORY_CN[cat],
"Total": d["total"],
"Risky": d["risky"],
"RiskCounts": dict(d["risk_counts"]),
})
global_risk = Counter()
for mid, result in result_idx.items():
if result.get("Status") == "Finished":
risk = result.get("Risk")
if risk and risk != "None":
global_risk[risk] += 1
output["RiskDistribution"] = dict(global_risk)
risky_items.sort(key=lambda x: (
risk_order.get(x.get("Risk") or "None", 99),
level_order.get(x.get("RecommendationLevel") or "", 99),
))
output["RiskyItems"] = risky_items
return output
def cmd_pillar(meta_idx, result_idx, summary, category, level=None, risk=None, risky_only=False):
risk_order = {r: i for i, r in enumerate(RISKS)}
level_order = {l: i for i, l in enumerate(LEVELS)}
levels = [l.strip() for l in level.split(",")] if level else None
risks = [r.strip() for r in risk.split(",")] if risk else None
items = []
for mid, meta in meta_idx.items():
if meta.get("Category") != category:
continue
result = result_idx.get(mid, {})
status = result.get("Status", "Unknown")
r = result.get("Risk")
if risky_only and (status != "Finished" or r in (None, "None")):
continue
if levels and meta.get("RecommendationLevel") not in levels:
continue
if risks and (r or "None") not in risks:
continue
items.append(merge_item(mid, meta, result))
items.sort(key=lambda x: (
risk_order.get(x.get("Risk") or "None", 99),
level_order.get(x.get("RecommendationLevel") or "", 99),
))
return {
"TotalScore": summary["TotalScore"],
"EvaluationTime": summary["EvaluationTime"],
"Category": category,
"CategoryCN": CATEGORY_CN.get(category, ""),
"MatchedCount": len(items),
"Items": items,
}
def cmd_detail(meta_idx, result_idx, metric_id=None, keyword=None):
target_meta = None
target_id = None
if metric_id:
target_meta = meta_idx.get(metric_id)
target_id = metric_id
elif keyword:
matches = []
for mid, meta in meta_idx.items():
if keyword in (meta.get("DisplayName") or "") or keyword in (meta.get("Description") or ""):
matches.append((mid, meta))
if len(matches) == 0:
return {"error": f"未找到包含关键字 '{keyword}' 的检测项"}
if len(matches) > 1:
return {
"error": f"关键字 '{keyword}' 匹配到 {len(matches)} 条,请更精确",
"matches": [{"Id": m[0], "DisplayName": m[1].get("DisplayName")} for m in matches[:10]],
}
target_id, target_meta = matches[0]
if not target_meta:
return {"error": f"未找到 Id={metric_id} 的检测项"}
result = result_idx.get(target_id, {})
remediation_list = []
for r in target_meta.get("RemediationMetadata", {}).get("Remediation", []):
rem = {"RemediationType": r.get("RemediationType"), "Steps": []}
for action in r.get("Actions", []):
step = {}
if action.get("Classification"):
step["Classification"] = action["Classification"]
if action.get("Description"):
step["Description"] = action["Description"]
if action.get("Suggestion"):
step["Suggestion"] = action["Suggestion"]
if action.get("CostDescription"):
step["CostDescription"] = action["CostDescription"]
if action.get("Notice"):
step["Notice"] = action["Notice"]
guidance = []
for g in action.get("Guidance", []):
entry = {}
if g.get("Title"):
entry["Title"] = g["Title"]
if g.get("Content"):
content = g["Content"].replace("</br>", "\n")
entry["Content"] = content
if g.get("ButtonName"):
entry["ButtonName"] = g["ButtonName"]
if g.get("ButtonRef"):
entry["ButtonRef"] = g["ButtonRef"]
guidance.append(entry)
if guidance:
step["Guidance"] = guidance
rem["Steps"].append(step)
remediation_list.append(rem)
resource_props = []
for p in target_meta.get("ResourceMetadata", {}).get("ResourcePropertyMetadata", []):
resource_props.append({
"DisplayName": p.get("DisplayName"),
"PropertyName": p.get("PropertyName"),
"PropertyType": p.get("PropertyType"),
})
merged = merge_item(target_id, target_meta, result)
merged["Scope"] = target_meta.get("Scope")
merged["Stage"] = target_meta.get("Stage")
merged["TopicCode"] = target_meta.get("TopicCode")
merged["Remediation"] = remediation_list
if resource_props:
merged["ResourceProperties"] = resource_props
if result.get("PotentialScoreIncrease"):
merged["PotentialScoreIncrease"] = result["PotentialScoreIncrease"]
return merged
def cmd_resources(metric_id, max_results=50, timeout=60, max_pages=100):
"""Query non-compliant resources for a specific check item."""
all_resources = []
next_token = None
page_count = 0
while page_count < max_pages:
page_count += 1
cmd = [
"aliyun", "governance", "list-evaluation-metric-details",
"--id", metric_id,
"--max-results", str(max_results),
"--user-agent", "AlibabaCloud-Agent-Skills"
]
if next_token:
cmd.extend(["--next-token", next_token])
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return {"error": f"API 调用超时 (>{timeout}s): {' '.join(cmd)}"}
if proc.returncode != 0:
return {"error": f"API 调用失败: {proc.stderr.strip()}"}
data = json.loads(proc.stdout)
resources = data.get("Resources", [])
all_resources.extend(resources)
next_token = data.get("NextToken")
if not next_token or not resources:
break
if page_count >= max_pages and next_token:
print(f"警告: 已达到最大分页限制 ({max_pages} 页),可能存在更多资源", file=sys.stderr)
# Format resources for output
formatted = []
for res in all_resources:
item = {
"ResourceId": res.get("ResourceId"),
"ResourceName": res.get("ResourceName"),
"ResourceType": res.get("ResourceType"),
"RegionId": res.get("RegionId"),
"ResourceOwnerId": res.get("ResourceOwnerId"),
"Classification": res.get("ResourceClassification"),
}
# Extract properties as key-value pairs
props = {}
for p in res.get("ResourceProperties", []):
props[p.get("PropertyName")] = p.get("PropertyValue")
if props:
item["Properties"] = props
formatted.append(item)
return {
"MetricId": metric_id,
"TotalCount": len(formatted),
"Resources": formatted,
}
def main():
parser = argparse.ArgumentParser(description="阿里云治理中心查询工具")
parser.add_argument("--refresh", action="store_true", help="强制刷新缓存")
sub = parser.add_subparsers(dest="mode", required=True)
p_overview = sub.add_parser("overview", help="全局成熟度报告")
p_overview.add_argument("-r", "--risk", help="实际风险过滤(逗号分隔,如 Error,Warning)")
p_pillar = sub.add_parser("pillar", help="指定支柱的风险明细")
p_pillar.add_argument("-c", "--category", required=True, help="支柱名称")
p_pillar.add_argument("-l", "--level", help="推荐等级过滤(逗号分隔)")
p_pillar.add_argument("-r", "--risk", help="实际风险过滤(逗号分隔)")
p_pillar.add_argument("--risky", dest="risky_only", action="store_true", help="只显示有风险的项")
p_detail = sub.add_parser("detail", help="检测项详情")
p_detail.add_argument("--id", dest="metric_id", help="检测项 Id")
p_detail.add_argument("--keyword", help="按名称关键字搜索")
p_resources = sub.add_parser("resources", help="查询不合规资源列表")
p_resources.add_argument("--id", dest="metric_id", required=True, help="检测项 Id")
p_resources.add_argument("--max-results", type=int, default=50, help="每页最大数量")
args = parser.parse_args()
meta_idx, result_idx, summary = load_data(args.refresh)
if args.mode == "overview":
result = cmd_overview(meta_idx, result_idx, summary, args.risk)
elif args.mode == "pillar":
result = cmd_pillar(meta_idx, result_idx, summary,
args.category, args.level, args.risk, args.risky_only)
elif args.mode == "detail":
if not args.metric_id and not args.keyword:
parser.error("请指定 --id 或 --keyword")
result = cmd_detail(meta_idx, result_idx, args.metric_id, args.keyword)
elif args.mode == "resources":
result = cmd_resources(args.metric_id, args.max_results)
json.dump(result, sys.stdout, ensure_ascii=False, indent=2)
sys.stdout.write("\n")
if __name__ == "__main__":
main()