Skip to main content

Search the Dev Center

Search tutorials, templates, examples, and more.

Kubernetes Cluster on Azure

The Azure Kubernetes Cluster template scaffolds a Pulumi project that provisions a managed Azure Kubernetes Service (AKS) cluster inside a new Azure Virtual Network with three subnets. Worker nodes are deployed with private IP addresses for improved security and spread across multiple availability zones for resilience. The HCL version is simpler: it creates only a resource group and the cluster, which uses AKS’s default networking and doesn’t spread nodes across availability zones.

Architecture diagram of the Azure Kubernetes Cluster template Azure Azure Kubernetes Service Azure Virtual Network Managed endpoint KubernetesResources Worker Nodes

Before you begin#

For this walkthrough, you'll need:

Create a new project#

Create a new project from the template:

Terminal window
mkdir my-k8s-cluster; cd my-k8s-cluster
pulumi new kubernetes-azure-typescript

The pulumi new command walks you through creating and configuring the new project and stack. A stack is an instance of a project, and you can have many of them (dev, staging, prod), each with its own configuration settings. Depending on the language, you may also be asked for your preferred package manager or toolchain.

This template’s settings include:

KeyDescriptionDefault
azure-native:locationThe Azure location (region) in which to create the clusterwestus2
numWorkerNodesNumber of worker nodes in the cluster3
prefixForDnsDNS prefix for the clusterpulumi
kubernetesVersionKubernetes version to deploy in the cluster1.37
nodeVmSizeVM size to use for worker nodes in the clusterStandard_DS2_v2
mgmtGroupIdThe object ID (from az ad group list) of a group to make cluster admins—
sshPubKeyContents of the public key for SSH access to cluster nodes—
You can change values like these later with pulumi config set :
Terminal window
pulumi config set azure-native:location <value>
pulumi config set numWorkerNodes <value>
pulumi config set prefixForDns <value>
pulumi config set kubernetesVersion <value>
pulumi config set nodeVmSize <value>
pulumi config set mgmtGroupId <value>
pulumi config set sshPubKey <value>

For mgmtGroupId, pick a group you belong to, or kubectl won’t let you in later. This lists your groups with their IDs:

Terminal window
az ad user get-member-groups --id $(az ad signed-in-user show --query id --output tsv) --query "[].{Name:displayName, ObjectId:id}" --output table

For sshPubKey, paste your public key, such as the output of cat ~/.ssh/id_ed25519.pub or cat ~/.ssh/id_rsa.pub.

Review the code#

When setup completes, you’ll see a few files:

  • Pulumi.yaml contains the project name and the language it’s written in.
  • Pulumi.dev.yaml contains the dev stack’s settings, including the values you just entered.
  • index.ts contains the program code that declares your cloud resources.

Take a moment to open them up and have a look. Here’s what’s in index.ts:

