Make kubectl work inside a container in k8s

This commit is contained in:
Daniel Smith
2015-06-01 16:58:19 -07:00
parent e3b80db02c
commit 67f53d2eff
3 changed files with 43 additions and 1 deletions

View File

@@ -17,6 +17,7 @@ limitations under the License.
package clientcmd
import (
"fmt"
"io"
"os"
@@ -284,3 +285,32 @@ func (config DirectClientConfig) getCluster() clientcmdapi.Cluster {
return mergedClusterInfo
}
// inClusterClientConfig makes a config that will work from within a kubernetes cluster container environment.
type inClusterClientConfig struct{}
func (inClusterClientConfig) RawConfig() (clientcmdapi.Config, error) {
return clientcmdapi.Config{}, fmt.Errorf("inCluster environment config doesn't support multiple clusters")
}
func (inClusterClientConfig) ClientConfig() (*client.Config, error) {
return client.InClusterConfig()
}
func (inClusterClientConfig) Namespace() (string, error) {
// TODO: generic way to figure out what namespace you are running in?
// This way assumes you've set the POD_NAMESPACE environment variable
// using the downward API.
if ns := os.Getenv("POD_NAMESPACE"); ns != "" {
return ns, nil
}
return "default", nil
}
// Possible returns true if loading an inside-kubernetes-cluster is possible.
func (inClusterClientConfig) Possible() bool {
fi, err := os.Stat("/var/run/secrets/kubernetes.io/serviceaccount/token")
return os.Getenv("KUBERNETES_SERVICE_HOST") != "" &&
os.Getenv("KUBERNETES_SERVICE_PORT") != "" &&
err == nil && !fi.IsDir()
}

View File

@@ -45,6 +45,11 @@ func NewInteractiveDeferredLoadingClientConfig(loadingRules *ClientConfigLoading
}
func (config DeferredLoadingClientConfig) createClientConfig() (ClientConfig, error) {
// Are we running in a cluster? If so, use that.
icc := inClusterClientConfig{}
if icc.Possible() {
return icc, nil
}
mergedConfig, err := config.loadingRules.Load()
if err != nil {
return nil, err