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


このクイックスタートでは、Terraform を使用して Google Kubernetes Engine(GKE)Autopilot クラスタを作成し、ワークロードをデプロイする方法について説明します。

Infrastructure as Code(IaC)は、コードを使用してソフトウェア インフラストラクチャ リソースを管理およびプロビジョニングする手法です。Terraform は、GKE を含む幅広いクラウド サービスをサポートする、一般的なオープンソースの IaC ツールです。GKE プラットフォーム管理者は、Terraform を使用して Kubernetes クラスタの構成を標準化し、DevOps ワークフローを効率化できます。詳細については、GKE での Terraform のサポートをご覧ください。

目標

  • IPv6 Virtual Private Cloud(VPC)ネットワークを作成する
  • GKE Autopilot クラスタを作成する
  • クラスタにワークロードをデプロイする
  • Service を使用してワークロードを公開する

始める前に

次の手順で 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. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. GKE API を有効にします。

    API を有効にする

  5. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  6. Google Cloud プロジェクトで課金が有効になっていることを確認します

  7. GKE API を有効にします。

    API を有効にする

  8. プロジェクトに次のロールがあることを確認します。 roles/container.admin, roles/compute.networkAdmin, roles/iam.serviceAccountUser

    ロールを確認する

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

      [IAM] に移動
    2. プロジェクトを選択します。
    3. [プリンシパル] 列で、自分のメールアドレスを含む行を見つけます。

      自分のメールアドレスがその列にない場合、ロールは割り当てられていません。

    4. 自分のメールアドレスを含む行の [ロール] 列で、ロールのリストに必要なロールが含まれているかどうかを確認します。

    ロールを付与する

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

      [IAM] に移動
    2. プロジェクトを選択します。
    3. [ アクセスを許可] をクリックします。
    4. [新しいプリンシパル] フィールドに、自分のメールアドレスを入力します。
    5. [ロールを選択] リストでロールを選択します。
    6. 追加のロールを付与するには、 [別のロールを追加] をクリックして各ロールを追加します。
    7. [保存] をクリックします。

Terraform の基本を理解している必要があります。まだ慣れていない場合は次のリソースをご利用ください。

環境を準備する

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

  1. Google Cloud コンソールで「Cloud Shell をアクティブにする」アイコン Shell をアクティブにするボタン をクリックして、Google Cloud コンソールから 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 プロバイダは、HashiCorp の Infrastructure as Code(IaC)ツールである Terraform を使用して Google Cloud リソースを管理、プロビジョニングできるプラグインです。Terraform 構成と Google Cloud APIs 間のブリッジとして機能し、仮想マシンやネットワークなどのインフラストラクチャ リソースを宣言的に定義できます。

  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
    }

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

    • 内部 IPv6 が有効になっている VPC ネットワーク。アプリケーションをインターネットに公開するには、ipv6_access_typeEXTERNAL に変更します。この変更を行う場合は、次のステップで app.tf ファイルの networking.gke.io/load-balancer-type アノテーションも削除する必要があります。
    • デュアルスタック サブネットワーク
    • us-central1 にあるデュアル スタック Autopilot クラスタ
  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"
    }

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

    • サンプル コンテナ イメージを含む Deployment
    • LoadBalancer タイプの Service。Service は、ポート 80 で Deployment を公開します。アプリケーションをインターネットに公開するには、networking.gke.io/load-balancer-type アノテーションを削除して、外部ロードバランサを構成します。

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

  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 をクリックします。サービスの詳細ページが表示されます。このページには、サービスに関連付けられた Pod や、サービスが使用するポートなど、サービスに関する情報が表示されます。

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

    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
    

次のステップ

  • Google Cloud プロバイダのドキュメントで、google_container_clustergoogle_container_node_pool のリソースを確認する。このページでは、Google が Terraform でサポートする GKE クラスタとノードプールの構成の引数と属性について説明しています。
  • Terraform GKE モジュールの GitHub リポジトリで独自の構成サンプルを確認する。