Skip to content

Automation ​

KKP Rest-API ​

The ESC Kubernetes Service provides a fully featured API that can be used to manage all aspects of a Kubernetes Service environment.

Swagger documentation

The Swagger documentation of the Rest-API can be accessed by clicking on the "KKP API" link in the project sidebar on the left side in the Kubernetes Service UI: Project sidebar

It is also available on the official Kubermatic Kubernetes Platform documentation, under https://docs.kubermatic.com/kubermatic/v2.30/references/rest-api-reference/ (please make sure to select the appropriate version matching your environment)

There are various examples available as part of the KKP Community Components - Cluster Management by API repository on GitHub. These can provide a good starting point.

Service Accounts ​

To authenticate against the KKP REST API programmatically (e.g. from CI/CD pipelines, Terraform, or scripts), you need a Service Account with an associated token. Service accounts are scoped to a project and can be assigned different roles.

For step-by-step instructions on creating service accounts and tokens, see Projects — Create a Service Account and Tokens.

Roles ​

RolePermissionsTypical Use Case
Project ManagerManage project members, service accounts, and project settings. Cannot interact with clusters.Administrative automation (user provisioning, access management)
EditorCreate, update, and delete clusters, machine deployments, and resources within the project. Cannot manage project members or settings.CI/CD pipelines, Terraform/OpenTofu cluster provisioning, day-2 automation
ViewerRead-only access to all clusters and resources in the project.Monitoring, dashboards, auditing scripts

💡 Which role for cluster automation?

For creating and managing clusters via the API or Terraform, use the Editor role. This is the minimum required role for the REST-API examples below.

REST-API Examples ​

This section provides a complete, step-by-step example for creating a cluster via the KKP REST API using curl and jq. All required parameters (Kubernetes versions, storage classes, subnets, OS images, etc.) are discovered dynamically from the API.

Prerequisites ​

  • curl and jq installed
  • A valid bearer token (obtained via a KKP service account or Dex login)
  • The KKP domain URL of your Kubernetes Service environment

Environment Variables ​

Set the following variables before running the examples. Adjust values to match your environment:

bash
KKP_DOMAIN="<your-kkp-domain>"   # e.g. ab1c2defgh.ks.private.cloud.swisscom.ch
TOKEN="<your-bearer-token>"
PROJECT="<your-project-id>"
REGION="central"                  # e.g. central, east, west
CLUSTER_NAME="my-cluster"

# Derived from region
DATACENTER="swisscom-${REGION}"
PRESET="swisscom-${REGION}"

💡 Service Account Token

A service account token can be created as described in the Service Accounts section above. Use a token with Editor or Project Manager privileges for cluster creation.

Step 1: Discover the Seed Name ​

API Reference: GET /api/v1/seed

bash
SEED=$(curl -sk "https://${KKP_DOMAIN}/api/v1/seed" \
  -H "Authorization: Bearer ${TOKEN}" | jq -r '.[0]')

echo "Seed: ${SEED}"

Step 2: Get Available Kubernetes Versions ​

API Reference: GET /api/v2/providers/kubevirt/versions

bash
VERSIONS=$(curl -sk "https://${KKP_DOMAIN}/api/v2/providers/kubevirt/versions" \
  -H "Authorization: Bearer ${TOKEN}")

# Pick the latest version
K8S_VERSION=$(echo "$VERSIONS" | jq -r '[.[].version] | sort_by(split(".") | map(tonumber)) | last')

echo "Kubernetes version: ${K8S_VERSION}"

Step 3: Get the Default Cluster Spec ​

API Reference: GET /api/v2/providers/{provider}/dc/{dc}/defaultcluster

The default cluster spec provides sensible defaults for cluster networking, CNI, and expose strategy:

bash
DEFAULT_CLUSTER=$(curl -sk "https://${KKP_DOMAIN}/api/v2/providers/kubevirt/dc/${DATACENTER}/defaultcluster" \
  -H "Authorization: Bearer ${TOKEN}")

