-
Notifications
You must be signed in to change notification settings - Fork 54
/
main.go
234 lines (189 loc) · 5.61 KB
/
main.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package main
import (
"context"
"errors"
"fmt"
"io/ioutil"
stdlog "log"
"os"
"os/signal"
"strings"
"time"
"github.com/apex/log"
"github.com/apex/log/handlers/cli"
aws_ssmhelpers "github.com/disneystreaming/go-ssmhelpers/aws"
"github.com/fatih/color"
"github.com/jckuester/awsls/internal"
"github.com/jckuester/awsls/resource"
"github.com/jckuester/awstools-lib/aws"
"github.com/jckuester/awstools-lib/terraform"
flag "github.com/spf13/pflag"
)
func main() {
os.Exit(mainExitCode())
}
func mainExitCode() int {
var logDebug bool
var allProfilesFlag bool
var profiles internal.CommaSeparatedListFlag
var regions internal.CommaSeparatedListFlag
var attributes internal.CommaSeparatedListFlag
var version bool
var jsonOutput bool
flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
flags.Usage = func() {
printHelp(flags)
}
flags.BoolVar(&logDebug, "debug", false, "Enable debug logging")
flags.VarP(&profiles, "profiles", "p", "Comma-separated list of named AWS profiles for accounts to list resources in")
flags.BoolVar(&allProfilesFlag, "all-profiles", false, "List resources for all profiles in ~/.aws/config")
flags.VarP(®ions, "regions", "r", "Comma-separated list of regions to list resources in")
flags.VarP(&attributes, "attributes", "a", "Comma-separated list of attributes to show for each resource")
flags.BoolVar(&version, "version", false, "Show application version")
flags.BoolVar(&jsonOutput, "json", false, "Show output as json")
_ = flags.Parse(os.Args[1:])
args := flags.Args()
fmt.Println()
defer fmt.Println()
// discard TRACE logs of GRPCProvider
stdlog.SetOutput(ioutil.Discard)
log.SetHandler(cli.Default)
if logDebug {
log.SetLevel(log.DebugLevel)
}
if version {
fmt.Println(internal.BuildVersionString())
return 0
}
if len(args) == 0 {
fmt.Fprint(os.Stderr, color.RedString("Error: resource type glob pattern expected\n"))
printHelp(flags)
return 1
}
if profiles != nil && allProfilesFlag == true {
fmt.Fprint(os.Stderr, color.RedString("Error:️ --profiles and --all-profiles flag cannot be used together\n"))
printHelp(flags)
return 1
}
resourceTypePattern := args[0]
matchedTypes, err := resource.MatchSupportedTypes(resourceTypePattern)
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("Error: invalid glob pattern: %s\n", resourceTypePattern))
return 1
}
if len(matchedTypes) == 0 {
fmt.Fprint(os.Stderr, color.RedString("Error: no resource type found: %s\n", resourceTypePattern))
return 1
}
if profiles == nil && allProfilesFlag == false {
env, ok := os.LookupEnv("AWS_PROFILE")
if ok {
profiles = []string{env}
}
}
if allProfilesFlag {
var awsConfigPath []string
awsConfigFileEnv, ok := os.LookupEnv("AWS_CONFIG_FILE")
if ok {
awsConfigPath = []string{awsConfigFileEnv}
}
profilesFromConfig, err := aws_ssmhelpers.GetAWSProfiles(awsConfigPath...)
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("Error: failed to load all profiles: %s\n", err))
return 1
}
if profilesFromConfig == nil {
fmt.Fprint(os.Stderr, color.RedString("Error: no profiles found in ~/.aws/config\n"))
return 1
}
profiles = profilesFromConfig
}
ctx := context.Background()
clients, err := aws.NewClientPool(ctx, profiles, regions)
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("\nError: %s\n", err))
return 1
}
// suppress provider debug and info logs
log.SetLevel(log.ErrorLevel)
clientKeys := make([]aws.ClientKey, 0, len(clients))
for k := range clients {
clientKeys = append(clientKeys, k)
}
// trap Ctrl+C and call cancel on the context
ctx, cancel := context.WithCancel(ctx)
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, ignoreSignals...)
signal.Notify(signalCh, forwardSignals...)
defer func() {
signal.Stop(signalCh)
cancel()
}()
go func() {
select {
case <-signalCh:
fmt.Fprint(os.Stderr, color.RedString("\nAborting...\n"))
cancel()
case <-ctx.Done():
}
}()
if logDebug {
log.SetLevel(log.DebugLevel)
}
// initialize a Terraform AWS provider for each AWS client with a matching config
providers, err := terraform.NewProviderPool(ctx, clientKeys, "v3.42.0", "~/.awsls", 10*time.Second)
if err != nil {
if !errors.Is(err, context.Canceled) {
fmt.Fprint(os.Stderr, color.RedString("\nError: %s\n", err))
}
return 1
}
defer func() {
for _, p := range providers {
_ = p.Close()
}
}()
for _, rType := range matchedTypes {
// any provider here is sufficient to check if a resource type has attributes
p := providers[clientKeys[0]]
hasAttrs, err := resource.HasAttributes(attributes, rType, &p)
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("Error: failed to check if resource type has attribute: %s\n",
err))
return 1
}
var resources []terraform.Resource
resourcesCh := make(chan resource.UpdatedResources, 1)
go func() {
resourcesCh <- resource.ListInMultipleAccountsAndRegions(context.Background(), rType, hasAttrs, clients, providers)
}()
select {
case <-ctx.Done():
return 1
case result := <-resourcesCh:
resources = result.Resources
for _, err := range result.Errors {
fmt.Fprint(os.Stderr, color.RedString("Error %s: %s\n", rType, err))
}
}
if len(resources) == 0 {
continue
}
if jsonOutput {
resource.PrintResourcesAsJSON(resources, hasAttrs, attributes)
} else {
resource.PrintResources(resources, hasAttrs, attributes)
}
}
return 0
}
func printHelp(fs *flag.FlagSet) {
fmt.Fprintf(os.Stderr, "\n"+strings.TrimSpace(help)+"\n")
fs.PrintDefaults()
}
const help = `
awsls - list AWS resources.
USAGE:
$ awsls [flags] <resource_type glob pattern>
FLAGS:
`