In this project, we will learn how to use Terraform to deploy a Kubernetes cluster. This project will cover the following steps:

  1. Setting Up the Environment
  2. Creating a Kubernetes Cluster
  3. Deploying Applications to Kubernetes
  4. Managing Kubernetes Resources with Terraform
  5. Cleaning Up

  1. Setting Up the Environment

Before we start, ensure you have the following prerequisites:

  • Terraform installed on your machine. If not, refer to Installing Terraform.
  • kubectl installed for interacting with the Kubernetes cluster.
  • Cloud provider CLI (e.g., AWS CLI, Azure CLI, or gcloud CLI) installed and configured.

Example: Installing kubectl

# For macOS
brew install kubectl

# For Windows
choco install kubernetes-cli

# For Linux
curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x ./kubectl
sudo mv ./kubectl /usr/local/bin/kubectl

  1. Creating a Kubernetes Cluster

We will use Terraform to create a Kubernetes cluster on a cloud provider. For this example, we will use AWS and the EKS (Elastic Kubernetes Service).

Step-by-Step Guide

  1. Initialize Terraform Configuration

Create a directory for your project and navigate into it:

mkdir terraform-k8s-project
cd terraform-k8s-project
  1. Create a main.tf file

This file will contain the configuration for creating the EKS cluster.

provider "aws" {
  region = "us-west-2"
}

resource "aws_eks_cluster" "k8s_cluster" {
  name     = "my-k8s-cluster"
  role_arn = aws_iam_role.eks_role.arn

  vpc_config {
    subnet_ids = aws_subnet.public.*.id
  }
}

resource "aws_iam_role" "eks_role" {
  name = "eks-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "eks.amazonaws.com"
        }
      },
    ]
  })
}

resource "aws_subnet" "public" {
  count = 2
  vpc_id     = aws_vpc.main.id
  cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, count.index)
  availability_zone = element(data.aws_availability_zones.available.names, count.index)
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

data "aws_availability_zones" "available" {}
  1. Initialize and Apply Terraform Configuration
terraform init
terraform apply

This will create the necessary AWS resources for your Kubernetes cluster.

  1. Deploying Applications to Kubernetes

Once the cluster is up and running, we can deploy applications to it using kubectl.

Example: Deploying a Simple Nginx Application

  1. Configure kubectl

Get the kubeconfig file for your EKS cluster:

aws eks --region us-west-2 update-kubeconfig --name my-k8s-cluster
  1. Create a Deployment

Create a file named nginx-deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

Apply the deployment:

kubectl apply -f nginx-deployment.yaml
  1. Expose the Deployment

Create a file named nginx-service.yaml:

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  type: LoadBalancer
  selector:
    app: nginx
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80

Apply the service:

kubectl apply -f nginx-service.yaml

  1. Managing Kubernetes Resources with Terraform

Terraform can also manage Kubernetes resources directly. We will use the Kubernetes provider for Terraform.

Example: Managing the Nginx Deployment with Terraform

  1. Add Kubernetes Provider to main.tf
provider "kubernetes" {
  config_path = "~/.kube/config"
}

resource "kubernetes_deployment" "nginx" {
  metadata {
    name = "nginx-deployment"
  }

  spec {
    replicas = 2

    selector {
      match_labels = {
        app = "nginx"
      }
    }

    template {
      metadata {
        labels = {
          app = "nginx"
        }
      }

      spec {
        container {
          image = "nginx:1.14.2"
          name  = "nginx"
          port {
            container_port = 80
          }
        }
      }
    }
  }
}

resource "kubernetes_service" "nginx" {
  metadata {
    name = "nginx-service"
  }

  spec {
    selector = {
      app = "nginx"
    }

    port {
      port        = 80
      target_port = 80
    }

    type = "LoadBalancer"
  }
}
  1. Apply the Configuration
terraform apply

  1. Cleaning Up

To clean up the resources created by Terraform, simply run:

terraform destroy

This will remove all the resources created by Terraform.

Conclusion

In this project, we have learned how to:

  • Set up the environment for using Terraform with Kubernetes.
  • Create a Kubernetes cluster using Terraform.
  • Deploy applications to the Kubernetes cluster.
  • Manage Kubernetes resources using Terraform.
  • Clean up the resources.

This project provides a solid foundation for managing Kubernetes clusters and resources using Terraform, enabling you to automate and streamline your infrastructure management processes.

© Copyright 2024. All rights reserved