Google GKE and SQL with terraform

Ion Mudreac
6 min readAug 7, 2018

--

Few weeks back I started testing kubernetes offerings from few cloud providers Google GKE, Amazon AWS EKS and Microsoft Azure AKS. In this 1st article we will discuss on how to spin up Kubernetes Google cloud offering and SQL PostgreSQL with Terraform, using dedicated project and terraform service-account for automated deployment.

By the end of this tutorial you should have functional version of kubernetes running on GKE and PostgreSQL using Google Cloud SQL offering.

NOTE: This tutorial is not secured and is not production ready

Tutorial is structure in 5 parts

  1. Initial tooling setup gcloud, kubectl and terraform
  2. Creating Google Cloud project and service account for terraform
  3. Creating back-end storage to tfstate file in Cloud Storage
  4. Setting up separate projects for Development and Production environments
  5. Creating Kubernetes cluster on GKE and PostgreSQL on Cloud SQL

NOTE: This tutorial will not describe in details every tool used.

1. Initial tooling setup gcloud, kubectl and terraform

Assuming you already have Google Cloud account we will need additional binaries for gcloud CLI,, terraform and kubectl .

Gcloud deployment differs from Linux distribution and you can follow the link to deploy for OSX and diff Linux distributions

Deploying terraform

OS X

curl -o terraform_0.11.7_darwin_amd64.zip https://releases.hashicorp.com/terraform/0.11.7/terraform_0.11.7_darwin_amd64.zipunzip terraform_0.11.7_linux_amd64.zip -d /usr/local/bin/

Linux

curl https://releases.hashicorp.com/terraform/0.11.7/terraform_0.11.7_linux_amd64.zip > terraform_0.11.7_linux_amd64.zipunzip terraform_0.11.7_linux_amd64.zip -d /usr/local/bin/

Verification

Verify terraform version 0.11.7 or higher is installed:

terraform versionTerraform v0.11.7

Deploying kubectl

OS X

curl -o kubectl https://storage.googleapis.com/kubernetes-release/release/v1.11.0/bin/darwin/amd64/kubectlchmod +x kubectlsudo mv kubectl /usr/local/bin/

Linux

wget https://storage.googleapis.com/kubernetes-release/release/v1.11.0/bin/linux/amd64/kubectlchmod +x kubectlsudo mv kubectl /usr/local/bin/

Verification

Verify kubectl version 1.11.0 or higher is installed:

