huawei-cloud-flexus-l-server-scripts-excute

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
⚠️ Security Execution Rules (Highest Priority):
  1. All scripts MUST be executed via skill action=exec, NEVER run directly in shell
  2. NEVER print script contents or commands containing AK/SK/Token in conversation
  3. NEVER create temporary script files, prefer inline execution (python -c)
  4. On execution failure, only return error info, do NOT rewrite scripts or print full commands
  5. AK/SK/Token MUST be passed via environment variables, NEVER appear in conversation
  6. ABSOLUTELY NEVER expose, log, or print AK/SK/Token values in any form - this is a critical security requirement
  7. Credentials are resolved in priority order: environment variables (HW_ACCESS_KEY, HW_SECRET_KEY, HW_SECURITY_TOKEN, HW_REGION) -> command-line args -> interactive prompt. Prefer environment variables; do NOT pass AK/SK as command-line arguments.
⚠️ 安全执行规则(最高优先级):
  1. 所有脚本必须通过skill action=exec执行,严禁直接在shell中运行
  2. 严禁在对话中打印包含AK/SK/Token的脚本内容或命令
  3. 严禁创建临时脚本文件,优先使用内联执行方式(如python -c)
  4. 执行失败时,仅返回错误信息,不得重写脚本或打印完整命令
  5. AK/SK/Token必须通过环境变量传递,严禁出现在对话中
  6. 绝对禁止以任何形式暴露、记录或打印AK/SK/Token值——这是关键安全要求
  7. 凭证优先级解析顺序:环境变量 (HW_ACCESS_KEY, HW_SECRET_KEY, HW_SECURITY_TOKEN, HW_REGION) -> 命令行参数 -> 交互式提示。优先使用环境变量;严禁将AK/SK作为命令行参数传递。

Huawei Cloud Flexus L Instance COC Skill

华为云Flexus L实例COC Skill

Overview

概述

Architecture Diagram

架构图

This skill is built on Huawei Cloud COC (Cloud Operations Center) service, involving the following cloud services and components:
User/Agent    │──────▶│   COC API   │──────▶│   UniAgent    │──────▶│  Flexus L Instance│
(Skill caller)       (Cloud Ops Center)       (Proxy program)              (Target Host) 
Component Description:
  • User/Agent: Skill caller that triggers script management operations via natural language or API
  • COC API: Huawei Cloud COC (Cloud Operations Center) provides core capabilities including script management, execution scheduling, and status query
  • UniAgent: Agent program deployed on target hosts, responsible for receiving scripts and executing them locally
  • Flexus L Instance: Huawei Cloud Elastic Cloud Server, serving as the target host for script execution
本Skill基于华为云COC(Cloud Operations Center)服务构建,涉及以下云服务与组件:
User/Agent    │──────▶│   COC API   │──────▶│   UniAgent    │──────▶│  Flexus L Instance│
(Skill调用方)       (云运维中心)       (代理程序)              (目标主机) 
组件说明:
  • User/Agent: 通过自然语言或API触发脚本管理操作的Skill调用方
  • COC API: 华为云COC(Cloud Operations Center)提供脚本管理、执行调度、状态查询等核心能力
  • UniAgent: 部署在目标主机上的代理程序,负责接收脚本并在本地执行
  • Flexus L Instance: 华为云弹性云服务器,作为脚本执行的目标主机

Applicable Scenarios

适用场景

  • Batch Operations: Execute the same script on multiple Flexus L instances (e.g., software installation, configuration updates)
  • Automated Operations: Periodically execute inspection scripts, log collection, health checks
  • Emergency Response: Quickly deploy emergency scripts to handle security incidents or system failures
  • Application Deployment: Batch deploy applications and update configuration files
  • Data Processing: Execute data processing tasks in parallel across multiple instances
  • 批量操作: 在多台Flexus L实例上执行同一脚本(如软件安装、配置更新)
  • 自动化运维: 定期执行巡检脚本、日志收集、健康检查
  • 应急响应: 快速部署应急脚本以处理安全事件或系统故障
  • 应用部署: 批量部署应用并更新配置文件
  • 数据处理: 在多台实例上并行执行数据处理任务

Typical Use Cases

典型用例

  1. "Create a Shell script to clean server logs"
  2. "Execute backup script on all L instances"
  3. "List my recently created scripts"
  4. "Execute Python script on specified L instance"
  5. "Create a script to batch install Nginx"
  1. "创建一个清理服务器日志的Shell脚本"
  2. "在所有L实例上执行备份脚本"
  3. "列出我最近创建的脚本"
  4. "在指定L实例上执行Python脚本"
  5. "创建一个批量安装Nginx的脚本"

Trigger Keywords

触发关键词