# Extract networking defaults (keep only IPv4 CIDR blocks)
CLUSTER_NETWORK=$(echo "$DEFAULT_CLUSTER" | jq '.spec.clusterNetwork
  | .services.cidrBlocks = [.services.cidrBlocks[0]]
  | .pods.cidrBlocks = [.pods.cidrBlocks[0]]')
CNI_PLUGIN=$(echo "$DEFAULT_CLUSTER" | jq '.spec.cniPlugin')
EXPOSE_STRATEGY=$(echo "$DEFAULT_CLUSTER" | jq -r '.spec.exposeStrategy')

echo "Expose strategy: ${EXPOSE_STRATEGY}"
echo "CNI: $(echo $CNI_PLUGIN | jq -r '.type')"

💡 Why use the default cluster spec?

Fetching the default spec from the API ensures your cluster uses the correct networking configuration for the datacenter. This avoids hardcoding values that may change between environments or versions.

Step 4: Get Available Storage Classes ​

API Reference: GET /api/v2/projects/{project}/providers/kubevirt/storageclasses

bash
STORAGE_CLASSES=$(curl -sk "https://${KKP_DOMAIN}/api/v2/projects/${PROJECT}/providers/kubevirt/storageclasses" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "credential: ${PRESET}" \
  -H "datacentername: ${DATACENTER}")

# Pick the first storage class
STORAGE_CLASS=$(echo "$STORAGE_CLASSES" | jq -r '.[0].name')

echo "Storage class: ${STORAGE_CLASS}"

Step 5: Get Available Subnets ​

API Reference: GET /api/v2/projects/{project}/providers/kubevirt/subnets

bash
SUBNETS=$(curl -sk "https://${KKP_DOMAIN}/api/v2/projects/${PROJECT}/providers/kubevirt/subnets" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "credential: ${PRESET}" \
  -H "datacentername: ${DATACENTER}")

# Pick the first subnet
SUBNET=$(echo "$SUBNETS" | jq -r '.[0].name')

echo "Subnet: ${SUBNET}"

Step 6: Get Available OS Images ​

API Reference: GET /api/v2/providers/kubevirt/dc/{dc}/images

bash
IMAGES=$(curl -sk "https://${KKP_DOMAIN}/api/v2/providers/kubevirt/dc/${DATACENTER}/images" \
  -H "Authorization: Bearer ${TOKEN}")

# Get the latest Ubuntu image
OS_IMAGE=$(echo "$IMAGES" | jq -r '.standard.operatingSystems.ubuntu | to_entries | sort_by(.key) | last | .value')

echo "OS image: ${OS_IMAGE}"

Step 7: Get the Operating System Profile ​

API Reference: GET /api/v2/seeds/{seed}/operatingsystemprofiles

bash
OS_PROFILES=$(curl -sk "https://${KKP_DOMAIN}/api/v2/seeds/${SEED}/operatingsystemprofiles" \
  -H "Authorization: Bearer ${TOKEN}")

# Find the Ubuntu OSP that supports kubevirt (pick latest version)
OSP_NAME=$(echo "$OS_PROFILES" | jq -r '
  [.[] | select(.operatingSystem == "ubuntu" and (.supportedCloudProviders | index("kubevirt")))]
  | sort_by(.osVersion) | last | .name')

echo "OSP: ${OSP_NAME}"

Step 8: Get the SSH Key ​

API Reference: GET /api/v1/projects/{project}/sshkeys

bash
SSH_KEYS=$(curl -sk "https://${KKP_DOMAIN}/api/v1/projects/${PROJECT}/sshkeys" \
  -H "Authorization: Bearer ${TOKEN}")

SSH_KEY_ID=$(echo "$SSH_KEYS" | jq -r '.[0].id')

echo "SSH key: ${SSH_KEY_ID}"

⚠️ SSH Key

If no SSH key exists in the project, you must create one before creating the cluster. You can create one via the KKP Dashboard or via the API:

bash
curl -sk -X POST "https://${KKP_DOMAIN}/api/v1/projects/${PROJECT}/sshkeys" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{"name": "my-key", "spec": {"publicKey": "ssh-ed25519 AAAA..."}}'

Step 9: Create the Cluster ​

API Reference: POST /api/v2/projects/{project}/clusters

This request creates the cluster together with an initial machine deployment (node pool):

bash
CLUSTER_BODY=$(cat <<EOF
{
  "cluster": {
    "name": "${CLUSTER_NAME}",
    "labels": {},
    "spec": {
      "cloud": {
        "kubevirt": {},
        "dc": "${DATACENTER}"
      },
      "version": "${K8S_VERSION}",
      "auditLogging": {
        "enabled": true
      },
      "kubernetesDashboard": {
        "enabled": true
      },
      "kubelb": {
        "enabled": true,
        "useLoadBalancerClass": false,
        "enableGatewayAPI": true
      },
      "disableCsiDriver": false,
      "mla": {},
      "enableUserSSHKeyAgent": true,
      "exposeStrategy": "${EXPOSE_STRATEGY}",
      "containerRuntime": "containerd",
      "clusterNetwork": ${CLUSTER_NETWORK},
      "cniPlugin": ${CNI_PLUGIN},
      "oidc": {},
      "admissionPlugins": []
    },
    "credential": "${PRESET}"
  },
  "nodeDeployment": {
    "name": "${CLUSTER_NAME}-workers",
    "annotations": {
      "k8c.io/operating-system-profile": "${OSP_NAME}"
    },
    "spec": {
      "template": {
        "cloud": {
          "kubevirt": {
            "cpus": "2",
            "memory": "4096M",
            "primaryDiskStorageClassName": "${STORAGE_CLASS}",
            "primaryDiskSize": "20G",
            "subnet": "${SUBNET}",
            "primaryDiskOSImage": "${OS_IMAGE}"
          }
        },
        "operatingSystem": {
          "ubuntu": {}
        }
      },
      "replicas": 1,
      "dynamicConfig": false
    }
  },
  "applications": []
}
EOF
)

CLUSTER_RESPONSE=$(curl -sk -X POST "https://${KKP_DOMAIN}/api/v2/projects/${PROJECT}/clusters" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "${CLUSTER_BODY}")

CLUSTER_ID=$(echo "$CLUSTER_RESPONSE" | jq -r '.id')

echo "Cluster created: ${CLUSTER_ID}"

Step 10: Assign the SSH Key ​

API Reference: PUT /api/v2/projects/{project}/clusters/{cluster}/sshkeys/{key}

bash
curl -sk -X PUT "https://${KKP_DOMAIN}/api/v2/projects/${PROJECT}/clusters/${CLUSTER_ID}/sshkeys/${SSH_KEY_ID}" \
  -H "Authorization: Bearer ${TOKEN}"

echo "SSH key assigned"

Step 11: Wait for Cluster Health ​

API Reference: GET /api/v2/projects/{project}/clusters/{cluster}/health

Poll the health endpoint until all control plane components are ready:

bash
echo "Waiting for cluster to become healthy..."

while true; do
  HEALTH=$(curl -sk "https://${KKP_DOMAIN}/api/v2/projects/${PROJECT}/clusters/${CLUSTER_ID}/health" \
    -H "Authorization: Bearer ${TOKEN}")

  APISERVER=$(echo "$HEALTH" | jq -r '.apiserver')
  ETCD=$(echo "$HEALTH" | jq -r '.etcd')
  CONTROLLER=$(echo "$HEALTH" | jq -r '.controller')
  MACHINE_CTRL=$(echo "$HEALTH" | jq -r '.machineController')

  echo "  apiserver=${APISERVER} etcd=${ETCD} controller=${CONTROLLER} machineController=${MACHINE_CTRL}"

  if [ "$APISERVER" = "HealthStatusUp" ] && \
     [ "$ETCD" = "HealthStatusUp" ] && \
     [ "$CONTROLLER" = "HealthStatusUp" ] && \
     [ "$MACHINE_CTRL" = "HealthStatusUp" ]; then
    echo "Cluster is healthy!"
    break
  fi

  sleep 15
done

Step 12: Download Kubeconfig ​

API Reference: GET /api/v2/projects/{project}/clusters/{cluster}/kubeconfig

bash
curl -sk "https://${KKP_DOMAIN}/api/v2/projects/${PROJECT}/clusters/${CLUSTER_ID}/kubeconfig" \
  -H "Authorization: Bearer ${TOKEN}" > kubeconfig-${CLUSTER_NAME}.yaml

echo "Kubeconfig saved to kubeconfig-${CLUSTER_NAME}.yaml"

Adding a Machine Deployment to an Existing Cluster ​

API Reference: POST /api/v2/projects/{project}/clusters/{cluster}/machinedeployments

To add an additional node pool to an already running cluster:

bash
curl -sk -X POST "https://${KKP_DOMAIN}/api/v2/projects/${PROJECT}/clusters/${CLUSTER_ID}/machinedeployments" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
  "name": "additional-workers",
  "annotations": {
    "k8c.io/operating-system-profile": "'"${OSP_NAME}"'"
  },
  "spec": {
    "replicas": 2,
    "dynamicConfig": false,
    "template": {
      "cloud": {
        "kubevirt": {
          "cpus": "4",
          "memory": "8192M",
          "primaryDiskOSImage": "'"${OS_IMAGE}"'",
          "primaryDiskStorageClassName": "'"${STORAGE_CLASS}"'",
          "primaryDiskSize": "50G",
          "subnet": "'"${SUBNET}"'"
        }
      },
      "operatingSystem": {
        "ubuntu": {}
      }
    }
  }
}'

Deleting a Cluster ​

API Reference: DELETE /api/v2/projects/{project}/clusters/{cluster}

bash
curl -sk -X DELETE "https://${KKP_DOMAIN}/api/v2/projects/${PROJECT}/clusters/${CLUSTER_ID}" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "deletevolumes: true" \
  -H "deleteloadbalancers: true"

echo "Cluster ${CLUSTER_ID} deletion initiated"

⚠️ Cleanup

Setting deletevolumes: true and deleteloadbalancers: true ensures that persistent volumes and load balancers provisioned by the cluster are cleaned up. Omitting these headers will leave those resources behind.