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.
Before you begin#
For this walkthrough, you'll need:
- The Pulumi CLI
- The gcloud CLI (optional, but recommended and used in this guide)
- Permission to manage GKE, VPC networks, and service accounts
- The kubectl CLI
For this walkthrough, you'll need:
- The Pulumi CLI
- The gcloud CLI (optional, but recommended and used in this guide)
- Permission to manage GKE, VPC networks, and service accounts
- The kubectl CLI
For this walkthrough, you'll need:
- The Pulumi CLI
- The gcloud CLI (optional, but recommended and used in this guide)
- Permission to manage GKE, VPC networks, and service accounts
- A current version of Go installed locally
- The kubectl CLI
For this walkthrough, you'll need:
- The Pulumi CLI
- The gcloud CLI (optional, but recommended and used in this guide)
- Permission to manage GKE, VPC networks, and service accounts
- A current version of .NET installed locally
- The kubectl CLI
For this walkthrough, you'll need:
- The Pulumi CLI
- The gcloud CLI (optional, but recommended and used in this guide)
- Permission to manage GKE, VPC networks, and service accounts
- The kubectl CLI
For this walkthrough, you'll need:
- A current version of the Pulumi CLI (Pulumi HCL requires no additional runtime)
- The gcloud CLI (optional, but recommended and used in this guide)
- Permission to manage GKE, VPC networks, and service accounts
- The kubectl CLI
Create a new project#
Create a new project from the template:
mkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-typescriptmkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-typescriptmkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-pythonmkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-pythonmkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-gomkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-gomkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-csharpmkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-csharpmkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-yamlmkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-yamlmkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-hclmkdir my-k8s-cluster; cd my-k8s-clusterpulumi new kubernetes-gcp-hclThe 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:
| Key | Description | Default |
|---|---|---|
| gcp:project | The Google Cloud project to deploy into | — |
| gcp:region | The Google Cloud region to deploy into | us-central1 |
| nodesPerZone | The desired number of nodes PER ZONE in the nodepool | 1 |
pulumi config set
:
pulumi config set gcp:project <value>pulumi config set gcp:region <value>pulumi config set nodesPerZone <value>pulumi config set gcp:project "<value>"pulumi config set gcp:region "<value>"pulumi config set nodesPerZone "<value>"| Key | Description | Default |
|---|---|---|
| gcp:project | The Google Cloud project to deploy into | — |
| gcp:region | The Google Cloud region to deploy into | us-central1 |
| nodesPerZone | The desired number of nodes PER ZONE in the nodepool | 1 |
pulumi config set
:
pulumi config set gcp:project <value>pulumi config set gcp:region <value>pulumi config set nodesPerZone <value>pulumi config set gcp:project "<value>"pulumi config set gcp:region "<value>"pulumi config set nodesPerZone "<value>"| Key | Description | Default |
|---|---|---|
| gcp:project | The Google Cloud project to deploy into | — |
| gcp:region | The Google Cloud region to deploy into | us-central1 |
| nodesPerZone | The desired number of nodes PER ZONE in the nodepool | 1 |
pulumi config set
:
pulumi config set gcp:project <value>pulumi config set gcp:region <value>pulumi config set nodesPerZone <value>pulumi config set gcp:project "<value>"pulumi config set gcp:region "<value>"pulumi config set nodesPerZone "<value>"| Key | Description | Default |
|---|---|---|
| gcp:project | The Google Cloud project to deploy into | — |
| gcp:region | The Google Cloud region to deploy into | us-central1 |
| nodesPerZone | The desired number of nodes PER ZONE in the nodepool | 1 |
pulumi config set
:
pulumi config set gcp:project <value>pulumi config set gcp:region <value>pulumi config set nodesPerZone <value>pulumi config set gcp:project "<value>"pulumi config set gcp:region "<value>"pulumi config set nodesPerZone "<value>"| Key | Description | Default |
|---|---|---|
| gcp:project | The Google Cloud project to deploy into | — |
| gcp:region | The Google Cloud region to deploy into | us-central1 |
| nodesPerZone | The desired number of nodes PER ZONE in the nodepool | 1 |
pulumi config set
:
pulumi config set gcp:project <value>pulumi config set gcp:region <value>pulumi config set nodesPerZone <value>pulumi config set gcp:project "<value>"pulumi config set gcp:region "<value>"pulumi config set nodesPerZone "<value>"| Key | Description | Default |
|---|---|---|
| gcp:project | The Google Cloud project to deploy into | — |
| region | The Google Cloud region to deploy into | us-central1 |
| nodes_per_zone | The number of nodes per zone in the node pool | 1 |
pulumi config set
:
pulumi config set gcp:project <value>pulumi config set region <value>pulumi config set nodes_per_zone <value>pulumi config set gcp:project "<value>"pulumi config set region "<value>"pulumi config set nodes_per_zone "<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.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the resources it declares.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains 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.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf:
import * as pulumi from "@pulumi/pulumi";import * as gcp from "@pulumi/gcp";
// Get some provider-namespaced configuration valuesconst providerCfg = new pulumi.Config("gcp");const gcpProject = providerCfg.require("project");const gcpRegion = providerCfg.get("region") || "us-central1";// Get some other configuration values or use defaultsconst cfg = new pulumi.Config();const nodesPerZone = cfg.getNumber("nodesPerZone") || 1;
// Create a new networkconst 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 aboveconst gkeSubnet = new gcp.compute.Subnetwork("gke-subnet", { ipCidrRange: "10.128.0.0/12", network: gkeNetwork.id, privateIpGoogleAccess: true,});
// Create a new GKE clusterconst 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 poolconst 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 clusterconst 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 clusterconst clusterKubeconfig = pulumi.interpolate `apiVersion: v1clusters:- 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: Configpreferences: {}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 elsewhereexport const networkName = gkeNetwork.name;export const networkId = gkeNetwork.id;export const clusterName = gkeCluster.name;export const clusterId = gkeCluster.id;export const kubeconfig = clusterKubeconfig;import pulumiimport pulumi_gcp as gcp
# Get some provider-namespaced configuration valuesprovider_cfg = pulumi.Config("gcp")gcp_project = provider_cfg.require("project")gcp_region = provider_cfg.get("region", "us-central1")# Get some additional configuration valuesconfig = pulumi.Config()nodes_per_zone = config.get_int("nodesPerZone", 1)
# Create a new networkgke_network = gcp.compute.Network( "gke-network", auto_create_subnetworks=False, description="A virtual network for your GKE cluster(s)")
# Create a subnet in the new networkgke_subnet = gcp.compute.Subnetwork( "gke-subnet", ip_cidr_range="10.128.0.0/12", network=gke_network.id, private_ip_google_access=True)
# Create a cluster in the new network and subnetgke_cluster = gcp.container.Cluster( "gke-cluster", addons_config={ "dns_cache_config": { "enabled": True }, }, binary_authorization={ "evaluation_mode": "PROJECT_SINGLETON_POLICY_ENFORCE" }, datapath_provider="ADVANCED_DATAPATH", deletion_protection=False, description="A GKE cluster", initial_node_count=1, ip_allocation_policy={ "cluster_ipv4_cidr_block": "/14", "services_ipv4_cidr_block": "/20" }, location=gcp_region, master_authorized_networks_config={ "cidr_blocks": [{ "cidr_block": "0.0.0.0/0", "display_name": "All networks" }] }, network=gke_network.name, networking_mode="VPC_NATIVE", private_cluster_config={ "enable_private_nodes": True, "enable_private_endpoint": False, "master_ipv4_cidr_block": "10.100.0.0/28" }, remove_default_node_pool=True, release_channel={ "channel": "STABLE" }, subnetwork=gke_subnet.name, workload_identity_config={ "workload_pool": f"{gcp_project}.svc.id.goog" })
# Create a GCP service account for the nodepoolgke_nodepool_sa = gcp.serviceaccount.Account( "gke-nodepool-sa", account_id=pulumi.Output.concat(gke_cluster.name, "-np-1-sa"), display_name="Nodepool 1 Service Account")
# Create a nodepool for the clustergke_nodepool = gcp.container.NodePool( "gke-nodepool", cluster=gke_cluster.id, node_count=nodes_per_zone, node_config={ "oauth_scopes": ["https://www.googleapis.com/auth/cloud-platform"], "service_account": gke_nodepool_sa.email })
# Build a Kubeconfig to access the clustercluster_kubeconfig = pulumi.Output.all( gke_cluster.master_auth.cluster_ca_certificate, gke_cluster.endpoint, gke_cluster.name).apply(lambda l: f"""apiVersion: v1clusters:- cluster: certificate-authority-data: {l[0]} server: https://{l[1]} name: {l[2]}contexts:- context: cluster: {l[2]} user: {l[2]} name: {l[2]}current-context: {l[2]}kind: Configpreferences: {{}}users:- name: {l[2]} 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 elsewherepulumi.export("networkName", gke_network.name)pulumi.export("networkId", gke_network.id)pulumi.export("clusterName", gke_cluster.name)pulumi.export("clusterId", gke_cluster.id)pulumi.export("kubeconfig", cluster_kubeconfig)package main
import ( "fmt"
"github.com/pulumi/pulumi-gcp/sdk/v10/go/gcp/compute" "github.com/pulumi/pulumi-gcp/sdk/v10/go/gcp/container" "github.com/pulumi/pulumi-gcp/sdk/v10/go/gcp/serviceaccount" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config")
func main() { pulumi.Run(func(ctx *pulumi.Context) error { // Get some provider-namespaced configuration values providerCfg := config.New(ctx, "gcp") gcpProject := providerCfg.Require("project") gcpRegion, err := providerCfg.Try("region") if err != nil { gcpRegion = "us-central1" } // Get some additional configuration values or use defaults cfg := config.New(ctx, "") nodesPerZone, err := cfg.TryInt("nodesPerZone") if err != nil { nodesPerZone = 1 }
// Create a new network gkeNetwork, err := compute.NewNetwork(ctx, "gke-network", &compute.NetworkArgs{ AutoCreateSubnetworks: pulumi.Bool(false), Description: pulumi.String("A virtual network for your GKE cluster(s)"), }) if err != nil { return err }
// Create a subnet in the network gkeSubnet, err := compute.NewSubnetwork(ctx, "gke-subnet", &compute.SubnetworkArgs{ IpCidrRange: pulumi.String("10.128.0.0/12"), Network: gkeNetwork.ID(), PrivateIpGoogleAccess: pulumi.Bool(true), }) if err != nil { return err }
// Create a new GKE cluster gkeCluster, err := container.NewCluster(ctx, "gke-cluster", &container.ClusterArgs{ AddonsConfig: &container.ClusterAddonsConfigArgs{ DnsCacheConfig: &container.ClusterAddonsConfigDnsCacheConfigArgs{ Enabled: pulumi.Bool(true), }, }, BinaryAuthorization: &container.ClusterBinaryAuthorizationArgs{ EvaluationMode: pulumi.String("PROJECT_SINGLETON_POLICY_ENFORCE"), }, DatapathProvider: pulumi.String("ADVANCED_DATAPATH"), DeletionProtection: pulumi.Bool(false), Description: pulumi.String("A GKE cluster"), InitialNodeCount: pulumi.Int(1), IpAllocationPolicy: &container.ClusterIpAllocationPolicyArgs{ ClusterIpv4CidrBlock: pulumi.String("/14"), ServicesIpv4CidrBlock: pulumi.String("/20"), }, Location: pulumi.String(gcpRegion), MasterAuthorizedNetworksConfig: &container.ClusterMasterAuthorizedNetworksConfigArgs{ CidrBlocks: container.ClusterMasterAuthorizedNetworksConfigCidrBlockArray{ &container.ClusterMasterAuthorizedNetworksConfigCidrBlockArgs{ CidrBlock: pulumi.String("0.0.0.0/0"), DisplayName: pulumi.String("All networks"), }, }, }, Network: gkeNetwork.Name, NetworkingMode: pulumi.String("VPC_NATIVE"), PrivateClusterConfig: &container.ClusterPrivateClusterConfigArgs{ EnablePrivateNodes: pulumi.Bool(true), EnablePrivateEndpoint: pulumi.Bool(false), MasterIpv4CidrBlock: pulumi.String("10.100.0.0/28"), }, RemoveDefaultNodePool: pulumi.Bool(true), ReleaseChannel: &container.ClusterReleaseChannelArgs{ Channel: pulumi.String("STABLE"), }, Subnetwork: gkeSubnet.Name, WorkloadIdentityConfig: &container.ClusterWorkloadIdentityConfigArgs{ WorkloadPool: pulumi.String(fmt.Sprintf("%v.svc.id.goog", gcpProject)), }, }) if err != nil { return err }
// Create a GCP Service Account for the node pool gkeNodepoolSa, err := serviceaccount.NewAccount(ctx, "gke-nodepool-sa", &serviceaccount.AccountArgs{ AccountId: pulumi.Sprintf("%v-np-1-sa", gkeCluster.Name), DisplayName: pulumi.String("Nodepool 1 Service Account"), }) if err != nil { return err }
// Create a new node pool _, err = container.NewNodePool(ctx, "gke-nodepool", &container.NodePoolArgs{ Cluster: gkeCluster.ID(), NodeCount: pulumi.Int(nodesPerZone), NodeConfig: &container.NodePoolNodeConfigArgs{ OauthScopes: pulumi.StringArray{ pulumi.String("https://www.googleapis.com/auth/cloud-platform"), }, ServiceAccount: gkeNodepoolSa.Email, }, }) if err != nil { return err }
// Build Kubeconfig for accessing the cluster clusterKubeconfig := pulumi.Sprintf(`apiVersion: v1clusters:- cluster: certificate-authority-data: %[3]s server: https://%[2]s name: %[1]scontexts:- context: cluster: %[1]s user: %[1]s name: %[1]scurrent-context: %[1]skind: Configpreferences: {}users:- name: %[1]s 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 `, gkeCluster.Name, gkeCluster.Endpoint, gkeCluster.MasterAuth.ClusterCaCertificate().Elem())
// Export some values for use elsewhere ctx.Export("networkName", gkeNetwork.Name) ctx.Export("networkId", gkeNetwork.ID()) ctx.Export("clusterName", gkeCluster.Name) ctx.Export("clusterId", gkeCluster.ID()) ctx.Export("kubeconfig", clusterKubeconfig) return nil })}using System.Collections.Generic;using Pulumi;using Gcp = Pulumi.Gcp;
return await Deployment.RunAsync(() =>{ // Get some provider-namespaced configuration values (or use defaults) var provCfg = new Config("gcp"); var gcpProject = provCfg.Require("project"); var gcpRegion = provCfg.Get("region") ?? "us-central1"; // Get some additional configuration values (or use defaults) var config = new Config(); var nodesPerZone = config.GetInt32("nodesPerZone") ?? 1;
// Create a new network var gkeNetwork = new Gcp.Compute.Network("gke-network", new() { AutoCreateSubnetworks = false, Description = "A virtual network for your GKE cluster(s)", });
// Create a new subnet within the network var gkeSubnet = new Gcp.Compute.Subnetwork("gke-subnet", new() { IpCidrRange = "10.128.0.0/12", Network = gkeNetwork.Id, PrivateIpGoogleAccess = true, });
// Create a new GKE cluster var gkeCluster = new Gcp.Container.Cluster("gke-cluster", new() { AddonsConfig = new Gcp.Container.Inputs.ClusterAddonsConfigArgs { DnsCacheConfig = new Gcp.Container.Inputs.ClusterAddonsConfigDnsCacheConfigArgs { Enabled = true, }, }, BinaryAuthorization = new Gcp.Container.Inputs.ClusterBinaryAuthorizationArgs { EvaluationMode = "PROJECT_SINGLETON_POLICY_ENFORCE", }, DatapathProvider = "ADVANCED_DATAPATH", DeletionProtection = false, Description = "A GKE cluster", InitialNodeCount = 1, IpAllocationPolicy = new Gcp.Container.Inputs.ClusterIpAllocationPolicyArgs { ClusterIpv4CidrBlock = "/14", ServicesIpv4CidrBlock = "/20", }, Location = gcpRegion, MasterAuthorizedNetworksConfig = new Gcp.Container.Inputs.ClusterMasterAuthorizedNetworksConfigArgs { CidrBlocks = new[] { new Gcp.Container.Inputs.ClusterMasterAuthorizedNetworksConfigCidrBlockArgs { CidrBlock = "0.0.0.0/0", DisplayName = "All networks", }, }, }, Network = gkeNetwork.Name, NetworkingMode = "VPC_NATIVE", PrivateClusterConfig = new Gcp.Container.Inputs.ClusterPrivateClusterConfigArgs { EnablePrivateNodes = true, EnablePrivateEndpoint = false, MasterIpv4CidrBlock = "10.100.0.0/28", }, RemoveDefaultNodePool = true, ReleaseChannel = new Gcp.Container.Inputs.ClusterReleaseChannelArgs { Channel = "STABLE", }, Subnetwork = gkeSubnet.Name, WorkloadIdentityConfig = new Gcp.Container.Inputs.ClusterWorkloadIdentityConfigArgs { WorkloadPool = $"{gcpProject}.svc.id.goog", }, });
// Create a GCP service account for the node pool var gkeNodepoolSa = new Gcp.ServiceAccount.Account("gke-nodepool-sa", new() { AccountId = gkeCluster.Name.Apply(name => $"{name}-np-1-sa"), DisplayName = "Nodepool 1 Service Account", });
// Create a new node pool var gkeNodepool = new Gcp.Container.NodePool("gke-nodepool", new() { Cluster = gkeCluster.Id, NodeCount = nodesPerZone, NodeConfig = new Gcp.Container.Inputs.NodePoolNodeConfigArgs { OauthScopes = new[] { "https://www.googleapis.com/auth/cloud-platform", }, ServiceAccount = gkeNodepoolSa.Email, }, });
// Build Kubeconfig for accessing the cluster var clusterKubeconfig = Output.CreateSecret(Output.Tuple(gkeCluster.MasterAuth, gkeCluster.Endpoint, gkeCluster.Name).Apply(values => { var masterAuth = values.Item1; var endpoint = values.Item2; var gkeClusterName = values.Item3; return @$"apiVersion: v1clusters:- cluster: certificate-authority-data: {masterAuth.ClusterCaCertificate} server: https://{endpoint} name: {gkeClusterName}contexts:- context: cluster: {gkeClusterName} user: {gkeClusterName} name: {gkeClusterName}current-context: {gkeClusterName}kind: Configpreferences: {{}}users:- name: {gkeClusterName} 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 return new Dictionary<string, object?> { ["networkName"] = gkeNetwork.Name, ["networkId"] = gkeNetwork.Id, ["clusterName"] = gkeCluster.Name, ["clusterId"] = gkeCluster.Id, ["kubeconfig"] = clusterKubeconfig, };});name: my-projectdescription: A Pulumi YAML program to deploy a Kubernetes cluster on Google Cloudruntime: yamlconfig: nodesPerZone: type: integer default: 1
resources: # Create a GCP network (global VPC) gke-network: type: gcp:compute:Network properties: # Disable autoCreateSubnetworks because Private Google Access is needed autoCreateSubnetworks: false description: A virtual network for your GKE cluster(s) # Create a subnet in the new GCP network gke-subnet: type: gcp:compute:Subnetwork properties: ipCidrRange: 10.128.0.0/12 network: ${gke-network.id} privateIpGoogleAccess: true # Create a new GKE cluster gke-cluster: type: gcp:container:Cluster properties: addonsConfig: dnsCacheConfig: enabled: true binaryAuthorization: evaluationMode: PROJECT_SINGLETON_POLICY_ENFORCE datapathProvider: ADVANCED_DATAPATH deletionProtection: false description: A GKE cluster # Enabling Autopilot will invalidate many of the other settings included here # enableAutopilot: false initialNodeCount: 1 ipAllocationPolicy: clusterIpv4CidrBlock: /14 servicesIpv4CidrBlock: /20 location: ${gcp:region} masterAuthorizedNetworksConfig: cidrBlocks: # Change this CIDR block to something more restrictive for enhanced security - cidrBlock: 0.0.0.0/0 displayName: All networks network: ${gke-network.name} networkingMode: VPC_NATIVE privateClusterConfig: enablePrivateNodes: true # Changing this to true requires some form of connectivity to GCP (VPN or equivalent) enablePrivateEndpoint: false masterIpv4CidrBlock: 10.100.0.0/28 removeDefaultNodePool: true releaseChannel: channel: STABLE subnetwork: ${gke-subnet.name} workloadIdentityConfig: workloadPool: ${gcp:project}.svc.id.goog # Create a new service account for the nodepool gke-nodepool-sa: type: gcp:serviceaccount:Account properties: accountId: ${gke-cluster.name}-np-1-sa displayName: Nodepool 1 Service Account # Create a new nodepool for the cluster gke-nodepool: type: gcp:container:NodePool properties: cluster: ${gke-cluster.id} # Specify the number of nodes PER ZONE nodeCount: ${nodesPerZone} nodeConfig: # These scopes should be tightened down to only the required services/access oauthScopes: - https://www.googleapis.com/auth/cloud-platform serviceAccount: ${gke-nodepool-sa.email}
variables: clusterKubeconfig: fn::secret: | apiVersion: v1 clusters: - cluster: certificate-authority-data: ${gke-cluster.masterAuth["clusterCaCertificate"]} server: https://${gke-cluster.endpoint} name: ${gke-cluster.name} contexts: - context: cluster: ${gke-cluster.name} user: ${gke-cluster.name} name: ${gke-cluster.name} current-context: ${gke-cluster.name} kind: Config preferences: {} users: - name: ${gke-cluster.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
outputs: # Export some values to be used elsewhere networkName: ${gke-network.name} networkId: ${gke-network.id} clusterName: ${gke-cluster.name} clusterId: ${gke-cluster.id} kubeconfig: ${clusterKubeconfig}terraform { required_providers { gcp = { source = "pulumi/gcp" } }}
variable "region" { description = "The Google Cloud region to deploy into" type = string default = "us-central1"}
variable "nodes_per_zone" { description = "The desired number of nodes PER ZONE in the nodepool" type = number default = 1}
# Read the active project from the provider's credentials.data "gcp_organizations_client_config" "current" {}
locals { project = data.gcp_organizations_client_config.current.project
# Build a kubeconfig for the cluster. kubeconfig = <<-EOF apiVersion: v1 clusters: - cluster: certificate-authority-data: ${gcp_container_cluster.gke-cluster.master_auth.cluster_ca_certificate} server: https://${gcp_container_cluster.gke-cluster.endpoint} name: ${gcp_container_cluster.gke-cluster.name} contexts: - context: cluster: ${gcp_container_cluster.gke-cluster.name} user: ${gcp_container_cluster.gke-cluster.name} name: ${gcp_container_cluster.gke-cluster.name} current-context: ${gcp_container_cluster.gke-cluster.name} kind: Config preferences: {} users: - name: ${gcp_container_cluster.gke-cluster.name} user: exec: apiVersion: client.authentication.k8s.io/v1beta1 command: gke-gcloud-auth-plugin provideClusterInfo: true EOF}
# Create a GCP network (global VPC)resource "gcp_compute_network" "gke-network" { description = "A virtual network for the GKE cluster" auto_create_subnetworks = false}
# Create a subnet in the new GCP networkresource "gcp_compute_subnetwork" "gke-subnet" { region = var.region ip_cidr_range = "10.128.0.0/12" network = gcp_compute_network.gke-network.id private_ip_google_access = true}
# Create a new GKE clusterresource "gcp_container_cluster" "gke-cluster" { description = "A GKE cluster" location = var.region network = gcp_compute_network.gke-network.name subnetwork = gcp_compute_subnetwork.gke-subnet.name networking_mode = "VPC_NATIVE" initial_node_count = 1 remove_default_node_pool = true datapath_provider = "ADVANCED_DATAPATH" deletion_protection = false
addons_config = { dns_cache_config = { enabled = true } }
binary_authorization = { evaluation_mode = "PROJECT_SINGLETON_POLICY_ENFORCE" }
ip_allocation_policy = { cluster_ipv4_cidr_block = "/14" services_ipv4_cidr_block = "/20" }
master_authorized_networks_config = { cidr_blocks = [{ cidr_block = "0.0.0.0/0" display_name = "All networks" }] }
private_cluster_config = { enable_private_nodes = true enable_private_endpoint = false master_ipv4_cidr_block = "10.100.0.0/28" }
release_channel = { channel = "STABLE" }
workload_identity_config = { workload_pool = "${local.project}.svc.id.goog" }}
# Create a new service account for the nodepoolresource "gcp_serviceaccount_account" "gke-nodepool-sa" { account_id = "${gcp_container_cluster.gke-cluster.name}-np-1-sa" display_name = "Nodepool 1 Service Account"}
# Create a new nodepool for the clusterresource "gcp_container_node_pool" "gke-nodepool" { cluster = gcp_container_cluster.gke-cluster.id node_count = var.nodes_per_zone
node_config = { oauth_scopes = ["https://www.googleapis.com/auth/cloud-platform"] service_account = gcp_serviceaccount_account.gke-nodepool-sa.email }}
# Export some values to be used elsewhereoutput "network_name" { value = gcp_compute_network.gke-network.name}
output "cluster_name" { value = gcp_container_cluster.gke-cluster.name}
output "kubeconfig" { value = local.kubeconfig sensitive = true}Deploy the project#
Before the first deploy, turn on the Kubernetes Engine API in your project:
gcloud services enable container.googleapis.com --project $(pulumi config get gcp:project)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.
pulumi uppulumi upPulumi 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
kubectlto access and communicate with your cluster.
- 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
kubectlto access and communicate with your cluster.
- 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
kubectlto access and communicate with your cluster.
- 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
kubectlto access and communicate with your cluster.
- 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
kubectlto access and communicate with your cluster.
- network_name
The name of the VPC network containing the Kubernetes cluster resources.
- cluster_name
The name of the GKE cluster.
- kubeconfig
The cluster’s kubeconfig file, which you can use with
kubectlto 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:
gcloud components install gke-gcloud-auth-plugingcloud auth loginpulumi stack output kubeconfig --show-secrets > kubeconfigkubectl --kubeconfig kubeconfig get nodesgcloud components install gke-gcloud-auth-plugingcloud auth loginpulumi stack output kubeconfig --show-secrets | Out-File -Encoding ascii kubeconfigkubectl --kubeconfig kubeconfig get nodesIf 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:
gcloud auth application-default logingcloud auth application-default loginStill 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.
- 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.
- 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.
- 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.
- 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.
- gcp:project
The Google Cloud project ID to deploy into.
- region
The Google Cloud region to deploy into. Defaults to
us-central1.- nodes_per_zone
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:
pulumi config set nodesPerZone 2pulumi uppulumi config set nodesPerZone 2pulumi uppulumi config set nodesPerZone 2pulumi uppulumi config set nodesPerZone 2pulumi uppulumi config set nodesPerZone 2pulumi uppulumi config set nodesPerZone 2pulumi uppulumi config set nodesPerZone 2pulumi uppulumi config set nodesPerZone 2pulumi uppulumi config set nodesPerZone 2pulumi uppulumi config set nodesPerZone 2pulumi uppulumi config set nodes_per_zone 2pulumi uppulumi config set nodes_per_zone 2pulumi upWhen it finishes, list the nodes again; there are six:
kubectl --kubeconfig kubeconfig get nodeskubectl --kubeconfig kubeconfig get nodesTo see what else you can add, browse the Google Cloud provider in the Pulumi Registry.
Cleaning up#
You can cleanly destroy the stack and all of its infrastructure with pulumi destroy:
pulumi destroypulumi destroyDeleting the cluster takes about 10 minutes.
Learn more#
- Browse other architecture templates in the Templates gallery.
- Explore the Google Cloud provider API docs in the Pulumi Registry.
- Walk through Pulumi from the ground up in Pulumi Tutorials.
- Read the latest Google Cloud posts on the Pulumi blog.