index.ts
import * as pulumi from "@pulumi/pulumi";
import * as resources from "@pulumi/azure-native/resources";
import * as network from "@pulumi/azure-native/network";
import * as containerservice from "@pulumi/azure-native/containerservice";
// Grab some values from the Pulumi stack configuration (or use defaults)
const projCfg = new pulumi.Config();
const numWorkerNodes = projCfg.getNumber("numWorkerNodes") || 3;
const k8sVersion = projCfg.get("kubernetesVersion") || "1.37";
const prefixForDns = projCfg.get("prefixForDns") || "pulumi";
const nodeVmSize = projCfg.get("nodeVmSize") || "Standard_DS2_v2";
// The next two configuration values are required (no default can be provided)
const mgmtGroupId = projCfg.require("mgmtGroupId");
const sshPubKey = projCfg.require("sshPubKey");
// Create a new Azure Resource Group
const resourceGroup = new resources.ResourceGroup("resourceGroup", {});
// Create a new Azure Virtual Network
const virtualNetwork = new network.VirtualNetwork("virtualNetwork", {
addressSpace: {
addressPrefixes: ["10.0.0.0/16"],
},
resourceGroupName: resourceGroup.name,
});
// Create three subnets in the virtual network
const subnet1 = new network.Subnet("subnet1", {
addressPrefix: "10.0.0.0/22",
resourceGroupName: resourceGroup.name,
virtualNetworkName: virtualNetwork.name,
});
const subnet2 = new network.Subnet("subnet2", {
addressPrefix: "10.0.4.0/22",
resourceGroupName: resourceGroup.name,
virtualNetworkName: virtualNetwork.name,
});
const subnet3 = new network.Subnet("subnet3", {
addressPrefix: "10.0.8.0/22",
resourceGroupName: resourceGroup.name,
virtualNetworkName: virtualNetwork.name,
});
// Create an Azure Kubernetes Cluster
const managedCluster = new containerservice.ManagedCluster("managedCluster", {
aadProfile: {
enableAzureRBAC: true,
managed: true,
adminGroupObjectIDs: [mgmtGroupId],
},
addonProfiles: {},
// Use multiple agent/node pool profiles to distribute nodes across subnets
agentPoolProfiles: [{
availabilityZones: ["1","2","3"],
count: numWorkerNodes,
enableNodePublicIP: false,
mode: "System",
name: "systempool",
osType: "Linux",
osDiskSizeGB: 30,
type: "VirtualMachineScaleSets",
vmSize: nodeVmSize,
// Change next line for additional node pools to distribute across subnets
vnetSubnetID: subnet1.id,
}],
// Change authorizedIPRanges to limit access to API server
// Changing enablePrivateCluster requires alternate access to API server (VPN or similar)
apiServerAccessProfile: {
authorizedIPRanges: ["0.0.0.0/0"],
enablePrivateCluster: false,
},
dnsPrefix: prefixForDns,
enableRBAC: true,
identity: {
type: "SystemAssigned",
},
kubernetesVersion: k8sVersion,
linuxProfile: {
adminUsername: "azureuser",
ssh: {
publicKeys: [{
keyData: sshPubKey,
}],
},
},
networkProfile: {
networkPlugin: "azure",
networkPolicy: "azure",
serviceCidr: "10.96.0.0/16",
dnsServiceIP: "10.96.0.10",
},
resourceGroupName: resourceGroup.name,
});
// Build a user Kubeconfig
// This SHOULD NOT be used for an explicit provider
// This SHOULD be used for user logins to the cluster
const creds = containerservice.listManagedClusterUserCredentialsOutput({
resourceGroupName: resourceGroup.name,
resourceName: managedCluster.name,
});
const encoded = creds.kubeconfigs[0].value;
const decoded = encoded.apply(enc => Buffer.from(enc, "base64").toString());
// Build an admin Kubeconfig
// This SHOULD be used for an explicit provider
// This SHOULD NOT be used for user logins to the cluster
const adminCreds = containerservice.listManagedClusterAdminCredentialsOutput({
resourceGroupName: resourceGroup.name,
resourceName: managedCluster.name,
});
const adminEncoded = adminCreds.kubeconfigs[0].value;
const adminDecoded = adminEncoded.apply(enc => Buffer.from(enc, "base64").toString());
// Export some values for use elsewhere
export const rgName = resourceGroup.name;
export const networkName = virtualNetwork.name;
export const clusterName = managedCluster.name;
export const kubeconfig = decoded;
export const adminKubeconfig = pulumi.secret(adminDecoded)

Deploy the project#

Deploy with pulumi up. It starts with a preview of what it’s about to create and asks before it changes anything. Choose yes to deploy.

Terminal window
pulumi up

Pulumi adds a random suffix to most resource names, so the resource group resourceGroup becomes something like resourceGroup3f8a2c1d. This is autonaming. It lets you deploy the same program to more than one stack, and lets Pulumi create a replacement before it deletes the old resource, without names colliding.

When it finishes, Pulumi prints the stack’s outputs, values it only knows once the resources exist:

rgName

The name of the Azure Resource Group containing the Kubernetes cluster resources.

networkName

The name of the Azure Virtual Network used for worker nodes, apps, and workloads.

clusterName

The name of the AKS cluster.

kubeconfig

The cluster’s kubeconfig file, which you can use with kubectl to access and communicate with your cluster.

adminKubeconfig

An admin kubeconfig for the cluster, stored as a secret.

Read one any time with pulumi stack output <name>, or pass it to another command. The cluster signs you in with Microsoft Entra ID, so save the kubeconfig to a file, let kubelogin switch it to your Azure CLI login, and list the cluster’s nodes. If you don’t have kubelogin, install it with az aks install-cli, or with brew install Azure/kubelogin/kubelogin on macOS or winget install --id=Microsoft.Azure.Kubelogin -e on Windows:

Terminal window
pulumi stack output kubeconfig --show-secrets > kubeconfig
kubelogin convert-kubeconfig -l azurecli --kubeconfig kubeconfig
kubectl --kubeconfig kubeconfig get nodes

You should see three nodes with the status Ready.

Need help?

If pulumi up asks you to run az login, or says your sign-in has expired, sign in again:

Terminal window
az login

Still stuck? Let us know.

Customize the project#

Projects created with this template expose the following configuration settings:

numWorkerNodes

The number of nodes in your cluster. Defaults to 3.

kubernetesVersion

The version of Kubernetes used in your AKS cluster. Defaults to 1.37.

prefixForDns

The unique DNS prefix for your AKS cluster. Defaults to pulumi.

nodeVmSize

The VM instance type used to run your nodes. Defaults to Standard_DS2_v2.

All of these settings are optional and may be adjusted either by editing the stack configuration file directly (by default, Pulumi.dev.yaml) or by changing their values with pulumi config set.

For example, grow the cluster to five nodes:

Terminal window
pulumi config set numWorkerNodes 5
pulumi up

When it finishes, list the nodes again; there are five:

Terminal window
kubectl --kubeconfig kubeconfig get nodes

Cleaning up#

You can cleanly destroy the stack and all of its infrastructure with pulumi destroy:

Terminal window
pulumi destroy

Learn more#

Related

The infrastructure platform for humans and agents.