Routing Keywords: COC script, script management, script execution, cloud operations, custom script, batch execution; COC, script management, script execution, cloud operations.
路由关键词: COC script、script management、script execution、cloud operations、custom script、batch execution;COC、script management、script execution、cloud operations。

Important Notes

重要提示

All scripts and environment check scripts are inside the skill package. You must use skill action=exec to execute them; do not run them directly in the shell.
所有脚本和环境检查脚本均包含在Skill包内。必须使用skill action=exec执行;请勿直接在shell中运行。

Prerequisites

前置条件

CLI Version Requirements and Verification Commands

CLI版本要求与验证命令

COC SDK Version Requirement: huaweicloudsdkcoc >= 3.1.0
Verification Commands:
bash
undefined
COC SDK版本要求: huaweicloudsdkcoc >= 3.1.0
验证命令:
bash
undefined

Check current SDK version

检查当前SDK版本

python -c "import huaweicloudsdkcoc; print(huaweicloudsdkcoc.version)"
python -c "import huaweicloudsdkcoc; print(huaweicloudsdkcoc.version)"

Verify COC client availability

验证COC客户端可用性

python -c "from huaweicloudsdkcoc.v1 import CocClient; print('COC SDK version verification passed')"
undefined
python -c "from huaweicloudsdkcoc.v1 import CocClient; print('COC SDK版本验证通过')"
undefined

Authentication Configuration and Security Rules

认证配置与安全规则

Supported Authentication Methods:
  1. Credential Acquisition Methods:
    This skill supports obtaining Huawei Cloud credentials through the following methods (in order of priority from high to low):
    1. Environment Variables (highest priority)
      • HW_ACCESS_KEY
        : Huawei Cloud Access Key AK
      • HW_SECRET_KEY
        : Huawei Cloud Access Key SK
      • HW_SECURITY_TOKEN
        : Security token for temporary credentials
    2. Command Line Parameters (used when environment variables are not provided)
      • --ak
        : Huawei Cloud Access Key AK
      • --sk
        : Huawei Cloud Access Key SK
      • --security-token
        : Security token for temporary credentials (required when using temporary AK/SK)
    3. Interactive Input (when neither of the above methods are provided)
    • The program will prompt the user to input credential information such as AK/SK
bash
undefined
支持的认证方式:
  1. 凭证获取方式:
    本Skill支持通过以下方式获取华为云凭证(优先级从高到低):
    1. 环境变量(最高优先级)
      • HW_ACCESS_KEY
        : 华为云访问密钥AK
      • HW_SECRET_KEY
        : 华为云访问密钥SK
      • HW_SECURITY_TOKEN
        : 临时凭证的安全令牌
    2. 命令行参数(当环境变量未提供时使用)
      • --ak
        : 华为云访问密钥AK
      • --sk
        : 华为云访问密钥SK
      • --security-token
        : 临时凭证的安全令牌(使用临时AK/SK时必填)
    3. 交互式输入(当上述两种方式均未提供时)
    • 程序将提示用户输入AK/SK等凭证信息
bash
undefined

Execute script directly (will automatically use environment variables)

直接执行脚本(将自动使用环境变量)

python {baseDir}/scripts/caller.py create --name "test_script" --type SHELL --content "echo hello" --description "Test script"

2. **Environment Variables** (recommended):
```bash
export HW_ACCESS_KEY="your_access_key"
export HW_SECRET_KEY="***"
python {baseDir}/scripts/caller.py create --name "test_script" --type SHELL --content "echo hello" --description "Test script"

2. **环境变量**(推荐):
```bash
export HW_ACCESS_KEY="your_access_key"
export HW_SECRET_KEY="***"

Optional for temporary credentials:

临时凭证可选:

export HW_SECURITY_TOKEN="your_security_token" export HW_REGION="cn-north-4"
export HW_SECURITY_TOKEN="your_security_token" export HW_REGION="cn-north-4"

Run without --ak/--sk; credentials are read from environment variables

无需传递--ak/--sk;凭证将从环境变量读取

python {baseDir}/scripts/caller.py create --name "test_script" --type SHELL --content "echo hello" --description "Test script"

> ⚠️ **Security note**: Passing AK/SK via `--ak "..." --sk "..."` on the command
> line exposes the credentials in the process list (e.g. `ps aux`). Only do this
> in a trusted, single-user environment; prefer environment variables or `hcloud configure`.

3. **Interactive Input** (Testing):
```bash
python {baseDir}/scripts/caller.py create
python {baseDir}/scripts/caller.py create --name "test_script" --type SHELL --content "echo hello" --description "Test script"

> ⚠️ **安全提示**: 通过命令行`--ak "..." --sk "..."`传递AK/SK会在进程列表(如`ps aux`)中暴露凭证。仅在可信的单用户环境中使用此方式;优先使用环境变量或`hcloud configure`。

3. **交互式输入**(测试用):
```bash
python {baseDir}/scripts/caller.py create

