Terraform

Using Terraform with Kubernetes

This is a tutorial about Using Terraform with Kubernetes for beginners. Kubestack has managed services like AKS, EKS, and GKE for Terraform with kubernetes deployment. They help in integrating cluster services from different bases in to GitOps workflow.

You can also check this tutorial in the following video:

Terraform Tutorial – video

1. Overview

Terraform was created on May 21st, 2014 by Mitchell Hashimoto. Hashimoto was Hashicorp’s founder. Terraform is used for building code and handling infrastructure security. Terraform is a popular DevOps tool in the software world. Terraform has code resources and a plan to take the environment from one state to the other state.

2. Terraform with Kubernetes

2.1 Prerequisites

Terraform is necessary on the operating system in which you want to execute the code.

2.2 Download

You can download Terraform from this website.

2.3 Setup

2.3.1 Terraform Setup

You can set up the Terraform by using the command below on macOS:

Terraform Setup

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

You can run this command to check if it is working:

Terraform Execution

 terraform -v

The output of the above command executed is shown below:

Terraform Execution Output

apples-MacBook-Air:~ bhagvan.kommadi$  terraform -v
Terraform v1.1.5
on darwin_amd64
apples-MacBook-Air:~ bhagvan.kommadi$

The terraform execution command has other options which are shown below:

Terraform Execution Options

$ terraform Usage: terraform [-version] [-help]  [args] ... help content omitted

2.4 Start a New Terraform Project

You can create a Terraform Project using resource definitions. Resource definitions are the files with the suffix .tf. You can use Terraform’s language for configuring the resources like EC2 instance, an Azure MariaDB, or a DNS entry. You can create a sample Terraform project with the commands shown below:

Terraform Project Creation Commands

$ cd $HOME
$ mkdir sample-terraform
$ cd sample-terraform
$ cat > main.tf <<EOF
provider "local" {
  version = "~> 1.4"
 }
resource "local_file" "sample" {
content = "sample, Terraform"
filename = "sample.txt"
}
EOF

The above main.tf file has resource and provider definitions. Local provider version 1.4 or other compatible version is used. sample of type local_file has the resource definition. You can run the terraform project by using the command below:

Terraform Project Execution

terraform init

The output of the above command when executed is shown below:

Terraform Project Execution Output

apples-MacBook-Air:sample-terraform bhagvan.kommadi$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/local versions matching "~> 1.4"...
- Installing hashicorp/local v1.4.0...
- Installed hashicorp/local v1.4.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

╷
│ Warning: Version constraints inside provider configuration blocks are deprecated
│ 
│   on main.tf line 2, in provider "local":
│    2:   version = "~> 1.4"
│ 
│ Terraform 0.13 and earlier allowed provider version constraints inside the
│ provider configuration block, but that is now deprecated and will be removed
│ in a future version of Terraform. To silence this warning, move the provider
│ version constraint into the required_providers block.
╵

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

Above, terraform reads the project files and downloads the required providers from public registries. The next step is to execute the plan command as shown below:

Terraform Project Execution – Plan

 terraform plan

The output of the above command when executed is shown below:

Terraform Project Execution – Plan Output

