-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
99 lines (82 loc) · 2.56 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
package main
import (
"crypto/tls"
"fmt"
log "github.com/Sirupsen/logrus"
"github.com/marthjod/ansible-one-inventory/config"
"github.com/marthjod/ansible-one-inventory/discovery"
"github.com/marthjod/ansible-one-inventory/filter"
"github.com/marthjod/ansible-one-inventory/hostnameextractor"
"github.com/marthjod/gocart/api"
"github.com/marthjod/gocart/vmpool"
flag "github.com/ogier/pflag"
"net/http"
"os"
"path"
)
const (
configFile = "opennebula-inventory.yaml"
)
func main() {
var (
host = flag.String("host", "", "")
list = flag.Bool("list", true, "")
debug = flag.Bool("debug", false, "Enable debug output.")
extractor hostnameextractor.HostnameExtractor
)
flag.Parse()
if *debug {
log.SetLevel(log.DebugLevel)
}
confPath := path.Dir(os.Args[0]) + "/" + configFile
log.Debug("Loading config ", confPath)
f, err := os.Open(confPath)
if err != nil {
log.Fatal(err.Error())
}
defer f.Close()
conf, err := config.FromFile(f)
if err != nil {
log.Error(err.Error())
log.Fatalf("Config file %s missing (expected in same directory).", configFile)
}
log.Debug("Accessing API at ", conf.Url)
apiClient, err := api.NewClient(conf.Url, conf.Username, conf.Password, &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: conf.SslSkipVerify},
})
if err != nil {
log.Fatal(err.Error())
}
log.Debug("Fetching VM pool")
vmPool := vmpool.NewVmPool()
if err := apiClient.Call(vmPool); err != nil {
log.Fatal(err.Error())
}
extractor = &hostnameextractor.VmNameExtractor{}
if conf.HostnameFieldInUserTemplate != "" {
extractor = &hostnameextractor.UserTemplateExtractor{
Field: conf.HostnameFieldInUserTemplate,
}
}
hostNames := discovery.GetHostnames(vmPool, extractor)
log.Debugf("Hostnames: %v", hostNames)
groupFilters := conf.StaticGroupFilters
if conf.DynamicGroupFilters.Pattern != "" {
distinctPatterns := vmPool.GetDistinctVmNamePatternsExtractHostname(
conf.DynamicGroupFilters.Pattern, conf.DynamicGroupFilters.Prefix, conf.DynamicGroupFilters.Infix,
conf.DynamicGroupFilters.Suffix, extractor.Extract)
log.Debugf("Distinct patterns: %+v", distinctPatterns)
for pattern, _ := range distinctPatterns {
groupFilters[filter.AdjustPatternName(pattern, conf.DynamicGroupFilters.PatternReplace)] = pattern
}
}
log.Debugf("Group filters: %+v", groupFilters)
inventory := discovery.GetInventoryGroups(hostNames, groupFilters)
if *host != "" {
log.Error("--host option not implemented yet")
os.Exit(1)
} else if *list {
log.Debug("Writing inventory")
fmt.Println(inventory.Json())
}
}