32 lines
953 B
Go
32 lines
953 B
Go
package resolver
|
|
|
|
import (
|
|
"context"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
|
)
|
|
|
|
var validHostname = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$`)
|
|
|
|
// HostnameStrategy connects by the NetBox name instead of an IP, so DNS or
|
|
// ~/.ssh/config resolves it. Names without a dot get the optional domain.
|
|
// Names that are no valid hostname fall through to the next strategy.
|
|
type HostnameStrategy struct {
|
|
domain string
|
|
}
|
|
|
|
func (s *HostnameStrategy) Name() string { return "hostname" }
|
|
|
|
func (s *HostnameStrategy) Resolve(_ context.Context, entry *netbox.HostEntry, _ *netbox.Client) (string, error) {
|
|
name := strings.ToLower(entry.Name)
|
|
if domain := strings.Trim(s.domain, "."); domain != "" && !strings.Contains(name, ".") {
|
|
name += "." + strings.ToLower(domain)
|
|
}
|
|
if !validHostname.MatchString(name) {
|
|
return "", ErrNoIP
|
|
}
|
|
return name, nil
|
|
}
|