-
Notifications
You must be signed in to change notification settings - Fork 0
/
awsxacct.go
448 lines (378 loc) · 9.8 KB
/
awsxacct.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package cmds
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"strings"
"syscall"
"github.com/alphauslabs/blue-sdk-go/admin/v1"
"github.com/alphauslabs/bluectl/params"
"github.com/alphauslabs/bluectl/pkg/grpcconn"
"github.com/alphauslabs/bluectl/pkg/logger"
"github.com/alphauslabs/bluectl/pkg/ops"
"github.com/spf13/cobra"
)
func CreateDefaultCostAccessInfo() *cobra.Command {
var (
silent bool
)
cmd := &cobra.Command{
Use: "create <account> [type]",
Short: "Create default cost access",
Long: `Create default cost access. You will be presented with link to a CloudFormation deployment based on type.
Valid values for the optional [type] are:
apionly - Read-only access to cost information without CUR setup.
s3only - Setup S3 bucket compatible for CUR definition export. Useful if you prefer a different
region other than the default.
You can deploy the template manually as well using StackSets if you prefer, in which case, you have to
deploy manually. The command will work all the same, although you have to run for each target account.
For Wave(Pro) accounts, we recommended you to deploy this stack (type=apionly). This will allow us to
query a more accurate billing-related information such as your Reserved Instances, Savings Plans, etc.
through the AWS API. Currently, we only do a best-effort detection of these information from the parent
CUR, which is not always accurate.
The stack template will create an IAM role with read-only access to your billing-related information.
If you want to audit the template, it is publicly available from the link below:
default:
https://alphaus-cloudformation-templates.s3.ap-northeast-1.amazonaws.com/alphauscurexportdef-v1.yml
apionly:
https://alphaus-cloudformation-templates.s3.ap-northeast-1.amazonaws.com/alphausdefaultcostaccess-v1.yml
s3only:
https://alphaus-cloudformation-templates.s3.ap-northeast-1.amazonaws.com/alphauscurexportbucket-v1.yml`,
Run: func(cmd *cobra.Command, args []string) {
var ret int
defer func(r *int) {
if *r != 0 {
os.Exit(*r)
}
}(&ret)
fnerr := func(e error) {
logger.Error(e)
ret = 1
}
if len(args) == 0 {
fnerr(fmt.Errorf("account is required"))
return
}
ctx := context.Background()
mycon, err := grpcconn.GetConnection(ctx, grpcconn.AdminService)
if err != nil {
fnerr(err)
return
}
client, err := admin.NewClient(ctx, &admin.ClientOptions{Conn: mycon})
if err != nil {
fnerr(err)
return
}
var s3only bool
req := admin.GetDefaultCostAccessTemplateUrlRequest{}
if len(args) >= 2 {
switch args[1] {
case "": // empty is default (valid)
case "apionly":
req.Type = args[1]
case "s3only":
req.Type = args[1]
s3only = true
default:
fnerr(fmt.Errorf("unknown type: %v", args[1]))
return
}
}
defer client.Close()
resp, err := client.GetDefaultCostAccessTemplateUrl(ctx, &req)
if err != nil {
fnerr(err)
return
}
fmt.Println("Open the link below in your browser and deploy:")
fmt.Println(resp.LaunchUrl)
if s3only {
fmt.Println("\nTo use the deployed bucket, rerun this command with the default type (empty) then select the 'USE_EXISTING' parameter in your CloudFormation console.")
return
}
var rep string
if !silent {
fmt.Print("Confirm successful deployment? [Y/n]: ")
fmt.Scanln(&rep)
}
switch strings.ToLower(rep) {
case "n":
return
case "":
fallthrough
case "y":
fmt.Println("Validating access...")
resp, err := client.CreateDefaultCostAccess(ctx, &admin.CreateDefaultCostAccessRequest{
Target: args[0],
})
if err != nil {
fnerr(err)
return
}
b, _ := json.Marshal(resp)
fmt.Println(string(b))
default:
fnerr(fmt.Errorf("unknown reply"))
return
}
},
}
cmd.Flags().SortFlags = false
cmd.Flags().BoolVar(&silent, "silent", silent, "if true, no input required (non-interactive)")
return cmd
}
func ListDefaultCostAccessInfo() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List default cost access information",
Long: `List default cost access information.`,
Run: func(cmd *cobra.Command, args []string) {
var ret int
defer func(r *int) {
if *r != 0 {
os.Exit(*r)
}
}(&ret)
fnerr := func(e error) {
logger.Error(e)
ret = 1
}
ctx := context.Background()
mycon, err := grpcconn.GetConnection(ctx, grpcconn.AdminService)
if err != nil {
fnerr(err)
return
}
client, err := admin.NewClient(ctx, &admin.ClientOptions{Conn: mycon})
if err != nil {
fnerr(err)
return
}
defer client.Close()
stream, err := client.ListDefaultCostAccess(ctx, &admin.ListDefaultCostAccessRequest{})
if err != nil {
fnerr(err)
return
}
for {
v, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
fnerr(err)
return
}
b, _ := json.Marshal(v)
logger.Info(string(b))
}
},
}
cmd.Flags().SortFlags = false
return cmd
}
func GetDefaultCostAccessInfo() *cobra.Command {
cmd := &cobra.Command{
Use: "get <account>",
Short: "Get default cost access information",
Long: `Get default cost access information.`,
Run: func(cmd *cobra.Command, args []string) {
var ret int
defer func(r *int) {
if *r != 0 {
os.Exit(*r)
}
}(&ret)
fnerr := func(e error) {
logger.Error(e)
ret = 1
}
if len(args) == 0 {
fnerr(fmt.Errorf("account is required"))
return
}
ctx := context.Background()
mycon, err := grpcconn.GetConnection(ctx, grpcconn.AdminService)
if err != nil {
fnerr(err)
return
}
client, err := admin.NewClient(ctx, &admin.ClientOptions{Conn: mycon})
if err != nil {
fnerr(err)
return
}
defer client.Close()
resp, err := client.GetDefaultCostAccess(ctx, &admin.GetDefaultCostAccessRequest{
Target: args[0],
})
if err != nil {
fnerr(err)
return
}
switch {
case params.OutFile != "" && params.OutFmt == "csv":
logger.Info("format not supported yet")
default:
b, _ := json.Marshal(resp)
logger.Info(string(b))
}
},
}
cmd.Flags().SortFlags = false
return cmd
}
func UpdateDefaultCostAccessInfo() *cobra.Command {
var (
wait bool
)
cmd := &cobra.Command{
Use: "update <account>",
Short: "Update default cost access",
Long: `Update default cost access. Recommended when the status is 'outdated', which means there is an
update to the CloudFormation template.`,
Run: func(cmd *cobra.Command, args []string) {
var ret int
defer func(r *int) {
if *r != 0 {
os.Exit(*r)
}
}(&ret)
fnerr := func(e error) {
logger.Error(e)
ret = 1
}
if len(args) == 0 {
fnerr(fmt.Errorf("account is required"))
return
}
ctx := context.Background()
mycon, err := grpcconn.GetConnection(ctx, grpcconn.AdminService)
if err != nil {
fnerr(err)
return
}
client, err := admin.NewClient(ctx, &admin.ClientOptions{Conn: mycon})
if err != nil {
fnerr(err)
return
}
defer client.Close()
resp, err := client.UpdateDefaultCostAccess(ctx, &admin.UpdateDefaultCostAccessRequest{
Target: args[0],
})
if err != nil {
fnerr(err)
return
}
logger.Infof("operation=%v", resp.Name)
if wait {
quit, cancel := context.WithCancel(context.Background())
done := make(chan struct{}, 1)
// Interrupt handler.
go func() {
sigch := make(chan os.Signal)
signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
<-sigch
cancel()
}()
go func() {
for {
q := context.WithValue(quit, struct{}{}, nil)
op, err := ops.WaitForOperation(q, ops.WaitForOperationInput{
Name: resp.Name,
})
if err != nil {
logger.Error(err)
done <- struct{}{}
return
}
if op != nil {
if op.Done {
done <- struct{}{}
return
}
}
}
}()
logger.Infof("wait for %v, this could take some time...", resp.Name)
select {
case <-done:
case <-quit.Done():
logger.Info("interrupted")
}
}
},
}
cmd.Flags().SortFlags = false
cmd.Flags().BoolVar(&wait, "wait", wait, "wait for the update to finish")
return cmd
}
func DelDefaultCostAccessInfo() *cobra.Command {
cmd := &cobra.Command{
Use: "rm <account>",
Short: "Remove default cost access",
Long: `Remove default cost access. This does not delete the CloudFormation stack.`,
Run: func(cmd *cobra.Command, args []string) {
var ret int
defer func(r *int) {
if *r != 0 {
os.Exit(*r)
}
}(&ret)
fnerr := func(e error) {
logger.Error(e)
ret = 1
}
if len(args) == 0 {
fnerr(fmt.Errorf("account is required"))
return
}
ctx := context.Background()
mycon, err := grpcconn.GetConnection(ctx, grpcconn.AdminService)
if err != nil {
fnerr(err)
return
}
client, err := admin.NewClient(ctx, &admin.ClientOptions{Conn: mycon})
if err != nil {
fnerr(err)
return
}
defer client.Close()
_, err = client.DeleteDefaultCostAccess(ctx, &admin.DeleteDefaultCostAccessRequest{
Target: args[0],
})
if err != nil {
fnerr(err)
return
}
logger.Info("cross-account access removed")
},
}
cmd.Flags().SortFlags = false
return cmd
}
func CrossAcctAccessCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "xacct",
Short: "Subcommand for AWS cost access operations",
Long: `Subcommand for AWS cost access operations.`,
Run: func(cmd *cobra.Command, args []string) {
logger.Info("see -h for more information")
},
}
cmd.Flags().SortFlags = false
cmd.AddCommand(
CreateDefaultCostAccessInfo(),
ListDefaultCostAccessInfo(),
GetDefaultCostAccessInfo(),
UpdateDefaultCostAccessInfo(),
DelDefaultCostAccessInfo(),
)
return cmd
}