-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
110 lines (99 loc) · 2.64 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const {Client} = require("../../lib/services");
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function main() {
// Build client
const client = new Client({
config: {
region: 'cn-bj2',
projectId: process.env.UCLOUD_PROJECT_ID || '',
},
credential: {
publicKey: process.env.UCLOUD_PUBLIC_KEY || '',
privateKey: process.env.UCLOUD_PRIVATE_KEY || '',
}
});
const zone = "cn-bj2-05";
let resp = null;
// Describe Image
try {
resp = await client.uhost().describeImage();
} catch (e) {
throw e;
}
const image = resp["ImageSet"][0];
// Create Instance
try {
resp = await client.uhost().createUHostInstance({
Name: "sdk-js-example",
Zone: zone,
ImageId: image["ImageId"],
LoginMode: "Password",
Password: new Buffer("UCloud1234!").toString('base64'),
CPU: 1,
Memory: 1024,
Disks: [{
Size: image["ImageSize"],
Type: "CLOUD_SSD",
IsBoot: "true",
}],
});
} catch (e) {
throw e;
}
const id = resp["UHostIds"][0];
// Wait instance to boot
while (true) {
try {
resp = await client.uhost().describeUHostInstance({
Zone: zone,
UHostIds: [id],
});
} catch (e) {
break;
}
await sleep(3000);
const instance = resp["UHostSet"][0];
console.log(`waiting ${id} to boot, got ${instance["State"]}`);
if (["Running"].includes(instance["State"])) {
break;
}
}
// Stop the instance
try {
resp = await client.uhost().stopUHostInstance({
Zone: zone,
UHostId: id,
});
} catch (e) {
throw e;
}
// Wait instance to boot
while (true) {
try {
resp = await client.uhost().describeUHostInstance({
Zone: zone,
UHostIds: [id],
});
} catch (e) {
break;
}
await sleep(3000);
const instance = resp["UHostSet"][0];
console.log(`waiting ${id} to stopped, got ${instance["State"]}`);
if (["Stopped"].includes(instance["State"])) {
break;
}
}
// Cleanup the instance
try {
resp = await client.uhost().terminateUHostInstance({
Zone: zone,
UHostId: id,
});
} catch (e) {
throw e;
}
}
main().catch(e => { console.error(e) })