Membuat cluster dan men-deploy workload menggunakan Terraform


Cluster Kubernetes menyediakan komputasi, penyimpanan, jaringan, dan layanan lainnya untuk aplikasi, mirip dengan pusat data virtual. Aplikasi dan layanan terkait yang berjalan di Kubernetes disebut workload.

Tutorial ini memungkinkan Anda melihat dengan cepat cluster Google Kubernetes Engine dan contoh beban kerja yang sedang berjalan, yang semuanya disiapkan menggunakan Terraform. Kemudian, Anda dapat menjelajahi beban kerja di Google Cloud konsol sebelum melanjutkan ke jalur pembelajaran yang lebih mendalam, atau mulai merencanakan dan membuat cluster siap produksi Anda sendiri. Tutorial ini mengasumsikan bahwa Anda sudah memahami Terraform.

Jika Anda lebih suka menyiapkan cluster dan workload contoh di konsol Google Cloud , lihat Membuat cluster di konsol Google Cloud .

Sebelum memulai

Lakukan langkah-langkah berikut untuk mengaktifkan Kubernetes Engine API:

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  4. To initialize the gcloud CLI, run the following command:

    gcloud init
  5. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the GKE API:

    gcloud services enable container.googleapis.com
  8. Install the Google Cloud CLI.

  9. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  10. To initialize the gcloud CLI, run the following command:

    gcloud init
  11. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  12. Make sure that billing is enabled for your Google Cloud project.

  13. Enable the GKE API:

    gcloud services enable container.googleapis.com
  14. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/container.admin, roles/compute.networkAdmin, roles/iam.serviceAccountUser

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE
    • Replace PROJECT_ID with your project ID.
    • Replace USER_IDENTIFIER with the identifier for your user account. For example, user:myemail@example.com.

    • Replace ROLE with each individual role.

Menyiapkan lingkungan

Dalam tutorial ini, Anda akan menggunakan Cloud Shell untuk mengelola resource yang dihosting di Google Cloud. Cloud Shell telah diinstal dengan software yang Anda perlukan untuk tutorial ini, termasuk Terraform, kubectl, dan Google Cloud CLI.

  1. Luncurkan sesi Cloud Shell dari konsol Google Cloud , dengan mengklik ikon aktivasi Cloud Shell Activate Cloud Shell Tombol Activate Shell. Tindakan ini akan meluncurkan sesi di panel bawah konsol Google Cloud .

    Kredensial layanan yang terkait dengan mesin virtual ini bersifat otomatis, sehingga Anda tidak perlu menyiapkan atau mendownload kunci akun layanan.

  2. Sebelum menjalankan perintah, tetapkan project default Anda di gcloud CLI menggunakan perintah berikut:

    gcloud config set project PROJECT_ID
    

    Ganti PROJECT_ID dengan project ID Anda.

  3. Buat clone repositori GitHub:

    git clone https://github.com/terraform-google-modules/terraform-docs-samples.git --single-branch
    
  4. Ubah ke direktori kerja:

    cd terraform-docs-samples/gke/quickstart/autopilot
    

Meninjau file Terraform

PenyediaGoogle Cloud adalah plugin yang memungkinkan Anda mengelola dan menyediakan resource Google Cloud menggunakan Terraform. Provider ini berfungsi sebagai jembatan antara konfigurasi Terraform dan API, sehingga Anda dapat menentukan resource infrastruktur secara deklaratif, seperti mesin virtual dan jaringan. Google Cloud

