Skip to main content

Search the Dev Center

Search tutorials, templates, examples, and more.

Kubernetes Cluster on Google Cloud

The Google Cloud Kubernetes Cluster template scaffolds a Pulumi project that provisions a managed Google Kubernetes Engine (GKE) cluster and a node pool inside a new VPC network with a subnet. Worker nodes are deployed with private IP addresses for improved security.

Architecture diagram of the Google Cloud Kubernetes Cluster template Google Cloud Compute Network (VPC) GKE Cluster VPC Subnet GKE API Endpoint Node Pool

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-gcp-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
gcp:projectThe Google Cloud project to deploy into—
gcp:regionThe Google Cloud region to deploy intous-central1
nodesPerZoneThe desired number of nodes PER ZONE in the nodepool1
You can change values like these later with pulumi config set :
Terminal window
pulumi config set gcp:project <value>
pulumi config set gcp:region <value>
pulumi config set nodesPerZone <value>

For gcp:project, enter the ID of an existing Google Cloud project. gcloud config get-value project prints the one gcloud is using. Press Enter at the others to keep the defaults.

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 gcp from "@pulumi/gcp";
// Get some provider-namespaced configuration values
const providerCfg = new pulumi.Config("gcp");
const gcpProject = providerCfg.require("project");
const gcpRegion = providerCfg.get("region") || "us-central1";
// Get some other configuration values or use defaults
const cfg = new pulumi.Config();
const nodesPerZone = cfg.getNumber("nodesPerZone") || 1;
// Create a new network
const gkeNetwork = new gcp.compute.Network("gke-network", {
autoCreateSubnetworks: false,
description: "A virtual network for your GKE cluster(s)",
});
// Create a new subnet in the network created above
const gkeSubnet = new gcp.compute.Subnetwork("gke-subnet", {
ipCidrRange: "10.128.0.0/12",
network: gkeNetwork.id,
privateIpGoogleAccess: true,
});
// Create a new GKE cluster
const gkeCluster = new gcp.container.Cluster("gke-cluster", {
addonsConfig: {
dnsCacheConfig: {
enabled: true,
},
},
binaryAuthorization: {
evaluationMode: "PROJECT_SINGLETON_POLICY_ENFORCE",
},
datapathProvider: "ADVANCED_DATAPATH",
deletionProtection: false,
description: "A GKE cluster",
initialNodeCount: 1,
ipAllocationPolicy: {
clusterIpv4CidrBlock: "/14",
servicesIpv4CidrBlock: "/20",
},
location: gcpRegion,
masterAuthorizedNetworksConfig: {
cidrBlocks: [{
cidrBlock: "0.0.0.0/0",
displayName: "All networks",
}],
},
network: gkeNetwork.name,
networkingMode: "VPC_NATIVE",
privateClusterConfig: {
enablePrivateNodes: true,
enablePrivateEndpoint: false,
masterIpv4CidrBlock: "10.100.0.0/28",
},
removeDefaultNodePool: true,
releaseChannel: {
channel: "STABLE",
},
subnetwork: gkeSubnet.name,
workloadIdentityConfig: {
workloadPool: `${gcpProject}.svc.id.goog`,
},
});
// Create a service account for the node pool
const gkeNodepoolSa = new gcp.serviceaccount.Account("gke-nodepool-sa", {
accountId: pulumi.interpolate `${gkeCluster.name}-np-1-sa`,
displayName: "Nodepool 1 Service Account",
});
// Create a nodepool for the GKE cluster
const gkeNodepool = new gcp.container.NodePool("gke-nodepool", {
cluster: gkeCluster.id,
nodeCount: nodesPerZone,
nodeConfig: {
oauthScopes: ["https://www.googleapis.com/auth/cloud-platform"],
serviceAccount: gkeNodepoolSa.email,
},
});
// Build a Kubeconfig for accessing the cluster
const clusterKubeconfig = pulumi.interpolate `apiVersion: v1
clusters:
- cluster:
certificate-authority-data: ${gkeCluster.masterAuth.clusterCaCertificate}
server: https://${gkeCluster.endpoint}
name: ${gkeCluster.name}
contexts:
- context:
cluster: ${gkeCluster.name}
user: ${gkeCluster.name}
name: ${gkeCluster.name}
current-context: ${gkeCluster.name}
kind: Config
preferences: {}
users:
- name: ${gkeCluster.name}
user:
exec:
apiVersion: client.authentication.k8s.io/v1beta1
command: gke-gcloud-auth-plugin
installHint: Install gke-gcloud-auth-plugin for use with kubectl by following
https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
provideClusterInfo: true
`;
// Export some values for use elsewhere
export const networkName = gkeNetwork.name;
export const networkId = gkeNetwork.id;
export const clusterName = gkeCluster.name;
export const clusterId = gkeCluster.id;
export const kubeconfig = clusterKubeconfig;

Deploy the project#

Before the first deploy, turn on the Kubernetes Engine API in your project:

Terminal window
gcloud services enable container.googleapis.com --project $(pulumi config get gcp:project)

Then 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. A GKE cluster takes 10 to 15 minutes to create, so expect pulumi up to run that long.

Terminal window
pulumi up

Pulumi adds a random suffix to most resource names, so gke-cluster becomes something like gke-cluster-4f8a2c1. 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:

networkName

The name of the VPC network containing the Kubernetes cluster resources.

networkId

The unique ID of the VPC network containing the Kubernetes cluster resources.

clusterName

The name of the GKE cluster.

clusterId

The unique ID of the GKE cluster.

kubeconfig

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

Read one any time with pulumi stack output <name>, or pass it to another command. The kubeconfig logs in through gcloud’s gke-gcloud-auth-plugin, which uses the gcloud CLI’s own sign-in. So install the plugin if you don’t have it and sign in the CLI, then save the kubeconfig to a file and list the cluster’s nodes:

Terminal window
gcloud components install gke-gcloud-auth-plugin
gcloud auth login
pulumi stack output kubeconfig --show-secrets > kubeconfig
kubectl --kubeconfig kubeconfig get nodes

If gcloud components install says the component manager is disabled, your gcloud CLI came from a Linux package manager. Install the plugin as a package instead: sudo apt-get install google-cloud-cli-gke-gcloud-auth-plugin, or sudo dnf install google-cloud-cli-gke-gcloud-auth-plugin.

GKE spreads the node pool across three of the region’s zones, so you should see three nodes with the status Ready.

Need help?

If pulumi up reports failed to load application credentials, sign in again:

Terminal window
gcloud auth application-default login

Still stuck? Let us know.

Customize the project#

Projects created with this template expose the following configuration settings:

gcp:project

The Google Cloud project ID to deploy into.

gcp:region

The Google Cloud region to deploy into. Defaults to us-central1.

nodesPerZone

The desired number of nodes per zone in the node pool. Defaults to 1.

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, run two nodes in each zone:

Terminal window
pulumi config set nodesPerZone 2
pulumi up

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

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

Deleting the cluster takes about 10 minutes.

Learn more#

Related

The infrastructure platform for humans and agents.