Sling Academy
Home/DevOps/Using Terraform with Kubernetes: A Practical Guide

Using Terraform with Kubernetes: A Practical Guide

Last updated: February 03, 2024

Introduction

Kubernetes has become the go-to solution for deploying and managing containerized applications at scale. Meanwhile, Terraform by HashiCorp has gained popularity for its declarative approach and infrastructure as code (IaC) capabilities. Combining these two can significantly streamline the provisioning and management of Kubernetes resources. This tutorial will guide you through the basics to more advanced usages of Terraform with Kubernetes, complete with code examples.

Prerequisites

  • Basic understanding of Kubernetes and Terraform
  • Kubernetes cluster (Minikube, EKS, GKE, etc.)
  • Terraform installed on your machine

Setting Up Your Terraform Configuration

Firstly, we’ll start with setting up Terraform to work with your Kubernetes cluster. Ensure that you have your Kubernetes cluster up and running and that you can access it via kubectl.

provider "kubernetes" {
  config_path = "~/.kube/config"
}
    

This code snippet tells Terraform to use your local Kubernetes configuration file for connecting to your cluster.

Deploying a Simple Application

Let’s deploy a simple Nginx application to demonstrate how you can use Terraform to create Kubernetes resources.

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:latest"
          name  = "nginx"
          port {
            container_port = 80
          }
        }
      }
    }
  }
}
    

To see your newly deployed Nginx application, run kubectl get deployments. You should see nginx-deployment listed among the deployments.

Managing Kubernetes Resources

With Terraform, you can also manage other Kubernetes resources such as services, pods, and namespaces. Here’s how to create a LoadBalancer service for the Nginx deployment we just created.

resource "kubernetes_service" "nginx" {
  metadata {
    name = "nginx-service"
  }
  spec {
    selector {
      app = "nginx"
    }
    ports {
      port = 80
      target_port = 80
    }
    type = "LoadBalancer"
  }
}
    

After applying these Terraform configurations, you can use kubectl get services to see the external IP and port of your Nginx service.

Advanced Terraform with Kubernetes

As your applications and infrastructure grow, you’ll likely need to manage more complex Kubernetes resources. Let’s explore how to use Terraform to manage ConfigMaps and Secrets.

resource "kubernetes_config_map" "example" {
  metadata {
    name = "example-config"
  }
  data = {
    "variable" = "value"
  }
}

resource "kubernetes_secret" "example" {
  metadata {
    name = "example-secret"
  }
  type = "Opaque"
  data = {
    "password" = base64encode("verysecret")
  }
}
    

This will help you securely manage application configurations and secrets, leveraging Terraform’s capabilities to maintain versioned infrastructure code.

Modularizing Your Terraform Configuration

As your infrastructure grows, it’s a good practice to modularize your Terraform configurations. Modules allow you to reuse and share pieces of your infrastructure code across projects or teams, simplifying management and enhancing code quality.

module "nginx_module" {
  source = "./modules/nginx"
  replicas = 3
}
    

This snippet shows how you could structure a module for deploying Nginx, which can be reused with different configurations across your infrastructure.

Conclusion

Combining Terraform with Kubernetes offers a powerful approach to managing your containerized infrastructure as code. By starting with simple deployments and gradually incorporating more complex resources and modularization, you can build scalable, maintainable, and secure infrastructure. As Terraform and Kubernetes continue to evolve, staying updated with their latest features and best practices will help you maximize their potential.

Next Article: Terraform: How to prevent accidental deletion of resources

Previous Article: How to auto generate Terraform documentation

Series: Terraform Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide