Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snehesht/dd9c8a71a1eb5f0c02a879c819a2db86 to your computer and use it in GitHub Desktop.
Save snehesht/dd9c8a71a1eb5f0c02a879c819a2db86 to your computer and use it in GitHub Desktop.
The simple Terraform and Kubernetes with Docker on macOS

If you'd like to experiment with Terraform and Kubernetes on macOS locally, a great provider for doing so is the Kubernetes provider. You can get set up in a few simple steps, like so:

1. Install Docker

Install Docker for Mac if you have not already.

2. Enable Kubernetes

Enable Kubernetes

k8s

3. Install Terraform

Grab the latest Terraform for macOS from releases.hashicorp.com and place the terafform binary somewhere in your PATH or you can install with Homebrew:

brew install terraform

3. Configure, Plan & Apply!

Start with a basic NGINX Kubernetes pod definition in a minimal Terraform configuration — create a main.tf file, and add this to it:

# Configure Kubernetes provider and connect to the Kubernetes API server
provider "kubernetes" {
  host = "https://localhost:6443"
  config_context_auth_info = "docker-for-desktop"
  config_context_cluster   = "docker-for-desktop-cluster"
}

# Create an Nginx pod
resource "kubernetes_pod" "nginx" {
  metadata {
    name = "terraform-example"
  }

  spec {
    container {
      image = "nginx:1.15.3"
      name  = "example"
    }
  }
}

# Create an service
resource "kubernetes_service" "nginx" {
  metadata {
    name = "terraform-example"
  }
  spec {
    selector {
      run = "${kubernetes_pod.nginx.metadata.0.labels.run}"
    }
    port {
      port = 80
    }

    type = "NodePort"
  }
}

Save the file, then apply the configuration:

terraform plan

If the plan is good and without error, apply it:

terraform apply

Check to see that the pod is running:

kubectl get pod

The output should have something like this:

NAME                READY     STATUS    RESTARTS   AGE
terraform-example   1/1       Running   1          11m

Find the NodePort

kubectl get svc terraform-example -o jsonpath='{.spec.ports[0].nodePort}'

The output

31761

Now visit http://localhost:31761 in your browser and you should see the Welcome to nginx! default page!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment