Support docker machine for kubeconfig.yaml
The kubeconfig.yaml generated by K3S uses local host as the host name by default. It won't work when running with docker machine. This patch detects if the docker environment is set up with docker machine. If it is, then replace the host name to the IP address of the docker machine.
This commit is contained in:
parent
df5cc1da84
commit
de6e845abd
@ -9,6 +9,7 @@ import (
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/docker/docker/api/types"
|
||||
"github.com/docker/docker/api/types/filters"
|
||||
@ -139,8 +140,23 @@ func createKubeConfigFile(cluster string) error {
|
||||
}
|
||||
defer kubeconfigfile.Close()
|
||||
|
||||
// write to file, skipping the first 512 bytes which contain file metadata and trimming any NULL characters
|
||||
_, err = kubeconfigfile.Write(bytes.Trim(readBytes[512:], "\x00"))
|
||||
// write to file, skipping the first 512 bytes which contain file metadata
|
||||
// and trimming any NULL characters
|
||||
trimBytes := bytes.Trim(readBytes[512:], "\x00")
|
||||
|
||||
// If running on a docker machine, replace localhost with
|
||||
// docker machine's IP
|
||||
dockerMachineIp, err := getDockerMachineIp()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if dockerMachineIp != "" {
|
||||
s := string(trimBytes)
|
||||
s = strings.Replace(s, "localhost", dockerMachineIp, 1)
|
||||
trimBytes = []byte(s)
|
||||
}
|
||||
_, err = kubeconfigfile.Write(trimBytes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ERROR: couldn't write to kubeconfig.yaml\n%+v", err)
|
||||
}
|
||||
|
||||
26
cli/docker-machine.go
Normal file
26
cli/docker-machine.go
Normal file
@ -0,0 +1,26 @@
|
||||
package run
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func getDockerMachineIp() (string, error) {
|
||||
machine := os.ExpandEnv("$DOCKER_MACHINE_NAME")
|
||||
|
||||
if machine == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
dockerMachinePath, err := exec.LookPath("docker-machine")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
out, err := exec.Command(dockerMachinePath, "ip").Output()
|
||||
|
||||
ipStr := strings.TrimSuffix(string(out), "\n")
|
||||
ipStr = strings.TrimSuffix(ipStr, "\r")
|
||||
return ipStr, err
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user