יצירת אשכול מרובה דיירים באמצעות Terraform

אשכול מרובה דיירים ב-Google Kubernetes Engine הוא אשכול Kubernetes שמשותף לכמה צוותים או משתמשים נפרדים, שנקראים דיירים. לכל דייר יש בדרך כלל קבוצה משלו של משאבים ואפליקציות באשכול.

במדריך הזה ל-Terraform נסביר איך ליצור במהירות אשכול GKE שמשותף לשני צוותים, backend ו-frontend, שיכולים לפרוס עומסי עבודה ספציפיים לצוות באשכול. במדריך הזה אנחנו מניחים שאתם כבר מכירים את Terraform. אם לא, תוכלו להיעזר במשאבים הבאים כדי להכיר את היסודות של Terraform:

לפני שמתחילים

כדי להפעיל את Kubernetes Engine API:

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  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 role (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 GKE Fleet, 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 role (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 GKE Fleet, 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. צריך לוודא שיש לכם בפרויקט את התפקיד או התפקידים הבאים: roles/owner, roles/iam.serviceAccountTokenCreator

    בדיקת התפקידים

    1. נכנסים לדף IAM במסוף Google Cloud .

      כניסה לדף IAM
    2. בוחרים את הפרויקט.
    3. בעמודה Principal (חשבון המשתמש), מוצאים את כל השורות שבהן מופיע השם שלכם או של קבוצה שאתם נכללים בה. כדי לברר באילו קבוצות אתם נכללים, פנו לאדמין.

    4. בודקים את העמודה Role בכל השורות שבהן מצוין או מופיע השם שלכם, כדי לראות אם רשימת התפקידים כוללת את התפקידים הנדרשים.

    מתן התפקידים

    1. נכנסים לדף IAM במסוף Google Cloud .

      כניסה לדף IAM
    2. בוחרים את הפרויקט.
    3. לוחצים על Grant access.
    4. בשדה New principals, מזינים את מזהה המשתמש. ‫ בדרך כלל מזהה המשתמש הוא כתובת האימייל של חשבון Google.

    5. לוחצים על Select a role ומחפשים את התפקיד.
    6. כדי לתת עוד תפקידים, לוחצים על Add another role ומוסיפים אותם.
    7. לוחצים על Save.

הכנת הסביבה

במדריך הזה תשתמשו ב-Cloud Shell כדי לנהל משאבים שמתארחים ב-Google Cloud. ב-Cloud Shell מותקן מראש התוכנה שדרושה למדריך הזה, כולל Terraform,‏ kubectl ו-Google Cloud CLI.

  1. מפעילים סשן Cloud Shell מהמסוף על ידי לחיצה על סמל ההפעלה של Cloud Shell‏ Activate Cloud Shellכפתור הפעלת Shell. Google Cloud הפעולה הזו תפעיל סשן בחלונית התחתונה של Google Cloud המסוף.

    פרטי הכניסה לשירות שמשויכים למכונה הווירטואלית נוצרים אוטומטית, כך שלא צריך ליצור או להוריד מפתח לחשבון שירות.

  2. לפני שמריצים פקודות, מגדירים את פרויקט ברירת המחדל ב-CLI של gcloud באמצעות הפקודה הבאה:

    gcloud config set project PROJECT_ID
    

    מחליפים את PROJECT_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 provider הוא פלאגין שמאפשר לכם לנהל ולהקצות משאבי Google Cloud באמצעות Terraform. הוא משמש כגשר בין הגדרות Terraform לבין ממשקי API שלGoogle Cloud , ומאפשר להגדיר באופן הצהרתי משאבי תשתית, כמו מכונות וירטואליות ורשתות.

  1. בודקים את הקובץ main.tf שמתאר משאב של אשכול GKE:

    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

    בקובץ הזה מתוארים המשאבים הבאים:

    • פריסה עם אפליקציה לדוגמה.
    • שירות מסוג LoadBalancer. השירות חושף את הפריסה ביציאה 80. כדי לחשוף את האפליקציה לאינטרנט, צריך להגדיר מאזן עומסים חיצוני על ידי הסרת ההערה networking.gke.io/load-balancer-type.
  2. ב-Cloud Shell, מריצים את הפקודה הבאה כדי להתחזות לחשבון השירות של צוות ה-Backend:

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

    מחליפים את PROJECT_ID במזהה הפרויקט.

  3. מאחזרים את פרטי הכניסה לאשכול:

    gcloud container fleet memberships get-credentials gke-enterprise-cluster --location us-central1
    
  4. מחילים את המניפסט של צוות ה-Backend על האשכול:

    kubectl apply -f backend.yaml
    

אימות הפעולה של אפליקציית ה-Backend

כדי לוודא שהאשכול פועל בצורה תקינה:

  1. נכנסים לדף Workloads במסוף Google Cloud :

    כניסה לדף Workloads

  2. לוחצים על עומס העבודה backend. יוצג דף הפרטים של הפודקאסט. בדף הזה מוצג מידע על ה-Pod, כמו הערות, קונטיינרים שפועלים ב-Pod, שירותים שחושפים את ה-Pod ומדדים, כולל שימוש ב-CPU, בזיכרון ובדיסק.

  3. לוחצים על backend LoadBalancer Service. יוצג דף הפרטים של השירות. בדף הזה מוצג מידע על השירות, כמו ה-Pods שמשויכים לשירות והיציאות שבהן השירות משתמש.

  4. בקטע Endpoints (נקודות קצה), לוחצים על הקישור IPv4 כדי להציג את השירות בדפדפן. הפלט אמור להיראות כך:

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

    בכל פעם שמשתמש ניגש לנקודת הקצה של הקצה העורפי, השירות בוחר באופן אקראי צבע מתוך אדום, ירוק או כחול ומאחסן אותו במסד הנתונים המשותף.

פריסת אפליקציה של צוות קצה קדמי

  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

    בקובץ הזה מתוארים המשאבים הבאים:

    • פריסה עם אפליקציה לדוגמה.
    • שירות מסוג LoadBalancer. השירות חושף את הפריסה ביציאה 80. כדי לחשוף את האפליקציה לאינטרנט, צריך להגדיר מאזן עומסים חיצוני על ידי הסרת ההערה networking.gke.io/load-balancer-type.
  2. ב-Cloud Shell, מריצים את הפקודה הבאה כדי להתחזות לחשבון השירות של צוות הפרונט-אנד:

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

    מחליפים את PROJECT_ID במזהה הפרויקט.

  3. מאחזרים את פרטי הכניסה לאשכול:

    gcloud container fleet memberships get-credentials gke-enterprise-cluster --location us-central1
    
  4. מחילים את המניפסט של צוות ה-Frontend על האשכול:

    kubectl apply -f frontend.yaml
    

אימות של אפליקציית הקצה הקדמי

כדי לוודא שהאשכול פועל בצורה תקינה:

  1. נכנסים לדף Workloads במסוף Google Cloud :

    כניסה לדף Workloads

  2. לוחצים על עומס העבודה frontend. יוצג דף הפרטים של הפודקאסט. בדף הזה מוצג מידע על ה-Pod, כמו הערות, קונטיינרים שפועלים ב-Pod, שירותים שחושפים את ה-Pod ומדדים, כולל שימוש ב-CPU, בזיכרון ובדיסק.

  3. לוחצים על frontend LoadBalancer Service. יוצג דף הפרטים של השירות. בדף הזה מוצג מידע על השירות, כמו ה-Pods שמשויכים לשירות והיציאות שבהן השירות משתמש.

  4. בקטע Endpoints (נקודות קצה), לוחצים על הקישור IPv4 כדי להציג את השירות בדפדפן. הפלט אמור להיראות כך:

    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
    

המאמרים הבאים