Initial bootapi: NetBox-driven PXE/kickstart boot service
bootapi replaces Cobbler's PXE/kickstart side. It resolves a PXE-booting host
from NetBox (by MAC or hostname), renders an iPXE boot script and a kickstart
from Go text/templates, and serves them over HTTP. The ENC half already moved to
encapi; this covers the provisioning/boot half.
What's here:
- cmd/bootapi + internal/{config,model,netbox,render,server}; embedded default
templates under templates/ (AlmaLinux 9 + Fedora kickstarts, iPXE boot +
unknown-MAC fallbacks) ported from Cobbler's boot/bootstrap contract.
- NetBox client (v4.x API) behind a Resolver interface with a short-TTL cache;
tested against httptest fixtures using real NetBox JSON shapes.
- chi HTTP server: /ipxe/{mac}, /boot/ipxe?mac=, /ks/{ident}, healthz/readyz,
Prometheus /metrics. Unknown MAC -> safe fallback iPXE (200), unknown KS -> 404.
- Secrets (root pw hash, ssh keys) injected at render time from env/Vault, never
NetBox. Config is env-based per estate convention.
- Makefile (build/test/lint/docker + patch/minor/major), Dockerfile (distroless),
.woodpecker (pre-commit, golangci-lint v2 + go test -race, docker build on PR;
image push + Gitea binary release on v* tag), docs/ and example config.
go build/vet clean, go test -race green, golangci-lint v2 clean, pre-commit clean.
Claude-Session: https://claude.ai/code/session_015ur3i7D2azsMAWTSVABApv
This commit is contained in:
@@ -0,0 +1,163 @@
|
||||
// Package config loads bootapi server configuration from the environment,
|
||||
// following the same env-first convention as encapi.
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config is the fully-resolved server configuration.
|
||||
type Config struct {
|
||||
// ListenAddr is the HTTP bind address, e.g. ":8000".
|
||||
ListenAddr string
|
||||
|
||||
// NetBoxURL is the base URL of the NetBox API,
|
||||
// e.g. "https://netbox.k8s.syd1.au.unkin.net".
|
||||
NetBoxURL string
|
||||
// NetBoxToken is the NetBox API token. Prefer NetBoxTokenFile in k8s.
|
||||
NetBoxToken string
|
||||
// NetBoxTimeout bounds each NetBox HTTP request.
|
||||
NetBoxTimeout time.Duration
|
||||
// NetBoxInsecure disables TLS verification against NetBox (dev only).
|
||||
NetBoxInsecure bool
|
||||
|
||||
// CacheTTL is how long a resolved host is cached in memory. Short by
|
||||
// design: NetBox is the source of truth and a machine's provisioning data
|
||||
// can change between boots.
|
||||
CacheTTL time.Duration
|
||||
|
||||
// TemplateDir, when set, is a directory of override templates layered on
|
||||
// top of the embedded defaults (a Kubernetes ConfigMap mount in prod).
|
||||
TemplateDir string
|
||||
// DefaultTemplate is the kickstart template used when NetBox provides no
|
||||
// platform/role/override selection key.
|
||||
DefaultTemplate string
|
||||
|
||||
// BaseURL is bootapi's own externally-reachable base URL, baked into the
|
||||
// iPXE script's inst.ks= and repo URLs so a booting host calls back here.
|
||||
// e.g. "http://bootapi.k8s.syd1.au.unkin.net".
|
||||
BaseURL string
|
||||
|
||||
// BootBaseURL is the base URL of the OS install trees (kernel/initrd +
|
||||
// inst.repo), e.g. "http://mirror.k8s.syd1.au.unkin.net/almalinux".
|
||||
BootBaseURL string
|
||||
|
||||
// PuppetServer / PuppetCAServer are baked into kickstart %post so the
|
||||
// freshly-installed host checks in to the right place.
|
||||
PuppetServer string
|
||||
PuppetCAServer string
|
||||
|
||||
// Domain is the default DNS domain applied when NetBox does not record one
|
||||
// for a device.
|
||||
Domain string
|
||||
|
||||
// Nameservers is the default resolver list applied when NetBox records
|
||||
// none for a device.
|
||||
Nameservers []string
|
||||
|
||||
// RootPasswordHash is a crypt(3) hash injected into kickstarts at render
|
||||
// time (sourced from Vault in k8s). Empty locks the root account.
|
||||
RootPasswordHash string
|
||||
// SSHAuthorizedKeys are public keys installed for root at render time.
|
||||
SSHAuthorizedKeys []string
|
||||
|
||||
// UnknownMACFallback selects what the iPXE endpoint returns for a MAC that
|
||||
// NetBox does not know: "local" (chain to local disk, the safe default) or
|
||||
// "shell" (drop to an iPXE shell for debugging). See docs/endpoints.md.
|
||||
UnknownMACFallback string
|
||||
}
|
||||
|
||||
// Load reads configuration from the environment, applying defaults, and reads a
|
||||
// token file when BOOTAPI_NETBOX_TOKEN_FILE is set (Vault-mounted secret).
|
||||
func Load() (*Config, error) {
|
||||
cacheTTL, err := time.ParseDuration(getenv("BOOTAPI_CACHE_TTL", "30s"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid BOOTAPI_CACHE_TTL: %w", err)
|
||||
}
|
||||
nbTimeout, err := time.ParseDuration(getenv("BOOTAPI_NETBOX_TIMEOUT", "5s"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid BOOTAPI_NETBOX_TIMEOUT: %w", err)
|
||||
}
|
||||
|
||||
token := os.Getenv("BOOTAPI_NETBOX_TOKEN")
|
||||
if tf := os.Getenv("BOOTAPI_NETBOX_TOKEN_FILE"); tf != "" {
|
||||
b, err := os.ReadFile(tf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read BOOTAPI_NETBOX_TOKEN_FILE %q: %w", tf, err)
|
||||
}
|
||||
token = strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
fallback := getenv("BOOTAPI_UNKNOWN_MAC_FALLBACK", "local")
|
||||
if fallback != "local" && fallback != "shell" {
|
||||
return nil, fmt.Errorf("invalid BOOTAPI_UNKNOWN_MAC_FALLBACK %q: want \"local\" or \"shell\"", fallback)
|
||||
}
|
||||
|
||||
rootHash := os.Getenv("BOOTAPI_ROOT_PASSWORD_HASH")
|
||||
if rf := os.Getenv("BOOTAPI_ROOT_PASSWORD_HASH_FILE"); rf != "" {
|
||||
b, err := os.ReadFile(rf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read BOOTAPI_ROOT_PASSWORD_HASH_FILE %q: %w", rf, err)
|
||||
}
|
||||
rootHash = strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
return &Config{
|
||||
ListenAddr: getenv("BOOTAPI_LISTEN_ADDR", ":8000"),
|
||||
NetBoxURL: strings.TrimRight(os.Getenv("BOOTAPI_NETBOX_URL"), "/"),
|
||||
NetBoxToken: token,
|
||||
NetBoxTimeout: nbTimeout,
|
||||
NetBoxInsecure: getenv("BOOTAPI_NETBOX_INSECURE", "false") == "true",
|
||||
CacheTTL: cacheTTL,
|
||||
TemplateDir: os.Getenv("BOOTAPI_TEMPLATE_DIR"),
|
||||
DefaultTemplate: getenv("BOOTAPI_DEFAULT_TEMPLATE", "almalinux9"),
|
||||
BaseURL: strings.TrimRight(os.Getenv("BOOTAPI_BASE_URL"), "/"),
|
||||
BootBaseURL: strings.TrimRight(os.Getenv("BOOTAPI_BOOT_BASE_URL"), "/"),
|
||||
PuppetServer: getenv("BOOTAPI_PUPPET_SERVER", "puppet.query.consul"),
|
||||
PuppetCAServer: getenv("BOOTAPI_PUPPET_CA_SERVER", "puppetca.query.consul"),
|
||||
Domain: getenv("BOOTAPI_DOMAIN", "main.unkin.net"),
|
||||
Nameservers: splitList(os.Getenv("BOOTAPI_NAMESERVERS")),
|
||||
RootPasswordHash: rootHash,
|
||||
SSHAuthorizedKeys: splitLines(os.Getenv("BOOTAPI_SSH_AUTHORIZED_KEYS")),
|
||||
UnknownMACFallback: fallback,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func getenv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// splitList splits a comma-separated env value into a trimmed, non-empty slice.
|
||||
func splitList(v string) []string {
|
||||
if v == "" {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
for _, p := range strings.Split(v, ",") {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// splitLines splits a newline-separated env value (e.g. multiple SSH keys) into
|
||||
// a trimmed, non-empty slice.
|
||||
func splitLines(v string) []string {
|
||||
if v == "" {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
for _, p := range strings.Split(v, "\n") {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLoadDefaults(t *testing.T) {
|
||||
clearEnv(t)
|
||||
c, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.ListenAddr != ":8000" {
|
||||
t.Errorf("ListenAddr = %q", c.ListenAddr)
|
||||
}
|
||||
if c.CacheTTL != 30*time.Second {
|
||||
t.Errorf("CacheTTL = %v", c.CacheTTL)
|
||||
}
|
||||
if c.DefaultTemplate != "almalinux9" {
|
||||
t.Errorf("DefaultTemplate = %q", c.DefaultTemplate)
|
||||
}
|
||||
if c.PuppetServer != "puppet.query.consul" || c.PuppetCAServer != "puppetca.query.consul" {
|
||||
t.Errorf("puppet servers = %q / %q", c.PuppetServer, c.PuppetCAServer)
|
||||
}
|
||||
if c.UnknownMACFallback != "local" {
|
||||
t.Errorf("UnknownMACFallback = %q", c.UnknownMACFallback)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadTokenFile(t *testing.T) {
|
||||
clearEnv(t)
|
||||
dir := t.TempDir()
|
||||
tf := filepath.Join(dir, "token")
|
||||
if err := os.WriteFile(tf, []byte(" secret-token\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("BOOTAPI_NETBOX_TOKEN_FILE", tf)
|
||||
c, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.NetBoxToken != "secret-token" {
|
||||
t.Errorf("token = %q, want trimmed file contents", c.NetBoxToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsBadFallback(t *testing.T) {
|
||||
clearEnv(t)
|
||||
t.Setenv("BOOTAPI_UNKNOWN_MAC_FALLBACK", "bogus")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("expected error for invalid fallback")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadListsAndTrim(t *testing.T) {
|
||||
clearEnv(t)
|
||||
t.Setenv("BOOTAPI_NAMESERVERS", " 10.0.0.1, 10.0.0.2 ,")
|
||||
t.Setenv("BOOTAPI_NETBOX_URL", "https://netbox.example.net/")
|
||||
c, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.Nameservers) != 2 || c.Nameservers[1] != "10.0.0.2" {
|
||||
t.Errorf("nameservers = %v", c.Nameservers)
|
||||
}
|
||||
if c.NetBoxURL != "https://netbox.example.net" {
|
||||
t.Errorf("NetBoxURL trailing slash not trimmed: %q", c.NetBoxURL)
|
||||
}
|
||||
}
|
||||
|
||||
// clearEnv unsets every BOOTAPI_* var so a developer's shell can't leak into
|
||||
// the test. t.Setenv restores them after the test.
|
||||
func clearEnv(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, kv := range os.Environ() {
|
||||
if k, _, ok := cut(kv, '='); ok && len(k) > 8 && k[:8] == "BOOTAPI_" {
|
||||
// t.Setenv to "" is enough: Load treats empty as unset, and the
|
||||
// test framework restores the original value on cleanup.
|
||||
t.Setenv(k, "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cut(s string, sep byte) (before, after string, found bool) {
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == sep {
|
||||
return s[:i], s[i+1:], true
|
||||
}
|
||||
}
|
||||
return s, "", false
|
||||
}
|
||||
Reference in New Issue
Block a user