Créer un exemple de rapport de validation IaC


Ce tutoriel explique comment vérifier que votre infrastructure (IaC) n'enfreint pas vos règles d'administration ni vos détecteurs Security Health Analytics.

Objectifs

  • Créez une stratégie de sécurité.
  • Déployer la stratégie sur un projet
  • Recherchez les cas de non-respect dans un exemple de fichier Terraform.
  • Corrigez les cas de non-respect dans le fichier Terraform, puis vérifiez à nouveau le fichier pour vérifier la correction.

Avant de commencer

Configurer les autorisations

  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.

      Accéder à IAM
    2. Sélectionnez l'organisation.
    3. Cliquez sur Accorder l'accès.
    4. Dans le champ Nouveaux comptes principaux, saisissez votre identifiant utilisateur. Il s'agit généralement de l'adresse e-mail d'un compte Google.

    5. Dans la liste Sélectionner un rôle, sélectionnez un rôle.
    6. Pour attribuer des rôles supplémentaires, cliquez sur Ajouter un autre rôle et ajoutez chaque rôle supplémentaire.
    7. Cliquez sur Enregistrer.

    Configurer 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. Recherchez votre ID d'organisation:
      gcloud organizations list

Préparer l'environnement

  1. Connectez-vous à votre compte Google Cloud. Si vous débutez sur Google Cloud, créez un compte pour évaluer les performances de nos produits en conditions réelles. Les nouveaux clients bénéficient également de 300 $ de crédits gratuits pour exécuter, tester et déployer des charges de travail.
  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. Make sure that billing is enabled for your Google Cloud project.

  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. Make sure that billing is enabled for your Google Cloud project.

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

    gcloud services enable securityposture.googleapis.com  securitycentermanagement.googleapis.com
  12. Copiez le numéro du projet. Vous aurez besoin du numéro de projet pour définir la ressource cible lors du déploiement de la stratégie.
    gcloud projects describe PROJECT_ID
  13. Initialisez Terraform :
    terraform init

Créer et déployer une stratégie

  1. Dans Cloud Shell, lancez l'éditeur Cloud Shell. Pour lancer la éditeur, cliquez sur Bouton Éditeur de code Ouvrez l'éditeur dans la barre d'outils de la fenêtre Cloud Shell.

  2. Créez un fichier YAML nommé example-standard.yaml.

  3. Collez le code suivant dans votre fichier:

    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

    Remplacez ORGANIZATION_ID par votre ID d'organisation.

  4. Dans Cloud Shell, créez la stratégie:

    gcloud scc postures create organizations/ORGANIZATION_ID/locations/global/postures/example-standard --posture-from-file=example-standard.yaml
    
  5. Copiez l'ID de révision de stratégie généré par la commande.

  6. Déployez la stratégie dans votre projet:

    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
    

    Remplacez les éléments suivants :

    • ORGANIZATION_ID : ID de votre organisation
    • POSTURE REVISION_ID : ID de la révision de la posture que vous avez copiée.
    • PROJECT_NUMBER : votre numéro de projet.

Créer le fichier Terraform et valider

  1. Dans Cloud Shell, lancez l'éditeur Cloud Shell.

  2. Créez un fichier Terraform nommé main.tf.

  3. Collez le code suivant dans votre fichier:

    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
    }
    

    Remplacez PROJECT_ID par l'ID du projet. que vous avez créé.

  4. Dans Cloud Shell, créez le fichier de plan Terraform et convertissez-le au format JSON:

    terraform plan -out main.plan
    terraform show -json main.plan > mainplan.json
    
  5. Créez le rapport de validation IaC pour mainplan.json:

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

    Cette commande renvoie un rapport de validation de la gestion des accès et des identités qui décrit les cas de non-respect suivants :

    • La valeur de mtu pour example_network n'est pas 1 000.
    • La valeur de initial_node_count pour example_node_pool n'est pas de 3.
    • L'accès uniforme au niveau du bucket n'est pas activé pour example_bucket.
    • La journalisation n'est pas activée pour example_bucket.

Résoudre les cas de violation

  1. Dans Cloud Shell, lancez l'éditeur Cloud Shell.

  2. Mettez à jour le fichier main.tf avec les modifications suivantes :

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

    Remplacez PROJECT_ID par l'ID du projet que vous avez créé.

  3. Dans Cloud Shell, créez le fichier de plan Terraform et convertissez-le en Format JSON:

    terraform plan -out main.plan
    terraform show -json main.plan > mainplan.json
    
  4. Recréez le rapport de validation de l'IaC pour mainplan.json :

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

Effectuer un nettoyage

Pour éviter que les ressources utilisées lors de ce tutoriel soient facturées sur votre compte Google Cloud, supprimez le projet contenant les ressources, ou conservez le projet et supprimez les ressources individuelles.

Supprimer le projet

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

Étape suivante