kubectl version --clientClient Version: version.Info{Major:”1", Minor:”11", GitVersion:”v1.11.0", GitCommit:”91e7b4fd31fcd3d5f436da26c980becec37ceefe”, GitTreeState:”clean”, BuildDate:”2018–06–27T20:17:28Z”, GoVersion:”go1.10.2", Compiler:”gc”, Platform:”linux/amd64"}

Authenticate to gcloud

Before configuring gcloud CLI you can check available Zones and Regions nearest to your location

gcloud compute regions list
gcloud compute zones list

Follow gcloud init and select default Zone Ex. asia-south1

gcloud init

2. Creating Google Cloud project and service account for terraform

Best practice to use separate account “technical account” to manage infrastructure, this account can be used in automated code deployment like in Jenkins, CirceleCI or any other tool you may choose.

Set up environment

export TF_VAR_org_id=YOUR_ORG_ID
export TF_VAR_billing_account=YOUR_BILLING_ACCOUNT_ID
export TF_ADMIN=terraform-admin-example
export TF_CREDS=~/.config/gcloud/terraform-admin.json

Find the values for YOUR_ORG_ID and YOUR_BILLING_ACCOUNT_ID

gcloud organizations list
gcloud beta billing accounts list

Create the Terraform Admin Project

Create a new project and link it to your billing account

gcloud projects create ${TF_ADMIN} \
--organization ${TF_VAR_org_id} \
--set-as-default
gcloud beta billing projects link ${TF_ADMIN} \
--billing-account ${TF_VAR_billing_account}

Create the Terraform service account

Create the service account in the Terraform admin project and download the JSON credentials

gcloud iam service-accounts create terraform \
--display-name "Terraform admin account"
gcloud iam service-accounts keys create ${TF_CREDS} \
--iam-account terraform@${TF_ADMIN}.iam.gserviceaccount.com

Grant the service account permission to view the Admin Project and manage Cloud Storage

gcloud projects add-iam-policy-binding ${TF_ADMIN} \
--member serviceAccount:terraform@${TF_ADMIN}.iam.gserviceaccount.com \
--role roles/viewer
gcloud projects add-iam-policy-binding ${TF_ADMIN} \
--member serviceAccount:terraform@${TF_ADMIN}.iam.gserviceaccount.com \
--role roles/storage.admin

Enabled API for newly created projects

gcloud services enable cloudresourcemanager.googleapis.com && \
gcloud services enable cloudbilling.googleapis.com && \
gcloud services enable iam.googleapis.com && \
gcloud services enable compute.googleapis.com && \
gcloud services enable sqladmin.googleapis.com && \
gcloud services enable container.googleapis.com

Add organization/folder-level permissions

Grant the service account permission to create projects and assign billing accounts

gcloud organizations add-iam-policy-binding ${TF_VAR_org_id} \
--member serviceAccount:terraform@${TF_ADMIN}.iam.gserviceaccount.com \
--role roles/resourcemanager.projectCreator
gcloud organizations add-iam-policy-binding ${TF_VAR_org_id} \
--member serviceAccount:terraform@${TF_ADMIN}.iam.gserviceaccount.com \
--role roles/billing.user

3. Creating back-end storage to tfstate file in Cloud Storage

Terraform stores the state about infrastructure and configuration by default local file “terraform.tfstate. State is used by Terraform to map resources to configuration, track metadata.

Terraform allows state file to be stored remotely, which works better in a team environment or automated deployments.

We will used Google Storage and create new bucket where we can store state files.

Create the remote back-end bucket in Cloud Storage for storage of the terraform.tfstate file

gsutil mb -p ${TF_ADMIN} -l asia-southeast1 gs://${TF_ADMIN}

Enable versioning for said remote bucket:

gsutil versioning set on gs://${TF_ADMIN}

Configure your environment for the Google Cloud terraform provider

export GOOGLE_APPLICATION_CREDENTIALS=${TF_CREDS}

4. Setting up separate projects for Development and Production environments

In order to segregate Development environment we will use Google cloud projects that allows us to segregate infrastructure bur maintain same time same code base for terraform.

Terraform allow us to use separate tfstate file for different environment by using terraform functionality workspaces.

Let’s see current file structure

.
├── backend.tf
├── main.tf
├── outputs.tf
├── terraform.tfvars
└── variables.tf
  • 1st step is to keep sensitive information outside external git repository. Best practice is to create terraform.tfvars and keep sensitive information and add .tfvars to .gitignore
.gitignore
*.tfstate
*.tfstate.backup
*.tfvars
.terraform
tfplan

Create terraform.tfvars file in project folder and replace “XXXXXX” with proper data. In our case tfvars files data is reference in variables.tf where we keep variables for main.tf

billing_account     = "XXXXXX-XXXXXX-XXXXXX"
org_id = "XXXXXXXXXXX"
  • backend.tf allows us to use newly created Google storage bucket to keep our tfstate files.
  • Variable used in terraform main.tf file
  • Outputs, once terraform will deploy new infrastructure we will need some outputs that we can reuse for GKE and SQL setup
  • Finally main source of the gcloud project creation

Initialize and pull terraform cloud specific dependencies

Terraform uses modular setup and in order to download specific plugin for cloud provider, terraform will need to be 1st initiated.

terraform init
  • Once we have our project code and our tfvar secretes secure we can create workspaces for terraform

NOTE: in below example we will use only dev workspace but you can use both following same logic

Create dev workspace

terraform workspace new dev

List available workspaces

terraform workspace list

Switch between workspaces

terraform workspace select dev
  • Terraform plan will simulate what changes terraform will be done on cloud provider
terraform plan
  • Apply terraform plan for selected environment
terraform apply

With above code we only created new project in Google Cloud and this dependent of the in what terraform workspace we are in.

Below is the sequence of commands to run

5. Creating Kubernetes cluster on GKE and PostgreSQL on Cloud SQL

Once we have project ready for dev and prod we can move into deploying our gke and sql infrastructure.

Code structure

.
├── backend
│ ├── firewall
│ │ ├── main.tf
│ │ └── variables.tf
│ ├── subnet
│ │ ├── main.tf
│ │ ├── outputs.tf
│ │ └── variables.tf
│ └── vpc
│ ├── main.tf
│ └── outputs.tf
├── backend.tf
├── cloudsql
│ ├── main.tf
│ ├── outputs.tf
│ └── variables.tf
├── gke
│ ├── main.tf
│ ├── outputs.tf
│ └── variables.tf
├── main.tf
├── outputs.tf
└── variables.tf

Now is time to deploy our infrastructure, noticeable differences between prod and dev workspaces you can find in the terraform files.

  • dev — single instance of PostgreSQL without replication and read replica
  • prod — single instance in multi AZ for high availablity and additional one read replica for PostgreSQL
  • dev — single kubernetes node will be added to GKE
  • prod — two nodes will be created and added to kubernetes GKE

In order to keep our code clean I decided to use modules for every segment Networking(vpc, subnets and firewall), cloudsql and gke. All this modules can be maintained in separate git repositories and can be called byroot main.tf file.

All variables that is consumed by modules I keep in single variable.tf file.

We will use same google storage bucket but with different prefix not to conflict with project creation terraform plan.

As terraform needs to be aware of the new projects we created in previous step we will import state from terraform 1st run.

data "terraform_remote_state" "project_id" {
backend = "gcs"
workspace = "${terraform.workspace}"
config {
bucket = "${var.bucket_name}"
prefix = "terraform-project"
}
}

We are now ready to to run our plan and create infrastructure.

  • As we are in separate code base will need to follow same sequence as in project creation.
  • Just make sure you have new terraform.tfvars
bucket_name         = "terraform-admin-example"
gke_master_pass = "your-gke-password"
sql_pass = "your-sql-password"

Initialize and pull terraform cloud specific dependencies

terraform init

Create dev workspace

terraform workspace new dev

List available workspaces

terraform workspace list

Switch between workspaces

terraform workspace select dev
  • Terraform plan will simulate what changes terraform will be done on cloud provider
terraform plan
  • Apply terraform
terraform apply

To check what terraform deployed use

terraform show

Once test is completed you can remove “destroy“ all buildup infrastructure.

terraform destroy -auto-approve

Terraform Tips

  • Refresh terraform
terraform refresh
  • List and show terraform state file
terraform state listterraform state show

Use tflint to check syntax of the tf files

tflint

Destroy only selected module Ex.

terraform destroy -target=module.cloudsql

Source code can be found in Github

--

--

Ion Mudreac
Ion Mudreac

Written by Ion Mudreac

Bank CTO at Advance Intelligence Group

Responses (1)