-
Notifications
You must be signed in to change notification settings - Fork 20
/
firewall_list.go
80 lines (65 loc) · 1.93 KB
/
firewall_list.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
package cmd
import (
"fmt"
"strings"
"github.com/exoscale/cli/pkg/globalstate"
"github.com/exoscale/cli/pkg/output"
"github.com/exoscale/egoscale"
"github.com/spf13/cobra"
)
type firewallListItemOutput struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
NumRules int `json:"num_rules" outputLabel:"Rules"`
}
type firewallListOutput []firewallListItemOutput
func (o *firewallListOutput) ToJSON() { output.JSON(o) }
func (o *firewallListOutput) ToText() { output.Text(o) }
func (o *firewallListOutput) ToTable() { output.Table(o) }
func init() {
firewallCmd.AddCommand(&cobra.Command{
Use: "list [FILTER]...",
Short: "List Security Groups",
Long: fmt.Sprintf(`This command lists existing Security Groups.
Optional patterns can be provided to filter results by ID, name or description.
Supported output template annotations: %s`,
strings.Join(output.TemplateAnnotations(&firewallListOutput{}), ", ")),
Aliases: gListAlias,
RunE: func(cmd *cobra.Command, args []string) error {
return printOutput(listSecurityGroups(args))
},
})
}
func listSecurityGroups(filters []string) (output.Outputter, error) {
sgs, err := globalstate.EgoscaleClient.ListWithContext(gContext, &egoscale.SecurityGroup{})
if err != nil {
return nil, err
}
out := firewallListOutput{}
for _, s := range sgs {
sg := s.(*egoscale.SecurityGroup)
keep := true
if len(filters) > 0 {
keep = false
s := strings.ToLower(fmt.Sprintf("%s#%s#%s", sg.ID, sg.Name, sg.Description))
for _, filter := range filters {
substr := strings.ToLower(filter)
if strings.Contains(s, substr) {
keep = true
break
}
}
}
if !keep {
continue
}
out = append(out, firewallListItemOutput{
ID: sg.ID.String(),
Name: sg.Name,
Description: sg.Description,
NumRules: len(sg.IngressRule) + len(sg.EgressRule),
})
}
return &out, nil
}