Cluster dan aplikasi contoh untuk tutorial ini ditentukan dalam dua file Terraform yang menggunakan penyedia Google Cloud dan Kubernetes.

  1. Tinjau file cluster.tf:

    cat cluster.tf
    

    Outputnya mirip dengan yang berikut ini

    resource "google_compute_network" "default" {
      name = "example-network"
    
      auto_create_subnetworks  = false
      enable_ula_internal_ipv6 = true
    }
    
    resource "google_compute_subnetwork" "default" {
      name = "example-subnetwork"
    
      ip_cidr_range = "10.0.0.0/16"
      region        = "us-central1"
    
      stack_type       = "IPV4_IPV6"
      ipv6_access_type = "INTERNAL" # Change to "EXTERNAL" if creating an external loadbalancer
    
      network = google_compute_network.default.id
      secondary_ip_range {
        range_name    = "services-range"
        ip_cidr_range = "192.168.0.0/24"
      }
    
      secondary_ip_range {
        range_name    = "pod-ranges"
        ip_cidr_range = "192.168.1.0/24"
      }
    }
    
    resource "google_container_cluster" "default" {
      name = "example-autopilot-cluster"
    
      location                 = "us-central1"
      enable_autopilot         = true
      enable_l4_ilb_subsetting = true
    
      network    = google_compute_network.default.id
      subnetwork = google_compute_subnetwork.default.id
    
      ip_allocation_policy {
        stack_type                    = "IPV4_IPV6"
        services_secondary_range_name = google_compute_subnetwork.default.secondary_ip_range[0].range_name
        cluster_secondary_range_name  = google_compute_subnetwork.default.secondary_ip_range[1].range_name
      }
    
      # Set `deletion_protection` to `true` will ensure that one cannot
      # accidentally delete this instance by use of Terraform.
      deletion_protection = false
    }

    File ini menjelaskan resource berikut:

    • google_compute_network: jaringan VPC dengan IPv6 internal diaktifkan.
    • google_compute_subnetwork: subnetwork dual-stack.
    • google_container_cluster: cluster mode Autopilot dual-stack yang berada di us-central1. Setelan deletion_protection mengontrol apakah Anda dapat menggunakan Terraform untuk menghapus cluster ini. Jika Anda menetapkan nilai di kolom deletion_protection ke false, Terraform dapat menghapus cluster. Untuk mengetahui detailnya, lihat referensi google_container_cluster.
  2. Tinjau file app.tf:

    cat app.tf
    

    Outputnya mirip dengan hal berikut ini:

    data "google_client_config" "default" {}
    
    provider "kubernetes" {
      host                   = "https://${google_container_cluster.default.endpoint}"
      token                  = data.google_client_config.default.access_token
      cluster_ca_certificate = base64decode(google_container_cluster.default.master_auth[0].cluster_ca_certificate)
    
      ignore_annotations = [
        "^autopilot\\.gke\\.io\\/.*",
        "^cloud\\.google\\.com\\/.*"
      ]
    }
    
    resource "kubernetes_deployment_v1" "default" {
      metadata {
        name = "example-hello-app-deployment"
      }
    
      spec {
        selector {
          match_labels = {
            app = "hello-app"
          }
        }
    
        template {
          metadata {
            labels = {
              app = "hello-app"
            }
          }
    
          spec {
            container {
              image = "us-docker.pkg.dev/google-samples/containers/gke/hello-app:2.0"
              name  = "hello-app-container"
    
              port {
                container_port = 8080
                name           = "hello-app-svc"
              }
    
              security_context {
                allow_privilege_escalation = false
                privileged                 = false
                read_only_root_filesystem  = false
    
                capabilities {
                  add  = []
                  drop = ["NET_RAW"]
                }
              }
    
              liveness_probe {
                http_get {
                  path = "/"
                  port = "hello-app-svc"
    
                  http_header {
                    name  = "X-Custom-Header"
                    value = "Awesome"
                  }
                }
    
                initial_delay_seconds = 3
                period_seconds        = 3
              }
            }
    
            security_context {
              run_as_non_root = true
    
              seccomp_profile {
                type = "RuntimeDefault"
              }
            }
    
            # Toleration is currently required to prevent perpetual diff:
            # https://github.com/hashicorp/terraform-provider-kubernetes/pull/2380
            toleration {
              effect   = "NoSchedule"
              key      = "kubernetes.io/arch"
              operator = "Equal"
              value    = "amd64"
            }
          }
        }
      }
    }
    
    resource "kubernetes_service_v1" "default" {
      metadata {
        name = "example-hello-app-loadbalancer"
        annotations = {
          "networking.gke.io/load-balancer-type" = "Internal" # Remove to create an external loadbalancer
        }
      }
    
      spec {
        selector = {
          app = kubernetes_deployment_v1.default.spec[0].selector[0].match_labels.app
        }
    
        ip_family_policy = "RequireDualStack"
    
        port {
          port        = 80
          target_port = kubernetes_deployment_v1.default.spec[0].template[0].spec[0].container[0].port[0].name
        }
    
        type = "LoadBalancer"
      }
    
      depends_on = [time_sleep.wait_service_cleanup]
    }
    
    # Provide time for Service cleanup
    resource "time_sleep" "wait_service_cleanup" {
      depends_on = [google_container_cluster.default]
    
      destroy_duration = "180s"
    }

    File ini menjelaskan resource berikut:

(Opsional) Mengekspos aplikasi ke internet