Will prompt for AK/SK/region

将提示输入AK/SK/区域信息


**Authentication Parameter Description**:

| Parameter | Description | Required | Default | Example |
|-----------|-------------|----------|---------|---------|
| --ak | Huawei Cloud Access Key AK (can be temporary AK) | Yes* | Prompted | `--ak AXXX...` |
| --sk | Huawei Cloud Access Key SK (can be temporary SK) | Yes* | Prompted | `--sk SXXX...` |
| --security-token | Security token for temporary credentials (required when using temporary AK/SK) | No | Prompted | `--security-token XXXX...` |
| --region | COC Service Region | No | cn-north-4 | `--region cn-north-4` |

**Note**: Parameters marked with * can be provided via environment variables (`HW_ACCESS_KEY`, `HW_SECRET_KEY`, `HW_SECURITY_TOKEN`, `HW_REGION`). If environment variables are set, they take priority over command line parameters.

**Authentication Priority**:
1. First check environment variables: `HW_ACCESS_KEY`, `HW_SECRET_KEY`, `HW_SECURITY_TOKEN`, `HW_REGION`
2. If all required environment variables are set, use them directly
3. If environment variables are not set, use command line parameters
4. If neither is provided, prompt for interactive input

**Security Rules**:
- **No Hardcoded Credentials**: Never embed AK/SK directly in code or configuration files
- **Principle of Least Privilege**: Grant only the minimum permissions required
- **Regular Key Rotation**: Rotate AK/SK every 90 days
- **Enable Key Rotation Alerts**: Set up expiration reminders in Huawei Cloud Console

**认证参数说明**:

| 参数 | 描述 | 必填 | 默认值 | 示例 |
|-----------|-------------|----------|---------|---------|
| --ak | 华为云访问密钥AK(可为临时AK) | 是* | 提示输入 | `--ak AXXX...` |
| --sk | 华为云访问密钥SK(可为临时SK) | 是* | 提示输入 | `--sk SXXX...` |
| --security-token | 临时凭证的安全令牌(使用临时AK/SK时必填) | 否 | 提示输入 | `--security-token XXXX...` |
| --region | COC服务区域 | 否 | cn-north-4 | `--region cn-north-4` |

**注意**: 标记*的参数可通过环境变量提供(`HW_ACCESS_KEY`, `HW_SECRET_KEY`, `HW_SECURITY_TOKEN`, `HW_REGION`)。若设置了环境变量,其优先级高于命令行参数。

**认证优先级**:
1. 首先检查环境变量: `HW_ACCESS_KEY`, `HW_SECRET_KEY`, `HW_SECURITY_TOKEN`, `HW_REGION`
2. 若所有必填环境变量已设置,则直接使用
3. 若环境变量未设置,则使用命令行参数
4. 若两者均未提供,则提示交互式输入

**安全规则**:
- **禁止硬编码凭证**: 切勿在代码或配置文件中直接嵌入AK/SK
- **最小权限原则**: 仅授予所需的最小权限
- **定期轮换密钥**: 每90天轮换一次AK/SK
- **启用密钥轮换提醒**: 在华为云控制台设置过期提醒

IAM Permissions List

IAM权限列表

This skill requires the following IAM permissions. For detailed information, refer to IAM Policies Documentation:
Permission CategoryPermission NameDescription
Script Management
coc:script:create
Create script
Script Management
coc:script:list
List scripts
Script Management
coc:script:get
Get script details
Script Management
coc:script:update
Update script
Script Management
coc:script:delete
Delete script
Execution Management
coc:execution:create
Create execution task
Execution Management
coc:execution:list
List execution tasks
Execution Management
coc:execution:get
Get execution details
Instance Management
coc:instance:list
List target instances
本Skill需要以下IAM权限。详细信息请参考IAM策略文档:
权限类别权限名称描述
脚本管理
coc:script:create
创建脚本
脚本管理
coc:script:list
列出脚本
脚本管理
coc:script:get
获取脚本详情
脚本管理
coc:script:update
更新脚本
脚本管理
coc:script:delete
删除脚本
执行管理
coc:execution:create
创建执行任务
执行管理
coc:execution:list
列出执行任务
执行管理
coc:execution:get
获取执行详情
实例管理
coc:instance:list
列出目标实例

Permission Failure Handling Flow

权限失败处理流程

Insufficient Permission Error Handling:
  1. Error Identification:
bash
undefined
权限不足错误处理:
  1. 错误识别:
bash
undefined

Typical error message

典型错误信息

error: AccessDenied message: You do not have permission to perform this action.

