Terraform を使用してマルチテナント クラスタを作成する

Google Kubernetes Engine(GKE)Enterprise エディションのマルチテナント クラスタは、テナントと呼ばれる複数の個別のチームまたはユーザーによって共有される Kubernetes クラスタです。通常、各テナントにはクラスタ内に独自のリソースとアプリケーションのセットが用意されています。

この Terraform チュートリアルでは、2 つのチーム(backendfrontend)が共有する GKE Enterprise クラスタをすばやく作成し、クラスタにチーム固有のワークロードをデプロイできるようにします。このチュートリアルは、Terraform に精通していることを前提としています。まだ Terraform の基本を理解していない場合は、次のリソースを使用して Terraform の基本を学習してください。

始める前に

次の手順で 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. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  4. Enable the GKE, GKE Hub, Cloud SQL, Resource Manager, IAM, Connect gateway APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  7. Enable the GKE, GKE Hub, Cloud SQL, Resource Manager, IAM, Connect gateway APIs.

    Enable the APIs

  8. Make sure that you have the following role or roles on the project: roles/owner, roles/iam.serviceAccountTokenCreator

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      [IAM] に移動
    2. プロジェクトを選択します。
    3. [ アクセスを許可] をクリックします。
    4. [新しいプリンシパル] フィールドに、ユーザー ID を入力します。 これは通常、Google アカウントのメールアドレスです。

    5. [ロールを選択] リストでロールを選択します。
    6. 追加のロールを付与するには、 [別のロールを追加] をクリックして各ロールを追加します。
    7. [保存] をクリックします。

環境を準備する

このチュートリアルでは、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/multitenant
    

Terraform ファイルを確認する

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

  1. GKE Enterprise クラスタ リソースを記述する main.tf ファイルを確認します。

    cat main.tf
    

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

    resource "google_container_cluster" "default" {
      name               = "gke-enterprise-cluster"
      location           = "us-central1"
      initial_node_count = 3
      fleet {
        project = data.google_project.default.project_id
      }
      workload_identity_config {
        workload_pool = "${data.google_project.default.project_id}.svc.id.goog"
      }
      security_posture_config {
        mode               = "BASIC"
        vulnerability_mode = "VULNERABILITY_ENTERPRISE"
      }
      depends_on = [
        google_gke_hub_feature.policycontroller,
        google_gke_hub_namespace.default
      ]
      # Set `deletion_protection` to `true` will ensure that one cannot
      # accidentally delete this instance by use of Terraform.
      deletion_protection = false
    }
    
    resource "google_gke_hub_membership_binding" "default" {
      for_each = google_gke_hub_scope.default
    
      project               = data.google_project.default.project_id
      membership_binding_id = each.value.scope_id
      scope                 = each.value.name
      membership_id         = google_container_cluster.default.fleet[0].membership_id
      location              = google_container_cluster.default.fleet[0].membership_location
    }

クラスタと SQL データベースを作成する

  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: 23 added, 0 changed, 0 destroyed.
    

