-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinventory.go
111 lines (103 loc) · 2.19 KB
/
inventory.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
package sshutils
import (
"bytes"
"os"
"path/filepath"
"strings"
)
type Inventory struct {
Targets []Target
Groups map[string][]string
}
type Target struct {
Name string
Host string
Port string
User string
}
// For comparing hostnames
func (h Target) canonical() string {
host := h.Host
if host == "" {
host = h.Name
}
if h.Port != "" && h.Port != "22" {
return "[" + host + "]:" + h.Port
}
if strings.Index(host, ":") >= 0 {
return "[" + host + "]"
}
return host
}
// For dialing
func (h Target) dialer() string {
host := h.Host
if host == "" {
host = h.Name
}
if h.Port != "" {
host += ":" + h.Port
} else {
host += ":22"
}
return host
}
func prefix(v, s string) (string, bool) {
if strings.HasPrefix(v, s) {
return v[len(s):], true
}
return "", false
}
func parseInventory(name string) (Inventory, error) {
if strings.HasSuffix(name, ".yaml") {
return parseInventoryYaml(name)
}
info, rerr := os.Stat(name)
if rerr == nil && !info.IsDir() {
return parseInventoryINI(name)
}
hy := filepath.Join(name, "hosts.yaml")
if inv, err := parseInventoryYaml(hy); err == nil || !os.IsNotExist(err) {
return inv, err
}
hi := filepath.Join(name, "hosts")
if inv, err := parseInventoryINI(hi); err == nil || !os.IsNotExist(err) {
return inv, err
}
return Inventory{}, rerr
}
// TODO: support groups
func parseInventoryINI(fname string) (inv Inventory, err error) {
buf, err := os.ReadFile(fname)
if err != nil {
return
}
// TODO: support groups
lines := bytes.Split(buf, []byte("\n"))
for _, bline := range lines {
line := string(bline)
if c := strings.Index(line, "#"); c >= 0 {
line = line[:c]
}
if strings.Trim(line, " \t") == "" {
continue
}
parts := strings.Split(line, " ")
h := Target{Name: parts[0]}
for _, p := range parts[1:] {
if v, ok := prefix(p, "ansible_host="); ok {
h.Host = v
} else if v, ok := prefix(p, "ansible_ssh_host="); ok {
h.Host = v
} else if v, ok := prefix(p, "ansible_ssh_port="); ok {
h.Port = v
} else if v, ok := prefix(p, "ansible_ssh_user="); ok {
h.User = v
} else if v, ok := prefix(p, "ansible_user="); ok {
h.User = v
}
}
inv.Targets = append(inv.Targets, h)
}
return
}