2. **Troubleshooting Steps**:
   - Verify AK/SK configuration
   - Confirm user has required COC permissions
   - Validate region configuration
   - Check if IAM policy is active

3. **Resolution**:
   - Contact administrator for required permissions
   - Confirm IAM policy is properly attached to user/role
   - Wait for policy to take effect (typically 5-10 minutes)

4. **Verification**:
```bash
error: AccessDenied message: You do not have permission to perform this action.

2. **排查步骤**:
   - 验证AK/SK配置
   - 确认用户拥有所需的COC权限
   - 验证区域配置
   - 检查IAM策略是否已激活

3. **解决方法**:
   - 联系管理员获取所需权限
   - 确认IAM策略已正确附加到用户/角色
   - 等待策略生效(通常需要5-10分钟)

4. **验证**:
```bash

Re-execute to verify permissions

重新执行以验证权限

python {baseDir}/scripts/caller.py list
undefined
python {baseDir}/scripts/caller.py list
undefined

Core Commands

核心命令

Script Management Commands

脚本管理命令

Create Script:
bash
undefined
创建脚本:
bash
undefined

Set credentials via environment variables (recommended)

通过环境变量设置凭证(推荐)

export HW_ACCESS_KEY="your_ak" export HW_SECRET_KEY="your_sk"
export HW_ACCESS_KEY="your_ak" export HW_SECRET_KEY="your_sk"

Optional for temporary credentials:

临时凭证可选:

export HW_SECURITY_TOKEN="your_security_token" export HW_REGION="cn-north-4"
export HW_SECURITY_TOKEN="your_security_token" export HW_REGION="cn-north-4"

Run without --ak/--sk; credentials are read from environment variables

无需传递--ak/--sk;凭证将从环境变量读取

python {baseDir}/scripts/caller.py create --name "backup_script" --type SHELL --content "echo 'Backup completed'" --description "Data backup script"

**View Script Details**:
```bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"
python {baseDir}/scripts/caller.py create --name "backup_script" --type SHELL --content "echo 'Backup completed'" --description "数据备份脚本"

**查看脚本详情**:
```bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"

Optional for temporary credentials:

临时凭证可选:

export HW_SECURITY_TOKEN="your_security_token"
python {baseDir}/scripts/caller.py show --script-uuid "SC202xxxxxxxx13701c4a8a62"

**List Scripts**:
```bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"
export HW_SECURITY_TOKEN="your_security_token"
python {baseDir}/scripts/caller.py show --script-uuid "SC202xxxxxxxx13701c4a8a62"

**列出脚本**:
```bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"

Optional for temporary credentials:

临时凭证可选:

export HW_SECURITY_TOKEN="your_security_token"
python {baseDir}/scripts/caller.py list --page 1 --size 10

**Delete Script**:
```bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"
export HW_SECURITY_TOKEN="your_security_token"
python {baseDir}/scripts/caller.py list --page 1 --size 10

**删除脚本**:
```bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"

Optional for temporary credentials:

临时凭证可选:

export HW_SECURITY_TOKEN="your_security_token"
python {baseDir}/scripts/caller.py delete --script-uuid "SC202xxxxxxxx13701c4a8a62"
undefined
export HW_SECURITY_TOKEN="your_security_token"
python {baseDir}/scripts/caller.py delete --script-uuid "SC202xxxxxxxx13701c4a8a62"
undefined

Script Execution Commands

脚本执行命令

Execute Script:
bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"
执行脚本:
bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"

Optional for temporary credentials:

临时凭证可选:

export HW_SECURITY_TOKEN="your_security_token"
python {baseDir}/scripts/caller.py execute --script-uuid "SC202xxxxxxxx13701c4a8a62" --execute-user root --timeout 300

**Interactive Execution**: `python {baseDir}/scripts/caller.py execute` (credentials are read from environment variables)

**Query Execution Result**:
```bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"
export HW_SECURITY_TOKEN="your_security_token"
python {baseDir}/scripts/caller.py execute --script-uuid "SC202xxxxxxxx13701c4a8a62" --execute-user root --timeout 300

**交互式执行**: `python {baseDir}/scripts/caller.py execute`(凭证从环境变量读取)

**查询执行结果**:
```bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"

Optional for temporary credentials:

临时凭证可选:

export HW_SECURITY_TOKEN="your_security_token"
python {baseDir}/scripts/caller.py query --execute-uuid "SCT202xxxxxxxx01af694bf"
undefined
export HW_SECURITY_TOKEN="your_security_token"
python {baseDir}/scripts/caller.py query --execute-uuid "SCT202xxxxxxxx01af694bf"
undefined

Parameter Reference

参数参考

Global Parameters (All Commands)

全局参数(所有命令)

