Image for post
Image for post

Deploy Kubernetes Apps with Terraform

Infrastructure As Code during the cloud age is to use source code to document, version, and control your infrastructure. Terraform is by far the most popular and intuitive tool for this process. There are numerous articles, blogs, how-tos, and source code repositories about using Terraform to craft cloud resources on AWS, Azure, and GCP.

Installing the Tools

For this tutorial you need the following:

Install Tools on Mac OS X

With HomeBrew installed, you can do this to install the tools:

cat <<-"BREWFILE" > Brewfile
cask 'google-cloud-sdk'
brew 'kubectl'
brew 'terraform'
brew bundle --verbose

Organizing into Modules

We’ll start by setting up this directory structure, and files referenced will use this:

├── gke
│ ├──
│ ├──
│ └──
├── k8s
│ ├──
│ ├──
│ ├──
│ └──
mkdir terraform-gke
cd terraform-gke
mkdir gke k8s
for f in cluster gcp variables; do touch gke/$; done
for f in k8s pods services variables; do touch k8s/$; done

Cluster Specification

This is the module that will create a Kubernetes cluster on Google Cloud using GKE resource.

Guestbook Application Specification

Kubernetes code repository has an example application called guestbook that uses Redis cluster to store information. This module is divided into four parts:

  1. Kubernetes provider to connect to Kubernetes API
  2. Pods using Replication Controller
  3. Services creates permanent end point and connecting them to internal IP addresses as pods are added or removed.

Launch the Application

Before we start, we need to initialize some variables that the GCP provider requires, which is the target project and the desired region to create the cluster. We’ll use our default project configured with gcloud:

export TF_VAR_project="$(gcloud config list \
--format 'value(core.project)'
export TF_VAR_region="us-east1"
export TF_VAR_user="admin"
export TF_VAR_password="m8XBWrg2zt8R8JoH"
terraform init
terraform plan
terraform apply
kubectl get service

Final Thoughts

This is an easy way to quickly test clusters, pods, services, and other components. Currently, Terraform only supports deploying Pods and ReplicationControllers as deployable units.

Linux NinjaPants Automation Engineering Mutant — exploring DevOps, Kubernetes, CNI, IAC

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store