-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypes.go
84 lines (73 loc) · 1.66 KB
/
types.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
package main
import (
"fmt"
"regexp"
"strings"
"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
)
// Host is a map of HostVar, keyed by a hostname.
type Host struct {
Name string
Address string
Extra map[string]string
}
// Group is struct that contains a list of hosts.
type Group struct {
Hosts []Host `yaml:"hosts,omitempty"`
}
// Groups is a map of groups, keyed by a group name.
type Groups map[string]Group
// Inventory represents an Ansible Inventory consists of host variables and groups.
type Inventory struct {
Groups Groups `json:"groups,omitempty"`
}
// Filter represent a filter on server matadata
type Filter struct {
Key, Operator, Value string
}
// Match checks if a key, valur pair matches with the filter
func (f Filter) Match(k, v string) (bool, error) {
switch f.Operator {
case "=":
if strings.ToUpper(k) == strings.ToUpper(f.Key) && strings.ToUpper(v) == strings.ToUpper(f.Value) {
return true, nil
}
case "~":
if strings.ToUpper(k) == strings.ToUpper(f.Key) {
r, err := regexp.Compile(f.Value)
if err != nil {
return false, err
}
return r.Match([]byte(v)), nil
}
default:
return false, fmt.Errorf("unsupported operator %s", f.Operator)
}
return false, nil
}
// ServerList is a list of server
type ServerList struct {
l []servers.Server
err error
}
// Filter a list of server
func (l *ServerList) Filter(f Filter) {
if l.err != nil {
fmt.Println(l.err)
return
}
list := []servers.Server{}
for _, s := range l.l {
for k, v := range s.Metadata {
ok, err := f.Match(k, v)
if err != nil {
l.err = err
return
}
if ok {
list = append(list, s)
}
}
}
l.l = list
}