Crea una build privata con Gemini per l'assistenza Google Cloud

Questo tutorial mostra come utilizzare Gemini per Google Cloud, un collaboratore basato sull'AI di Google Cloud, per esplorare i log e configurare un ambiente di compilazione per un set di microservizi in Google Kubernetes Engine.

Questo tutorial è rivolto agli ingegneri DevOps di qualsiasi livello di esperienza.

Obiettivi

  • Chiedi a Gemini una query di logging in modo da poter osservare i log dei pod.
  • Scopri come creare un ambiente di creazione privato inviando domande a Gemini basate sul contesto.
  • Usa Gemini per scoprire come archiviare le immagini container in modo privato e sicuro.

Prodotti Google Cloud utilizzati

Questo tutorial utilizza i seguenti prodotti Google Cloud fatturabili. Utilizza il Calcolatore prezzi per generare una stima dei costi basata sull'utilizzo previsto.

  • Google Kubernetes Engine (GKE). GKE è un servizio Kubernetes gestito che consente di eseguire il deployment e gestire applicazioni containerizzate su larga scala.

  • Cloud Logging. Logging è un sistema di gestione dei log in tempo reale con supporto di archiviazione, ricerca, analisi e monitoraggio.

  • Cloud Build. Cloud Build è un servizio che esegue le tue build sull'infrastruttura Google Cloud. Cloud Build può importare codice sorgente da vari repository o spazi di Cloud Storage, eseguire una build in base alle tue specifiche e produrre artefatti come container Docker o archivi Java.

  • Artifact Registry. Artifact Registry offre una singola posizione da cui gestire immagini container e pacchetti di linguaggio. Consente di archiviare a livello centrale gli artefatti e creare dipendenze, come parte di un'esperienza integrata di Google Cloud.

  • Gemini. Gemini è un collaboratore sempre attivo in Google Cloud che offre assistenza basata sull'AI generativa a un'ampia gamma di utenti, tra cui sviluppatori e data scientist. Per offrire un'esperienza di assistenza integrata, Gemini è integrato in molti prodotti Google Cloud.

Prima di iniziare

  1. Assicurati che Gemini sia configurato per il tuo account utente e il tuo progetto Google Cloud. Assicurati inoltre di aver installato il plug-in Cloud Code nell'IDE preferito. Se preferisci utilizzare l'editor di Cloud Shell o Cloud Workstations come IDE, Cloud Code e Gemini Code Assist sono già disponibili per impostazione predefinita.
  2. Attiva Google Kubernetes Engine API.

    Abilita l'API

  3. Nella console Google Cloud, attiva Cloud Shell.

    Attiva Cloud Shell

    Nella parte inferiore della console Google Cloud viene avviata una sessione di Cloud Shell che mostra un prompt della riga di comando. Cloud Shell è un ambiente shell con Google Cloud CLI già installato e con valori già impostati per il progetto attuale. L'inizializzazione della sessione può richiedere alcuni secondi.

  4. Crea un cluster GKE utilizzando il comando gcloud container clusters create:

    gcloud container clusters create test --region us-central1
    

    L'esecuzione del comando richiede alcuni minuti. L'output è simile al seguente:

    Creating cluster test in us-central1... Cluster is being health-checked (master is healthy)...done.
    
    Created https://container.googleapis.com/v1/projects/agmsb-gke-lab/zones/us-central1/clusters/test.
    
    To inspect the contents of your cluster, go to: https://console.cloud.google.com/kubernetes/workload_/gcloud/us-central1/test?project=agmsb-gke-lab
    kubeconfig entry generated for test.
    
    NAME: test
    LOCATION: us-central1
    MASTER_VERSION: 1.27.3-gke.100
    MASTER_IP: 34.72.99.149
    MACHINE_TYPE: e2-medium
    NODE_VERSION: 1.27.3-gke.100
    NUM_NODES: 9
    STATUS: RUNNING
    
  5. Clona un repository e utilizza kubectl per eseguire il deployment di un set di microservizi che costituiscono un'app web di e-commerce nel cluster GKE:

    git clone https://github.com/GoogleCloudPlatform/microservices-demo && cd microservices-demo
    
    kubectl apply -f ./release/kubernetes-manifests.yaml
    
  6. Dopo qualche minuto, recupera l'indirizzo IP esterno per accedere alla tua app web da un browser:

    kubectl get service frontend-external | awk '{print $4}'
    

Comprendi i log per i carichi di lavoro in GKE

Nell'esempio seguente, considera di essere un DevOps Engineer con il compito di ereditare un set esistente di microservizi in esecuzione in un cluster GKE. Per comprendere l'ambiente, decidi di esaminare i log dei vari microservizi.

Nel tuo IDE integrato di Code Assist preferito, puoi chattare con Gemini per ricevere assistenza. Nel riquadro Gemini, inserisci i messaggi, ovvero domande o istruzioni che descrivono l'aiuto che cerchi, e Gemini restituisce le risposte.

Gemini non utilizza i tuoi prompt o le sue risposte come dati per addestrare i suoi modelli. Per maggiori informazioni, consulta In che modo Gemini per Google Cloud utilizza i tuoi dati.

Sai che il deployment dei microservizi è stato eseguito nello spazio dei nomi default. Per chiedere a Gemini di aiutarti a esaminare i log:

  1. Nella barra delle attività dell'IDE, fai clic su chat_spark Gemini Code Assist per aprire il riquadro Gemini Code Assist.

  2. Nel riquadro Gemini Code Assist, inserisci il seguente prompt:

    How can I write a Cloud Logging query to search for logs from Pods in
    a namespace called "default" in a Google Kubernetes Engine cluster named "test"?
    

    Gemini restituisce una risposta simile alla seguente:

    To write a Cloud Logging query to search for logs from Pods in a
    namespace called "default" in GKE cluster called "test", you
    can use the following query:
    
    resource.type="k8s_container"
    resource.labels.namespace_name="default"
    resource.labels.cluster_name="test"
    
    This query will search for all logs from Pods in the "default"
    namespace in the "test" GKE cluster. You can also use the
    Cloud Logging console to search for logs from Pods in a specific
    namespace and cluster. To do this, follow these steps:
    
    1. Go to the Cloud Logging console.
    2. In the Query builder pane, click
       Resource.
    3. In the Resource type list, select Kubernetes
       Container.
    4. In the Namespace name field, enter default.
    5. In the Cluster name field, enter test.
    6. Click Add.
    7. In the Query results pane, you will see a list of logs
       from Pods in the "default" namespace in the "test" GKE
       cluster.
    
  3. Per esaminare questi log, fai clic su ogni log restituito dalla query. In un singolo log, se fai clic su Spiega questa query, la risposta è simile alla seguente:

    Sure. Here are the bullet points that explain the log entry:
    
    • The log entry is about a GET request to the /_healthz path.
    • The request was successful and returned a 200 status code.
    • The request took 0 milliseconds to complete.
    • The request was made by the x-liveness-probe session.
    • The request was made from the frontend-755cdc7957-pv8x5 pod
      in the default namespace.
    

Crea un ambiente di build privato per le immagini container