ParameterDescriptionRequiredDefaultExample
--akHuawei Cloud Access Key AK (can be temporary AK)Yes*Prompted
--ak AXXX...
--skHuawei Cloud Access Key SK (can be temporary SK)Yes*Prompted
--sk SXXX...
--security-tokenSecurity token for temporary credentials (required when using temporary AK/SK)NoPrompted
--security-token XXXX...
--regionCOC Service RegionNocn-north-4
--region cn-north-4
Note: Parameters marked with * can be provided via environment variables:
  • HW_ACCESS_KEY
    - Huawei Cloud Access Key
  • HW_SECRET_KEY
    - Huawei Cloud Secret Key
  • HW_SECURITY_TOKEN
    - Temporary security token (optional)
  • HW_REGION
    - COC Service Region
If environment variables are set, they take priority over command line parameters.
参数描述必填默认值示例
--ak华为云访问密钥AK(可为临时AK)是*提示输入
--ak AXXX...
--sk华为云访问密钥SK(可为临时SK)是*提示输入
--sk SXXX...
--security-token临时凭证的安全令牌(使用临时AK/SK时必填)提示输入
--security-token XXXX...
--regionCOC服务区域cn-north-4
--region cn-north-4
注意: 标记*的参数可通过环境变量提供:
  • HW_ACCESS_KEY
    - 华为云访问密钥
  • HW_SECRET_KEY
    - 华为云密钥
  • HW_SECURITY_TOKEN
    - 临时安全令牌(可选)
  • HW_REGION
    - COC服务区域
若设置了环境变量,其优先级高于命令行参数。

create Command Parameters

create命令参数

ParameterDescriptionRequiredDefault
--nameScript nameYes-
--typeScript type (SHELL/PYTHON/BAT)Yes-
--contentScript contentYes-
--descriptionScript descriptionYes-
--risk-levelRisk level (LOW/MEDIUM/HIGH)NoLOW
--versionScript versionNo1.0.0
参数描述必填默认值
--name脚本名称-
--type脚本类型(SHELL/PYTHON/BAT)-
--content脚本内容-
--description脚本描述-
--risk-level风险等级(LOW/MEDIUM/HIGH)LOW
--version脚本版本1.0.0

execute Command Parameters

execute命令参数

ParameterDescriptionRequiredDefault
--script-uuidScript UUIDNoMost recent script
--execute-userExecute userNoroot
--timeoutTimeout in seconds (5-1800)No300
--success-rateSuccess rate (0.01-100)No1
--rotation-strategyRotation strategy (CONTINUE/PAUSE)NoCONTINUE
参数描述必填默认值
--script-uuid脚本UUID最近创建的脚本
--execute-user执行用户root
--timeout超时时间(秒,5-1800)300
--success-rate成功率(0.01-100)1
--rotation-strategy轮换策略(CONTINUE/PAUSE)CONTINUE

show Command Parameters

show命令参数

ParameterDescriptionRequiredDefault
--script-uuidScript UUIDYes-
参数描述必填默认值
--script-uuid脚本UUID-

list Command Parameters

list命令参数

ParameterDescriptionRequiredDefault
--pagePage numberNo1
--sizePage sizeNo10
参数描述必填默认值
--page页码1
--size每页数量10

delete Command Parameters

delete命令参数

ParameterDescriptionRequiredDefault
--script-uuidScript UUIDYes-
参数描述必填默认值
--script-uuid脚本UUID-

query Command Parameters

query命令参数

ParameterDescriptionRequiredDefault
--execute-uuidExecution task UUIDYes-
参数描述必填默认值
--execute-uuid执行任务UUID-

SDK Installation

SDK安装

Before creating or executing scripts for the first time, ensure the Huawei Cloud COC SDK dependencies are installed. Run from the skill directory (
skills/coc
):
bash
pip install -r {baseDir}/requirements.txt
Installation Notes:
  • Installation may take a few minutes, please be patient
  • After successful installation, you can call the Python code in the
    scripts
    directory for script creation and execution
  • Use the following mirrors to install the SDK (second pip mirror, preferred):
    bash
    pip install -r {baseDir}/requirements.txt -i https://pypi.org/project/huaweicloudsdkcoc/
    or
    bash
    pip install -r {baseDir}/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
Installation Verification:
bash
python -c "from huaweicloudsdkcoc.v1 import CocClient; print('SDK installed successfully!')"
首次创建或执行脚本前,请确保已安装华为云COC SDK依赖。在Skill目录(
skills/coc
)中运行:
bash
pip install -r {baseDir}/requirements.txt
安装注意事项:
  • 安装可能需要几分钟,请耐心等待
  • 安装成功后,可调用
    scripts
    目录下的Python代码进行脚本创建与执行
  • 使用以下镜像安装SDK(优先使用第二个pip镜像):
    bash
    pip install -r {baseDir}/requirements.txt -i https://pypi.org/project/huaweicloudsdkcoc/
    bash
    pip install -r {baseDir}/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
