Skip to content

Commit

Permalink
k3s: use random port for cluster API
Browse files Browse the repository at this point in the history
Signed-off-by: Abiola Ibrahim <git@abiosoft.com>
  • Loading branch information
abiosoft committed Jul 31, 2024
1 parent 4b14e8a commit f271238
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
30 changes: 29 additions & 1 deletion environment/container/kubernetes/k3s.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package kubernetes

import (
"fmt"
"strconv"
"strings"

"github.com/abiosoft/colima/cli"
Expand All @@ -11,10 +12,13 @@ import (
"github.com/abiosoft/colima/environment/container/containerd"
"github.com/abiosoft/colima/environment/container/docker"
"github.com/abiosoft/colima/environment/vm/lima/limautil"
"github.com/abiosoft/colima/util"
"github.com/abiosoft/colima/util/downloader"
"github.com/sirupsen/logrus"
)

const listenPortKey = "k3s_listen_port"

func installK3s(host environment.HostActions,
guest environment.GuestActions,
a *cli.ActiveCommandChain,
Expand Down Expand Up @@ -143,7 +147,6 @@ func installK3sCluster(
if ipAddress == "127.0.0.1" {
args = append(args, "--flannel-iface", "eth0")
} else {
args = append(args, "--bind-address", "0.0.0.0")
args = append(args, "--advertise-address", ipAddress)
args = append(args, "--flannel-iface", vmnet.NetInterface)
}
Expand All @@ -154,7 +157,32 @@ func installK3sCluster(
case containerd.Name:
args = append(args, "--container-runtime-endpoint", "unix:///run/containerd/containerd.sock")
}

a.Add(func() error {
port, err := getPortNumber(guest)
if err != nil {
return err
}
args = append(args, "--https-listen-port", strconv.Itoa(port))
return nil
})

a.Add(func() error {
return guest.Run("sh", "-c", "INSTALL_K3S_SKIP_DOWNLOAD=true INSTALL_K3S_SKIP_ENABLE=true k3s-install.sh "+strings.Join(args, " "))
})
}

// getPortNumber retrieves the previously set port number.
// If missing, an available random port is set and return.
func getPortNumber(guest environment.GuestActions) (int, error) {
if port, err := strconv.Atoi(guest.Get(listenPortKey)); err == nil && port > 0 {
return port, nil
}

port := util.RandomAvailablePort()
if err := guest.Set(listenPortKey, strconv.Itoa(port)); err != nil {
return 0, err
}

return port, nil
}
5 changes: 5 additions & 0 deletions environment/container/kubernetes/kubeconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ func (c kubernetesRuntime) provisionKubeconfig(ctx context.Context) error {
// replace name
kubeconfig = strings.ReplaceAll(kubeconfig, ": default", ": "+profile)

// replace IP
if ip != "" && ip != "127.0.0.1" {
kubeconfig = strings.ReplaceAll(kubeconfig, "https://127.0.0.1:", "https://"+ip+":")
}

// save on the host
return c.host.Write(tmpkubeconfFile, []byte(kubeconfig))
})
Expand Down

0 comments on commit f271238

Please sign in to comment.