Ora che conosci meglio i carichi di lavoro derivanti dall'osservazione dei log, decidi di configurare l'infrastruttura e creare le future immagini dei container del tuo team su un insieme di worker privati. In questa sezione, verrà chiesto a Gemini di aiutarti a comprendere come eseguire un ambiente di compilazione in modo da poter eseguire la migrazione delle build al tuo progetto Google Cloud.

  1. Nella barra delle attività dell'IDE, fai clic su chat_spark Gemini Code Assist per aprire il riquadro Gemini Code Assist.

  2. Nel riquadro Gemini Code Assist, inserisci il seguente prompt:

    How can I build a private build environment that is not connected to
    the internet in Google Cloud? I want to be able to use Docker to
    build my container images in this environment.
    

    Gemini restituisce una risposta simile alla seguente:

    To build a private build environment that is not connected to the internet
    in Google Cloud, you can use a Cloud Build private pool. A private pool
    is a group of build workers that are not connected to the public internet.
    You can create a private pool in a Virtual Private Cloud (VPC) network,
    which provides an additional layer of security for your build environment.
    
    To create a private pool, you will need to:
    
    1. Create a VPC network.
    2. Create a private pool in the VPC network.
    3. Configure your build config file to use the private pool.
    
    Once you have created a private pool, you can use it to build your
    container images using Docker. To do this, you will need to:
    
    1. Create a Dockerfile.
    2. Create a build config file.
    3. Run the `gcloud builds submit` command.
    
    The `gcloud builds submit` command will build your container image
    using the private pool.
    
    Find more information for your question here:
    
    • https://cloud.google.com/build/docs/private-pools/create-manage-private-pools
    
  3. I pool privati di Cloud Build sembrano un percorso attuabile, quindi chiedi a Gemini di aiutarti a creare il tuo primo pool privato. Digita il seguente prompt:

    Can you give me a gcloud command to create my first Cloud Build
    private worker pool?
    

    Gemini restituisce una risposta simile alla seguente:

    Here's how you can create your first private worker pool using the gcloud
    command:
    
    1. Define your pool configuration:
    
    First, you need to define the configuration of your private pool. This
    includes details like the pool name, region, machine type, disk size, and
    network settings. You can do this by creating a JSON file named
    workerpool.json with the following structure:
    
    {
      "name": "my-first-privatepool",
      "location": "us-central1",
      "machineType": "e2-standard-2",
      "diskSizeGb": 800,
      "network": "projects/your-project-id/global/networks/default",
      "assignExternalIP": true
    }
    
    2. Create the pool using gcloud:
    
    Once you have the configuration file ready, you can use the following gcloud
    command to create the private worker pool:
    
    gcloud builds worker-pools create \
      --project=gsm-project-382212 \
      --location=us-central1 \
      --worker-pool-id=my-first-privatepool \
      --file=workerpool.json
    
    Explanation of the command:
    
    - gcloud builds worker-pools create : This is the command to create a new worker pool.
    - --project=gsm-project-382212 : This specifies the project ID where you want to create the pool.
    - --location=us-central1 : This specifies the region where you want to create the pool.
    - --worker-pool-id=my-first-privatepool : This specifies the ID for your private pool.
    - --file=workerpool.json : This specifies the path to your configuration file.
    
    3. Verify the pool creation:
    
    After running the command, you can verify that the pool has been created by
    running the following command:
    
    gcloud builds worker-pools list
    
    Additional notes:
    
    - You can customize the configuration file to meet your specific needs. For
    example, you can change the machine type, disk size, or network settings.
    - You can also create private worker pools using the Cloud Build API or th
     Cloud Console.
    
    I hope this helps! Let me know if you have any other questions.
    
  4. Dalla risposta precedente, sembra che sia necessario passare un file di configurazione per sostituire la variabile PRIVATEPOOL_CONFIG_FILE, quindi richiedi a Gemini di aiutarti a creare un file di configurazione. Digita il seguente prompt:

    Can you show me an example of a Cloud Build private pool config file?
    

    Gemini restituisce una risposta simile alla seguente:

    Sure. Here is an example of a Cloud Build private pool config file:
    
    privatePoolV1Config:
       networkConfig:
         egressOption: NO_PUBLIC_EGRESS<br>
         peeredNetwork: 'projects/my-project/global/networks/my-network'
         peeredNetworkIpRange: '10.1.2.0/24'
       workerConfig:
         diskSizeGb: '100'
         machineType: 'e2-standard-4'
    
    This config file creates a private pool with the following
    properties:
    
    • The pool is not connected to the public internet.
    • The pool is connected to the `my-network` VPC network.
    • The pool's workers have a `100GB` boot disk and a
      `e2-standard-4` machine type.
    
    For more information, see the Cloud Build documentation.
    
  5. Inizierai a creare il tuo file di configurazione in cui i worker di build non hanno accesso alla rete internet pubblica. Vai alla console Google Cloud e avvia l'editor di Cloud Shell.

  6. In Cloud Shell, esegui questo comando, impostando egressOption su NO_PUBLIC_EGRESS:

    cat << EOF >> cloudbuild-privatepool-config.yaml
    
    privatePoolV1Config:
      networkConfig:
        egressOption: NO_PUBLIC_EGRESS
    
    EOF
    
  7. Non sai con certezza quali altre opzioni sono disponibili nel file di configurazione, quindi chiedi a Gemini di aiutarti:

    Is there a default value for any of these options?
    

    Gemini restituisce una risposta simile alla seguente:

    Yes, there are default values for some of the options in the private
    pool config file. For example, the default value for egressOption is
    ALLOW_PUBLIC_EGRESS, which means that the private pool will have
    access to the public internet. The default value for diskSizeGb is
    100, and the default value for machineType is e2-medium.
    
    For a full list of the default values, see the Cloud Build documentation.
    
  8. Gemini fornisce alcuni dei valori predefiniti già impostati nel file di configurazione e, dopo aver letto la documentazione, determina che il file di configurazione è di qualità com'è. In Cloud Shell, passa il comando gcloud che Gemini ha fornito in precedenza nel file di configurazione appena creato:

    gcloud builds worker-pools create max-pool-test \
        --config-from-file cloudbuild-privatepool-config.yaml \
        --region us-central1
    
  9. Dopo aver creato i worker, ti rendi conto che i container non avranno accesso ai gestori di pacchetti pubblici, come pip. Vuoi confermare che hai compreso l'hosting di pacchetti privati. Inserisci la seguente richiesta:

    If I create a private pool with NO_PUBLIC_EGRESS enabled, can I use
    Artifact Registry to host my packages privately and access them from
    a private pool?
    

    Gemini restituisce una risposta simile alla seguente:

    Yes, you can use Artifact Registry to host your packages privately
    and access them from a private pool. To do this, you will need to
    create a private pool with NO_PUBLIC_EGRESS enabled and then
    configure your Artifact Registry repository to use the private pool.
    For more information, see the Cloud Build documentation.
    
  10. Decidi di procedere con la creazione di un repository Artifact Registry. Nel riquadro Gemini, inserisci il seguente prompt:

    How can I use gcloud to create a private Docker repository for
    container images in Artifact Registry?
    

    Gemini restituisce una risposta simile alla seguente:

    To create a private Docker repository for container images in
    Artifact Registry, you can use the following command:
    
    gcloud artifacts repositories create REPOSITORY_NAME \\\
        --repository-format=docker \\\
        --location=LOCATION \\\
        --description="DESCRIPTION" \\\
        --kms-key=KMS_KEY
    
    Where:
    
    • REPOSITORY_NAME is the name of your repository.
    • LOCATION is the location of your repository.
    • DESCRIPTION is a description of your repository.
    • KMS_KEY is the name of your Cloud Key Management Service key that
      you want to use to encrypt your repository data.
    
    For more information, see the gcloud artifacts repositories create
    documentation.
    

  11. Se visualizzi la variabile KMS_KEY, ti rendi conto di non aver ancora creato una chiave Cloud KMS. Digita il seguente prompt:

    Do I need a KMS_KEY?
    

    Gemini restituisce una risposta simile alla seguente:

    No, you don't need a KMS_KEY to create a private Docker repository
    for container images in Artifact Registry. However, if you want to
    encrypt your container images, you can use a Cloud Key Management Service key. For more
    information, see the Artifact Registry CMEK documentation.
    
  12. Dopo aver risposto alle domande, in Cloud Shell esegui il comando gcloud che Gemini ti ha fornito:

    gcloud artifacts repositories create max-docker-repo-test \
        --repository-format=docker \
        --location=us-central1 \
        --description="test container repository"
    

Con l'assistenza di Gemini, hai creato correttamente un set privato di worker e il repository privato per creare e ospitare i tuoi artefatti.

Esegui la pulizia

Per evitare che al tuo account Google Cloud vengano addebitati costi relativi alle risorse utilizzate in questo tutorial, puoi eliminare il progetto Google Cloud che hai creato per questo tutorial. In alternativa, puoi eliminare le singole risorse.

  1. Nella console Google Cloud, vai alla pagina Gestisci risorse.

    Vai a Gestisci risorse

  2. Nell'elenco dei progetti, seleziona il progetto che vuoi eliminare, quindi fai clic su Elimina.
  3. Nella finestra di dialogo, digita l'ID del progetto e fai clic su Chiudi per eliminare il progetto.

Passaggi successivi