Creare un report di convalida IaC di esempio


Questo tutorial descrive come verificare che la tua infrastruttura come codice (IaC) non violi le norme dell'organizzazione o i rilevatori di Security Health Analytics.

Obiettivi

  • Crea una postura di sicurezza.
  • Esegui il deployment della postura su un progetto.
  • Controlla un file Terraform di esempio per rilevare violazioni.
  • Correggi le violazioni nel file Terraform e controllalo di nuovo per verificare la correzione.

Prima di iniziare

Configurare le autorizzazioni

  1. Make sure that you have the following role or roles on the organization: Project Creator and Security Posture Admin

    Check for the roles

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

      Go to IAM
    2. Select the organization.
    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 l'organizzazione.
    3. Fai clic su Concedi l'accesso.
    4. Nel campo Nuove entità, inserisci il tuo identificatore 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.

    Configura Cloud Shell

    1. In the Google Cloud console, activate Cloud Shell.

      Activate Cloud Shell

      At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

    2. Trova l'ID organizzazione:
      gcloud organizations list

Prepara l'ambiente

  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. Install the Google Cloud CLI.

  3. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  4. To initialize the gcloud CLI, run the following command:

    gcloud init
  5. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

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

  7. Enable the Security posture service and Security Command Center management APIs:

    gcloud services enable securityposture.googleapis.com  securitycentermanagement.googleapis.com
  8. Install the Google Cloud CLI.

  9. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  10. To initialize the gcloud CLI, run the following command:

    gcloud init
  11. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

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

  13. Enable the Security posture service and Security Command Center management APIs:

    gcloud services enable securityposture.googleapis.com  securitycentermanagement.googleapis.com
  14. Copia il numero del progetto. Per impostare la risorsa di destinazione durante il deployment della postura, avrai bisogno del numero di progetto.
    gcloud projects describe PROJECT_ID
  15. Inizializza Terraform:
    terraform init
  16. Creare ed eseguire il deployment di una postura

    1. In Cloud Shell, avvia l'editor di Cloud Shell. Per avviare l'editor, fai clic su Pulsante Editor di codice Apri editor sulla barra degli strumenti della finestra di Cloud Shell.

    2. Crea un file YAML denominato example-standard.yaml.

    3. Incolla il seguente codice nel file:

    name: organizations/ORGANIZATION_ID/locations/global/postures/example-standard
    state: ACTIVE
    policySets:
    - policies:
      - constraint:
          orgPolicyConstraintCustom:
            customConstraint:
              actionType: ALLOW
              condition: "resource.initialNodeCount == 3"
              description: Set initial node count to be exactly 3.
              displayName: fixedNodeCount
              methodTypes:
              - CREATE
              name: organizations/ORGANIZATION_ID/customConstraints/custom.fixedNodeCount
              resourceTypes:
              - container.googleapis.com/NodePool
            policyRules:
            - enforce: true
        policyId: fixedNodeCount
      - constraint:
          securityHealthAnalyticsCustomModule:
            config:
              customOutput: {}
              description: Set MTU for a network to be exactly 1000.
              predicate:
                expression: "!(resource.mtu == 1000)"
              recommendation: Only create networks whose MTU is 1000.
              resourceSelector:
                resourceTypes:
                - compute.googleapis.com/Network
              severity: HIGH
            displayName: fixedMTU
            moduleEnablementState: ENABLED
        policyId: fixedMTU
      - constraint:
          securityHealthAnalyticsModule:
            moduleEnablementState: ENABLED
            moduleName: BUCKET_POLICY_ONLY_DISABLED
        policyId: bucket_policy_only_disabled
      - constraint:
          securityHealthAnalyticsModule:
            moduleEnablementState: ENABLED
            moduleName: BUCKET_LOGGING_DISABLED
        policyId: bucket_logging_disabled
      policySetId: policySet1

    Sostituisci ORGANIZATION_ID con l'ID organizzazione.

    1. In Cloud Shell, crea la postura:

      gcloud scc postures create organizations/ORGANIZATION_ID/locations/global/postures/example-standard --posture-from-file=example-standard.yaml
      
    2. Copia l'ID revisione della postura generato dal comando.

    3. Esegui il deployment della postura nel tuo progetto:

      gcloud scc posture-deployments create organizations/ORGANIZATION_ID/locations/global/postureDeployments/example-standard \
      --posture-name=organizations/ORGANIZATION_ID/locations/global/postures/example-standard \
      --posture-revision-id="POSTURE_REVISION_ID" \
      --target-resource=projects/PROJECT_NUMBER
      

      Sostituisci quanto segue:

      • ORGANIZATION_ID: l'ID organizzazione.
      • POSTURE REVISION_ID: l'ID della revisione della postura che hai copiato.
      • PROJECT_NUMBER: il numero del progetto.

    Crea il file Terraform e convalidalo

    1. In Cloud Shell, avvia l'editor di Cloud Shell.

    2. Crea un file Terraform denominato main.tf.

    3. Incolla il seguente codice nel file:

      terraform {
        required_providers {
          google = {
            source  = "hashicorp/google"
          }
        }
      }
      
      provider "google" {
        region  = "us-central1"
        zone    = "us-central1-c"
      }
      
      resource "google_compute_network" "example_network"{
        name                            = "example-network-1"
        delete_default_routes_on_create = false
        auto_create_subnetworks         = false
        routing_mode                    = "REGIONAL"
        mtu                             = 100
        project                         = "PROJECT_ID"
      }
      
      resource "google_container_node_pool" "example_node_pool" {
        name               = "example-node-pool-1"
        cluster            = "example-cluster-1"
        project            = "PROJECT_ID"
        initial_node_count = 2
      
        node_config {
          preemptible  = true
          machine_type = "e2-medium"
        }
      }
      
      resource "google_storage_bucket" "example_bucket" {
        name          = "example-bucket-1"
        location      = "EU"
        force_destroy = true
      
        project = "PROJECT_ID"
      
        uniform_bucket_level_access = false
      }
      

      Sostituisci PROJECT_ID con l'ID del progetto che hai creato.

    4. In Cloud Shell, crea il file di piano Terraform e convertilo in formato JSON:

      terraform plan -out main.plan
      terraform show -json main.plan > mainplan.json
      
    5. Crea il report di convalida IaC per mainplan.json:

      gcloud scc iac-validation-reports create organizations/ORGANIZATION_ID/locations/global --tf-plan-file=mainplan.json
      

      Questo comando restituisce un report di convalida dell'infrastruttura come codice che descrive le seguenti violazioni:

      • Il valore di mtu per example_network non è 1000.
      • Il valore di initial_node_count per example_node_pool non è 3.
      • example_bucket non ha l'accesso uniforme a livello di bucket abilitato.
      • example_bucket non ha il logging abilitato.

    Risolvere le violazioni

    1. In Cloud Shell, avvia l'editor di Cloud Shell.

    2. Aggiorna il file main.tf apportando le seguenti modifiche:

      terraform {
        required_providers {
          google = {
            source  = "hashicorp/google"
          }
        }
      }
      
      provider "google" {
        region  = "us-central1"
        zone    = "us-central1-c"
      }
      
      resource "google_compute_network" "example_network"{
        name                            = "example-network-1"
        delete_default_routes_on_create = false
        auto_create_subnetworks         = false
        routing_mode                    = "REGIONAL"
        mtu                             = 1000
        project                         = "PROJECT_ID"
      }
      
      resource "google_container_node_pool" "example_node_pool" {
        name               = "example-node-pool-1"
        cluster            = "example-cluster-1"
        project            = "PROJECT_ID"
        initial_node_count = 3
      
        node_config {
          preemptible  = true
          machine_type = "e2-medium"
        }
      }
      
      resource "google_storage_bucket" "example_bucket" {
        name          = "example-bucket-1"
        location      = "EU"
        force_destroy = true
      
        project = "PROJECT_ID"
        uniform_bucket_level_access = true
      
        logging {
          log_bucket   = "my-unique-logging-bucket" // Create a separate bucket for logs
          log_object_prefix = "tf-logs/"             // Optional prefix for better structure
        }
      }
      

      Sostituisci PROJECT_ID con l'ID progetto del progetto che hai creato.

    3. In Cloud Shell, crea il file di piano Terraform e convertilo in formato JSON:

      terraform plan -out main.plan
      terraform show -json main.plan > mainplan.json
      
    4. Ricrea il report di convalida IaC per mainplan.json:

      gcloud scc iac-validation-reports create organizations/ORGANIZATION_ID/locations/global --tf-plan-file=mainplan.json
      

Esegui la pulizia

Per evitare che al tuo Account Google Cloud vengano addebitati costi relativi alle risorse utilizzate in questo tutorial, elimina il progetto che contiene le risorse oppure mantieni il progetto ed elimina le singole risorse.

Elimina il progetto

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

Passaggi successivi