diff --git a/modules/k3s/k3s.go b/modules/k3s/k3s.go index 0422069306..30f7c348d5 100644 --- a/modules/k3s/k3s.go +++ b/modules/k3s/k3s.go @@ -28,6 +28,11 @@ type K3sContainer struct { // RunContainer creates an instance of the K3s container type func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*K3sContainer, error) { + host, err := getContainerHost(ctx, opts...) + if err != nil { + return nil, err + } + req := testcontainers.ContainerRequest{ Image: "docker.io/rancher/k3s:v1.27.1-k3s1", ExposedPorts: []string{ @@ -47,7 +52,7 @@ func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomize Cmd: []string{ "server", "--disable=traefik", - "--tls-san=localhost", + "--tls-san=" + host, // Host which will be used to access the Kubernetes server from tests. }, Env: map[string]string{ "K3S_KUBECONFIG_MODE": "644", @@ -72,6 +77,31 @@ func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomize return &K3sContainer{Container: container}, nil } +func getContainerHost(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (string, error) { + // Use a dummy request to get the provider from options. + var req testcontainers.GenericContainerRequest + for _, opt := range opts { + opt.Customize(&req) + } + + logging := req.Logger + if logging == nil { + logging = testcontainers.Logger + } + p, err := req.ProviderType.GetProvider(testcontainers.WithLogger(logging)) + if err != nil { + return "", err + } + + switch p := p.(type) { + case *testcontainers.DockerProvider: + return p.DaemonHost(ctx) + } + + // Fall back to localhost. + return "localhost", nil +} + // GetKubeConfig returns the modified kubeconfig with server url func (c *K3sContainer) GetKubeConfig(ctx context.Context) ([]byte, error) { hostIP, err := c.Host(ctx)