バックエンド チーム アプリケーションをデプロイする

  1. 次の Terraform ファイルを確認します。

    cat backend.yaml
    

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

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: backend-configmap
      namespace: backend-team
      labels:
        app: backend
    data:
      go.mod: |
        module multitenant
    
        go 1.22
    
        require github.com/go-sql-driver/mysql v1.8.1
    
        require filippo.io/edwards25519 v1.1.0 // indirect
    
      go.sum: |
        filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
        filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
        github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
        github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
    
      backend.go: |
        package main
    
        import (
          "database/sql"
          "fmt"
          "log"
          "math/rand"
          "net/http"
          "os"
    
          _ "github.com/go-sql-driver/mysql"
        )
    
        func main() {
          mux := http.NewServeMux()
          mux.HandleFunc("/", frontend)
    
          port := "8080"
    
          log.Printf("Server listening on port %s", port)
          log.Fatal(http.ListenAndServe(":"+port, mux))
        }
    
        func frontend(w http.ResponseWriter, r *http.Request) {
          log.Printf("Serving request: %s", r.URL.Path)
    
          host, _ := os.Hostname()
          fmt.Fprintf(w, "Backend!\n")
          fmt.Fprintf(w, "Hostname: %s\n", host)
    
          // Open database using cloud-sql-proxy sidecar
          db, err := sql.Open("mysql", "multitenant-app@tcp/multitenant-app")
          if err != nil {
            fmt.Fprintf(w, "Error: %v\n", err)
            return
          }
    
          // Create metadata Table if not exists
          _, err = db.Exec("CREATE TABLE IF NOT EXISTS metadata (metadata_key varchar(255) NOT NULL, metadata_value varchar(255) NOT NULL, PRIMARY KEY (metadata_key))")
          if err != nil {
            fmt.Fprintf(w, "Error: %v\n", err)
            return
          }
    
          // Pick random primary color
          var color string
          randInt := rand.Intn(3) + 1
          switch {
          case randInt == 1:
            color = "red"
          case randInt == 2:
            color = "green"
          case randInt == 3:
            color = "blue"
          }
    
          // Set color in database
          _, err = db.Exec(fmt.Sprintf("REPLACE INTO metadata (metadata_key, metadata_value) VALUES ('color', '%s')", color))
          if err != nil {
            fmt.Fprintf(w, "Error: %v\n", err)
            return
          }
    
          fmt.Fprintf(w, "Set Color: %s\n", color)
        }
    
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: backendweb
      namespace: backend-team
      labels:
        app: backend
    spec:
      selector:
        matchLabels:
          app: backend
          tier: web
      template:
        metadata:
          labels:
            app: backend
            tier: web
        spec:
          containers:
          - name: backend-container
            image: golang:1.22
            command: ["go"]
            args: ["run", "."]
            workingDir: "/tmp/backend"
            volumeMounts:
              - name: backend-configmap
                mountPath: /tmp/backend/
                readOnly: true
          - name: cloud-sql-proxy
            image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.11.4
            args:
              - "--structured-logs"
              - "--port=3306"
              - "$(CONNECTION_NAME_KEY)"
            securityContext:
              runAsNonRoot: true
            env:
            - name: CONNECTION_NAME_KEY
              valueFrom:
                configMapKeyRef:
                  name: database-configmap
                  key: CONNECTION_NAME
          volumes:
            - name: backend-configmap
              configMap: { name: backend-configmap }
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: backendweb
      namespace: backend-team
      labels:
        app: backend
      annotations:
        networking.gke.io/load-balancer-type: "Internal" # Remove to create an external loadbalancer
    spec:
      selector:
        app: backend
        tier: web
      ports:
      - port: 80
        targetPort: 8080
      type: LoadBalancer

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

    • サンプル アプリケーションを含む Deployment
    • LoadBalancer タイプの Service。Service は、ポート 80 で Deployment を公開します。アプリケーションをインターネットに公開するには、networking.gke.io/load-balancer-type アノテーションを削除して、外部ロードバランサを構成します。
  2. Cloud Shell で次のコマンドを実行して、バックエンド チームのサービス アカウントの権限を借用します。

    gcloud config set auth/impersonate_service_account backend@PROJECT_ID.iam.gserviceaccount.com
    

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

  3. クラスタの認証情報を取得します。

    gcloud container fleet memberships get-credentials gke-enterprise-cluster --location us-central1
    
  4. バックエンド チームのマニフェストをクラスタに適用します。

    kubectl apply -f backend.yaml
    

バックエンド アプリケーションが動作していることを確認する

クラスタが正しく実行されていることを確認するには、次の操作を行います。

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

    [ワークロード] に移動

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

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

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

    Backend!
    Hostname: backendweb-765f6c4fc9-cl7jx
    Set Color: green
    

    ユーザーがバックエンド エンドポイントにアクセスするたびに、Service は赤、緑、青の色をランダムに選択して共有データベースに保存します。

