Terraform でクラスタを作成してワークロードをデプロイする


Kubernetes クラスタは、仮想データセンターと同様に、アプリケーション用のコンピューティング、ストレージ、ネットワーキングなどのサービスを提供します。Kubernetes で実行されるアプリとそれに関連するサービスは、ワークロードと呼ばれます。

このチュートリアルでは、Terraform によって Google Kubernetes Engine クラスタとサンプル ワークロードを簡単に設定して動作を確認できます。その後は、 Google Cloud コンソールでワークロードを確認してから、詳細な学習プログラムに進むか、独自のプロダクション レディなクラスタの計画と作成を開始できます。このチュートリアルは、Terraform に精通していることを前提としています。

Google Cloud コンソールでサンプル クラスタとワークロードを設定する場合は、 Google Cloud コンソールでクラスタを作成するをご覧ください。

始める前に

次の手順で 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.

環境を準備する

このチュートリアルでは、Google Cloudでホストされているリソースを Cloud Shell によって管理します。Cloud Shell には、このチュートリアルに必要なソフトウェア(TerraformkubectlGoogle Cloud CLI など)がプリインストールされています。

  1. Google Cloud コンソールで [Cloud Shell をアクティブにする] アイコン Shell をアクティブにするボタン をクリックして、Cloud Shell セッションを起動します。 Google Cloud コンソールの下部ペインでセッションが起動します。

    この仮想マシンに関連付けられているサービス認証情報は自動的に設定されるため、サービス アカウント キーを設定したり、ダウンロードしたりする必要はありません。

  2. コマンドを実行する前に、次のコマンドを使用して gcloud CLI でデフォルト プロジェクトを設定します。

    gcloud config set project PROJECT_ID
    

    PROJECT_ID は、実際のプロジェクト ID に置き換えます。

  3. GitHub リポジトリのクローンを作成します。

    git clone https://github.com/terraform-google-modules/terraform-docs-samples.git --single-branch
    
  4. 作業ディレクトリを変更します。

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

Terraform ファイルを確認する

Google Cloud プロバイダは、 Google Cloud リソースの管理とプロビジョニングを Terraform によって行えるようにするプラグインです。Terraform 構成と Google Cloud API 間のブリッジとして機能し、仮想マシンやネットワークなどのインフラストラクチャ リソースを宣言的に定義できます。

このチュートリアルのクラスタとサンプルアプリは、 Google Cloud プロバイダと Kubernetes プロバイダを使用する 2 つの Terraform ファイルで指定されています。

  1. cluster.tf ファイルを確認します。

    cat cluster.tf
    

    出力は次のようになります。

    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
    }

    このファイルでは、次のリソースを記述しています。

  2. app.tf ファイルを確認します。

    cat app.tf
    

    出力は次のようになります。

    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"
    }

    このファイルでは、次のリソースを記述しています。

(省略可)アプリケーションをインターネットに公開する

サンプルの Terraform ファイルでは、内部 IP アドレスを持つアプリが記述されています。このアプリには、サンプルアプリと同じ Virtual Private Cloud(VPC)からのみアクセスできます。実行中のデモアプリのウェブ インターフェースにインターネット(ノートパソコンなど)からアクセスする場合は、クラスタを作成する前に、代わりにパブリック IP アドレスを作成するように Terraform ファイルを変更します。それには、Cloud Shell で直接テキスト エディタを使用するか、Cloud Shell エディタを使用します。

デモ アプリケーションをインターネットに公開するには、次の操作を行います。

  1. cluster.tf で、ipv6_access_typeINTERNAL から EXTERNAL に変更します。

    ipv6_access_type = "EXTERNAL"
    
  2. app.tf で、networking.gke.io/load-balancer-type アノテーションを削除して外部ロードバランサを構成します。

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

クラスタを作成してアプリケーションをデプロイする

  1. Cloud Shell で次のコマンドを実行して、Terraform が使用可能であることを確認します。

    terraform
    

    出力例を以下に示します。

    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. Terraform を初期化します。

    terraform init
    
  3. Terraform 構成を計画します。

    terraform plan
    
  4. Terraform 構成を適用する

    terraform apply
    

    プロンプトが表示されたら、「yes」と入力して操作を確定します。このコマンドの完了までに数分かかることがあります。出力は次のようになります。

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

クラスタの動作を確認する

クラスタが正しく実行されていることを確認する手順は次のとおりです。

  1. Google Cloud コンソールの [ワークロード] ページに移動します。

    [ワークロード] に移動

  2. example-hello-app-deployment ワークロードをクリックします。Pod の詳細ページが表示されます。このページには、Pod に関する情報(アノテーション、Pod で実行されているコンテナ、Pod を公開している Service、CPU やメモリ、ディスクの使用量などの指標など)が表示されます。

  3. Google Cloud コンソールの [Service と Ingress] ページに移動します。

    [Service と Ingress] に移動

  4. example-hello-app-loadbalancer LoadBalancer Service をクリックします。Service の詳細ページが表示されます。このページには、Service に関連付けられた Pod や、Service が使用するポートなど、Service に関する情報が表示されます。

  5. [外部エンドポイント] セクションで、IPv4 リンクまたは IPv6 リンクをクリックして、ブラウザで Service を表示します。出力は次のようになります。

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

クリーンアップ

このページで使用したリソースについて、 Google Cloud アカウントに課金されないようにするには、リソースを含む Google Cloud プロジェクトを削除します。

別のチュートリアルを行う場合や、サンプルをさらに確認する場合は、すべてを終えてからこのクリーンアップ手順を実行してください。

  • Cloud Shell で次のコマンドを実行して、Terraform リソースを削除します。

    terraform destroy --auto-approve
    

クリーンアップ エラーのトラブルシューティング

The network resource 'projects/PROJECT_ID/global/networks/example-network' is already being used by 'projects/PROJECT_ID/global/firewalls/example-network-yqjlfql57iydmsuzd4ot6n5v' のようなエラー メッセージが表示されたら、次の操作を行います。

  1. ファイアウォール ルールを削除します。

    gcloud compute firewall-rules list --filter="NETWORK:example-network" --format="table[no-heading](name)" | xargs gcloud --quiet compute firewall-rules delete
    
  2. Terraform コマンドを再実行します。

    terraform destroy --auto-approve
    

次のステップ