metalstack cloud

Writing a Go client to communicate with the metalstack.cloud API

Generate an Access Token

First generate an access token as described here.

For this example you will need a token, that can access the cluster list method. Be sure to generate a token with the correct scope and store it somewhere safe.

Find out the Project ID

For some methods you will need to add the project ID to the request. The project ID is encoded within the access token, and can be retrieved by decoding it with jwt.

For the sake of simplicity, in this example you can just copy the project ID from the UI. For that, go to the metalstack.cloud dashboard and select the project you created the token for. Next to the heading, click on the copy icon to copy the project’s ID to the clipboard.

copy project id

Write the Code

With the following go code you can list all the clusters in your project using our API.

First, initialize the go project and get the required packages.

  go mod init your-example-project
  go get connectrpc.com/connect
  go get github.com/metal-stack-cloud/api/go/api/v1
  go get github.com/metal-stack-cloud/api/go/client

Create a file named main.go in the root of your project and paste the code below.

package main

import (
	"context"
	"fmt"
	"os"

	"connectrpc.com/connect"
	"github.com/metal-stack-cloud/api/go/api/v1"
	"github.com/metal-stack-cloud/api/go/client"
)

func main() {
	dialConfig := client.DialConfig{
		BaseURL:   "https://api.metalstack.cloud",
		Token:     "your-access-token", // add your personal access token here
		UserAgent: "metalstack-cloud-example",
	}

	mc := client.New(dialConfig)

	req := &apiv1.ClusterServiceListRequest{
		Project: "your-project-id", // add your project ID here
	}

	resp, err := mc.Apiv1().Cluster().List(context.Background(), connect.NewRequest(req))
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	for _, cluster := range resp.Msg.Clusters {
		fmt.Printf("cluster: %s | kubernetes version: %s\n", cluster.Name, cluster.Kubernetes.Version)
	}
}

Add your token and project ID at the marked positions and save the file.

Now, run go run main.go and you will see your running clusters printed to the terminal.