Skip to content

Commit

Permalink
init BearerTokenFile in toRestConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
sevennt committed May 7, 2024
1 parent 48ef6b7 commit d9436ac
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,32 @@ type Config struct {
Namespaces []string
DeploymentPrefix string // 命名前缀
TLSClientConfigInsecure bool
tokenFile string
}

// DefaultConfig 返回默认配置
// DefaultConfig 返回默认配置,默认采用集群内模式
func DefaultConfig() *Config {
return &Config{
Addr: inClusterAddr(),
Token: inClusterToken(),
Namespaces: []string{inClusterNamespace()},
TLSClientConfigInsecure: true,
tokenFile: tokenFile,
}
}

func (c *Config) toRestConfig() *rest.Config {
return &rest.Config{
Host: c.Addr,
BearerToken: c.Token,
// 当BearerToken和BearerTokenFile同时不为空时,k8s-go内部为优先采用BearerTokenFile在底层周期刷新token
// 详见 https://github.com/kubernetes/client-go/blob/v0.24.0/transport/round_trippers.go#L52
cfg := &rest.Config{
Host: c.Addr,
BearerToken: c.Token,
BearerTokenFile: c.tokenFile,
TLSClientConfig: rest.TLSClientConfig{
Insecure: c.TLSClientConfigInsecure,
},
}
return cfg
}

func inClusterAddr() string {
Expand All @@ -48,16 +54,21 @@ func inClusterAddr() string {
return fmt.Sprintf("https://%s:%s", host, port)
}

const (
tokenFile = "/var/run/secrets/kubernetes.io/serviceaccount/token"
nsFile = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
)

func inClusterToken() string {
t, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token")
t, err := ioutil.ReadFile(tokenFile)
if err != nil {
return ""
}
return strings.TrimSpace(string(t))
}

func inClusterNamespace() string {
t, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
t, err := ioutil.ReadFile(nsFile)
if err != nil {
return ""
}
Expand Down

0 comments on commit d9436ac

Please sign in to comment.