Crea un cluster multi-tenant utilizzando Terraform

Un cluster multi-tenant in Google Kubernetes Engine è un cluster Kubernetes condiviso da più team o utenti distinti, noti come tenant. In genere ogni tenant ha il proprio insieme di risorse e applicazioni all'interno del cluster.

Questo tutorial Terraform ti consente di creare rapidamente un cluster GKE condiviso da due team, backend e frontend, che possono eseguire il deployment di carichi di lavoro specifici del team sul cluster. Questo tutorial presuppone che tu abbia già familiarità con Terraform. In caso contrario, puoi utilizzare le seguenti risorse per acquisire familiarità con le nozioni di base di Terraform:

Prima di iniziare

Per abilitare l'API Kubernetes Engine, segui questi passaggi:

  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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

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

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

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

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    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.

      Vai a IAM
    2. Seleziona il progetto.
    3. Fai clic su Concedi l'accesso.
    4. Nel campo Nuove entità, inserisci il tuo identificatore dell'utente. In genere si tratta dell'indirizzo email di un Account Google.

    5. Nell'elenco Seleziona un ruolo, seleziona un ruolo.
    6. Per concedere altri ruoli, fai clic su Aggiungi un altro ruolo e aggiungi ogni ruolo aggiuntivo.
    7. Fai clic su Salva.
    8. Prepara l'ambiente

      In questo tutorial utilizzerai Cloud Shell per gestire le risorse ospitate su Google Cloud. Cloud Shell è preinstallato con il software necessario per questo tutorial, tra cui Terraform, kubectl e Google Cloud CLI.

      1. Avvia una sessione di Cloud Shell dalla console Google Cloud facendo clic sull'icona di attivazione di Cloud Shell Attiva Cloud Shell Pulsante Attiva Cloud Shell. Viene avviata una sessione nel riquadro inferiore della console Google Cloud .

        Le credenziali di servizio associate a questa macchina virtuale sono automatiche, quindi non devi configurare o scaricare una chiave delaccount di serviziot.

      2. Prima di eseguire i comandi, imposta il progetto predefinito in gcloud CLI utilizzando il seguente comando:

        gcloud config set project PROJECT_ID
        

        Sostituisci PROJECT_ID con l'ID progetto.

      3. Clona il repository GitHub:

        git clone https://github.com/terraform-google-modules/terraform-docs-samples.git --single-branch
        
      4. Passa alla directory di lavoro:

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

      Esamina i file Terraform

      Il providerGoogle Cloud è un plug-in che consente di gestire ed eseguire il provisioning delle risorse Google Cloud utilizzando Terraform. Funge da ponte tra le configurazioni Terraform e le APIGoogle Cloud , consentendoti di definire in modo dichiarativo le risorse dell'infrastruttura, come macchine virtuali e reti.

      1. Esamina il file main.tf, che descrive una risorsa cluster GKE:

        cat main.tf
        

        L'output è simile al seguente:

        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
        }

      Crea un cluster e un database SQL

      1. In Cloud Shell, esegui questo comando per verificare che Terraform sia disponibile:

        terraform
        

        L'output dovrebbe essere simile al seguente:

        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. Inizializza Terraform:

        terraform init
        
      3. (Facoltativo) Pianifica la configurazione di Terraform:

        terraform plan
        
      4. Applica la configurazione Terraform

        terraform apply
        

        Quando richiesto, inserisci yes per confermare le azioni. Il completamento di questo comando potrebbe richiedere diversi minuti. L'output è simile al seguente:

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

      Esegui il deployment dell'applicazione del team di backend

      1. Esamina il seguente file Terraform:

        cat backend.yaml
        

        L'output dovrebbe essere simile al seguente:

        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

        Questo file descrive le seguenti risorse:

        • Un deployment con un'applicazione di esempio.
        • Un servizio di tipo LoadBalancer. Il servizio espone il deployment sulla porta 80. Per esporre la tua applicazione a internet, configura un bilanciatore del carico esterno rimuovendo l'annotazione networking.gke.io/load-balancer-type.
      2. In Cloud Shell, esegui questo comando per rappresentare il account di servizio del team di backend:

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

        Sostituisci PROJECT_ID con l'ID progetto.

      3. Recupera le credenziali del cluster:

        gcloud container fleet memberships get-credentials gke-enterprise-cluster --location us-central1
        
      4. Applica il manifest del team di backend al cluster:

        kubectl apply -f backend.yaml
        

      Verifica che l'applicazione di backend funzioni

      Per verificare che il cluster sia in esecuzione correttamente:

      1. Vai alla pagina Workload nella console Google Cloud :

        Vai a Carichi di lavoro

      2. Fai clic sul carico di lavoro backend. Viene visualizzata la pagina Dettagli pod. Questa pagina mostra informazioni sul pod, come annotazioni, container in esecuzione sul pod, servizi che espongono il pod e metriche tra cui utilizzo di CPU, memoria e disco.

      3. Fai clic sul servizio backend LoadBalancer. Viene visualizzata la pagina Dettagli del servizio. Questa pagina mostra informazioni sul servizio, ad esempio i pod associati al servizio e le porte utilizzate dal servizio.

      4. Nella sezione Endpoint, fai clic sul link IPv4 per visualizzare il servizio nel browser. L'output è simile al seguente:

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

        Ogni volta che un utente accede all'endpoint di backend, il servizio sceglie e memorizza in modo casuale un colore tra rosso, verde o blu nel database condiviso.

      Esegui il deployment di un'applicazione del team frontend

      1. Esamina il seguente file Terraform:

        cat frontend.yaml
        

        L'output dovrebbe essere simile al seguente:

        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

        Questo file descrive le seguenti risorse:

        • Un deployment con un'applicazione di esempio.
        • Un servizio di tipo LoadBalancer. Il servizio espone il deployment sulla porta 80. Per esporre la tua applicazione a internet, configura un bilanciatore del carico esterno rimuovendo l'annotazione networking.gke.io/load-balancer-type.
      2. In Cloud Shell, esegui questo comando per rappresentare il account di servizio del team frontend:

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

        Sostituisci PROJECT_ID con l'ID progetto.

      3. Recupera le credenziali del cluster:

        gcloud container fleet memberships get-credentials gke-enterprise-cluster --location us-central1
        
      4. Applica il manifest del team frontend al cluster:

        kubectl apply -f frontend.yaml
        

      Verifica che l'applicazione frontend funzioni

      Per verificare che il cluster sia in esecuzione correttamente:

      1. Vai alla pagina Workload nella console Google Cloud :

        Vai a Carichi di lavoro

      2. Fai clic sul carico di lavoro frontend. Viene visualizzata la pagina Dettagli pod. Questa pagina mostra informazioni sul pod, come annotazioni, container in esecuzione sul pod, servizi che espongono il pod e metriche tra cui utilizzo di CPU, memoria e disco.

      3. Fai clic sul servizio frontend LoadBalancer. Viene visualizzata la pagina Dettagli del servizio. Questa pagina mostra informazioni sul servizio, ad esempio i pod associati al servizio e le porte utilizzate dal servizio.

      4. Nella sezione Endpoint, fai clic sul link IPv4 per visualizzare il servizio nel browser. L'output è simile al seguente:

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

      Esegui la pulizia

      Per evitare che al tuo account Google Cloud vengano addebitati costi relativi alle risorse utilizzate in questa pagina, segui questi passaggi.

      1. In Cloud Shell, esegui questo comando per annullare l'impersonificazione del account di servizio:

        gcloud config unset auth/impersonate_service_account
        
      2. Esegui questo comando per eliminare le risorse Terraform:

        terraform destroy --auto-approve
        

      Passaggi successivi