K3s¶
Since v0.21.0
Introduction¶
The Testcontainers module for K3s.
Adding this module to your project dependencies¶
Please run the following command to add the K3s module to your Go dependencies:
go get github.com/testcontainers/testcontainers-go/modules/k3s
Usage example¶
package k3s_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kwait "k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/k3s"
"github.com/testcontainers/testcontainers-go/wait"
)
func Test_LoadImages(t *testing.T) {
// Give up to three minutes to run this test
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(3*time.Minute))
defer cancel()
k3sContainer, err := k3s.Run(ctx, "rancher/k3s:v1.27.1-k3s1")
testcontainers.CleanupContainer(t, k3sContainer)
require.NoError(t, err)
kubeConfigYaml, err := k3sContainer.GetKubeConfig(ctx)
require.NoError(t, err)
restcfg, err := clientcmd.RESTConfigFromKubeConfig(kubeConfigYaml)
require.NoError(t, err)
k8s, err := kubernetes.NewForConfig(restcfg)
require.NoError(t, err)
provider, err := testcontainers.ProviderDocker.GetProvider()
require.NoError(t, err)
// ensure nginx image is available locally
err = provider.PullImage(ctx, "nginx")
require.NoError(t, err)
t.Run("Test load image not available", func(t *testing.T) {
err := k3sContainer.LoadImages(ctx, "fake.registry/fake:non-existing")
require.Error(t, err)
})
t.Run("Test load image in cluster", func(t *testing.T) {
err := k3sContainer.LoadImages(ctx, "nginx")
require.NoError(t, err)
pod := &corev1.Pod{
TypeMeta: metav1.TypeMeta{
Kind: "Pod",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-pod",
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "nginx",
Image: "nginx",
ImagePullPolicy: corev1.PullNever, // use image only if already present
},
},
},
}
_, err = k8s.CoreV1().Pods("default").Create(ctx, pod, metav1.CreateOptions{})
require.NoError(t, err)
err = kwait.PollUntilContextCancel(ctx, time.Second, true, func(ctx context.Context) (bool, error) {
state, err := getTestPodState(ctx, k8s)
if err != nil {
return false, err
}
if state.Terminated != nil {
return false, fmt.Errorf("pod terminated: %v", state.Terminated)
}
return state.Running != nil, nil
})
require.NoError(t, err)
state, err := getTestPodState(ctx, k8s)
require.NoError(t, err)
require.NotNil(t, state.Running)
})
}
func getTestPodState(ctx context.Context, k8s *kubernetes.Clientset) (corev1.ContainerState, error) {
var pod *corev1.Pod
var err error
pod, err = k8s.CoreV1().Pods("default").Get(ctx, "test-pod", metav1.GetOptions{})
if err != nil || len(pod.Status.ContainerStatuses) == 0 {
return corev1.ContainerState{}, err
}
return pod.Status.ContainerStatuses[0].State, nil
}
func Test_APIServerReady(t *testing.T) {
ctx := context.Background()
k3sContainer, err := k3s.Run(ctx, "rancher/k3s:v1.27.1-k3s1")
testcontainers.CleanupContainer(t, k3sContainer)
require.NoError(t, err)
kubeConfigYaml, err := k3sContainer.GetKubeConfig(ctx)
require.NoError(t, err)
restcfg, err := clientcmd.RESTConfigFromKubeConfig(kubeConfigYaml)
require.NoError(t, err)
k8s, err := kubernetes.NewForConfig(restcfg)
require.NoError(t, err)
pod := &corev1.Pod{
TypeMeta: metav1.TypeMeta{
Kind: "Pod",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-pod",
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "nginx",
Image: "nginx",
},
},
},
}
_, err = k8s.CoreV1().Pods("default").Create(context.Background(), pod, metav1.CreateOptions{})
require.NoError(t, err)
}
func Test_WithManifestOption(t *testing.T) {
ctx := context.Background()
k3sContainer, err := k3s.Run(ctx,
"rancher/k3s:v1.27.1-k3s1",
k3s.WithManifest("nginx-manifest.yaml"),
testcontainers.WithAdditionalWaitStrategy(wait.ForExec([]string{"kubectl", "wait", "pod", "nginx", "--for=condition=Ready"})),
)
testcontainers.CleanupContainer(t, k3sContainer)
require.NoError(t, err)
}
Module Reference¶
Run function¶
- Since v0.32.0
Info
The RunContainer(ctx, opts...) function is deprecated and will be removed in the next major release of Testcontainers for Go.
The K3s module exposes one entrypoint function to create the K3s container, and this function receives three parameters:
func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*K3sContainer, error)
context.Context, the Go context.string, the Docker image to use.testcontainers.ContainerCustomizer, a variadic argument for passing options.
Container Ports¶
These are the ports used by the K3s container:
defaultKubeSecurePort = "6443/tcp"
defaultRancherWebhookPort = "8443/tcp"
Image¶
Use the second argument in the Run function to set a valid Docker image.
In example: Run(context.Background(), "rancher/k3s:v1.27.1-k3s1").
Container Options¶
When starting the K3s container, you can pass options in a variadic way to configure it.
WithManifest¶
- Since v0.29.0
The WithManifest option loads a manifest obtained from a local file into the cluster. K3s applies it automatically during the startup process
func WithManifest(manifestPath string) testcontainers.CustomizeRequestOption
Example:
WithManifest("nginx-manifest.yaml")
The following options are exposed by the testcontainers package.
Basic Options¶
WithExposedPortsSince v0.37.0WithEnvSince v0.29.0WithWaitStrategySince v0.20.0WithAdditionalWaitStrategySince v0.38.0WithWaitStrategyAndDeadlineSince v0.20.0WithAdditionalWaitStrategyAndDeadlineSince v0.38.0WithEntrypointSince v0.37.0WithEntrypointArgsSince v0.37.0WithCmdSince v0.37.0WithCmdArgsSince v0.37.0WithLabelsSince v0.37.0
Lifecycle Options¶
WithLifecycleHooksSince v0.38.0WithAdditionalLifecycleHooksSince v0.38.0WithStartupCommandSince v0.25.0WithAfterReadyCommandSince v0.28.0
Files & Mounts Options¶
WithFilesSince v0.37.0WithMountsSince v0.37.0WithTmpfsSince v0.37.0WithImageMountSince v0.37.0
Build Options¶
WithDockerfileSince v0.37.0
Logging Options¶
WithLogConsumersSince v0.28.0WithLogConsumerConfigSince v0.38.0WithLoggerSince v0.29.0
Image Options¶
WithAlwaysPullSince v0.38.0WithImageSubstitutorsSince v0.26.0WithImagePlatformSince v0.38.0
Networking Options¶
WithNetworkSince v0.27.0WithNetworkByNameSince v0.38.0WithBridgeNetworkSince v0.38.0WithNewNetworkSince v0.27.0
Advanced Options¶
WithHostPortAccessSince v0.31.0WithConfigModifierSince v0.20.0WithHostConfigModifierSince v0.20.0WithEndpointSettingsModifierSince v0.20.0CustomizeRequestSince v0.20.0WithNameSince v0.38.0WithNoStartSince v0.38.0WithProviderNot available until the next release main
Experimental Options¶
WithReuseByNameSince v0.37.0
Container Methods¶
The K3s container exposes the following methods:
GetKubeConfig¶
- Since v0.21.0
The GetKubeConfig method returns the K3s cluster's kubeconfig, including the server URL, to be used for connecting
to the Kubernetes Rest Client API using a Kubernetes client. It'll be returned in the format of []bytes.
package k3s_test
import (
"context"
"fmt"
"log"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/k3s"
)
func ExampleRun() {
// runK3sContainer {
ctx := context.Background()
k3sContainer, err := k3s.Run(ctx, "rancher/k3s:v1.27.1-k3s1")
defer func() {
if err := testcontainers.TerminateContainer(k3sContainer); err != nil {
log.Printf("failed to terminate container: %s", err)
}
}()
if err != nil {
log.Printf("failed to start container: %s", err)
return
}
// }
state, err := k3sContainer.State(ctx)
if err != nil {
log.Printf("failed to get container state: %s", err)
return
}
fmt.Println(state.Running)
kubeConfigYaml, err := k3sContainer.GetKubeConfig(ctx)
if err != nil {
log.Printf("failed to get kubeconfig: %s", err)
return
}
restcfg, err := clientcmd.RESTConfigFromKubeConfig(kubeConfigYaml)
if err != nil {
log.Printf("failed to create rest config: %s", err)
return
}
k8s, err := kubernetes.NewForConfig(restcfg)
if err != nil {
log.Printf("failed to create k8s client: %s", err)
return
}
nodes, err := k8s.CoreV1().Nodes().List(ctx, v1.ListOptions{})
if err != nil {
log.Printf("failed to list nodes: %s", err)
return
}
fmt.Println(len(nodes.Items))
// Output:
// true
// 1
}
LoadImages¶
- Since v0.25.0
The LoadImages method loads a list of images into the kubernetes cluster and makes them available to pods.
This is useful for testing images generated locally without having to push them to a public docker registry or having to configure k3s to use a private registry.
The images must be already present in the node running the test. DockerProvider offers a method for pulling images, which can be used from the test code to ensure the image is present locally before loading them to the cluster.