This repository has been archived by the owner on May 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
lightsail.go
89 lines (72 loc) · 2.54 KB
/
lightsail.go
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
/******************************************************************************
Cloud Resource Counter
File: lightsail.go
Summary: Counts the number of Lightsail instances.
******************************************************************************/
package main
import (
"github.com/aws/aws-sdk-go/service/lightsail"
color "github.com/logrusorgru/aurora"
)
// LightsailInstances returns a count of Lightsail instances in the current region
// (allRegions = false) or for all regions (allRegions = true)
func LightsailInstances(sf ServiceFactory, am ActivityMonitor, allRegions bool) int {
// Indicate activity
am.StartAction("Retrieving Lightsail instance counts")
// Input for the list of regions...
input := &lightsail.GetRegionsInput{}
// Get the list of all enabled regions for this account
// Note that this call fails if the default region associated with this
// account is not in the supported list. Must use something supported,
// like US-EAST-1.
response, err := sf.GetLightsailService(DefaultRegion).GetRegions(input)
// If error, then get out now!
if am.CheckError(err) {
return 0
}
// Should we get the counts for all regions?
instanceCount := 0
if allRegions {
// Loop through all of the regions
for _, region := range response.Regions {
// Get the Lightsail instances counts for a specific region
instanceCount += lightsailInstancesForSingleRegion(sf.GetLightsailService(*region.Name), am)
}
} else {
// Is the current region supported by Lightsail?
var validLightsailRegion bool
for _, region := range response.Regions {
if sf.GetCurrentRegion() == *region.Name {
validLightsailRegion = true
}
}
if validLightsailRegion {
// Get the Lightsail instances counts for the region selected by this session
instanceCount = lightsailInstancesForSingleRegion(sf.GetLightsailService(""), am)
}
}
// Indicate end of activity
am.EndAction("OK (%d)", color.Bold(instanceCount))
return instanceCount
}
func lightsailInstancesForSingleRegion(lss *LightsailService, am ActivityMonitor) int {
// Construct our input to find all Lightsail instances
input := &lightsail.GetInstancesInput{}
// Indicate activity
am.Message(".")
// Invoke our service
response, err := lss.InspectInstances(input)
// Check for error
if am.CheckError(err) {
return 0
}
// Loop through the instances...
var instanceCount int
for _, inst := range response.Instances {
// Is the instance running?
if inst.State != nil && inst.State.Name != nil && *inst.State.Name == "running" {
instanceCount++
}
}
return instanceCount
}