Criar um exemplo de relatório de validação de IaC


Este tutorial descreve como verificar se a infraestrutura como código (IaC) não viola as políticas da sua organização ou os detectores da Análise de integridade de segurança.

Objetivos

  • Crie uma postura de segurança.
  • Implantar a postura em um projeto.
  • Verifique se há violações em um arquivo do Terraform de exemplo.
  • Corrija as violações no arquivo do Terraform e verifique o arquivo novamente a correção.

Antes de começar

Configurar permissões

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

      Acessar o IAM
    2. Selecionar uma organização.
    3. Clique em CONCEDER ACESSO.
    4. No campo Novos principais, insira seu identificador de usuário. Normalmente, é o endereço de e-mail de uma Conta do Google.

    5. Na lista Selecionar um papel, escolha um.
    6. Para conceder outros papéis, clique em Adicionar outro papel e adicione cada papel adicional.
    7. Clique em Salvar.

    Configurar o 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. Encontre o ID da sua organização:
      gcloud organizations list

Prepare o 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. To initialize the gcloud CLI, run the following command:

    gcloud init
  4. 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.

  5. Verifique se a cobrança está ativada para o seu projeto do Google Cloud.

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

    gcloud services enable securityposture.googleapis.com  securitycentermanagement.googleapis.com
  7. Install the Google Cloud CLI.
  8. To initialize the gcloud CLI, run the following command:

    gcloud init
  9. 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.

  10. Verifique se a cobrança está ativada para o seu projeto do Google Cloud.

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

    gcloud services enable securityposture.googleapis.com  securitycentermanagement.googleapis.com
  12. Copie o número do projeto. Você vai precisar do número do projeto para definir o recurso de destino durante a implantação da postura.
    gcloud projects describe PROJECT_ID
  13. Inicialize o Terraform:
    terraform init

Criar e implantar uma postura

  1. No Cloud Shell, inicie o Cloud Shell Editor. Para iniciar o editor, clique em Botão "Editor de código" Abrir o Editor na barra de ferramentas da janela do Cloud Shell.

  2. Crie um arquivo YAML chamado example-standard.yaml.

  3. Cole o código a seguir no arquivo:

    name: organizations/ORGANIZATION_ID/locations/global/postures/example-standard
    state: ACTIVE
    policySets:
    - policySetId: policySet1
    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

    SubstituaORGANIZATION_ID pelo ID da organização.

  4. No Cloud Shell, crie a postura:

    gcloud scc postures create organizations/ORGANIZATION_ID/locations/global/postures/example-standard --posture-from-file=example-standard.yaml
    
  5. Copie o ID da revisão de postura gerado pelo comando.

  6. Implante a postura no projeto:

    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
    

    Substitua:

    • ORGANIZATION_ID: o código da sua organização.
    • POSTURE REVISION_ID: o ID da revisão de postura que você copiou.
    • PROJECT_NUMBER: o número do projeto.

Crie o arquivo do Terraform e valide-o

  1. No Cloud Shell, inicie o Cloud Shell Editor.

  2. Crie um arquivo do Terraform chamado main.tf.

  3. Cole o código a seguir no arquivo:

    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
    }
    

    Substitua PROJECT_ID pelo ID do projeto. que você criou.

  4. No Cloud Shell, crie o arquivo de plano do Terraform e o converta para o formato JSON:

    terraform plan -out main.plan
    terraform show -json main.plan > mainplan.json
    
  5. Crie o relatório de validação de IaC para mainplan.json:

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

    Esse comando retorna um relatório de validação de IaC que descreve as seguintes violações:

    • O mtu de example_network não é 1.000.
    • O initial_node_count de example_node_pool não é 3.
    • O example_bucket não tem acesso uniforme no nível do bucket ativado.
    • O example_bucket não tem a geração de registros ativada.

Resolver violações

  1. No Cloud Shell, inicie o editor.

  2. Atualize o arquivo main.tf com as seguintes mudanças:

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

    Substitua PROJECT_ID pelo ID do projeto do do projeto que você criou.

  3. No Cloud Shell, crie o arquivo de plano do Terraform e o converta para o formato JSON:

    terraform plan -out main.plan
    terraform show -json main.plan > mainplan.json
    
  4. Recrie o relatório de validação de IaC para mainplan.json:

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

Limpar

Para evitar cobranças na sua conta do Google Cloud pelos recursos usados no tutorial, exclua o projeto que os contém ou mantenha o projeto e exclua os recursos individuais.

Exclua o projeto

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

A seguir