206 lines
5.1 KiB
Go
206 lines
5.1 KiB
Go
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
// Package inventory parses the Ansible INI inventory (the `hosts` file): sections, host lines with key=value
|
|
// variables, [group:children] and [group:vars]. Only what hub needs: addresses, users, ports, groups.
|
|
package inventory
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"regexp"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// Host is one inventory host with the merged variables of all its lines.
|
|
type Host struct {
|
|
Name string
|
|
Vars map[string]string
|
|
Groups []string // sorted
|
|
}
|
|
|
|
// Address is ansible_host, falling back to the inventory name.
|
|
func (h Host) Address() string {
|
|
if v := h.Vars["ansible_host"]; v != "" {
|
|
return v
|
|
}
|
|
return h.Name
|
|
}
|
|
|
|
// User is ansible_user ("" = let ssh decide).
|
|
func (h Host) User() string { return h.Vars["ansible_user"] }
|
|
|
|
// Port is ansible_port, default 22.
|
|
func (h Host) Port() int {
|
|
if v := h.Vars["ansible_port"]; v != "" {
|
|
if n, err := strconv.Atoi(v); err == nil && n > 0 && n < 65536 {
|
|
return n
|
|
}
|
|
}
|
|
return 22
|
|
}
|
|
|
|
// SyslogHostname is syslog_hostname ("" when unset).
|
|
func (h Host) SyslogHostname() string { return h.Vars["syslog_hostname"] }
|
|
|
|
// Inventory is the parsed file.
|
|
type Inventory struct {
|
|
Hosts map[string]*Host
|
|
Children map[string][]string // group -> child groups
|
|
}
|
|
|
|
// Host returns the named host.
|
|
func (inv *Inventory) Host(name string) (*Host, bool) {
|
|
h, ok := inv.Hosts[name]
|
|
return h, ok
|
|
}
|
|
|
|
// Names returns all host names, sorted.
|
|
func (inv *Inventory) Names() []string {
|
|
out := make([]string, 0, len(inv.Hosts))
|
|
for n := range inv.Hosts {
|
|
out = append(out, n)
|
|
}
|
|
sort.Strings(out)
|
|
return out
|
|
}
|
|
|
|
// Load parses a file.
|
|
func Load(path string) (*Inventory, error) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("inventory unreadable: %s", path)
|
|
}
|
|
defer f.Close()
|
|
return Parse(f)
|
|
}
|
|
|
|
var (
|
|
// Safe values for ssh arguments: nothing that could start an option or smuggle a second host.
|
|
safeHostRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:%-]*$`)
|
|
safeUserRe = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._-]*$`)
|
|
nameRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
|
|
)
|
|
|
|
// ValidName reports whether name is usable as a host name in file names and arguments.
|
|
func ValidName(name string) bool { return nameRe.MatchString(name) }
|
|
|
|
// SSHTarget returns validated user, address and port for ssh.
|
|
func (h Host) SSHTarget() (user, addr string, port int, err error) {
|
|
addr = h.Address()
|
|
if !safeHostRe.MatchString(addr) {
|
|
return "", "", 0, fmt.Errorf("host %s: ansible_host %q is not a plain address", h.Name, addr)
|
|
}
|
|
user = h.User()
|
|
if user != "" && !safeUserRe.MatchString(user) {
|
|
return "", "", 0, fmt.Errorf("host %s: ansible_user %q is not a plain user name", h.Name, user)
|
|
}
|
|
return user, addr, h.Port(), nil
|
|
}
|
|
|
|
// Parse reads an INI inventory.
|
|
func Parse(r io.Reader) (*Inventory, error) {
|
|
inv := &Inventory{Hosts: map[string]*Host{}, Children: map[string][]string{}}
|
|
groups := map[string]map[string]bool{}
|
|
section, kind := "", "hosts"
|
|
sc := bufio.NewScanner(r)
|
|
sc.Buffer(make([]byte, 64*1024), 1024*1024)
|
|
for sc.Scan() {
|
|
line := strings.TrimSpace(sc.Text())
|
|
if line == "" || line[0] == '#' || line[0] == ';' {
|
|
continue
|
|
}
|
|
if line[0] == '[' {
|
|
end := strings.IndexByte(line, ']')
|
|
if end < 0 {
|
|
return nil, fmt.Errorf("inventory: bad section line %q", line)
|
|
}
|
|
name := line[1:end]
|
|
section, kind = name, "hosts"
|
|
if i := strings.IndexByte(name, ':'); i >= 0 {
|
|
section, kind = name[:i], name[i+1:]
|
|
}
|
|
continue
|
|
}
|
|
switch kind {
|
|
case "vars":
|
|
continue
|
|
case "children":
|
|
inv.Children[section] = append(inv.Children[section], line)
|
|
continue
|
|
}
|
|
fields := splitFields(line)
|
|
if len(fields) == 0 {
|
|
continue
|
|
}
|
|
name := fields[0]
|
|
h := inv.Hosts[name]
|
|
if h == nil {
|
|
h = &Host{Name: name, Vars: map[string]string{}}
|
|
inv.Hosts[name] = h
|
|
}
|
|
for _, kv := range fields[1:] {
|
|
if k, v, ok := strings.Cut(kv, "="); ok {
|
|
h.Vars[k] = v
|
|
}
|
|
}
|
|
if section != "" {
|
|
if groups[name] == nil {
|
|
groups[name] = map[string]bool{}
|
|
}
|
|
groups[name][section] = true
|
|
}
|
|
}
|
|
if err := sc.Err(); err != nil {
|
|
return nil, fmt.Errorf("inventory unreadable")
|
|
}
|
|
for name, set := range groups {
|
|
for g := range set {
|
|
inv.Hosts[name].Groups = append(inv.Hosts[name].Groups, g)
|
|
}
|
|
sort.Strings(inv.Hosts[name].Groups)
|
|
}
|
|
return inv, nil
|
|
}
|
|
|
|
// splitFields splits on whitespace, honouring single and double quotes and dropping a trailing comment that
|
|
// starts with " #".
|
|
func splitFields(line string) []string {
|
|
var out []string
|
|
var cur strings.Builder
|
|
var quote rune
|
|
has := false
|
|
for i, r := range line {
|
|
switch {
|
|
case quote != 0:
|
|
if r == quote {
|
|
quote = 0
|
|
} else {
|
|
cur.WriteRune(r)
|
|
}
|
|
case r == '\'' || r == '"':
|
|
quote, has = r, true
|
|
case r == '#' && !has && cur.Len() == 0 && i > 0:
|
|
return append(out, flush(&cur, &has)...)
|
|
case r == ' ' || r == '\t':
|
|
out = append(out, flush(&cur, &has)...)
|
|
default:
|
|
cur.WriteRune(r)
|
|
has = true
|
|
}
|
|
}
|
|
return append(out, flush(&cur, &has)...)
|
|
}
|
|
|
|
func flush(cur *strings.Builder, has *bool) []string {
|
|
if !*has {
|
|
return nil
|
|
}
|
|
s := cur.String()
|
|
cur.Reset()
|
|
*has = false
|
|
return []string{s}
|
|
}
|