-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgcp.js
47 lines (41 loc) · 1.19 KB
/
gcp.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
const Compute = require('@google-cloud/compute')
const getLocalIps = require('./get-local-ips')
module.exports = (args, sendTo) => {
const compute = new Compute()
const gcpName = args.gcp.split(':', 2)
const zone = compute.zone(gcpName[0])
const ig = zone.instanceGroup(gcpName[1])
let previousIps = []
const updateFunc = () => {
const localIps = getLocalIps()
ig.getVMs().then((data) => {
const vms = data[0]
if (!vms || vms.length === 0) {
console.log('No VMs in group')
return
}
Promise.all(vms.map((vm) => vm.getMetadata())).then((responses) => {
const ips = []
for (let resp of responses) {
const md = resp[0]
for (let ni of md.networkInterfaces) {
if (ni.networkIP && !localIps.includes(ni.networkIP)) {
ips.push(ni.networkIP)
}
}
}
// Remove existing.
previousIps.forEach((addr) => {
delete sendTo[addr]
})
// Insert new.
ips.forEach((addr) => {
sendTo[addr] = args.uport
})
previousIps = ips
})
})
}
updateFunc()
setInterval(updateFunc, args.interval * 1000)
}