フロントエンド チーム アプリケーションをデプロイする

  1. 次の Terraform ファイルを確認します。

    cat frontend.yaml
    

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

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: frontend-configmap
      namespace: frontend-team
      labels:
        app: frontend
    data:
      go.mod: |
        module multitenant
    
        go 1.22
    
        require github.com/go-sql-driver/mysql v1.8.1
    
        require filippo.io/edwards25519 v1.1.0 // indirect
    
      go.sum: |
        filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
        filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
        github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
        github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
    
      frontend.go: |
        package main
    
        import (
          "database/sql"
          "fmt"
          "log"
          "net/http"
          "os"
    
          _ "github.com/go-sql-driver/mysql"
        )
    
        func main() {
          mux := http.NewServeMux()
          mux.HandleFunc("/", frontend)
    
          port := "8080"
    
          log.Printf("Server listening on port %s", port)
          log.Fatal(http.ListenAndServe(":"+port, mux))
        }
    
        func frontend(w http.ResponseWriter, r *http.Request) {
          log.Printf("Serving request: %s", r.URL.Path)
    
          host, _ := os.Hostname()
          fmt.Fprintf(w, "Frontend!\n")
          fmt.Fprintf(w, "Hostname: %s\n", host)
    
          // Open database using cloud-sql-proxy sidecar
          db, err := sql.Open("mysql", "multitenant-app@tcp/multitenant-app")
          if err != nil {
            fmt.Fprint(w, "Error: %v\n", err)
            return
          }
    
          // Retrieve color from the database
          var color string
          err = db.QueryRow("SELECT metadata_value FROM metadata WHERE metadata_key='color'").Scan(&color)
          switch {
          case err == sql.ErrNoRows:
            fmt.Fprintf(w, "Error: color not found in database\n")
          case err != nil:
            fmt.Fprintf(w, "Error: %v\n", err)
          default:
            fmt.Fprintf(w, "Got Color: %s\n", color)
          }
        }
    
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: frontendweb
      namespace: frontend-team
      labels:
        app: frontend
    spec:
      selector:
        matchLabels:
          app: frontend
          tier: web
      template:
        metadata:
          labels:
            app: frontend
            tier: web
        spec:
          containers:
          - name: frontend-container
            image: golang:1.22
            command: ["go"]
            args: ["run", "."]
            workingDir: "/tmp/frontend"
            volumeMounts:
              - name: frontend-configmap
                mountPath: /tmp/frontend/
                readOnly: true
          - name: cloud-sql-proxy
            image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.11.4
            args:
              - "--structured-logs"
              - "--port=3306"
              - "$(CONNECTION_NAME_KEY)"
            securityContext:
              runAsNonRoot: true
            env:
            - name: CONNECTION_NAME_KEY
              valueFrom:
                configMapKeyRef:
                  name: database-configmap
                  key: CONNECTION_NAME
          volumes:
            - name: frontend-configmap
              configMap: { name: frontend-configmap }
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: frontendweb
      namespace: frontend-team
      labels:
        app: frontend
      annotations:
        networking.gke.io/load-balancer-type: "Internal" # Remove to create an external loadbalancer
    spec:
      selector:
        app: frontend
        tier: web
      ports:
      - port: 80
        targetPort: 8080
      type: LoadBalancer

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

    • サンプル アプリケーションを含む Deployment
    • LoadBalancer タイプの Service。Service は、ポート 80 で Deployment を公開します。アプリケーションをインターネットに公開するには、networking.gke.io/load-balancer-type アノテーションを削除して、外部ロードバランサを構成します。
  2. Cloud Shell で次のコマンドを実行して、フロントエンド チームのサービス アカウントの権限を借用します。

    gcloud config set auth/impersonate_service_account frontend@PROJECT_ID.iam.gserviceaccount.com
    

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

  3. クラスタの認証情報を取得します。

    gcloud container fleet memberships get-credentials gke-enterprise-cluster --location us-central1
    
  4. フロントエンド チームのマニフェストをクラスタに適用します。

    kubectl apply -f frontend.yaml
    

フロントエンド アプリケーションが動作していることを確認する

クラスタが正しく実行されていることを確認するには、次の操作を行います。

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

    [ワークロード] に移動

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

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

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

    Frontend!
    Hostname: frontendweb-5cd888d88f-gwwtc
    Got Color: green
    

クリーンアップ

このページで使用したリソースについて、 Google Cloud アカウントに課金されないようにするには、次の手順を行います。

  1. Cloud Shell で次のコマンドを実行して、サービス アカウントの権限借用を設定解除します。

    gcloud config unset auth/impersonate_service_account
    
  2. 次のコマンドを実行して、Terraform リソースを削除します。

    terraform destroy --auto-approve
    

次のステップ