安装验证:
bash
python -c "from huaweicloudsdkcoc.v1 import CocClient; print('SDK安装成功!')"

Workflow

工作流程

Basic Workflow

基本流程

  1. Create a script (using environment variables):
bash
undefined
  1. 创建脚本(使用环境变量):
bash
undefined

Set environment variables first

先设置环境变量

export HW_ACCESS_KEY="your_ak" export HW_SECRET_KEY="your_sk" export HW_SECURITY_TOKEN="your_token" # Optional
export HW_ACCESS_KEY="your_ak" export HW_SECRET_KEY="your_sk" export HW_SECURITY_TOKEN="your_token" # 可选

Execute command (will automatically use environment variables)

执行命令(将自动使用环境变量)

python {baseDir}/scripts/caller.py create --name "test_script" --type SHELL --content "echo hello" --description "Test script"

2. **Execute a script**:
```bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"
export HW_SECURITY_TOKEN="your_token"  # Optional

python {baseDir}/scripts/caller.py execute --script-uuid "SC202xxxxxxxx13701c4a8a62" --execute-user root --timeout 300 --success-rate 100
⚠️ Never pass AK/SK via
--ak "..." --sk "..."
command line arguments; they become visible in the process list (e.g.
ps aux
). Always prefer environment variables or
hcloud configure
.
Tip: Refer to the "Parameter Reference" section for complete parameter documentation.
python {baseDir}/scripts/caller.py create --name "test_script" --type SHELL --content "echo hello" --description "测试脚本"

2. **执行脚本**:
```bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"
export HW_SECURITY_TOKEN="your_token"  # 可选

python {baseDir}/scripts/caller.py execute --script-uuid "SC202xxxxxxxx13701c4a8a62" --execute-user root --timeout 300 --success-rate 100
⚠️ 切勿通过
--ak "..." --sk "..."
命令行参数传递AK/SK;它们会在进程列表(如
ps aux
)中可见。始终优先使用环境变量或
hcloud configure
提示: 完整参数文档请参考「参数参考」章节。

Interactive Mode

交互模式

When executing scripts, the following information will be requested interactively (L-instance only):
Required Parameters:
  • L-instance resource ID (resource_id)
  • L-instance region (region_id)
Optional Parameters (press Enter to use default values):
  • Script UUID (default uses the most recently created script)
  • Execute user (default root)
  • Timeout (default 300 seconds)
  • Success rate (default 1)
  • Rotation strategy (default CONTINUE)
执行脚本时,将交互式请求以下信息(仅L实例):
必填参数:
  • L实例资源ID(resource_id)
  • L实例区域(region_id)
可选参数(按Enter使用默认值):
  • 脚本UUID(默认使用最近创建的脚本)
  • 执行用户(默认root)
  • 超时时间(默认300秒)
  • 成功率(默认1)
  • 轮换策略(默认CONTINUE)

Output Format

输出格式

List Scripts Output

列出脚本输出

Found 25 scripts (Page 1, 10 per page):
--------------------------------------------------------------------------------
No.    Script UUID                    Name                 Type        Risk Level
--------------------------------------------------------------------------------
1       SC202xxxxxxxx13701c4a8a62     backup_script        SHELL       LOW
2       SC202xxxxxxxx10302201d5b9e78     deploy_script        SHELL       HIGH
3       SC202xxxxxxxx13701c4a8a62     monitor_script       PYTHON      MEDIUM
--------------------------------------------------------------------------------
找到25个脚本(第1页,每页10个):
--------------------------------------------------------------------------------
序号    脚本UUID                    名称                 类型        风险等级
--------------------------------------------------------------------------------
1       SC202xxxxxxxx13701c4a8a62     backup_script        SHELL       LOW
2       SC202xxxxxxxx10302201d5b9e78     deploy_script        SHELL       HIGH
3       SC202xxxxxxxx13701c4a8a62     monitor_script       PYTHON      MEDIUM
--------------------------------------------------------------------------------

JSON Output Format

JSON输出格式

