Skip to content

Commit

Permalink
kubeadm-init: add --copy-credentials-for-user
Browse files Browse the repository at this point in the history
Using this new parameter the administrator's credentials
for the cluster will be copied to the specified
user's home directory.

WARNING: existing files will be overwritten.

Usage:
    kubeadm init --copy-credentials-for-user=<someuser>

Windows requires a different approach for copying the
credentials than Unix, thus a new package is added -
`platform` in `kubeadm/app/cmd`. It contains `init_unix.go`
and `init_windows.go` that define the exported function -
InitCopyCredentialsForUser(). The function works differently
on Unix and Windows.

The same package can be re-used for other multiplatform code.
  • Loading branch information
neolit123 committed Apr 18, 2018
1 parent fdbc9ef commit f67a150
Show file tree
Hide file tree
Showing 6 changed files with 322 additions and 15 deletions.
2 changes: 2 additions & 0 deletions cmd/kubeadm/app/cmd/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ go_library(
"//cmd/kubeadm/app/apis/kubeadm/v1alpha1:go_default_library",
"//cmd/kubeadm/app/apis/kubeadm/validation:go_default_library",
"//cmd/kubeadm/app/cmd/phases:go_default_library",
"//cmd/kubeadm/app/cmd/platform:go_default_library",
"//cmd/kubeadm/app/cmd/upgrade:go_default_library",
"//cmd/kubeadm/app/cmd/util:go_default_library",
"//cmd/kubeadm/app/constants:go_default_library",
Expand Down Expand Up @@ -115,6 +116,7 @@ filegroup(
srcs = [
":package-srcs",
"//cmd/kubeadm/app/cmd/phases:all-srcs",
"//cmd/kubeadm/app/cmd/platform:all-srcs",
"//cmd/kubeadm/app/cmd/upgrade:all-srcs",
"//cmd/kubeadm/app/cmd/util:all-srcs",
],
Expand Down
45 changes: 30 additions & 15 deletions cmd/kubeadm/app/cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import (
kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
kubeadmapiext "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1alpha1"
"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/validation"
platformutil "k8s.io/kubernetes/cmd/kubeadm/app/cmd/platform"
cmdutil "k8s.io/kubernetes/cmd/kubeadm/app/cmd/util"
kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
"k8s.io/kubernetes/cmd/kubeadm/app/features"
Expand Down Expand Up @@ -68,13 +69,7 @@ import (
var (
initDoneTempl = template.Must(template.New("init").Parse(dedent.Dedent(`
Your Kubernetes master has initialized successfully!
To start using your cluster, you need to run the following as a regular user:
mkdir -p $HOME/.kube
sudo cp -i {{.KubeConfigPath}} $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
{{.KubeConfigInfo}}
You should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
https://kubernetes.io/docs/concepts/cluster-administration/addons/
Expand Down Expand Up @@ -117,6 +112,7 @@ func NewCmdInit(out io.Writer) *cobra.Command {
var dryRun bool
var featureGatesString string
var ignorePreflightErrors []string
var copyCredentialsForUser string

cmd := &cobra.Command{
Use: "init",
Expand All @@ -134,15 +130,15 @@ func NewCmdInit(out io.Writer) *cobra.Command {
ignorePreflightErrorsSet, err := validation.ValidateIgnorePreflightErrors(ignorePreflightErrors, skipPreFlight)
kubeadmutil.CheckErr(err)

i, err := NewInit(cfgPath, internalcfg, ignorePreflightErrorsSet, skipTokenPrint, dryRun)
i, err := NewInit(cfgPath, internalcfg, ignorePreflightErrorsSet, skipTokenPrint, dryRun, copyCredentialsForUser)
kubeadmutil.CheckErr(err)
kubeadmutil.CheckErr(i.Validate(cmd))
kubeadmutil.CheckErr(i.Run(out))
},
}

AddInitConfigFlags(cmd.PersistentFlags(), cfg, &featureGatesString)
AddInitOtherFlags(cmd.PersistentFlags(), &cfgPath, &skipPreFlight, &skipTokenPrint, &dryRun, &ignorePreflightErrors)
AddInitOtherFlags(cmd.PersistentFlags(), &cfgPath, &skipPreFlight, &skipTokenPrint, &dryRun, &ignorePreflightErrors, &copyCredentialsForUser)

return cmd
}
Expand Down Expand Up @@ -203,7 +199,7 @@ func AddInitConfigFlags(flagSet *flag.FlagSet, cfg *kubeadmapiext.MasterConfigur
}

// AddInitOtherFlags adds init flags that are not bound to a configuration file to the given flagset
func AddInitOtherFlags(flagSet *flag.FlagSet, cfgPath *string, skipPreFlight, skipTokenPrint, dryRun *bool, ignorePreflightErrors *[]string) {
func AddInitOtherFlags(flagSet *flag.FlagSet, cfgPath *string, skipPreFlight, skipTokenPrint, dryRun *bool, ignorePreflightErrors *[]string, copyCredentialsForUser *string) {
flagSet.StringVar(
cfgPath, "config", *cfgPath,
"Path to kubeadm config file. WARNING: Usage of a configuration file is experimental.",
Expand Down Expand Up @@ -231,7 +227,7 @@ func AddInitOtherFlags(flagSet *flag.FlagSet, cfgPath *string, skipPreFlight, sk
}

// NewInit validates given arguments and instantiates Init struct with provided information.
func NewInit(cfgPath string, cfg *kubeadmapi.MasterConfiguration, ignorePreflightErrors sets.String, skipTokenPrint, dryRun bool) (*Init, error) {
func NewInit(cfgPath string, cfg *kubeadmapi.MasterConfiguration, ignorePreflightErrors sets.String, skipTokenPrint, dryRun bool, copyCredentialsForUser string) (*Init, error) {

if cfgPath != "" {
glog.V(1).Infof("[init] reading config file from: " + cfgPath)
Expand Down Expand Up @@ -275,14 +271,15 @@ func NewInit(cfgPath string, cfg *kubeadmapi.MasterConfiguration, ignorePrefligh
glog.V(1).Infof("Starting kubelet")
preflight.TryStartKubelet(ignorePreflightErrors)

return &Init{cfg: cfg, skipTokenPrint: skipTokenPrint, dryRun: dryRun}, nil
return &Init{cfg: cfg, skipTokenPrint: skipTokenPrint, dryRun: dryRun, copyCredentialsForUser: copyCredentialsForUser}, nil
}

// Init defines struct used by "kubeadm init" command
type Init struct {
cfg *kubeadmapi.MasterConfiguration
skipTokenPrint bool
dryRun bool
cfg *kubeadmapi.MasterConfiguration
skipTokenPrint bool
dryRun bool
copyCredentialsForUser string
}

// Validate validates configuration passed to "kubeadm init"
Expand Down Expand Up @@ -500,6 +497,24 @@ func (i *Init) Run(out io.Writer) error {
"joinCommand": joinCommand,
}

kubeConfigInfo := fmt.Sprintf(`
To start using your cluster, you need to run the following as a regular user:
mkdir -p $HOME/.kube
sudo cp -i %s $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
`, adminKubeConfigPath)

ctx["KubeConfigInfo"] = kubeConfigInfo
if i.copyCredentialsForUser != "" {
if err := platformutil.InitCopyCredentialsForUser(i.copyCredentialsForUser, adminKubeConfigPath); err == nil {
ctx["KubeConfigInfo"] = ""
} else {
fmt.Printf("[init] WARNING: Could not copy the administrator credentials for user %q: %v\n", i.copyCredentialsForUser, err)
}
}

return initDoneTempl.Execute(out, ctx)
}

Expand Down
59 changes: 59 additions & 0 deletions cmd/kubeadm/app/cmd/platform/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")

go_library(
name = "go_default_library",
srcs = [
"init_shared.go",
] + select({
"@io_bazel_rules_go//go/platform:android": [
"init_unix.go",
],
"@io_bazel_rules_go//go/platform:darwin": [
"init_unix.go",
],
"@io_bazel_rules_go//go/platform:dragonfly": [
"init_unix.go",
],
"@io_bazel_rules_go//go/platform:freebsd": [
"init_unix.go",
],
"@io_bazel_rules_go//go/platform:linux": [
"init_unix.go",
],
"@io_bazel_rules_go//go/platform:nacl": [
"init_unix.go",
],
"@io_bazel_rules_go//go/platform:netbsd": [
"init_unix.go",
],
"@io_bazel_rules_go//go/platform:openbsd": [
"init_unix.go",
],
"@io_bazel_rules_go//go/platform:plan9": [
"init_unix.go",
],
"@io_bazel_rules_go//go/platform:solaris": [
"init_unix.go",
],
"@io_bazel_rules_go//go/platform:windows": [
"init_windows.go",
],
"//conditions:default": [],
}),
importpath = "k8s.io/kubernetes/cmd/kubeadm/app/cmd/platform",
visibility = ["//visibility:public"],
)

filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)

filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
35 changes: 35 additions & 0 deletions cmd/kubeadm/app/cmd/platform/init_shared.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package platform

// shared constants for init
const (
InitErrorNoSuchUser = "no such user %q: %v"
InitErrorUserIsRoot = "user is root %q"
InitErrorNoHomeDir = "cannot obtain the home directory for user %q"
InitErrorAtoiString = "cannot Atoi() UID/GID string %q: %v"
InitErrorCannotCreateDir = "cannot create %q: %v"
InitErrorCannotChown = "cannot chown %q: %v"
InitErrorCannotOpenFileForReading = "cannot open file for reading %q: %v"
InitErrorCannotOpenFileForWriting = "cannot open file for writing %q: %v"
InitErrorCannotIoCopy = "cannot io.Copy() the configuration: %v"

InitMessageCopyingCredentials = "[init] Copying administrator credentials to %q from %q\n"

InitPathKube = "/.kube"
InitPathConfig = "/config"
)
95 changes: 95 additions & 0 deletions cmd/kubeadm/app/cmd/platform/init_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// +build !windows

/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package platform

import (
"fmt"
"io"
"os"
"os/user"
"strconv"
)

// InitCopyCredentialsForUser will copy the cluster admin credentials to the home path of a non-root user
func InitCopyCredentialsForUser(copyCredentialsForUser string, adminKubeConfigPath string) error {

var err error
var uid, gid int
var usr *user.User
var src, dest *os.File
var kubeDir, configFilePath string

usr, err = user.Lookup(copyCredentialsForUser)
if err != nil {
return fmt.Errorf(InitErrorNoSuchUser, copyCredentialsForUser, err)
}

if usr.Gid == "0" {
return fmt.Errorf(InitErrorUserIsRoot, copyCredentialsForUser)
}

if usr.HomeDir == "" {
return fmt.Errorf(InitErrorNoHomeDir, copyCredentialsForUser)
}
kubeDir = usr.HomeDir + InitPathKube
configFilePath = kubeDir + InitPathConfig

fmt.Printf(InitMessageCopyingCredentials, configFilePath, adminKubeConfigPath)

uid, err = strconv.Atoi(usr.Uid)
if err != nil {
return fmt.Errorf(InitErrorAtoiString, usr.Uid, err)
}

gid, err = strconv.Atoi(usr.Gid)
if err != nil {
return fmt.Errorf(InitErrorAtoiString, usr.Gid, err)
}

if err := os.MkdirAll(kubeDir, 0700); err != nil {
return fmt.Errorf(InitErrorCannotCreateDir, kubeDir, err)
}

// Chown doesn't work on Windows
if err := os.Chown(kubeDir, uid, gid); err != nil {
return fmt.Errorf(InitErrorCannotChown, kubeDir, err)
}

src, err = os.Open(adminKubeConfigPath)
if err != nil {
return fmt.Errorf(InitErrorCannotOpenFileForReading, adminKubeConfigPath, err)
}
defer src.Close()

dest, err = os.OpenFile(configFilePath, os.O_RDWR|os.O_CREATE, 0700)
if err != nil {
return fmt.Errorf(InitErrorCannotOpenFileForWriting, configFilePath, err)
}
defer dest.Close()

if _, err := io.Copy(dest, src); err != nil {
return fmt.Errorf(InitErrorCannotIoCopy, err)
}

if err := os.Chown(configFilePath, uid, gid); err != nil {
return fmt.Errorf(InitErrorCannotChown, configFilePath, err)
}

return nil
}
Loading

0 comments on commit f67a150

Please sign in to comment.