instance_lifecycle/
instance_lifecycle.rs

1use tencent_cloud_sdk::{
2    TencentCloudClient,
3    services::cvm::instance::{
4        InstanceService, StartInstancesRequest, StopInstancesRequest, RebootInstancesRequest
5    }
6};
7use std::env;
8
9#[tokio::main]
10async fn main() -> Result<(), Box<dyn std::error::Error>> {
11    // 从环境变量读取密钥
12    let secret_id = env::var("TENCENTCLOUD_SECRET_ID")
13        .expect("请设置环境变量TENCENTCLOUD_SECRET_ID");
14    let secret_key = env::var("TENCENTCLOUD_SECRET_KEY")
15        .expect("请设置环境变量TENCENTCLOUD_SECRET_KEY");
16
17    // 创建客户端
18    let client = TencentCloudClient::new(secret_id, secret_key);
19    
20    // 创建实例服务
21    let instance_service = InstanceService::new(&client);
22    
23    // 设置区域
24    let region = "ap-guangzhou";
25    
26    // 获取要操作的实例ID
27    let args: Vec<String> = env::args().collect();
28    if args.len() < 3 {
29        eprintln!("用法: cargo run --example instance_lifecycle <操作> <实例ID1> [<实例ID2> ...]");
30        eprintln!("操作可以是: start, stop, reboot");
31        return Ok(());
32    }
33    
34    let operation = &args[1];
35    let instance_ids: Vec<String> = args[2..].iter().cloned().collect();
36    
37    // 确认是否继续
38    println!("将对以下实例执行{}操作:", operation);
39    for id in &instance_ids {
40        println!("- {}", id);
41    }
42    println!("是否继续?[y/N]");
43    
44    let mut input = String::new();
45    std::io::stdin().read_line(&mut input)?;
46    
47    if input.trim().to_lowercase() != "y" {
48        println!("操作已取消");
49        return Ok(());
50    }
51    
52    match operation.as_str() {
53        "start" => {
54            // 创建启动实例请求
55            let request = StartInstancesRequest {
56                InstanceIds: instance_ids,
57            };
58            
59            // 发送启动请求
60            println!("正在启动实例...");
61            match instance_service.start_instances(&request, region).await {
62                Ok(_) => {
63                    println!("实例启动请求已提交成功");
64                    println!("实例将从STOPPED状态变为STARTING状态,然后再变为RUNNING状态");
65                },
66                Err(err) => {
67                    println!("启动实例失败: {}", err);
68                }
69            }
70        },
71        "stop" => {
72            // 创建关闭实例请求
73            let request = StopInstancesRequest {
74                InstanceIds: instance_ids,
75                StopType: Some("SOFT".to_string()),  // 软关机
76                ForceStop: None,  // 弃用的参数
77                StoppedMode: Some("KEEP_CHARGING".to_string()),  // 关机继续收费
78            };
79            
80            // 发送关闭请求
81            println!("正在关闭实例...");
82            match instance_service.stop_instances(&request, region).await {
83                Ok(_) => {
84                    println!("实例关闭请求已提交成功");
85                    println!("实例将从RUNNING状态变为STOPPING状态,然后再变为STOPPED状态");
86                },
87                Err(err) => {
88                    println!("关闭实例失败: {}", err);
89                }
90            }
91        },
92        "reboot" => {
93            // 创建重启实例请求
94            let request = RebootInstancesRequest {
95                InstanceIds: instance_ids,
96                StopType: Some("SOFT".to_string()),  // 软重启
97                ForceReboot: None,  // 弃用的参数
98            };
99            
100            // 发送重启请求
101            println!("正在重启实例...");
102            match instance_service.reboot_instances(&request, region).await {
103                Ok(_) => {
104                    println!("实例重启请求已提交成功");
105                    println!("实例将从RUNNING状态变为REBOOTING状态,然后再变为RUNNING状态");
106                },
107                Err(err) => {
108                    println!("重启实例失败: {}", err);
109                }
110            }
111        },
112        _ => {
113            eprintln!("未知操作: {}", operation);
114            eprintln!("支持的操作: start, stop, reboot");
115        }
116    }
117    
118    Ok(())
119}