Skip to content

Instantly share code, notes, and snippets.

@lxfontes
Created February 16, 2025 17:06
Show Gist options
  • Save lxfontes/1e8ae304564ce78aa619495404a2d141 to your computer and use it in GitHub Desktop.
Save lxfontes/1e8ae304564ce78aa619495404a2d141 to your computer and use it in GitHub Desktop.
minimal kube apiserver
package main
import (
"context"
"strconv"
"strings"
apiapp "k8s.io/kubernetes/cmd/kube-apiserver/app"
)
type APIServerConfig struct {
// Required
BindAddr string
BindPort int
ClusterDomain string
AdvertiseAddress string
APICertFile string
APIKeyFile string
ETCDServers []string
// Optional
// Uses a Certificate Authority file to authenticate requests
ClientCACertFile string
// Uses a csv file to authenticate requests with tokens
TokenAuthFile string
// Log level for apiserver
LogLevel int
// Not relevant to deployment, but required by apiserver
ClusterCIDR string
}
func defaultAPIServerConfig() *APIServerConfig {
return &APIServerConfig{
BindAddr: "0.0.0.0",
BindPort: 6443,
ClusterDomain: "cluster.local",
ClusterCIDR: "10.0.0.0/24",
ETCDServers: []string{"http://127.0.0.1:2380/"},
LogLevel: 4,
TokenAuthFile: "/tmp/apiserver/token.csv",
APIKeyFile: "/tmp/apiserver/apiserver.key",
APICertFile: "/tmp/apiserver/apiserver.crt",
}
}
func startAPIServer(ctx context.Context, cfg *APIServerConfig) error {
argsMap := map[string]string{
"authorization-mode": "RBAC",
"bind-address": cfg.BindAddr,
"secure-port": strconv.Itoa(cfg.BindPort),
"service-cluster-ip-range": cfg.ClusterCIDR,
"tls-cert-file": cfg.APICertFile,
"tls-private-key-file": cfg.APIKeyFile,
"service-account-signing-key-file": cfg.APIKeyFile,
"service-account-key-file": cfg.APIKeyFile,
"service-account-issuer": "https://kubernetes.default.svc." + cfg.ClusterDomain,
"api-audiences": "https://kubernetes.default.svc." + cfg.ClusterDomain,
"etcd-servers": strings.Join(cfg.ETCDServers, ","),
"v": strconv.Itoa(cfg.LogLevel),
"profiling": "false",
"storage-backend": "etcd3",
"anonymous-auth": "false",
}
if cfg.ClientCACertFile != "" {
argsMap["client-ca-file"] = cfg.ClientCACertFile
}
if cfg.TokenAuthFile != "" {
argsMap["token-auth-file"] = cfg.TokenAuthFile
}
if cfg.AdvertiseAddress != "" {
argsMap["advertise-address"] = cfg.AdvertiseAddress
}
command := apiapp.NewAPIServerCommand()
apiArgs := flattenArgs(argsMap)
command.SetArgs(apiArgs)
return command.ExecuteContext(ctx)
}
func flattenArgs(argsMap map[string]string) []string {
args := make([]string, 0, len(argsMap))
for k, v := range argsMap {
args = append(args, "--"+k+"="+v)
}
return args
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment