
Huawei Cloud Ecs Alert
- 79 installs
- 19 repo stars
- Updated July 31, 2026
- huaweicloud/huaweicloud-skills
Batch create and manage Huawei Cloud CES alarm rules for ECS instances via hcloud CLI, with web/database templates and SMN notifications.
About
Automates batch creation and management of CES alarm rules for ECS instances using hcloud CLI, with web/database templates, notification config, and metric queries. A developer uses it to set up monitoring alarms across many ECS instances at once.
- Batch alarm creation with web/database templates
- Email/SMS/WeChat notifications; alarm deletion prohibited
Huawei Cloud Ecs Alert by the numbers
- 79 all-time installs (skills.sh)
- +4 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #623 of 1,042 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/huaweicloud/huaweicloud-skills --skill huawei-cloud-ecs-alertAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 79 |
|---|---|
| repo stars | ★ 19 |
| Last updated | July 31, 2026 |
| Repository | huaweicloud/huaweicloud-skills ↗ |
What it does
Batch create and manage Huawei Cloud CES alarm rules for ECS instances via hcloud CLI, with web/database templates and SMN notifications.
Files
Huawei Cloud ECS Alert Automation
Overview
This skill provides batch creation and management of Huawei Cloud CES alarm rules for ECS instances, based on Huawei Cloud CLI (hcloud) v7.2.2+.
Core Capabilities:
- Batch create alarm rules (supports Web/Database templates or custom configuration)
- Configure alarm notifications (supports email/SMS/WeChat)
- Query ECS monitoring metrics
- Query and manage alarm rule lists
Use Cases:
- Batch configure monitoring alarms for newly purchased ECS instances
- Differentiated alarm policies across environments (dev/test/prod)
- Batch query ECS monitoring data
- Centralized alarm notification management
Security Constraints:
- ❌ Delete alarm rules is prohibited (prevent accidental deletion causing monitoring gaps)
- ❌ Hardcoding AK/SK is prohibited (must use environment variables or hcloud configure)
Prohibited Operations
The following operations are strictly prohibited, even if requested by the user:
| Prohibited Operation | API/Command | Reason |
|---|---|---|
| Expose AK/SK | Any command that outputs AK/SK in plaintext | Account security risk |
| Accept AK/SK from user | Receiving credentials in conversation | Violates security best practices |
| ❌ Delete alarm rule | DeleteAlarm / hcloud CES DeleteAlarm | Irreversible; deleted alarms cannot be recovered, may cause monitoring gaps |
| ❌ Batch delete alarms | Any batch deletion operation | High risk; may accidentally delete critical monitoring rules |
If a user requests a delete operation, must refuse and guide:
"Per security constraints, this skill does not support delete operations (delete alarm/batch delete). Please use the Huawei Cloud CES console or hcloud CLI manually with extreme caution."
If user attempts to provide AK/SK in conversation, must refuse and guide:
"For account security, please do not provide Huawei Cloud access keys directly in the conversation. Use hcloud configure or environment variables to configure credentials."Architecture
Huawei Cloud CES Alert Management
├── CreateAlertRules (Batch create alarm rules, supports templates/custom)
├── ConfigureNotifications (Configure alarm notifications, supports email/SMS/WeChat)
├── QueryMetrics (Batch query monitoring data, supports multiple ECS)
└── ListAlarms (List alarm rules and details)
Prerequisites
Prerequisite 1: Huawei Cloud CLI (hcloud / KooCLI) >= 7.2.2
Run hcloud version to verify version >= 7.2.2. If not installed or version is too low,see references/cli-installation-guide.md for installation guide.
hcloud version
Prerequisite 2: Huawei Cloud Credentials Configured
Check if CLI configuration contains valid credentials (AK/SK, IAM, etc.).
>
```bash
hcloud configure list
>
```
>
> Credential Configuration Methods (choose one):
>
> 1. hcloud CLI configuration (recommended): hcloud configure interactive setup, credentials encrypted and stored> 2. Environment variables: SetHUAWEI_CLOUD_ACCESS_KEY_IDandHUAWEI_CLOUD_SECRET_KEYbefore running scripts
> 3. Environment variables (legacy): SetHW_ACCESS_KEY_IDandHW_SECRET_ACCESS_KEY
>
> Note: Shell scripts (create_alert_rules.sh,list_ecs.sh, etc.) automatically use credentials from hcloud CLI configuration.
> Python SDK scripts (create_email_subscription.sh) support environment variables.If output does not contain valid configuration, stop operation and guide user to configure.
hcloud Parameter Format Requirement
hcloud (KooCLI) all parameters must use `--param=value` format (equals sign connection), does not support space
separation.
✅ Correct: hcloud CES ListAlarms --region=cn-north-4❌ Incorrect: hcloud CES ListAlarms --region cn-north-4>
This skill provides 8 Shell scripts, encapsulating common hcloud commands, supporting batch operations and formatted
output.
>
<details>
<summary>Script List and Usage Examples (Click to Expand)</summary>
>
| Script | Function | hcloud Command |
| ------------------------------- | --------------------------------------- | ------------------------------------- |
|list_ecs.sh| Query ECS instance list |hcloud ECS ListServersDetails|
|list_alarms.sh| Query alarm rule list |hcloud CES ListAlarms|
|create_alert_rules.sh| Batch create alarm rules |hcloud CES CreateAlarm|
|batch_query_metrics.sh| Batch query monitoring data |hcloud CES ShowMetricData|
|list_subscriptions.sh| Query SMN topics and subscriptions |hcloud SMN ListTopics/Subscriptions|
|manage_notifications.sh| Manage SMN subscriptions |hcloud SMN Subscribe/Unsubscribe|
|update_alarm_notifications.sh| Update alarm notification configuration |hcloud CES UpdateAlarm|
>
Usage Examples:
>
```bash
>
# Query ECS instances
>
./scripts/list_ecs.sh # Query all ECS
./scripts/list_ecs.sh --name ecs-001 # Filter by name
./scripts/list_ecs.sh --output json # Output as JSON
./scripts/list_ecs.sh --output ids # Output only ECS ID list
>
# Query alarm rules
>
./scripts/list_alarms.sh # Query all alarms
./scripts/list_alarms.sh --name-pattern "cpu.*" # Filter by name pattern
./scripts/list_alarms.sh --output ids # Output only alarm IDs
>
# Create alarm rules
>
./scripts/create_alert_rules.sh --template web --ecs-ids ecs-001,ecs-002
./scripts/create_alert_rules.sh --metric cpu_util --threshold 80 --ecs-ids ecs-001
./scripts/create_alert_rules.sh --template web --ecs-ids ecs-001 --smn-topic-urn
urn:smn:cn-north-4:xxx:ECS_ALARM_NOTIFY
./scripts/create_alert_rules.sh --template web --ecs-ids ecs-001 --dry-run # Dry run
>
```bash
>
</details>
Core Capabilities
- Batch Create Alarm Rules: Support template-based creation (Web/Database scenarios) or custom
metric/threshold configuration
- Batch Query Monitoring Data: Support multi-ECS concurrent query, output CPU/Memory/Disk metrics
- Notification Configuration: Support email/SMS/WeChat notification, SMN subscription management
- Security Compliance: AK/SK via environment variables or CLI config, never hardcode
Usage Scenarios
Scenario 1: Batch Configure Alarms for New ECS
Background: Purchased 10 new ECS instances, need to configure CPU/Memory alarm rules for all.
Steps:
1. Query ECS instance IDs 2. Batch create alarm rules using web template 3. Configure email notification
# 1. Query ECS instances
export HUAWEI_CLOUD_AK=<AK> && export HUAWEI_CLOUD_SK=<SK> && export HUAWEI_CLOUD_REGION=cn-north-4
./scripts/list_ecs.sh --output ids
# 2. Batch create alarm rules
./scripts/create_alert_rules.sh --template web --ecs-ids ecs-001,ecs-002,ecs-003
# 3. Configure notification
./scripts/manage_notifications.sh --action subscribe --topic-urn <SMN_TOPIC_URN> --protocol email --endpoint user@example.com
Scenario 2: Query Monitoring Data for Multiple ECS
Background: Need to check CPU utilization for 5 ECS instances over the past hour.
./scripts/batch_query_metrics.sh \
--ecs-ids ecs-001,ecs-002,ecs-003,ecs-004,ecs-005 \
--metric cpu_util \
--from 2024-01-01T10:00:00Z \
--to 2024-01-01T11:00:00Z \
--output table
Input Parameters
- AK/SK: Via environment variables
HUAWEI_CLOUD_AK/HUAWEI_CLOUD_SKorhcloud configure - Region: Via environment variable
HUAWEI_CLOUD_REGIONor--regionparameter - ECS IDs: Comma-separated ECS instance IDs
- Alarm IDs: Comma-separated alarm rule IDs
- Template: Alarm template (web/database)
- Metric: Monitoring metric name (cpu_util/mem_util/disk_usage)
- Threshold: Alarm threshold value
- SMN Topic URN: SMN topic URN for notifications
Output Format
- Table: Formatted table output (default)
- JSON: JSON format for programmatic processing
- IDs: Only ID list for scripting
Verification Method
After executing any operation, verify using the following methods:
1. List Alarms: ./scripts/list_alarms.sh --name-pattern <pattern> 2. Query Metrics: ./scripts/batch_query_metrics.sh --ecs-ids <ids> --metric cpu_util 3. Check Notifications: ./scripts/list_subscriptions.sh
See references/troubleshooting.md for common verification issues.
Best Practices
1. Use Templates for Standard Scenarios: Web/Database templates cover most use cases 2. Configure Multiple Notification Channels: Email + SMS for critical alarms 3. Set Reasonable Thresholds: CPU 80%, Memory 85%, Disk 90% recommended 4. Use Environment Variables for Credentials: Never hardcode AK/SK in scripts
Common Issues
Issue 1: hcloud Command Not Found
Solution: Install KooCLI, see references/cli-installation-guide.md
Issue 2: 403 Forbidden
Solution: Check IAM permissions, ensure CES FullAccess and SMN FullAccess policies are granted. See references/iam-policies.md
Issue 3: Alarm Creation Fails
Solution: Check metric name and threshold range. CPU/Memory thresholds should be 0-100.
Issue 4: No Monitoring Data
Solution: Check ECS instance status and metric collection interval. Data may have 5-minute delay.
See references/troubleshooting.md for more troubleshooting guides.
Important Notes
CLI Version Requirement: Must use hcloud CLI v7.2.2 or later. Older versions may not support certain API parameter formats.
Region Consistency: All operations must specify the same region (--cli-regionorHUAWEI_CLOUD_REGIONenvironment variable). Cross-region operations will fail.
Alarm Threshold Range: CPU/memory utilization thresholds must be between 0-100. Disk usage threshold is recommended to be set between 80-95.
Monitoring Data Delay: CES monitoring data typically has a 5-minute delay. Querying real-time data may return empty results.
SMN Subscription Creation:
>
- ✅ Recommended: Use ./scripts/create_email_subscription.sh script, which automatically uses hcloud CLI configured credentials (no need to manually set environment variables)- ✅ Alternative: Use Huawei Cloud Console (SMN → Topics → Subscribe) for subscription creation
- ⚠️ Note: Email/SMS subscriptions require confirmation before receiving notifications. Check your email and click the confirmation link.
>
See references/smn-subscription-guide.md for detailed guide.
Batch Operation Limits: Single batch creation is recommended for no more than 20 ECS instances. Too many instances may cause API timeout.
Credential Security:
>
- ✅ Recommended: Use hcloud configure to configure credentials- ✅ Recommended: Use environment variablesHUAWEI_CLOUD_AK/HUAWEI_CLOUD_SK
- ❌ Prohibited: Hardcode AK/SK in scripts or configuration files
Related Documents
- CLI Installation Guide
- IAM Policies
- Related APIs
- Troubleshooting
- SMN Subscription Guide
- Common Commands
Huawei Cloud CLI (KooCLI) Installation Guide
Prerequisites
- Python 3.6+
- pip3 (Python package manager)
- Internet connection
Installation Steps
Step 1: Install KooCLI
pip3 install --break-system-packages huaweicloudsdkcore huaweicloudsdkces huaweicloudsdksmnStep 2: Verify Installation
hcloud versionExpected output:
KooCLI Version 7.2.2 Copyright(C) 2020-2026 www.huaweicloud.comStep 3: Configure Credentials
Run the interactive configuration:
hcloud configureFollow the prompts: 1. Profile Name: default (press Enter) 2. AK (Access Key ID): Enter your AK 3. SK (Secret Access Key): Enter your SK 4. Region: cn-north-4 (or your preferred region) 5. Project ID: Auto-detected or enter manually
Step 4: Verify Configuration
hcloud configure listExpected output should show your configuration with masked AK/SK.
Troubleshooting
Issue 1: hcloud: command not found
Solution: Ensure KooCLI is installed and in your PATH:
which hcloudIf not found, reinstall:
pip3 install --break-system-packages huaweicloudsdkcoreIssue 2: 403 Forbidden
Solution: Check IAM permissions. Ensure your account has:
CES FullAccessSMN FullAccessECS FullAccess
Issue 3: Invalid AK/SK
Solution: 1. Log in to Huawei Cloud Console 2. Go to "My Credentials" → "Access Keys" 3. Verify AK/SK or create new ones
Security Best Practices
- ✅ Never hardcode AK/SK in scripts or configuration files
- ✅ Use
hcloud configureto store credentials securely (encrypted) - ✅ Use environment variables for temporary credentials
- ❌ Do not share AK/SK in chat, emails, or code repositories
Related Documents
- IAM Policies
- SMN Subscription Guide
- Troubleshooting
Common Commands Reference
Quick reference for commonly used commands - avoid duplicating these examples across multiple documents.
Credential Configuration
# View current configuration
hcloud configure list
# Configure AK/SK (must set both)
hcloud configure set --cli-access-key=<AK> --cli-secret-key=<SK>
# Configure default region
hcloud configure set --cli-region=cn-north-4
# Interactive configuration (recommended for first-time use)
hcloud configureVerification Commands
Basic Verification
# Check CLI version (should be >= 7.2.2)
hcloud version
# Check credential configuration status
hcloud configure listAPI Access Verification
# Verify ECS API access
hcloud ECS ListServersDetails --cli-region=cn-north-4
# Verify CES API access
hcloud CES ListMetrics --namespace=SYS.ECS --cli-region=cn-north-4
# Verify SMN API access
hcloud SMN ListTopics --cli-region=cn-north-4Region Configuration
| Region Code | Region Name | Description |
|---|---|---|
| cn-north-4 | Beijing 4 | Recommended for testing |
| cn-north-1 | Beijing 1 | |
| cn-east-3 | Shanghai 1 | |
| cn-east-2 | Shanghai 2 | |
| cn-south-1 | Guangzhou | |
| ap-southeast-1 | Hong Kong |
Note: CES service is available in all Huawei Cloud regions. Choose the region where your ECS instances are located.
Common Troubleshooting
hcloud Command Not Found
# Linux/macOS - Use official installation script
curl -o hcloud_install.sh https://hwcloudcli.obs.cn-north-4.myhuaweicloud.com/cli/latest/hcloud_install.sh
bash hcloud_install.sh
# Or install via pip
pip install hcloudAuthentication Failure (401/403)
# Clear existing configuration
hcloud configure set --cli-access-key= --cli-secret-key=
# Reconfigure with valid credentials
hcloud configure
# Verify configuration
hcloud configure listInsufficient Permissions
Add the following policies to the user in IAM:
CES FullAccess(Alarm management)ECS ReadOnlyAccess(Instance query)SMN FullAccess(Notification configuration)
Parameter Format Specification
hcloud requires --param=value format (with equals sign), not space-separated:
# ✅ Correct
hcloud CES ListAlarms --region=cn-north-4
# ❌ Incorrect
hcloud CES ListAlarms --region cn-north-4Related Documents
- CLI Installation Guide
- IAM Policies
- Troubleshooting
IAM Policies
This document describes the IAM permission policies required for the CES alarm automation skill.
Required IAM Permissions
Minimum Permission Requirements
To use this skill, the following IAM policies must be granted:
| Service | Policy Name | Scope | Description |
|---|---|---|---|
| CES | CES FullAccess | Region-level | Full access to Cloud Eye Service |
| ECS | ECS ReadOnlyAccess | Region-level | Read-only access to ECS instances |
| SMN | SMN FullAccess | Region-level | Full access to Simple Message Notification |
Policy Description
CES FullAccess:
- Create alarm rules
- Query monitoring metrics
- Update alarm notification configuration
- List alarm rules and history
ECS ReadOnlyAccess:
- List ECS instances
- Query instance details
- Read instance metadata
SMN FullAccess:
- Create and manage SMN topics
- Subscribe/unsubscribe endpoints
- Send notifications
Configuring IAM Policies
Via Console
1. Log in to Huawei Cloud Console 2. Navigate to IAM > Users 3. Select target user or user group 4. Click "Add Permission" 5. Select policies:
- CES FullAccess
- ECS ReadOnlyAccess
- SMN FullAccess
6. Confirm and save
Via CLI
# Add CES FullAccess to user
hcloud IAM AttachGroupToUser --user-id=<user-id> --group-id=<ces-fullaccess-group-id>
# Add ECS ReadOnlyAccess to user
hcloud IAM AttachGroupToUser --user-id=<user-id> --group-id=<ecs-readonly-group-id>
# Add SMN FullAccess to user
hcloud IAM AttachGroupToUser --user-id=<user-id> --group-id=<smn-fullaccess-group-id>Custom Policy (Optional)
For more granular control, create a custom policy:
{
"Version": "1.1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ces:CreateAlarm",
"ces:UpdateAlarm",
"ces:ListAlarms",
"ces:ShowMetricData"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"ecs:listServers",
"ecs:listServersDetails"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"smn:ListTopics",
"smn:Subscribe",
"smn:Unsubscribe"
],
"Resource": "*"
}
]
}Permission Verification
After granting permissions, verify using:
# Verify CES access
hcloud CES ListMetrics --namespace=SYS.ECS --cli-region=cn-north-4
# Verify ECS access
hcloud ECS ListServersDetails --cli-region=cn-north-4
# Verify SMN access
hcloud SMN ListTopics --cli-region=cn-north-4If any command returns 403 Forbidden, check IAM policy configuration.
Common Issues
Issue 1: 403 Forbidden on CES Operations
Solution: Ensure CES FullAccess policy is granted to the user.
Issue 2: 403 Forbidden on ECS Operations
Solution: Ensure ECS ReadOnlyAccess or ECS FullAccess policy is granted.
Issue 3: 403 Forbidden on SMN Operations
Solution: Ensure SMN FullAccess policy is granted.
References
- Common Commands
- IAM Official Documentation
- Policy Management
Memory Monitoring Guide
Problem Description
Failed to create memory usage alarm because ECS instances do not have the monitoring Agent installed.
Error Information
http_code: 400
code: ces.0014
details: Some content in message body is not correct.Root Cause
The mem_used_percent metric is not available in the SYS.ECS namespace because:
- Basic Monitoring (Free): Only provides virtualization-layer metrics such as CPU, network traffic, and disk I/O
- Operating System Monitoring (Requires Agent): Provides OS-level metrics such as memory, disk usage, and processes
---
Solutions
Solution 1: Install Monitoring Agent (Recommended)
Step 1: Log in to Huawei Cloud Console
1. Visit: https://console.huaweicloud.com/ces 2. Select region: Beijing 4 (cn-north-4)
Step 2: Install Agent
1. Left menu: Host Monitoring → Install Agent 2. Select hosts to install (ecs-9095-0001, ecs-9095-0002) 3. Click Batch Install 4. Choose installation method:
- One-Click Install (Recommended): Automatically install via Cloud Assistant
- Manual Install: Copy command and execute inside ECS
Step 3: Verify Installation
After installation, wait 5-10 minutes, then check in CES console:
- Host Monitoring → Host Details
- You should see memory, disk usage, and other OS-level metrics
Step 4: Create Memory Alarm
After Agent is successfully installed, re-run the command:
./scripts/create_alert_rules.sh --metric mem_used_percent --threshold 83.3 --ecs-ids <ecs-id>---
Solution 2: Use Available Metrics (Temporary)
If you cannot install the Agent temporarily, you can use existing CPU usage metrics:
# Create CPU alarm (threshold 80%)
./scripts/create_alert_rules.sh --metric cpu_util --threshold 80 --ecs-ids 738682b6-73e5-4ff4-a483-f024fdced6dd,01e72a37-9b31-4fb9-8ddb-9d2ae8685739Available Metrics:
| Metric Name | Description | Unit |
|---|---|---|
cpu_util | CPU usage | % |
cpu_credit_balance | CPU credit balance | Credit |
disk_read_bytes_rate | Disk read rate | B/s |
disk_write_bytes_rate | Disk write rate | B/s |
network_incoming_bytes_aggregate_rate | Network inbound traffic | B/s |
network_outgoing_bytes_aggregate_rate | Network outbound traffic | B/s |
---
Current Alarms
Successfully created alarm rules:
| Alarm ID | ECS Instance | Metric | Threshold | Status |
|---|---|---|---|---|
al260530T082112SuQbk5NAu | ecs-9095-0002 | cpu_util | 80% | ✅ Enabled |
al260530T082112SdnTa9qlY | ecs-9095-0001 | cpu_util | 80% | ✅ Enabled |
---
How to Check Agent Status
Method 1: Console View
1. Log in to Huawei Cloud Console 2. Go to CES Host Monitoring 3. Check the Agent Status column in the host list
Method 2: CLI Query
hcloud CES ListMetrics --cli-region=cn-north-4 --namespace=SYS.ECS | grep -i mem- Has output: Agent is installed
- No output: Agent needs to be installed
---
References
---
Recommended Actions: 1. Install Agent plugin first (takes 5 minutes) 2. Wait 10 minutes for Agent to report data 3. Re-run the command to create memory alarm
Created: 2026-05-30 Skill Version: huawei-cloud-ecs-alert v1.0.0
Related APIs
This document lists the core Huawei Cloud CES APIs used by this skill.
Core CES APIs
CreateAlarm
Function: Create a single alarm rule
API: POST /v1.0/{project_id}/alarms
hcloud Command:
hcloud CES CreateAlarm \
--cli-region=cn-north-4 \
--alarm_name=ecs-cpu-alarm \
--metric_namespace=SYS.ECS \
--metric_name=cpu_util \
--dim.0=name=instance_id,value=ecs-001 \
--condition.0.metric_name=cpu_util \
--condition.0.period=300 \
--condition.0.filter=average \
--condition.0.comparison=gt \
--condition.0.threshold=80 \
--condition.0.unit=count \
--condition.0.count=3 \
--alarm_action_id=<action-id> \
--alarm_enabled=true
Key Parameters:
alarm_name: Alarm rule name (must be unique)metric_namespace: Service namespace (SYS.ECS for ECS)metric_name: Metric name (cpu_util, mem_util, etc.)dim: Monitoring dimension (instance_id, etc.)condition: Alarm condition (threshold, period, etc.)alarm_action_id: SMN topic URN for notifications
ListAlarms
Function: Query alarm rule list
API: GET /v1.0/{project_id}/alarms
hcloud Command:
hcloud CES ListAlarms \
--cli-region=cn-north-4 \
--limit=100 \
--offset=0
Key Parameters:
limit: Number of results per page (default 100)offset: Offset for paginationalarm_type: Alarm type (MULTI_INSTANCE_ID, etc.)
UpdateAlarm
Function: Update alarm rule configuration
API: PUT /v1.0/{project_id}/alarms/{alarm_id}
hcloud Command:
hcloud CES UpdateAlarm \
--cli-region=cn-north-4 \
--alarm_id=alarm-001 \
--alarm_name=updated-alarm-name \
--alarm_enabled=true \
--condition.0.threshold=90
ShowMetricData
Function: Query monitoring metric data
API: POST /v1.0/{project_id}/metric-data
hcloud Command:
hcloud CES ShowMetricData \
--cli-region=cn-north-4 \
--namespace=SYS.ECS \
--metric_name=cpu_util \
--dim.0=instance_id,ecs-001 \
--from=2024-01-01T10:00:00Z \
--to=2024-01-01T11:00:00Z \
--period=300 \
--filter=average
Key Parameters:
namespace: Service namespacemetric_name: Metric namedim: Monitoring dimensionfrom: Start time (ISO 8601 format)to: End time (ISO 8601 format)period: Data aggregation interval (seconds)filter: Aggregation function (average, max, min)
ListMetrics
Function: Query available metrics
API: GET /v1.0/{project_id}/metrics
hcloud Command:
hcloud CES ListMetrics \
--cli-region=cn-north-4 \
--namespace=SYS.ECS
SMN APIs (Notifications)
ListTopics
Function: Query SMN topic list
API: GET /v2/{project_id}/notifications/topics
hcloud Command:
hcloud SMN ListTopics --cli-region=cn-north-4
Subscribe
Function: Subscribe endpoint to topic
API: POST /v2/{project_id}/notifications/topics/{topic_urn}/subscriptions
hcloud Command:
hcloud SMN Subscribe \
--cli-region=cn-north-4 \
--topic-urn=urn:smn:cn-north-4:xxx:topic-name \
--protocol=email \
--endpoint=user@example.com
Unsubscribe
Function: Unsubscribe endpoint from topic
API: DELETE /v2/{project_id}/notifications/topics/{topic_urn}/subscriptions/{subscription_urn}
hcloud Command:
hcloud SMN Unsubscribe \
--cli-region=cn-north-4 \
--subscription-urn=urn:smn:cn-north-4:xxx:topic-name:subscription-001
ECS APIs (Instance Query)
ListServersDetails
Function: Query ECS instance details
API: GET /v1/{project_id}/cloudservers/details
hcloud Command:
hcloud ECS ListServersDetails --cli-region=cn-north-4
API Documentation References
SMN Subscription Guide
Overview
This guide explains how to create email/SMS subscriptions for SMN (Simple Message Notification) topics to receive alarm notifications.
Method 1: Using Skill Script (Recommended)
The skill provides an automated script that uses your hcloud CLI configuration - no need to manually enter AK/SK.
Usage
cd /mnt/d/huaweicloud-skills/skills/monitoring/ecs/huawei-cloud-ecs-alert
./scripts/create_email_subscription.shWhat It Does
1. ✅ Checks hcloud CLI configuration 2. ✅ Creates email subscription to <your-email@example.com> 3. ✅ Uses the SMN topic (configured in script or via environment variable) 4. ✅ Returns subscription URN for verification
Expected Output
==========================================
SMN Email Subscription Created
==========================================
Topic: urn:smn:cn-north-4:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx:ECS_ALARM_NOTIFY
Email: user@example.com
Remark: ECS CPU Alarm Notification
Region: cn-north-4
Checking hcloud configuration...
✅ hcloud configuration is valid
Creating email subscription...
✅ Subscription created successfully!
Subscription URN: urn:smn:cn-north-4:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx:ECS_ALARM_NOTIFY:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
⚠️ IMPORTANT: Please check email at user@example.com and click the confirmation link
Subscription only becomes active after confirmation
==========================================
Complete
==========================================Next Steps
1. Check your email at <your-email@example.com> 2. Click the confirmation link in the email from Huawei Cloud 3. Verify subscription is active:
./scripts/list_subscriptions.shMethod 2: Huawei Cloud Console (Alternative)
If you prefer GUI operations:
Steps
1. Log in to Huawei Cloud Console
- URL: https://console.huaweicloud.com/smn/?region=cn-north-4
2. Navigate to Topics
- Left menu: Topic Management
- Region: Beijing 4 (cn-north-4)
3. Find the Topic
- Locate:
ECS_ALARM_NOTIFY_TEST
4. Create Subscription
- Click Subscribe button
- Fill in:
- Protocol: Email
- Endpoint:
<your-email@example.com> - Remark:
ECS CPU Alarm Notification - Click Create
5. Confirm Subscription
- Check email at the address you provided
- Click the confirmation link
Verification
After creating the subscription, verify it's active:
./scripts/list_subscriptions.shExpected output:
========== Topic List ==========
✓ ECS_ALARM_NOTIFY_TEST
========== Subscription List ==========
email -> user@example.com
Query completeTroubleshooting
Issue 1: Email Not Received
Possible Causes:
- Email went to spam folder
- Email address is incorrect
- Huawei Cloud email service delay
Solutions: 1. Check spam/junk folder 2. Verify email address is correct 3. Wait 5-10 minutes for delivery 4. Try recreating the subscription
Issue 2: Subscription Shows "Unconfirmed"
Solution:
- The subscription requires email confirmation
- Check email and click the confirmation link
- If email expired, delete and recreate the subscription
Issue 3: Permission Denied (403)
Solution:
- Ensure your account has
SMN FullAccesspolicy - Contact your account administrator to grant permissions
Security Notes
- ✅ Email subscriptions are tied to your Huawei Cloud account
- ✅ Confirmation links expire after 24 hours
- ✅ Each topic supports up to 10,000 subscriptions
- ✅ Delete unused subscriptions to avoid clutter
Related Documents
- CLI Installation Guide
- IAM Policies
- Troubleshooting
Troubleshooting
This document provides solutions for common issues encountered when using the CES alarm automation skill.
Installation Issues
Issue 1: hcloud Command Not Found
Symptom: Running hcloud version returns "command not found"
Solution:
# Install KooCLI
curl -o hcloud_install.sh https://hwcloudcli.obs.cn-north-4.myhuaweicloud.com/cli/latest/hcloud_install.sh
bash hcloud_install.sh
# Or install via pip
pip install hcloud
Issue 2: KooCLI Version Too Low
Symptom: hcloud version returns version < 7.2.2
Solution:
# Upgrade KooCLI
pip install --upgrade hcloud
# Verify version
hcloud version
Configuration Issues
Issue 3: AK/SK Not Configured
Symptom: Commands return "Error: AK/SK not configured"
Solution:
# Configure credentials
hcloud configure set --cli-access-key=<AK> --cli-secret-key=<SK>
hcloud configure set --cli-region=cn-north-4
# Verify configuration
hcloud configure list
Issue 4: 403 Forbidden
Symptom: API calls return 403 Forbidden error
Solution:
1. Check IAM permissions - ensure CES FullAccess is granted 2. Verify AK/SK credentials are correct 3. Check region parameter matches the resource location
# Verify IAM permissions
hcloud IAM ListPermissions
# Check resource region
hcloud ECS ListServersDetails --cli-region=cn-north-4
Alarm Creation Issues
Issue 5: Alarm Creation Fails
Symptom: CreateAlarm API returns error
Possible Causes:
1. Invalid metric name 2. Threshold out of range (0-100 for CPU/Memory) 3. Missing required parameters 4. Insufficient permissions
Solution:
# Verify metric name
hcloud CES ListMetrics --namespace=SYS.ECS --cli-region=cn-north-4
# Check threshold value (should be 0-100 for percentage metrics)
# Use dry-run to validate parameters
./scripts/create_alert_rules.sh --template web --ecs-ids ecs-001 --dry-run
Issue 6: Duplicate Alarm Name
Symptom: "Alarm with this name already exists"
Solution:
- Use unique alarm names
- Add suffix or timestamp to alarm names
- Check existing alarms:
./scripts/list_alarms.sh
Monitoring Data Issues
Issue 7: No Monitoring Data Returned
Symptom: ShowMetricData returns empty data
Possible Causes:
1. ECS instance is stopped 2. Metric collection interval (data has 5-minute delay) 3. Incorrect instance ID 4. Metric not enabled for the instance
Solution:
# Check ECS instance status
hcloud ECS ListServersDetails --cli-region=cn-north-4
# Verify instance ID is correct
./scripts/list_ecs.sh --output ids
# Wait 5-10 minutes and retry
./scripts/batch_query_metrics.sh --ecs-ids ecs-001 --metric cpu_util
Issue 8: Metric Data Delay
Symptom: Monitoring data is 5-10 minutes behind real-time
Solution: This is normal behavior. CES metric data has inherent delay. Wait for next collection cycle.
Notification Issues
Issue 9: SMN Subscription Fails
Symptom: Subscribe API returns error
Possible Causes:
1. Invalid topic URN 2. Topic does not exist 3. Insufficient SMN permissions
Solution:
# List available topics
hcloud SMN ListTopics --cli-region=cn-north-4
# Verify topic URN format
# Correct format: urn:smn:region:account-id:topic-name
# Check SMN permissions
hcloud IAM ListAttachedGroupPolicies --group-id=<group-id>
Issue 10: Notifications Not Received
Symptom: Alarm triggers but no notification received
Solution:
1. Verify subscription status is "Confirmed" 2. Check email spam folder 3. Verify phone number format for SMS 4. Test notification manually:
hcloud SMN PublishMessage --topic-urn=<topic-urn> --message="Test notification"
Script Execution Issues
Issue 11: Script Permission Denied
Symptom: Running script returns "Permission denied"
Solution:
# Add execute permission
chmod +x scripts/*.sh
# Or run with bash explicitly
bash scripts/list_ecs.sh
Issue 12: Script Output Format Error
Symptom: Script output is not in expected format
Solution:
- Check
--outputparameter (table/json/ids) - Verify jq is installed for JSON processing
- Check script has correct hcloud parameter format (--param=value)
Parameter Format Issues
Issue 13: hcloud Parameter Format Error
Symptom: Commands fail with parameter parsing errors
Solution: hcloud requires --param=value format (equals sign), not space separation.
# ✅ Correct
hcloud CES ListAlarms --region=cn-north-4
# ❌ Incorrect
hcloud CES ListAlarms --region cn-north-4
References
- Common Commands
- CLI Installation Guide
- IAM Policies
- Official CES Documentation
#!/usr/bin/env bash
# -*- coding: utf-8 -*-
#
# Batch Query Monitoring Metrics
# Function: Batch query monitoring data for multiple ECS instances (CPU/memory/disk, etc.)
#
# Usage:
# # Query CPU data for a single ECS
# ./scripts/batch_query_metrics.sh --ecs-ids ecs-001 --metric cpu_util --period 1h
#
# # Batch query multiple ECS instances
# ./scripts/batch_query_metrics.sh --ecs-ids ecs-001,ecs-002,ecs-003 --metric cpu_util --period 24h --format table
#
# # Export as JSON
# ./scripts/batch_query_metrics.sh --ecs-ids ecs-001 --metric cpu_util --period 24h --format json > metrics.json
#
set -e
# Default values
ECS_IDS=""
METRIC=""
PERIOD="1h"
OUTPUT_FORMAT="table"
REGION="${HUAWEI_CLOUD_REGION:-cn-north-4}"
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--ecs-ids|-i)
ECS_IDS="$2"
shift 2
;;
--metric|-m)
METRIC="$2"
shift 2
;;
--period|-p)
PERIOD="$2"
shift 2
;;
--format|-f)
OUTPUT_FORMAT="$2"
shift 2
;;
--region|-r)
REGION="$2"
shift 2
;;
--help|-h)
echo "Usage: $0 [options]"
echo ""
echo "Options:"
echo " --ecs-ids, -i IDS List of ECS instance IDs (comma-separated)"
echo " --metric, -m METRIC Monitoring metric (cpu_util, memory_util, disk_util, etc.)"
echo " --period, -p PERIOD Time range (1h, 24h, 7d, 30d)"
echo " --format, -f FORMAT Output format: table (default), json, csv"
echo " --region, -r REGION Huawei Cloud region (default: cn-north-4)"
echo " --help, -h Show this help message"
echo ""
echo "Common metrics:"
echo " cpu_util - CPU utilization (%)"
echo " memory_util - Memory utilization (%) (requires Agent)"
echo " disk_util - Disk utilization (%) (requires Agent)"
echo " net_bitRecv - Network inbound traffic (Kbps)"
echo " net_bitSent - Network outbound traffic (Kbps)"
exit 0
;;
*)
echo "Unknown option: $1" >&2
echo "Use --help to see usage" >&2
exit 1
;;
esac
done
# Validate parameters
if [[ -z "$ECS_IDS" ]]; then
echo "Error: --ecs-ids is required" >&2
exit 1
fi
if [[ -z "$METRIC" ]]; then
echo "Error: --metric is required" >&2
exit 1
fi
# Check if hcloud is installed
if ! command -v hcloud &> /dev/null; then
echo "Error: hcloud command not found" >&2
exit 1
fi
# Parse time range
parse_period() {
local period="$1"
local now
now=$(date +%s)
case $period in
1h)
echo $((now - 3600))
;;
24h)
echo $((now - 86400))
;;
7d)
echo $((now - 604800))
;;
30d)
echo $((now - 2592000))
;;
*)
# Default 1 hour
echo $((now - 3600))
;;
esac
}
# Query monitoring data
query_metric() {
local ecs_id="$1"
local metric="$2"
local from_ts="$3"
local to_ts="$4"
local region="$5"
# Convert to milliseconds
local from_ms=$((from_ts * 1000))
local to_ms=$((to_ts * 1000))
hcloud CES ShowMetricData \
--cli-region="$region" \
--namespace=SYS.ECS \
--metric_name="$metric" \
--dim.0="instance_id,$ecs_id" \
--period=300 \
--filter=average \
--from="$from_ms" \
--to="$to_ms"
}
# Main logic
main() {
echo "Batch querying monitoring data..." >&2
echo " Region: $REGION" >&2
echo " Metric: $METRIC" >&2
echo " Time range: $PERIOD" >&2
echo " ECS count: $(echo "$ECS_IDS" | tr ',' '\n' | wc -l)" >&2
echo "" >&2
# Calculate time range
local to_ts
to_ts=$(date +%s)
local from_ts
from_ts=$(parse_period "$PERIOD")
# Store results
declare -A results
# Query monitoring data for each ECS
IFS=',' read -ra IDS <<< "$ECS_IDS"
for ecs_id in "${IDS[@]}"; do
echo "Querying ECS: $ecs_id" >&2
local metric_data
metric_data=$(query_metric "$ecs_id" "$METRIC" "$from_ts" "$to_ts" "$REGION" 2>/dev/null || echo "{}")
results["$ecs_id"]="$metric_data"
done
echo "" >&2
# Process based on output format
case $OUTPUT_FORMAT in
json)
echo "{"
local first=true
for ecs_id in "${!results[@]}"; do
if [[ "$first" == true ]]; then
first=false
else
echo ","
fi
echo " \"$ecs_id\": ${results[$ecs_id]}"
done
echo "}"
;;
csv)
echo "ecs_id,timestamp,value"
for ecs_id in "${!results[@]}"; do
echo "${results[$ecs_id]}" | python3 -c "
import sys, json
data = json.load(sys.stdin)
datapoints = data.get('datapoints', [])
for dp in datapoints:
ts = dp.get('timestamp', '')
val = dp.get('average', '')
print(f'$ecs_id,{ts},{val}')
"
done
;;
table|*)
echo "================================================================================"
echo "Monitoring Data Query Results"
echo "================================================================================"
echo ""
for ecs_id in "${!results[@]}"; do
echo "ECS: $ecs_id"
echo "${results[$ecs_id]}" | python3 -c "
import sys, json
data = json.load(sys.stdin)
datapoints = data.get('datapoints', [])
if not datapoints:
print(' No data available')
else:
values = [dp.get('average', 0) for dp in datapoints]
avg_val = sum(values) / len(values) if values else 0
max_val = max(values) if values else 0
min_val = min(values) if values else 0
print(f' Data points: {len(datapoints)}')
print(f' Average: {avg_val:.2f}')
print(f' Maximum: {max_val:.2f}')
print(f' Minimum: {min_val:.2f}')
"
echo ""
done
;;
esac
echo "Query complete" >&2
}
main
#!/usr/bin/env bash
# -*- coding: utf-8 -*-
#
# Create CES Alarm Rules (using hcloud CLI)
# Function: Create alarm rules for ECS instances, supports preset templates or custom thresholds
#
# Usage:
# # Use web template
# ./scripts/create_alert_rules.sh --template web --ecs-ids ecs-001,ecs-002
#
# # Custom threshold
# ./scripts/create_alert_rules.sh --metric cpu_util --threshold 80 --ecs-ids ecs-001
#
# # With notifications
# ./scripts/create_alert_rules.sh --template web --ecs-ids ecs-001 --smn-topic-urn urn:smn:cn-north-4:xxx:ECS_ALARM_NOTIFY
#
set -e
# Default values
TEMPLATE=""
ECS_IDS=""
METRIC=""
THRESHOLD=""
OPERATOR=">"
LEVEL=2
SMN_TOPIC_URN=""
DRY_RUN=false
REGION="${HUAWEI_CLOUD_REGION:-cn-north-4}"
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--template|-t)
TEMPLATE="$2"
shift 2
;;
--ecs-ids|-i)
ECS_IDS="$2"
shift 2
;;
--metric|-m)
METRIC="$2"
shift 2
;;
--threshold)
THRESHOLD="$2"
shift 2
;;
--operator|-o)
OPERATOR="$2"
shift 2
;;
--level|-l)
LEVEL="$2"
shift 2
;;
--smn-topic-urn)
SMN_TOPIC_URN="$2"
shift 2
;;
--dry-run)
DRY_RUN=true
shift
;;
--region|-r)
REGION="$2"
shift 2
;;
--help|-h)
echo "Usage: $0 [options]"
echo ""
echo "Options:"
echo " --template, -t TEMPLATE Preset template (web, database)"
echo " --ecs-ids, -i IDS List of ECS instance IDs (comma-separated)"
echo " --metric, -m METRIC Monitoring metric (cpu_util, memory_util, etc.)"
echo " --threshold VALUE Alarm threshold"
echo " --operator, -o OPERATOR Comparison operator (>, <, >=, <=)"
echo " --level, -l LEVEL Alarm level (1=Info, 2=Important, 3=Minor, 4=General)"
echo " --smn-topic-urn URN SMN topic URN (for alarm notifications)"
echo " --dry-run Preview configuration without creating"
echo " --region, -r REGION Huawei Cloud region (default: cn-north-4)"
echo " --help, -h Show this help message"
echo ""
echo "Preset templates:"
echo " web - Web server template (CPU > 70%, period 5min, count 3)"
echo " database - Database template (CPU > 80%, period 5min, count 5)"
echo ""
echo "Examples:"
echo " # Create CPU alarm for multiple ECS using web template"
echo " $0 --template web --ecs-ids ecs-001,ecs-002"
echo ""
echo " # Create custom memory alarm"
echo " $0 --metric memory_util --threshold 85 --ecs-ids ecs-001"
exit 0
;;
*)
echo "Unknown option: $1" >&2
echo "Use --help to see usage" >&2
exit 1
;;
esac
done
# Validate parameters
if [[ -z "$ECS_IDS" ]]; then
echo "Error: --ecs-ids is required" >&2
exit 1
fi
# Check if hcloud is installed
if ! command -v hcloud &> /dev/null; then
echo "Error: hcloud command not found" >&2
exit 1
fi
# Template configuration
declare -A TEMPLATES
TEMPLATES[web]="cpu_util,70,>,2,5,3"
TEMPLATES[database]="cpu_util,80,>,2,5,5"
# Parse template or use custom values
if [[ -n "$TEMPLATE" ]]; then
if [[ -z "${TEMPLATES[$TEMPLATE]}" ]]; then
echo "Error: Unknown template '$TEMPLATE'. Available: web, database" >&2
exit 1
fi
IFS=',' read -r METRIC THRESHOLD OPERATOR LEVEL PERIOD COUNT <<< "${TEMPLATES[$TEMPLATE]}"
echo "Using template: $TEMPLATE" >&2
echo " Metric: $METRIC" >&2
echo " Threshold: $THRESHOLD" >&2
echo " Operator: $OPERATOR" >&2
echo " Level: $LEVEL" >&2
echo " Period: $PERIOD min" >&2
echo " Count: $COUNT" >&2
else
# Validate custom parameters
if [[ -z "$METRIC" ]] || [[ -z "$THRESHOLD" ]]; then
echo "Error: When not using --template, both --metric and --threshold are required" >&2
exit 1
fi
PERIOD=5
COUNT=3
fi
# Main logic
main() {
echo "Creating alarm rules..." >&2
echo " Region: $REGION" >&2
echo " Metric: $METRIC" >&2
echo " Threshold: $THRESHOLD $OPERATOR" >&2
echo " ECS count: $(echo "$ECS_IDS" | tr ',' '\n' | wc -l)" >&2
echo "" >&2
if [[ "$DRY_RUN" == true ]]; then
echo "[DRY RUN] Would create the following alarms:" >&2
IFS=',' read -ra IDS <<< "$ECS_IDS"
for ecs_id in "${IDS[@]}"; do
echo " - Alarm: ECS-${ecs_id:0:8}-${METRIC}" >&2
done
exit 0
fi
# Create alarm for each ECS
IFS=',' read -ra IDS <<< "$ECS_IDS"
for ecs_id in "${IDS[@]}"; do
# Shorten ECS ID for alarm name (first 8 chars)
local ecs_short="${ecs_id:0:8}"
# Replace underscores with hyphens in metric name
local metric_clean="${METRIC//_/-}"
local alarm_name="ECS-${ecs_short}-${metric_clean}"
echo "Creating alarm for ECS: $ecs_id" >&2
echo " Alarm name: $alarm_name" >&2
# Build hcloud command
local cmd="hcloud CES CreateAlarm \\
--cli-region=\"$REGION\" \\
--alarm_name=\"$alarm_name\" \\
--alarm_type=\"MONITOR\" \\
--alarm_level=$LEVEL \\
--namespace=SYS.ECS \\
--metric_name=\"$METRIC\" \\
--dim.0=\"instance_id,$ecs_id\" \\
--period=$PERIOD \\
--filter=average \\
--condition.0.metric_name=\"$METRIC\" \\
--condition.0.operator=\"$OPERATOR\" \\
--condition.0.threshold=$THRESHOLD \\
--condition.0.count=$COUNT \\
--condition.0.unit=\"\" \\
--alarm_enabled=true"
# Add SMN notification if provided
if [[ -n "$SMN_TOPIC_URN" ]]; then
cmd="$cmd \\
--ok_actions.0=\"$SMN_TOPIC_URN\" \\
--alarm_actions.0=\"$SMN_TOPIC_URN\""
fi
# Execute command
if eval "$cmd"; then
echo " ✓ Alarm created successfully" >&2
else
echo " ✗ Failed to create alarm" >&2
fi
echo "" >&2
done
echo "Alarm creation complete" >&2
}
main
#!/bin/bash
# SMN Email Subscription Creation Script
# Automatically uses hcloud CLI configured AK/SK, no need to set environment variables manually
#
# Usage:
# ./scripts/create_email_subscription.sh
set -e
# Support environment variable configuration or use default placeholder values
TOPIC_URN="${SMN_TOPIC_URN:-urn:smn:cn-north-4:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx:ECS_ALARM_NOTIFY}"
ENDPOINT="${ENDPOINT:-}"
REMARK="${REMARK:-ECS CPU Alarm Notification}"
REGION="${REGION:-cn-north-4}"
# If email is not provided, prompt for interactive input
if [ -z "$ENDPOINT" ]; then
echo "=========================================="
echo "SMN Email Subscription Creation"
echo "=========================================="
echo ""
read -p "Please enter the email address to receive alarms: " ENDPOINT
if [ -z "$ENDPOINT" ]; then
echo "❌ Error: Email address cannot be empty"
exit 1
fi
echo ""
fi
# Check if hcloud is available
if ! command -v hcloud &> /dev/null; then
echo "❌ Error: hcloud command not found"
echo "Please install Huawei Cloud CLI (KooCLI) >= 7.2.2 first"
exit 1
fi
# Check hcloud configuration
echo "Checking hcloud configuration..."
if ! hcloud configure list &> /dev/null; then
echo "❌ Error: hcloud credentials not configured"
echo "Please run 'hcloud configure' to configure AK/SK first"
exit 1
fi
echo "✅ hcloud configuration OK"
echo ""
# Create subscription
echo "Creating email subscription..."
RESULT=$(hcloud SMN AddSubscription \
--cli-region="$REGION" \
--topic_urn="$TOPIC_URN" \
--protocol=email \
--endpoint="$ENDPOINT" \
--remark="$REMARK" 2>&1)
# Parse result
if echo "$RESULT" | grep -q "subscription_urn"; then
SUBSCRIPTION_URN=$(echo "$RESULT" | grep -oP 'urn:smn:[^"]*')
echo ""
echo "✅ Subscription created successfully!"
echo " Subscription URN: $SUBSCRIPTION_URN"
echo ""
echo "⚠️ IMPORTANT: Please check email $ENDPOINT and click the confirmation link"
echo " Subscription will only be active after confirmation to receive alarm notifications"
echo ""
echo "=========================================="
echo "Complete"
echo "=========================================="
exit 0
else
echo "❌ Failed: $RESULT"
exit 1
fi
#!/usr/bin/env bash
# -*- coding: utf-8 -*-
#
# Query CES Alarm Rule List
# Function: Query and list all alarm rules, supports filtering by name/tag, outputs formatted list
#
# Usage:
# # Query all alarms
# ./scripts/list_alarms.sh
#
# # Filter by name
# ./scripts/list_alarms.sh --name ECS
#
# # Output as JSON
# ./scripts/list_alarms.sh --format json
set -e
# Default values
NAME_FILTER=""
OUTPUT_FORMAT="table"
REGION="${HUAWEI_CLOUD_REGION:-cn-north-4}"
PAGE_SIZE=100
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--name|-n)
NAME_FILTER="$2"
shift 2
;;
--format|-f)
OUTPUT_FORMAT="$2"
shift 2
;;
--region|-r)
REGION="$2"
shift 2
;;
--help|-h)
echo "Usage: $0 [options]"
echo ""
echo "Options:"
echo " --name, -n NAME Filter alarms by name (supports partial match)"
echo " --format, -f FORMAT Output format: table (default), json"
echo " --region, -r REGION Huawei Cloud region (default: cn-north-4)"
echo " --help, -h Show this help message"
exit 0
;;
*)
echo "Unknown option: $1" >&2
echo "Use --help to see usage" >&2
exit 1
;;
esac
done
# Check if hcloud is installed
if ! command -v hcloud &> /dev/null; then
echo "Error: hcloud command not found" >&2
exit 1
fi
# Main logic
main() {
echo "Querying alarm rules..." >&2
echo " Region: $REGION" >&2
if [[ -n "$NAME_FILTER" ]]; then
echo " Filter: name contains '$NAME_FILTER'" >&2
fi
echo "" >&2
# Build command
local cmd="hcloud CES ListAlarms \
--cli-region=\"$REGION\" \
--limit=$PAGE_SIZE"
if [[ -n "$NAME_FILTER" ]]; then
cmd="$cmd --alarm_name=\"$NAME_FILTER\""
fi
# Execute and parse results
local result
result=$(eval "$cmd" 2>/dev/null)
if [[ "$OUTPUT_FORMAT" == "json" ]]; then
echo "$result"
else
# Parse and display as table
echo "================================================================================"
echo "CES Alarm Rule List"
echo "================================================================================"
echo ""
# Use Python to parse JSON and format output
echo "$result" | python3 -c "
import sys, json
try:
data = json.load(sys.stdin)
alarms = data.get('alarms', [])
if not alarms:
print('No alarm rules found')
sys.exit(0)
print(f'Found {len(alarms)} alarm rule(s)')
print('')
print(f'{\"ID\":<40} {\"Name\":<35} {\"Metric\":<20} {\"Level\":<6} {\"Status\":<10}')
print('-' * 115)
for alarm in alarms:
alarm_id = alarm.get('alarm_id', 'N/A')[:36]
name = alarm.get('alarm_name', 'N/A')[:30]
metric = alarm.get('metric_name', 'N/A')
level = alarm.get('alarm_level', 'N/A')
status = alarm.get('alarm_enabled', False)
status_str = 'Enabled' if status else 'Disabled'
# Truncate long IDs with ellipsis
if len(alarm_id) > 36:
alarm_id = alarm_id[:33] + '...'
print(f'{alarm_id:<40} {name:<35} {metric:<20} {level:<6} {status_str:<10}')
print('')
print('Query complete')
except Exception as e:
print(f'Error parsing response: {e}', file=sys.stderr)
print('Raw response:')
print(data)
sys.exit(1)
"
fi
}
main
#!/usr/bin/env bash
# -*- coding: utf-8 -*-
#
# Query ECS Instance List
# Function: Query and list all ECS instances, supports filtering by name, outputs formatted list
#
# Usage:
# # Query all ECS instances
# ./scripts/list_ecs.sh
#
# # Filter by name
# ./scripts/list_ecs.sh --name web
#
# # Output as JSON
# ./scripts/list_ecs.sh --format json
set -e
# Default values
NAME_FILTER=""
OUTPUT_FORMAT="table"
REGION="${HUAWEI_CLOUD_REGION:-cn-north-4}"
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--name|-n)
NAME_FILTER="$2"
shift 2
;;
--format|-f)
OUTPUT_FORMAT="$2"
shift 2
;;
--region|-r)
REGION="$2"
shift 2
;;
--help|-h)
echo "Usage: $0 [options]"
echo ""
echo "Options:"
echo " --name, -n NAME Filter ECS by name (supports partial match)"
echo " --format, -f FORMAT Output format: table (default), json"
echo " --region, -r REGION Huawei Cloud region (default: cn-north-4)"
echo " --help, -h Show this help message"
exit 0
;;
*)
echo "Unknown option: $1" >&2
echo "Use --help to see usage" >&2
exit 1
;;
esac
done
# Check if hcloud is installed
if ! command -v hcloud &> /dev/null; then
echo "Error: hcloud command not found" >&2
exit 1
fi
# Main logic
main() {
echo "Querying ECS instances..." >&2
echo " Region: $REGION" >&2
if [[ -n "$NAME_FILTER" ]]; then
echo " Filter: name contains '$NAME_FILTER'" >&2
fi
echo "" >&2
# Build command
local cmd="hcloud ECS ListServersDetails \
--cli-region=\"$REGION\" \
--limit=100"
if [[ -n "$NAME_FILTER" ]]; then
cmd="$cmd --name=\"$NAME_FILTER\""
fi
# Execute and parse results
local result
result=$(eval "$cmd" 2>/dev/null)
if [[ "$OUTPUT_FORMAT" == "json" ]]; then
echo "$result"
else
# Parse and display as table
echo "================================================================================"
echo "ECS Instance List"
echo "================================================================================"
echo ""
# Use Python to parse JSON and format output
echo "$result" | python3 -c "
import sys, json
try:
data = json.load(sys.stdin)
servers = data.get('servers', [])
if not servers:
print('No ECS instances found')
sys.exit(0)
print(f'Found {len(servers)} ECS instance(s)')
print('')
print(f'{\"ID\":<40} {\"Name\":<25} {\"Status\":<12} {\"Flavor\":<20} {\"IP Address\":<18}')
print('-' * 115)
for server in servers:
server_id = server.get('id', 'N/A')[:36]
name = server.get('name', 'N/A')[:22]
status = server.get('status', 'N/A')
flavor = server.get('flavor', {}).get('name', 'N/A')[:17]
# Get first IP address
addresses = server.get('addresses', {})
ip = 'N/A'
for network, addr_list in addresses.items():
if addr_list:
ip = addr_list[0].get('addr', 'N/A')[:15]
break
print(f'{server_id:<40} {name:<25} {status:<12} {flavor:<20} {ip:<18}')
print('')
print('Query complete')
except Exception as e:
print(f'Error parsing response: {e}', file=sys.stderr)
sys.exit(1)
"
fi
}
main
#!/usr/bin/env bash
# -*- coding: utf-8 -*-
#
# Query SMN Topics and Subscriptions List
# Usage:
# # Query all topics
# ./scripts/list_subscriptions.sh
#
# # Query topic list only
# ./scripts/list_subscriptions.sh --topics
#
# # Query subscription list only
# ./scripts/list_subscriptions.sh --subscriptions
set -e
# Default values
MODE="both"
REGION="${HUAWEI_CLOUD_REGION:-cn-north-4}"
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--topics|-t)
MODE="topics"
shift
;;
--subscriptions|-s)
MODE="subscriptions"
shift
;;
--region|-r)
REGION="$2"
shift 2
;;
--help|-h)
echo "Usage: $0 [options]"
echo ""
echo "Options:"
echo " --topics, -t List SMN topics only"
echo " --subscriptions, -s List SMN subscriptions only"
echo " --region, -r REGION Huawei Cloud region (default: cn-north-4)"
echo " --help, -h Show this help message"
echo ""
echo "Examples:"
echo " # List both topics and subscriptions"
echo " $0"
echo ""
echo " # List topics only"
echo " $0 --topics"
exit 0
;;
*)
echo "Unknown option: $1" >&2
echo "Use --help to see usage" >&2
exit 1
;;
esac
done
# Check if hcloud is installed
if ! command -v hcloud &> /dev/null; then
echo "Error: hcloud command not found" >&2
exit 1
fi
# List topics
list_topics() {
echo "Querying SMN topics..." >&2
echo " Region: $REGION" >&2
echo "" >&2
local result
result=$(hcloud SMN ListTopics --cli-region="$REGION" 2>/dev/null)
echo "================================================================================"
echo "SMN Topic List"
echo "================================================================================"
echo ""
echo "$result" | python3 -c "
import sys, json
try:
data = json.load(sys.stdin)
topics = data.get('topics', [])
if not topics:
print('No SMN topics found')
sys.exit(0)
print(f'Found {len(topics)} topic(s)')
print('')
print(f'{\"Topic Name\":<35} {\"Topic URN\":<80}')
print('-' * 115)
for topic in topics:
name = topic.get('name', 'N/A')[:32]
urn = topic.get('topic_urn', 'N/A')
print(f'{name:<35} {urn:<80}')
print('')
except Exception as e:
print(f'Error parsing response: {e}', file=sys.stderr)
sys.exit(1)
"
}
# List subscriptions
list_subscriptions() {
echo "Querying SMN subscriptions..." >&2
echo " Region: $REGION" >&2
echo "" >&2
local result
result=$(hcloud SMN ListSubscriptions --cli-region="$REGION" 2>/dev/null)
echo "================================================================================"
echo "SMN Subscription List"
echo "================================================================================"
echo ""
echo "$result" | python3 -c "
import sys, json
try:
data = json.load(sys.stdin)
subscriptions = data.get('subscriptions', [])
if not subscriptions:
print('No SMN subscriptions found')
sys.exit(0)
print(f'Found {len(subscriptions)} subscription(s)')
print('')
print(f'{\"Protocol\":<12} {\"Endpoint\":<35} {\"Topic Name\":<30} {\"Status\":<10}')
print('-' * 90)
for sub in subscriptions:
protocol = sub.get('protocol', 'N/A')
endpoint = sub.get('endpoint', 'N/A')[:32]
topic_name = sub.get('topic_name', 'N/A')[:27]
status = sub.get('status', 0)
status_str = 'Confirmed' if status == 1 else 'Pending'
print(f'{protocol:<12} {endpoint:<35} {topic_name:<30} {status_str:<10}')
print('')
print('Note: Status 1 = Confirmed, 0 = Pending confirmation')
except Exception as e:
print(f'Error parsing response: {e}', file=sys.stderr)
sys.exit(1)
"
}
# Main logic
case $MODE in
topics)
list_topics
;;
subscriptions)
list_subscriptions
;;
both)
list_topics
echo ""
list_subscriptions
;;
esac
echo "Query complete" >&2
#!/usr/bin/env bash
# -*- coding: utf-8 -*-
#
# Manage Alarm Notifications (SMN Topic Subscriptions)
# Function: Create/delete SMN subscriptions, configure alarm notification recipients
#
# Usage:
# # Create email subscription (requires token confirmation, recommended via console)
# ./scripts/manage_notifications.sh --action create --protocol email --endpoint user@example.com --topic-urn urn:smn:xxx
#
# # Delete subscription
# ./scripts/manage_notifications.sh --action delete --subscription-urn urn:smn:xxx:subscription
set -e
# Default values
ACTION=""
PROTOCOL=""
ENDPOINT=""
TOPIC_URN=""
SUBSCRIPTION_URN=""
REMARK="ECS Alarm Notification"
REGION="${HUAWEI_CLOUD_REGION:-cn-north-4}"
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--action|-a)
ACTION="$2"
shift 2
;;
--protocol|-p)
PROTOCOL="$2"
shift 2
;;
--endpoint|-e)
ENDPOINT="$2"
shift 2
;;
--topic-urn)
TOPIC_URN="$2"
shift 2
;;
--subscription-urn)
SUBSCRIPTION_URN="$2"
shift 2
;;
--remark)
REMARK="$2"
shift 2
;;
--region|-r)
REGION="$2"
shift 2
;;
--help|-h)
echo "Usage: $0 [options]"
echo ""
echo "Options:"
echo " --action, -a ACTION Action: create, delete"
echo " --protocol, -p PROTOCOL Protocol: email, sms (required for create)"
echo " --endpoint, -e ENDPOINT Endpoint: email address or phone number (required for create)"
echo " --topic-urn URN SMN topic URN (required for create)"
echo " --subscription-urn URN SMN subscription URN (required for delete)"
echo " --remark TEXT Subscription remark (optional)"
echo " --region, -r REGION Huawei Cloud region (default: cn-north-4)"
echo " --help, -h Show this help message"
echo ""
echo "Examples:"
echo " # Create email subscription"
echo " $0 --action create --protocol email --endpoint user@example.com --topic-urn urn:smn:cn-north-4:xxx:ECS_ALARM"
echo ""
echo " # Delete subscription"
echo " $0 --action delete --subscription-urn urn:smn:cn-north-4:xxx:subscription-id"
exit 0
;;
*)
echo "Unknown option: $1" >&2
echo "Use --help to see usage" >&2
exit 1
;;
esac
done
# Check if hcloud is installed
if ! command -v hcloud &> /dev/null; then
echo "Error: hcloud command not found" >&2
exit 1
fi
# Validate parameters
if [[ -z "$ACTION" ]]; then
echo "Error: --action is required (create or delete)" >&2
exit 1
fi
# Main logic
case $ACTION in
create)
if [[ -z "$PROTOCOL" ]] || [[ -z "$ENDPOINT" ]] || [[ -z "$TOPIC_URN" ]]; then
echo "Error: For create action, --protocol, --endpoint, and --topic-urn are required" >&2
exit 1
fi
echo "Creating SMN subscription..." >&2
echo " Region: $REGION" >&2
echo " Protocol: $PROTOCOL" >&2
echo " Endpoint: $ENDPOINT" >&2
echo " Topic URN: $TOPIC_URN" >&2
echo " Remark: $REMARK" >&2
echo "" >&2
RESULT=$(hcloud SMN AddSubscription \
--cli-region="$REGION" \
--topic_urn="$TOPIC_URN" \
--protocol="$PROTOCOL" \
--endpoint="$ENDPOINT" \
--remark="$REMARK" 2>&1)
if echo "$RESULT" | grep -q "subscription_urn"; then
SUBSCRIPTION_URN=$(echo "$RESULT" | grep -oP 'urn:smn:[^"]*')
echo "✅ Subscription created successfully!" >&2
echo " Subscription URN: $SUBSCRIPTION_URN" >&2
echo "" >&2
if [[ "$PROTOCOL" == "email" ]]; then
echo "⚠️ IMPORTANT: Please check email $ENDPOINT and click the confirmation link" >&2
echo " Subscription will only be active after confirmation" >&2
fi
else
echo "❌ Failed to create subscription: $RESULT" >&2
exit 1
fi
;;
delete)
if [[ -z "$SUBSCRIPTION_URN" ]]; then
echo "Error: For delete action, --subscription-urn is required" >&2
exit 1
fi
echo "Deleting SMN subscription..." >&2
echo " Subscription URN: $SUBSCRIPTION_URN" >&2
echo " Region: $REGION" >&2
echo "" >&2
if hcloud SMN DeleteSubscription \
--cli-region="$REGION" \
--subscription_urn="$SUBSCRIPTION_URN" 2>&1; then
echo "✅ Subscription deleted successfully" >&2
else
echo "❌ Failed to delete subscription" >&2
exit 1
fi
;;
*)
echo "Error: Unknown action '$ACTION'. Valid actions: create, delete" >&2
exit 1
;;
esac
echo "Operation complete" >&2
#!/usr/bin/env bash
# -*- coding: utf-8 -*-
#
# Update Alarm Rule Notification Configuration
# Function: Add/modify/remove SMN notifications for existing alarm rules
#
# Usage:
# # Add notification to alarm
# ./scripts/update_alarm_notifications.sh --action add --alarm-id xxx --smn-topic-urn urn:smn:xxx
#
# # Remove notification from alarm
# ./scripts/update_alarm_notifications.sh --action remove --alarm-id xxx
set -e
# Default values
ACTION=""
ALARM_ID=""
SMN_TOPIC_URN=""
REGION="${HUAWEI_CLOUD_REGION:-cn-north-4}"
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--action|-a)
ACTION="$2"
shift 2
;;
--alarm-id)
ALARM_ID="$2"
shift 2
;;
--smn-topic-urn)
SMN_TOPIC_URN="$2"
shift 2
;;
--region|-r)
REGION="$2"
shift 2
;;
--help|-h)
echo "Usage: $0 [options]"
echo ""
echo "Options:"
echo " --action, -a ACTION Action: add, remove"
echo " --alarm-id ID Alarm rule ID (required)"
echo " --smn-topic-urn URN SMN topic URN (required for add action)"
echo " --region, -r REGION Huawei Cloud region (default: cn-north-4)"
echo " --help, -h Show this help message"
echo ""
echo "Examples:"
echo " # Add notification to alarm"
echo " $0 --action add --alarm-id alrm-xxx --smn-topic-urn urn:smn:cn-north-4:xxx:ECS_ALARM"
echo ""
echo " # Remove notification from alarm"
echo " $0 --action remove --alarm-id alrm-xxx"
exit 0
;;
*)
echo "Unknown option: $1" >&2
echo "Use --help to see usage" >&2
exit 1
;;
esac
done
# Check if hcloud is installed
if ! command -v hcloud &> /dev/null; then
echo "Error: hcloud command not found" >&2
exit 1
fi
# Validate parameters
if [[ -z "$ALARM_ID" ]]; then
echo "Error: --alarm-id is required" >&2
exit 1
fi
if [[ -z "$ACTION" ]]; then
echo "Error: --action is required (add or remove)" >&2
exit 1
fi
# Main logic
case $ACTION in
add)
if [[ -z "$SMN_TOPIC_URN" ]]; then
echo "Error: For add action, --smn-topic-urn is required" >&2
exit 1
fi
echo "Adding notification to alarm..." >&2
echo " Alarm ID: $ALARM_ID" >&2
echo " SMN Topic URN: $SMN_TOPIC_URN" >&2
echo " Region: $REGION" >&2
echo "" >&2
# Update alarm with notification
if hcloud CES UpdateAlarm \
--cli-region="$REGION" \
--alarm_id="$ALARM_ID" \
--ok_actions.0="$SMN_TOPIC_URN" \
--alarm_actions.0="$SMN_TOPIC_URN" 2>&1; then
echo "✅ Notification added successfully" >&2
else
echo "❌ Failed to add notification" >&2
exit 1
fi
;;
remove)
echo "Removing notification from alarm..." >&2
echo " Alarm ID: $ALARM_ID" >&2
echo " Region: $REGION" >&2
echo "" >&2
# Update alarm without notifications (empty arrays)
if hcloud CES UpdateAlarm \
--cli-region="$REGION" \
--alarm_id="$ALARM_ID" \
--ok_actions="" \
--alarm_actions="" 2>&1; then
echo "✅ Notification removed successfully" >&2
else
echo "❌ Failed to remove notification" >&2
exit 1
fi
;;
*)
echo "Error: Unknown action '$ACTION'. Valid actions: add, remove" >&2
exit 1
;;
esac
echo "Operation complete" >&2