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'
BREWFILE
brew bundle --verbose

Organizing into Modules

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

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

Cluster Specification

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

variables.tf
gcp.tf
cluster.tf

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.
variables.tf
k8s.tf
pods.tf
services.tf

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