Crea un informe de validación de IaC de muestra

En este instructivo, se describe cómo puedes verificar que tu infraestructura como código (IaC) no incumpla las políticas de tu organización ni los detectores de Security Health Analytics.

Prepare el entorno

  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. Si usas un proveedor de identidad externo (IdP), primero debes acceder a gcloud CLI con tu identidad federada.

  4. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    gcloud init
  5. Create or select 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.
    • 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. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Security posture service and Security Command Center management 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.

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

  9. Si usas un proveedor de identidad externo (IdP), primero debes acceder a gcloud CLI con tu identidad federada.

  10. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    gcloud init
  11. Create or select 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.
    • 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. Verify that billing is enabled for your Google Cloud project.

  13. Enable the Security posture service and Security Command Center management 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.

    gcloud services enable securityposture.googleapis.com  securitycentermanagement.googleapis.com
  14. Copia el número del proyecto. Necesitarás el número de proyecto para establecer el recurso de destino cuando implementes la postura.
    gcloud projects describe PROJECT_ID
  15. Inicializa Terraform mediante este comando:
    terraform init
  16. Crea e implementa una postura

    1. En Cloud Shell, inicia el editor de Cloud Shell. Para iniciar el editor, haz clic en Botón del editor de código Abrir editor en la barra de herramientas de la ventana de Cloud Shell.

    2. Crea un archivo YAML llamado example-standard.yaml.

    3. Pega el siguiente código en tu archivo:

    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

    Reemplaza ORGANIZATION_ID por el ID de tu organización.

    1. En 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 el ID de revisión de la postura que genera el comando.

    3. Implementa la postura en tu proyecto:

      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
      

      Reemplaza lo siguiente:

      • ORGANIZATION_ID: Es el ID de tu organización.
      • POSTURE REVISION_ID: Es el ID de revisión de la postura que copiaste.
      • PROJECT_NUMBER: Es el número de tu proyecto.

    Crea el archivo de Terraform y valídalo

    1. En Cloud Shell, inicia el editor de Cloud Shell.

    2. Crea un archivo de Terraform llamado main.tf.

    3. Pega el siguiente código en tu archivo:

      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
      }
      

      Reemplaza PROJECT_ID por el ID del proyecto que creaste.

    4. En Cloud Shell, crea el archivo de plan de Terraform y conviértelo al formato JSON:

      terraform plan -out main.plan
      terraform show -json main.plan > mainplan.json
      
    5. Crea el informe de validación de IaC para mainplan.json:

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

      Este comando devuelve un informe de validación de IaC que describe los siguientes incumplimientos:

      • El valor de mtu para example_network no es 1,000.
      • El initial_node_count de example_node_pool no es 3.
      • El example_bucket no tiene habilitado el acceso uniforme a nivel del bucket.
      • El example_bucket no tiene habilitado el registro.

    Resuelve incumplimientos

    1. En Cloud Shell, inicia el editor de Cloud Shell.

    2. Actualiza el archivo main.tf con los siguientes cambios:

      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
        }
      }
      

      Reemplaza PROJECT_ID por el ID del proyecto que creaste.

    3. En Cloud Shell, crea el archivo de plan de Terraform y conviértelo al formato JSON:

      terraform plan -out main.plan
      terraform show -json main.plan > mainplan.json
      
    4. Vuelve a crear el informe de validación de IaC para mainplan.json:

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