Kubernetes on AWS - VPC Setup with Terraform

Introduction

In this blog post, we will walk through a basic Terraform VPC setup for AWS. The resulting VPC will consist of 3 public subnets which are directly connected to an internet gateway and 3 private subnets which are connected to a NAT gateway. The NAT gateway restricts internet access to outgoing connections. If you already deployed a VPC to your AWS account with at least 2 private and 2 public subnets feel free to skip this post.

Prerequisites

Kubernetes on AWS - From Zero To Production
  • AWS CLI V2 with admin credentials.
  • terraform cli
  • basic familarity with the following terms:
    • VPC, private subnet, public subnet, internet gateway, NAT gateway, s3 bucket
  • git clone git@github.com:canida-software/k8s-on-aws.git
 

Terraform Remote State

First, we will set up a Terraform backend. Backends determine where Terraform stores its state. Terraform uses this persisted state data to keep track of the resources it manages. We won’t use the local .tfstate file because it contains sensitive data e.g. database secrets. Instead, we will use the s3 backend to store the state on s3. Create a bucket such as canida-terraform and enable bucket versioning to be able to restore old state.
aws s3api create-bucket --bucket canida-terraform --region eu-central-1 --create-bucket-configuration LocationConstraint=eu-central-1
aws s3api put-bucket-versioning --bucket canida-terraform --versioning-configuration Status=Enabled
 
Then, adapt the backend configuration in backend.tf and substitute your bucket name. You can also freely change the file name for the state or the region.
terraform {
  backend "s3" {
    bucket = "canida-terraform"
    key    = "k8s-main-eks.tfstate"
    region = "eu-central-1"
  }
}

VPC Setup

Please rename and modify canida.tfvars to adapt it to your needs. Keep in mind that the terraform module only creates a single NAT gateway. For a high availability setup you can adapt it to create a second NAT gateway. The second NAT gateway can also be added in a later stage after you run production workloads in the VPC.
 
The next step is to set up the VPC using Terraform.
git clone git@github.com:canida-software/k8s-on-aws.git
cd k8s-on-aws/vpc

# install Terraform modules
terraform init

# setup the cluster and configure it using the tfvars file
terraform apply -var-file canida.tfvars
 
Nico Duldhardt

Written by

Nico Duldhardt

https://www.linkedin.com/in/nico-duldhardt/