Crear un informe de validación de IaC de ejemplo


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

Objetivos

  • Crea una postura de seguridad.
  • Implementa la postura en un proyecto.
  • Comprobar si hay infracciones en un archivo de Terraform de ejemplo.
  • Corrige las infracciones en el archivo de Terraform y vuelve a comprobarlo para verificar la corrección.

Antes de empezar

Configurar permisos

  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.

      Ir a IAM
    2. Selecciona la organización.
    3. Haz clic en Conceder acceso.
    4. En el campo Nuevos principales, introduce tu identificador de usuario. Normalmente, se trata de la dirección de correo de una cuenta de Google.

    5. En la lista Selecciona un rol, elige un rol.
    6. Para conceder más roles, haz clic en Añadir otro rol y añade cada rol adicional.
    7. Haz clic en Guardar.

    Configurar 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. Para encontrar el ID de tu organización, sigue estos pasos:
      gcloud organizations list
    3. Preparar 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. 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 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.

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

        Enable the APIs

      8. Copia el número de proyecto. Necesitará el número de proyecto para definir el recurso de destino al implementar la postura.
        gcloud projects describe PROJECT_ID
      9. Inicializa Terraform:
        terraform init
      10. Crear y desplegar una postura

        1. En Cloud Shell, inicia el editor de Cloud Shell. Para iniciar el editor, haz clic en Botón 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

        Sustituye 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
          

          Haz los cambios siguientes:

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

        Crear el archivo de Terraform y validarlo

        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
          }
          

          Sustituye PROJECT_ID por el ID del proyecto que has creado.

        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 las siguientes infracciones:

          • El mtu de example_network no es 1000.
          • El initial_node_count de example_node_pool no es 3.
          • El example_bucket no tiene habilitado el acceso uniforme a nivel de segmento.
          • El example_bucket no tiene habilitado el registro.

        Resolver infracciones

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

          Sustituye PROJECT_ID por el ID del proyecto que has creado.

        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
          

      Limpieza

      Para evitar que los recursos utilizados en este tutorial se cobren en tu cuenta de Google Cloud, elimina el proyecto que contiene los recursos o conserva el proyecto y elimina los recursos.

      Eliminar el proyecto

      1. In the Google Cloud console, go to the Manage resources page.

        Go to Manage resources

      2. In the project list, select the project that you want to delete, and then click Delete.
      3. In the dialog, type the project ID, and then click Shut down to delete the project.

      Siguientes pasos