Create Script Success Response:
json
{
  "ok": true,
  "text": "Script created successfully: SC202xxxxxxxx13701c4a8a62",
  "result": {
    "data": "SC202xxxxxxxx13701c4a8a62"
  },
  "error": null
}
Execute Script Success Response:
json
{
  "ok": true,
  "text": "Script execution started: SCT202xxxxxxxx01af694bf",
  "result": {
    "data": "SCT202xxxxxxxx01af694bf"
  },
  "error": null
}
Query Execution Result Response:
json
{
  "data": {
    "batch_index": 1,
    "total_instances": 1,
    "execute_instances": [
      {
        "id": 40304358,
        "cmd_uuid": "2exxxxxxxxxxxxxx6b5",
        "job_sign": null,
        "target_instance": {
          "resource_id": "6axxxxxxxxxxxxxxx9e",
          "agent_sn": "e5xxxxxxxxxxxxxxxxxx77",
          "agent_status": null,
          "agent_version": "1.1.8",
          "region_id": "cn-north-4",
          "project_id": null,
          "properties": {
            "host_name": "dify-test-001",
            "fixed_ip": null,
            "floating_ip": null,
            "region_id": "cn-north-4",
            "zone_id": null,
            "application": null,
            "group": null,
            "project_id": null
          },
          "custom_attributes": null,
          "provider": "hcss",
          "type": "l-instance"
        },
        "gmt_created": 1779934038727,
        "gmt_finished": 1779934107670,
        "execute_costs": 68943,
        "status": "ABNORMAL",
        "message": "Reading package lists...\nWARNING: apt does not have a stable CLI interface. Use with caution in scripts.\n\n\nBuilding dependency tree...\nReading state information...\nexpect is already the newest version (5.45.4-2build1).\n\n[SYSTEM INFO] script job execute timeout."
      }
    ]
  }
}
Status Description:
  • FINISHED
    - Execution successful
  • ABNORMAL
    - Execution failed
  • PROCESSING
    /
    READY
    - In progress
创建脚本成功响应:
json
{
  "ok": true,
  "text": "脚本创建成功: SC202xxxxxxxx13701c4a8a62",
  "result": {
    "data": "SC202xxxxxxxx13701c4a8a62"
  },
  "error": null
}
执行脚本成功响应:
json
{
  "ok": true,
  "text": "脚本执行已启动: SCT202xxxxxxxx01af694bf",
  "result": {
    "data": "SCT202xxxxxxxx01af694bf"
  },
  "error": null
}
查询执行结果响应:
json
{
  "data": {
    "batch_index": 1,
    "total_instances": 1,
    "execute_instances": [
      {
        "id": 40304358,
        "cmd_uuid": "2exxxxxxxxxxxxxx6b5",
        "job_sign": null,
        "target_instance": {
          "resource_id": "6axxxxxxxxxxxxxxx9e",
          "agent_sn": "e5xxxxxxxxxxxxxxxxxx77",
          "agent_status": null,
          "agent_version": "1.1.8",
          "region_id": "cn-north-4",
          "project_id": null,
          "properties": {
            "host_name": "dify-test-001",
            "fixed_ip": null,
            "floating_ip": null,
            "region_id": "cn-north-4",
            "zone_id": null,
            "application": null,
            "group": null,
            "project_id": null
          },
          "custom_attributes": null,
          "provider": "hcss",
          "type": "l-instance"
        },
        "gmt_created": 1779934038727,
        "gmt_finished": 1779934107670,
        "execute_costs": 68943,
        "status": "ABNORMAL",
        "message": "Reading package lists...\nWARNING: apt does not have a stable CLI interface. Use with caution in scripts.\n\n\nBuilding dependency tree...\nReading state information...\nexpect is already the newest version (5.45.4-2build1).\n\n[SYSTEM INFO] script job execute timeout."
      }
    ]
  }
}
状态说明:
  • FINISHED
    - 执行成功
  • ABNORMAL
    - 执行失败
  • PROCESSING
    /
    READY
    - 执行中

Validation Methods

验证方法

1. SDK Installation Verification

1. SDK安装验证

bash
python -c "from huaweicloudsdkcoc.v1 import CocClient; print('SDK installed successfully!')"
bash
python -c "from huaweicloudsdkcoc.v1 import CocClient; print('SDK安装成功!')"

2. Create Script Verification

2. 创建脚本验证

bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"

python {baseDir}/scripts/caller.py create --name "test_script" --type SHELL --content "echo hello" --description "Test script" --non-interactive
bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"

python {baseDir}/scripts/caller.py create --name "test_script" --type SHELL --content "echo hello" --description "测试脚本" --non-interactive

Expected output: Script UUID returned

预期输出: 返回脚本UUID

undefined
undefined

3. Execute Script Verification

3. 执行脚本验证

bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"

python {baseDir}/scripts/caller.py execute --script-uuid "SC202xxxxxxxx13701c4a8a62" --execute-user root --timeout 300 --non-interactive
bash
export HW_ACCESS_KEY="your_ak"
export HW_SECRET_KEY="your_sk"

python {baseDir}/scripts/caller.py execute --script-uuid "SC202xxxxxxxx13701c4a8a62" --execute-user root --timeout 300 --non-interactive

Expected output: Execution task ID returned

预期输出: 返回执行任务ID

undefined
undefined

4. Smoke Test

4. 冒烟测试

bash
python {baseDir}/scripts/smoke_test.py
bash
python {baseDir}/scripts/smoke_test.py

This will test the configuration and optional API connectivity

此脚本将测试配置与可选API连通性

undefined
undefined

Notes

注意事项

General Notes

通用注意事项

  • Script execution required parameters - Need to provide L-instance resource_id and region_id
  • Script UUID auto-retrieval - If not specified, will automatically use the most recently created script
  • Script type must match - SHELL/PYTHON/BAT
  • Risk level must be set correctly - LOW/MEDIUM/HIGH
  • Execution results need polling - Execute API returns task ID, need to query execution status separately
  • 脚本执行必填参数 - 需要提供L实例resource_id和region_id
  • 脚本UUID自动获取 - 若未指定,将自动使用最近创建的脚本
  • 脚本类型必须匹配 - SHELL/PYTHON/BAT
  • 风险等级必须正确设置 - LOW/MEDIUM/HIGH
  • 执行结果需要轮询 - Execute API返回任务ID,需单独查询执行状态

Best Practices

最佳实践

Script Management Best Practices

脚本管理最佳实践

  1. Script Reusability: Create generic scripts with configurable parameters for maximum reusability
  2. Error Handling: Always include error handling and logging in your scripts
  3. Idempotency: Design scripts to be idempotent (can be safely run multiple times)
  4. Script Versioning: Maintain version control for important scripts
  5. Resource Tagging: Use consistent naming conventions and tags for scripts
  1. 脚本复用性: 创建带有可配置参数的通用脚本,最大化复用性
  2. 错误处理: 脚本中始终包含错误处理与日志记录
  3. 幂等性: 设计可安全重复运行的幂等脚本
  4. 脚本版本控制: 对重要脚本进行版本管理
  5. 资源标记: 为脚本使用一致的命名规范与标签

Execution Best Practices

执行最佳实践

  1. Test First: Always test scripts on a single L-instance before batch execution
  2. Risk Assessment: Set appropriate risk levels for scripts (LOW/MEDIUM/HIGH)
  3. Scheduling: Use scheduled execution for periodic tasks
  4. Monitoring: Monitor execution results and set up alerts for failures
  1. 先测试: 在批量执行前,始终先在单台L实例上测试脚本
  2. 风险评估: 为脚本设置合适的风险等级(LOW/MEDIUM/HIGH)
  3. 调度执行: 对周期性任务使用定时执行
  4. 监控: 监控执行结果并为失败设置告警

Region Concepts

区域概念

COC involves two different region concepts:
1. COC Service Region (API endpoint region):
  • cn-north-4 (China North-Beijing-4, default)
  • ap-southeast-3 (APAC-Singapore)
  • eu-west-101 (Europe-Frankfurt)
2. Target Instance Region (where the L-instance is located):
  • Can be any Huawei Cloud global region
  • Interactive input supports both region ID and region name
Important: COC service region and target instance region can be different.
COC涉及两种不同的区域概念:
1. COC服务区域(API端点区域):
  • cn-north-4(中国区-北京四,默认)
  • ap-southeast-3(亚太区-新加坡)
  • eu-west-101(欧洲区-法兰克福)
2. 目标实例区域(L实例所在区域):
  • 可为华为云全球任意区域
  • 交互式输入支持区域ID与区域名称
重要提示: COC服务区域与目标实例区域可以不同。

Error Handling

错误处理

Authentication Failed (403):
error: Authentication failed
  • AK/SK is invalid, reconfigure with correct credentials
API Quota Exceeded (429):
error: API quota exceeded
  • API quota exhausted, wait or upgrade
Parameter Error (400):
error: Invalid parameter
  • Check if request parameters are correct
认证失败(403):
error: Authentication failed
  • AK/SK无效,使用正确凭证重新配置
API配额超限(429):
error: API quota exceeded
  • API配额耗尽,请等待或升级
参数错误(400):
error: Invalid parameter
  • 检查请求参数是否正确

Security Notes

安全提示

  • AK/SK Security: AK/SK are important credentials for accessing Huawei Cloud APIs. Please keep them safe and do not share them with others.
  • Credential Obtaining: Log in to Huawei Cloud Management Console → My Credentials → Access Keys → New Access Key
  • AK/SK安全: AK/SK是访问华为云API的重要凭证,请妥善保管,勿与他人共享。
  • 凭证获取: 登录华为云管理控制台 → 我的凭证 → 访问密钥 → 新建访问密钥

Reference Documentation

参考文档

  • IAM Policy Configuration
  • Verification Method
  • Acceptance Criteria
  • Project Dependencies Configuration
  • IAM策略配置
  • 验证方法
  • 验收标准
  • 项目依赖配置