apples-MacBook-Air:sample-terraform bhagvan.kommadi$ terraform plan

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # local_file.sample will be created
  + resource "local_file" "sample" {
      + content              = "sample, Terraform"
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "sample.txt"
      + id                   = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.
╷
│ Warning: Version constraints inside provider configuration blocks are deprecated
│ 
│   on main.tf line 2, in provider "local":
│    2:   version = "~> 1.4"
│ 
│ Terraform 0.13 and earlier allowed provider version constraints inside the
│ provider configuration block, but that is now deprecated and will be removed
│ in a future version of Terraform. To silence this warning, move the provider
│ version constraint into the required_providers block.
╵

───────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't
guarantee to take exactly these actions if you run "terraform apply" now.
apples-MacBook-Air:sample-terraform bhagvan.kommadi$

The above terraform plan command helps in verifying the actions for resource creation. Terraform assumes that default values will be used where ever you have not shared them in the resource definition. You can now execute the apply command for resource creation.

Terraform Project Execution – Apply

 terraform apply

The output of the above command when executed is shown below:

Terraform Project Execution – Apply Output

apples-MacBook-Air:sample-terraform bhagvan.kommadi$ terraform apply

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # local_file.sample will be created
  + resource "local_file" "sample" {
      + content              = "sample, Terraform"
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "sample.txt"
      + id                   = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.
╷
│ Warning: Version constraints inside provider configuration blocks are deprecated
│ 
│   on main.tf line 2, in provider "local":
│    2:   version = "~> 1.4"
│ 
│ Terraform 0.13 and earlier allowed provider version constraints inside the
│ provider configuration block, but that is now deprecated and will be removed
│ in a future version of Terraform. To silence this warning, move the provider
│ version constraint into the required_providers block.
╵

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

local_file.sample: Creating...
local_file.sample: Creation complete after 0s [id=37d2f5fd67a0734d5d8d1626a47ae46f5b4dee17]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
apples-MacBook-Air:sample-terraform bhagvan.kommadi$

In the above command, the execution plan is generated. You can see the sample.txt. It will have the expected content Sample, Terraform.

Terraform Project Execution – Sample.txt

sample, Terraform

You can run the apply-auto-approve command next.

Terraform Project Execution – Apply Auto Approve

terraform apply -auto-approve

The output of the above command when executed is shown below:

Terraform Project Execution – Apply Auto Approve Output

apples-MacBook-Air:sample-terraform bhagvan.kommadi$ terraform apply -auto-approve
local_file.sample: Refreshing state... [id=37d2f5fd67a0734d5d8d1626a47ae46f5b4dee17]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and
found no differences, so no changes are needed.
╷
│ Warning: Version constraints inside provider configuration blocks are deprecated
│ 
│   on main.tf line 2, in provider "local":
│    2:   version = "~> 1.4"
│ 
│ Terraform 0.13 and earlier allowed provider version constraints inside the
│ provider configuration block, but that is now deprecated and will be removed
│ in a future version of Terraform. To silence this warning, move the provider
│ version constraint into the required_providers block.
╵

Apply complete! Resources: 0 added, 0 changed, 0 destroyed

You can have modules in Terraform which can have resources defined across different projects.

2.5 Kubernetes Setup

You need an existing kubernetes cluster like kind. Let us install the kind software. You can also download the config.yaml and run kind executable to setup the kubernetes cluster.

Install Kubernetes Cluster

brew install kind
curl https://raw.githubusercontent.com/hashicorp/learn-terraform-deploy-nginx-kubernetes-provider/main/kind-config.yaml --output kind-config.yaml
kind create cluster --name terraform-hello --config kind-config.yaml

The output is shown below:

Kind setup output

 kind create cluster --name terraform-hello --config kind-config.yaml
Creating cluster "terraform-hello" ...
 ✓ Ensuring node image (kindest/node:v1.23.4) 🖼 
 ✓ Preparing nodes 📦  
 ✓ Writing configuration 📜 
 ✓ Starting control-plane 🕹️ 
 ✓ Installing CNI 🔌 
 ✓ Installing StorageClass 💾 
Set kubectl context to "kind-terraform-hello"
You can now use your cluster with:

kubectl cluster-info --context kind-terraform-hello

Have a nice day!

2.6 Terraform with Kubernetes

Using terraform with kubernetes helps in providing unified workflow, full lifecycle management, and graph of relationships. Let us add NGINX deployment with two replicas on the kubernetes cluster internally exposing port 80 for HTTP.Now, create a new file named kubernetes.tf and add the following configuration to it. This serves as a base configuration for the provider.

Terraform Project Execution – Config

terraform {
  required_providers {
    kubernetes = {
      source = "hashicorp/kubernetes"
    }
  }
}

variable "host" {
  type = string
}

variable "client_certificate" {
  type = string
}

variable "client_key" {
  type = string
}

variable "cluster_ca_certificate" {
  type = string
}

provider "kubernetes" {
  host = var.host

  client_certificate     = base64decode(var.client_certificate)
  client_key             = base64decode(var.client_key)
  cluster_ca_certificate = base64decode(var.cluster_ca_certificate)
}

resource "kubernetes_deployment" "nginx" {
  metadata {
    name = "scalable-nginx-example"
    labels = {
      App = "ScalableNginxExample"
    }
  }

  spec {
    replicas = 2
    selector {
      match_labels = {
        App = "ScalableNginxExample"
      }
    }
    template {
      metadata {
        labels = {
          App = "ScalableNginxExample"
        }
      }
      spec {
        container {
          image = "nginx:1.7.8"
          name  = "example"

          port {
            container_port = 80
          }

          resources {
            limits = {
              cpu    = "0.5"
              memory = "512Mi"
            }
            requests = {
              cpu    = "250m"
              memory = "50Mi"
            }
          }
        }
      }
    }
  }
}


Let us check for kubernetes cluster to configure the terraform with the command kubectl config view and you can see the output as below.

Kind cluster check

apples-MacBook-Air:terraform-kubernetes bhagvan.kommadi$ kubectl config view --minify --flatten --context=kind-terraform-hello
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvakNDQWVhZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeU1ETXlPREU0TURrMU1Gb1hEVE15TURNeU5URTRNRGsxTUZvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBT0ViCjZMNXZGY1ZNbjVFcXdhL01nZjZDM3N5Rit5RS9LZGIwb2dUaVN4c0V2eFlLR091VURYUmd6aHBXVTF6RVp6SncKNFRzb0xodW9Ta3NaTU03S2ZWd3ZXQ0NhOVFic3lOSjdZbzdOTmJ5VjBCOWQ2N1BpMERjUXFzSkpRQ0Q2cFI3dQovMWlpanJSMHhNKzh0SjRXdXE2UU1TQnllcUJZdVFGbzVKbDVIcmRyb1NuUElwWmh1TDJVYU9WVnZSWkhybjZGCkk3d3JIWVRiMTYvZjBndDVtYTQvOFd2TWNRYkhmR3k0SlhPYmdqWVk1R2l5cnVBa2V4aG9mUjRKQnN4dE5SYnUKNFNyVXhVU3Z5SVkzc3lmNjBabVY0amM3TU9KSDlFVFF2WSs4U0ZBenpua25GeFloSUZwRVU0WnFaSmpJZWEwUQpXOHJZU2Q2d2lLQkZKZTdJa3JzQ0F3RUFBYU5aTUZjd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0hRWURWUjBPQkJZRUZBOHUzYjgwdC9rTjVxT0MxenNRSHdRaktTYlRNQlVHQTFVZEVRUU8KTUF5Q0NtdDFZbVZ5Ym1WMFpYTXdEUVlKS29aSWh2Y05BUUVMQlFBRGdnRUJBTTZBM05yVExOMVR6ZER0N1RPcgpsS2RFdHAwSU50ZlV0UmVVVDhRcFVOdDlOUlozL2NzN25Yc1pGajBwV2kvYW1DYW0wLy9lVENnQkxYQWc1cTRxCjVtdUt3WHpsYnVmU3llcm9oNHg2ZjVEUEJIdTNSUW5iSXlENnRiYkUyUmZpN0djajFLZVB6N1U5Zlp5eGJaMzEKZDNqbFJHL09zeSszTXNUeXZPZzE0TDNvRXhKemJrMk1RWTc4ek4xS0hJbVM2YlBiTDNSUld1c2R2aStQZTFGTwpwYjRTYklmVEpqTUJ4bDBTMFUyZE11Qy9RQmVlK0pOT1FTMmJYeXVkM0h1ZWZlaHhhVHNXNkNEM21yenQrUHVsCk52YzVibXZianp6L2dYWG0yaVVqNTVUb0s5NGFEczNzbjNuOE9lNGxvak5GaXR3SGdrdXlzWUZzMU93aStSKysKR0RFPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==
    server: https://127.0.0.1:50419
  name: kind-terraform-hello
contexts:
- context:
    cluster: kind-terraform-hello
    user: kind-terraform-hello
  name: kind-terraform-hello
current-context: kind-terraform-hello
kind: Config
preferences: {}
users:
- name: kind-terraform-hello
  user:
    client-certificate-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURJVENDQWdtZ0F3SUJBZ0lJQ0EwamFObE1ES2N3RFFZSktvWklodmNOQVFFTEJRQXdGVEVUTUJFR0ExVUUKQXhNS2EzVmlaWEp1WlhSbGN6QWVGdzB5TWpBek1qZ3hPREE1TlRCYUZ3MHlNekF6TWpneE9EQTVOVGhhTURRe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dlhSNnB1aXA4bWFuR0VDN0hxcUk1bStOUzdoTzA2Kwo4U1pmUndrbVFDOUdoVFBkZWlaTm9pTVdsWmdDQldneWJqcmV6OCt6eFRlTlpEMHgrMUdCRmw3dFhUM1M1OFVTCk41Z25YT3NDZ1lFQXZsRUlDaVNic1g0NlF5SFg4anJjMVVsTHJYNG04ZjZUOUhrS0JKRWRhdktCbzVHeUZnaDkKVTZuM1V0MkUvaTFpZUN5STMzMGtOL2wwTkliWGNNT1RPN003a2Erb1hhR3FCSTFpcHVkVnhObFhBbWxWY1hTQwpDc1ZxR255Nk1WQTBqWllkeS9TZzcwQXdQc1pKRzRvNFB5RnA3Z2JvSFFFVitmWit2QVV3YkdBPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=

Now let us define terraform.tfvars based on the above output as shown in the file below:

Terraform TF Vars

# terraform.tfvars

host = "https://127.0.0.1:50419"

client_certificate =       "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURJVENDQWdtZ0F3SUJBZ0lJQ0EwamFObE1ES2N3RFFZSktvWklodmNOQVFFTEJRQXdGVEVUTUJFR0ExVUUKQXhNS2EzVmlaWEp1WlhSbGN6QWVGdzB5TWpBek1qZ3hPREE1TlRCYUZ3MHlNekF6TWpneE9EQTVOVGhhTURReApGekFWQmdOVkJBb1REbk41YzNSbGJUcHRZWE4wWlhKek1Sa3dGd1lEVlFRREV4QnJkV0psY201bGRHVnpMV0ZrCmJXbHVNSUlCSWpBTkJna3Foa2lHOXcwQkFRRUZBQU9DQVE4QU1JSUJDZ0tDQVFFQXduVG9hUzJTMHlVeVNXT2YKTSszYU42NTdjUGN4d1VZQzVLZ3JYQ3NrRUpCNXJUdzQvMThNNzNiTVBKRWtRS2txdHBQSnNpbGVRQnR6cXlrSAppRmJaRWtFVlBoR3hvNWhYdGlzRzQrT2QvZlIreFU0dDJ1dFBXNlVVbjlFL0tLaER0ZjRiNlBMY042MWFJNlNPCjV2bkNuWVlrN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OMVR6ZER0N1RPcgpsS2RFdHAwSU50ZlV0UmVVVDhRcFVOdDlOUlozL2NzN25Yc1pGajBwV2kvYW1DYW0wLy9lVENnQkxYQWc1cTRxCjVtdUt3WHpsYnVmU3llcm9oNHg2ZjVEUEJIdTNSUW5iSXlENnRiYkUyUmZpN0djajFLZVB6N1U5Zlp5eGJaMzEKZDNqbFJHL09zeSszTXNUeXZPZzE0TDNvRXhKemJrMk1RWTc4ek4xS0hJbVM2YlBiTDNSUld1c2R2aStQZTFGTwpwYjRTYklmVEpqTUJ4bDBTMFUyZE11Qy9RQmVlK0pOT1FTMmJYeXVkM0h1ZWZlaHhhVHNXNkNEM21yenQrUHVsCk52YzVibXZianp6L2dYWG0yaVVqNTVUb0s5NGFEczNzbjNuOE9lNGxvak5GaXR3SGdrdXlzWUZzMU93aStSKysKR0RFPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg=="

You can now execute command terraform init and apply to see the output as below.

Terraform Project Execution – init and approve

apples-MacBook-Air:terraform-kubernetes bhagvan.kommadi$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/kubernetes...
- Installing hashicorp/kubernetes v2.9.0...
- Installed hashicorp/kubernetes v2.9.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
apples-MacBook-Air:terraform-kubernetes bhagvan.kommadi$ terraform apply

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # kubernetes_deployment.nginx will be created
  + resource "kubernetes_deployment" "nginx" {
      + id               = (known after apply)
      + wait_for_rollout = true

      + metadata {
          + generation       = (known after apply)
          + labels           = {
              + "App" = "ScalableNginxExample"
            }
          + name             = "scalable-nginx-example"
          + namespace        = "default"
          + resource_version = (known after apply)
          + uid              = (known after apply)
        }

      + spec {
          + min_ready_seconds         = 0
          + paused                    = false
          + progress_deadline_seconds = 600
          + replicas                  = "2"
          + revision_history_limit    = 10

          + selector {
              + match_labels = {
                  + "App" = "ScalableNginxExample"
                }
            }

          + strategy {
              + type = (known after apply)

              + rolling_update {
                  + max_surge       = (known after apply)
                  + max_unavailable = (known after apply)
                }
            }

          + template {
              + metadata {
                  + generation       = (known after apply)
                  + labels           = {
                      + "App" = "ScalableNginxExample"
                    }
                  + name             = (known after apply)
                  + resource_version = (known after apply)
                  + uid              = (known after apply)
                }

              + spec {
                  + automount_service_account_token  = true
                  + dns_policy                       = "ClusterFirst"
                  + enable_service_links             = true
                  + host_ipc                         = false
                  + host_network                     = false
                  + host_pid                         = false
                  + hostname                         = (known after apply)
                  + node_name                        = (known after apply)
                  + restart_policy                   = "Always"
                  + service_account_name             = (known after apply)
                  + share_process_namespace          = false
                  + termination_grace_period_seconds = 30

                  + container {
                      + image                      = "nginx:1.7.8"
                      + image_pull_policy          = (known after apply)
                      + name                       = "example"
                      + stdin                      = false
                      + stdin_once                 = false
                      + termination_message_path   = "/dev/termination-log"
                      + termination_message_policy = (known after apply)
                      + tty                        = false

                      + port {
                          + container_port = 80
                          + protocol       = "TCP"
                        }

                      + resources {
                          + limits   = {
                              + "cpu"    = "0.5"
                              + "memory" = "512Mi"
                            }
                          + requests = {
                              + "cpu"    = "250m"
                              + "memory" = "50Mi"
                            }
                        }
                    }

                  + image_pull_secrets {
                      + name = (known after apply)
                    }

                  + readiness_gate {
                      + condition_type = (known after apply)
                    }

                  + volume {
                      + name = (known after apply)

                      + aws_elastic_block_store {
                          + fs_type   = (known after apply)
                          + partition = (known after apply)
                          + read_only = (known after apply)
                          + volume_id = (known after apply)
                        }

                      + azure_disk {
                          + caching_mode  = (known after apply)
                          + data_disk_uri = (known after apply)
                          + disk_name     = (known after apply)
                          + fs_type       = (known after apply)
                          + kind          = (known after apply)
                          + read_only     = (known after apply)
                        }

                      + azure_file {
                          + read_only        = (known after apply)
                          + secret_name      = (known after apply)
                          + secret_namespace = (known after apply)
                          + share_name       = (known after apply)
                        }

                      + ceph_fs {
                          + monitors    = (known after apply)
                          + path        = (known after apply)
                          + read_only   = (known after apply)
                          + secret_file = (known after apply)
                          + user        = (known after apply)

                          + secret_ref {
                              + name      = (known after apply)
                              + namespace = (known after apply)
                            }
                        }

                      + cinder {
                          + fs_type   = (known after apply)
                          + read_only = (known after apply)
                          + volume_id = (known after apply)
                        }

                      + config_map {
                          + default_mode = (known after apply)
                          + name         = (known after apply)
                          + optional     = (known after apply)

                          + items {
                              + key  = (known after apply)
                              + mode = (known after apply)
                              + path = (known after apply)
                            }
                        }

                      + csi {
                          + driver            = (known after apply)
                          + fs_type           = (known after apply)
                          + read_only         = (known after apply)
                          + volume_attributes = (known after apply)

                          + node_publish_secret_ref {
                              + name = (known after apply)
                            }
                        }

                      + downward_api {
                          + default_mode = (known after apply)

                          + items {
                              + mode = (known after apply)
                              + path = (known after apply)

                              + field_ref {
                                  + api_version = (known after apply)
                                  + field_path  = (known after apply)
                                }

                              + resource_field_ref {
                                  + container_name = (known after apply)
                                  + divisor        = (known after apply)
                                  + resource       = (known after apply)
                                }
                            }
                        }

                      + empty_dir {
                          + medium     = (known after apply)
                          + size_limit = (known after apply)
                        }

                      + fc {
                          + fs_type      = (known after apply)
                          + lun          = (known after apply)
                          + read_only    = (known after apply)
                          + target_ww_ns = (known after apply)
                        }

                      + flex_volume {
                          + driver    = (known after apply)
                          + fs_type   = (known after apply)
                          + options   = (known after apply)
                          + read_only = (known after apply)

                          + secret_ref {
                              + name      = (known after apply)
                              + namespace = (known after apply)
                            }
                        }

                      + flocker {
                          + dataset_name = (known after apply)
                          + dataset_uuid = (known after apply)
                        }

                      + gce_persistent_disk {
                          + fs_type   = (known after apply)
                          + partition = (known after apply)
                          + pd_name   = (known after apply)
                          + read_only = (known after apply)
                        }

                      + git_repo {
                          + directory  = (known after apply)
                          + repository = (known after apply)
                          + revision   = (known after apply)
                        }

                      + glusterfs {
                          + endpoints_name = (known after apply)
                          + path           = (known after apply)
                          + read_only      = (known after apply)
                        }

                      + host_path {
                          + path = (known after apply)
                          + type = (known after apply)
                        }

                      + iscsi {
                          + fs_type         = (known after apply)
                          + iqn             = (known after apply)
                          + iscsi_interface = (known after apply)
                          + lun             = (known after apply)
                          + read_only       = (known after apply)
                          + target_portal   = (known after apply)
                        }

                      + local {
                          + path = (known after apply)
                        }

                      + nfs {
                          + path      = (known after apply)
                          + read_only = (known after apply)
                          + server    = (known after apply)
                        }

                      + persistent_volume_claim {
                          + claim_name = (known after apply)
                          + read_only  = (known after apply)
                        }

                      + photon_persistent_disk {
                          + fs_type = (known after apply)
                          + pd_id   = (known after apply)
                        }

                      + projected {
                          + default_mode = (known after apply)

                          + sources {
                              + config_map {
                                  + name     = (known after apply)
                                  + optional = (known after apply)

                                  + items {
                                      + key  = (known after apply)
                                      + mode = (known after apply)
                                      + path = (known after apply)
                                    }
                                }

                              + downward_api {
                                  + items {
                                      + mode = (known after apply)
                                      + path = (known after apply)

                                      + field_ref {
                                          + api_version = (known after apply)
                                          + field_path  = (known after apply)
                                        }

                                      + resource_field_ref {
                                          + container_name = (known after apply)
                                          + divisor        = (known after apply)
                                          + resource       = (known after apply)
                                        }
                                    }
                                }

                              + secret {
                                  + name     = (known after apply)
                                  + optional = (known after apply)

                                  + items {
                                      + key  = (known after apply)
                                      + mode = (known after apply)
                                      + path = (known after apply)
                                    }
                                }

                              + service_account_token {
                                  + audience           = (known after apply)
                                  + expiration_seconds = (known after apply)
                                  + path               = (known after apply)
                                }
                            }
                        }

                      + quobyte {
                          + group     = (known after apply)
                          + read_only = (known after apply)
                          + registry  = (known after apply)
                          + user      = (known after apply)
                          + volume    = (known after apply)
                        }

                      + rbd {
                          + ceph_monitors = (known after apply)
                          + fs_type       = (known after apply)
                          + keyring       = (known after apply)
                          + rados_user    = (known after apply)
                          + rbd_image     = (known after apply)
                          + rbd_pool      = (known after apply)
                          + read_only     = (known after apply)

                          + secret_ref {
                              + name      = (known after apply)
                              + namespace = (known after apply)
                            }
                        }

                      + secret {
                          + default_mode = (known after apply)
                          + optional     = (known after apply)
                          + secret_name  = (known after apply)

                          + items {
                              + key  = (known after apply)
                              + mode = (known after apply)
                              + path = (known after apply)
                            }
                        }

                      + vsphere_volume {
                          + fs_type     = (known after apply)
                          + volume_path = (known after apply)
                        }
                    }
                }
            }
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

kubernetes_deployment.nginx: Creating...
kubernetes_deployment.nginx: Still creating... [10s elapsed]
kubernetes_deployment.nginx: Still creating... [20s elapsed]
kubernetes_deployment.nginx: Still creating... [30s elapsed]
kubernetes_deployment.nginx: Still creating... [40s elapsed]
kubernetes_deployment.nginx: Creation complete after 46s [id=default/scalable-nginx-example]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
apples-MacBook-Air:terraform-kubernetes bhagvan.kommadi$

3. Download the Source Code

Download
You can download the full source code of this example here: Using Terraform with Kubernetes

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button