Skip to content

Getting started with cdk8s for Go

In this guide, we’ll walk you through the process of building a basic Kubernetes application using cdk8s for Go.

Prerequisites

  1. To install the cdk8s CLI, you need the Node Package Manager (npm) installed on your local machine.
  2. cdk8s for Go supports Go versions 1.16+. Check your Go version:
    go version
    

Set up an environment

Install the CLI

To initialize a cdk8s project and auto-generate Kubernetes manifests based on our code, we need the cdk8s CLI:

  1. Run the following command to install the CLI using npm. For more installation methods, see Install the cdk8s CLI.
    npm install -g cdk8s-cli
    

Create a project

Next, we’ll initialize a project to create the directory structure and install the necessary dependencies using the init command.

  1. In a terminal window, create a new directory:

    mkdir cdk8s-golang
    

  2. Next, run the following command inside the cdk8s-golang directory:

    cdk8s init go-app
    

  3. In your preferred code editor, open the main.go file.

    package main
    
    import (
        "github.com/aws/constructs-go/constructs/v10"
        "github.com/aws/jsii-runtime-go"
        "github.com/cdk8s-team/cdk8s-core-go/cdk8s/v2"
    )
    
    type MyChartProps struct {
        cdk8s.ChartProps
    }
    
    func NewMyChart(scope constructs.Construct, id string, props *MyChartProps) cdk8s.Chart {
        var cprops cdk8s.ChartProps
        if props != nil {
            cprops = props.ChartProps
        }
        chart := cdk8s.NewChart(scope, jsii.String(id), &cprops)
    
        // define resources here
    
        return chart
    }
    
    func main() {
        app := cdk8s.NewApp(nil)
        NewMyChart(app, "cdk8s-golang", nil)
        app.Synth()
    }
    

This sample shows the basic structure of a cdk8s application with the essential libraries: constructs and cdk8s. These libraries supply the foundational classes and methods required for working with cdk8s. It includes the following components:

  • A NewMyChart function that creates a specific instance of a Chart. It is responsible for initializing the Chart instance and registering the Kubernetes resources to it.
  • A main function acting as the primary entry point of the cdk8s application. It instantiates the App instance, which oversees the application’s lifecycle and resources.
  • The function NewMyChart is called by passing the app instance and a string identifier, “go”, as arguments. This action generates and registers the chart and all its resources to the app. Note that in this example, the “cdk8s-golang” string identifier is autogenerated based on the current directory name.
  • The Synth method is called on the app instance, which produces the required Kubernetes YAML manifest files based on the defined resources. Note that in this example, we haven’t defined any resources within the NewMyChart function, so running the “cdk8s synth” command in the CLI would generate a blank Kubernetes manifest.

Define Kubernetes resources

Now, let’s delve into defining Kubernetes resources for our application. In this example, we’ll outline a basic Kubernetes Deployment for a sample app. We’ll start by importing the imports directory and the k8s sub-directory, which houses all cdk8s Kubernetes classes and functions.

Copy the code sample

  1. Copy and paste the following code sample into the existing main.go file of your project.
package main

import (
    "example.com/cdk8s-golang/imports/k8s"
    "github.com/aws/constructs-go/constructs/v10"
    "github.com/aws/jsii-runtime-go"
    "github.com/cdk8s-team/cdk8s-core-go/cdk8s/v2"
)

func NewChart(scope constructs.Construct, id string, ns string, appLabel string) cdk8s.Chart {

    chart := cdk8s.NewChart(scope, jsii.String(id), &cdk8s.ChartProps{
        Namespace: jsii.String(ns),
    })

    labels := map[string]*string{
        "app": jsii.String(appLabel),
    }

    k8s.NewKubeDeployment(chart, jsii.String("deployment"), &k8s.KubeDeploymentProps{
        Spec: &k8s.DeploymentSpec{
            Replicas: jsii.Number(3),
            Selector: &k8s.LabelSelector{
                MatchLabels: &labels,
            },
            Template: &k8s.PodTemplateSpec{
                Metadata: &k8s.ObjectMeta{
                    Labels: &labels,
                },
                Spec: &k8s.PodSpec{
                    Containers: &[]*k8s.Container{{
                        Name:  jsii.String("app-container"),
                        Image: jsii.String("nginx:1.19.10"),
                        Ports: &[]*k8s.ContainerPort{{
                            ContainerPort: jsii.Number(80),
                        }},
                    }},
                },
            },
        },
    })

    return chart
}

func main() {
    app := cdk8s.NewApp(nil)

    NewChart(app, "getting-started", "default", "my-app")

    app.Synth()
}

A few things worth noting about this sample:

  • The NewChart function utilizes Go’s strong typing and interface-based design to construct a Kubernetes Deployment. This Deployment is set up with specific parameters like replica count, label selectors, and pod specifications. This method takes advantage of Go’s map data structures to dynamically assign the “app” key in label selectors and metadata labels, offering a straightforward and efficient way to configure essential details.

Generate Kubernetes manifests

After you have defined the Kubernetes resources for your application, you are ready to generate the Kubernetes manifest that will define your Deployment resource.

Run the synth command

  1. Open a terminal and navigate to your project directory.
  2. Run the synth command. This command generates a Kubernetes manifest file in the dist folder of your project directory. The manifest file contains all the resources you defined inside the MyChart class.
    cdk8s synth
    

View the manifest

  1. Open the dist/getting-started.k8s.yaml file. You should see a Kubernetes manifest similar to the following:
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: getting-started-deployment-c80c7257
      namespace: default
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: my-app
      template:
        metadata:
          labels:
            app: my-app
        spec:
          containers:
            - image: nginx:1.19.10
              name: app-container
              ports:
                - containerPort: 80
    

Conclusion

Throughout this guide, we introduced you to the cdk8s Go library and guided you through the process of creating a cdk8s Go application. We initiated a simple project and constructed a Kubernetes Deployment using cdk8s code. This included leveraging Go-specific programming language conventions to dynamically set the “app” key in “label” selectors and “metadata” labels for Kubernetes resources using Go’s versatile handling of map data structures.

Next up

  • To run a complete code sample, we recommend diving into the Kubernetes Deployment and Service using the cdk8s-core sample application.