File Terraform untuk contoh ini menjelaskan aplikasi dengan alamat IP internal, yang hanya dapat diakses dari Virtual Private Cloud (VPC) yang sama dengan aplikasi contoh. Jika Anda ingin mengakses antarmuka web aplikasi demo yang sedang berjalan dari internet (misalnya, dari laptop Anda), ubah file Terraform untuk membuat alamat IP publik sebelum Anda membuat cluster. Anda dapat melakukannya menggunakan editor teks langsung di Cloud Shell atau menggunakan Cloud Shell Editor.

Untuk mengekspos aplikasi demo ke internet:

  1. Di cluster.tf, ubah ipv6_access_type dari INTERNAL menjadi EXTERNAL.

    ipv6_access_type = "EXTERNAL"
    
  2. Di app.tf, konfigurasi load balancer eksternal dengan menghapus anotasi networking.gke.io/load-balancer-type.

     annotations = {
       "networking.gke.io/load-balancer-type" = "Internal" # Remove this line
     }
    

Membuat cluster dan men-deploy aplikasi

  1. Di Cloud Shell, jalankan perintah ini untuk memverifikasi bahwa Terraform tersedia:

    terraform
    

    Outputnya akan mirip dengan berikut ini:

    Usage: terraform [global options] <subcommand> [args]
    
    The available commands for execution are listed below.
    The primary workflow commands are given first, followed by
    less common or more advanced commands.
    
    Main commands:
      init          Prepare your working directory for other commands
      validate      Check whether the configuration is valid
      plan          Show changes required by the current configuration
      apply         Create or update infrastructure
      destroy       Destroy previously-created infrastructure
    
  2. Lakukan inisialisasi Terraform:

    terraform init
    
  3. Rencanakan konfigurasi Terraform:

    terraform plan
    
  4. Menerapkan konfigurasi Terraform

    terraform apply
    

    Saat diminta, masukkan yes untuk mengonfirmasi tindakan. Pemrosesan perintah ini mungkin memerlukan waktu beberapa menit. Outputnya mirip dengan hal berikut ini:

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

Memverifikasi bahwa cluster berfungsi

Lakukan hal berikut untuk mengonfirmasi bahwa cluster Anda berjalan dengan benar:

  1. Buka halaman Workloads di konsol Google Cloud :

    Buka Workloads

  2. Klik workload example-hello-app-deployment. Halaman Detail pod akan ditampilkan. Halaman ini menampilkan informasi tentang Pod, seperti anotasi, container yang berjalan di Pod, Layanan yang mengekspos Pod, dan metrik termasuk penggunaan CPU, Memori, dan Disk.

  3. Buka halaman Services & Ingress di konsol Google Cloud :

    Buka Services & Ingress

  4. Klik Layanan LoadBalancer example-hello-app-loadbalancer. Halaman detail layanan akan ditampilkan. Halaman ini menampilkan informasi tentang Service, seperti Pod yang terkait dengan Service, dan Port yang digunakan Service.

  5. Di bagian Endpoint eksternal, klik link IPv4 atau link IPv6 untuk melihat Layanan Anda di browser. Outputnya mirip dengan hal berikut ini:

    Hello, world!
    Version: 2.0.0
    Hostname: example-hello-app-deployment-5df979c4fb-kdwgr
    

Pembersihan

Agar tidak menimbulkan biaya pada akun Google Cloud Anda untuk resource yang digunakan di halaman ini, hapus project Google Cloud yang berisi resource tersebut.

Jika Anda berencana untuk mengikuti tutorial tambahan atau menjelajahi sampel lebih lanjut, tunggu hingga Anda selesai untuk melakukan langkah pembersihan ini.

  • Di Cloud Shell, jalankan perintah berikut untuk menghapus resource Terraform:

    terraform destroy --auto-approve
    

Memecahkan masalah error pembersihan

Jika Anda melihat pesan error yang mirip dengan The network resource 'projects/PROJECT_ID/global/networks/example-network' is already being used by 'projects/PROJECT_ID/global/firewalls/example-network-yqjlfql57iydmsuzd4ot6n5v', lakukan hal berikut:

  1. Hapus aturan Firewall:

    gcloud compute firewall-rules list --filter="NETWORK:example-network" --format="table[no-heading](name)" | xargs gcloud --quiet compute firewall-rules delete
    
  2. Jalankan kembali perintah Terraform:

    terraform destroy --auto-approve
    

Langkah berikutnya