Este tutorial descreve como pode verificar se a sua infraestrutura como código (IaC) não viola as políticas da organização nem os detetores do Security Health Analytics.
Objetivos
- Crie uma postura de segurança.
- Implemente a postura num projeto.
- Verifique um ficheiro Terraform de exemplo quanto a violações.
- Corrija as violações no ficheiro Terraform e verifique novamente o ficheiro para validar a correção.
Antes de começar
Configure as autorizações
-
Make sure that you have the following role or roles on the organization: Project Creator and Security Posture Admin
Check for the roles
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the organization.
-
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.
- 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
-
In the Google Cloud console, go to the IAM page.
Aceder ao IAM - Selecione a organização.
- Clique em Conceder acesso.
-
No campo Novos responsáveis, introduza o identificador do utilizador. Normalmente, este é o endereço de email de uma Conta Google.
- Na lista Selecionar uma função, selecione uma função.
- Para conceder funções adicionais, clique em Adicionar outra função e adicione cada função adicional.
- Clique em Guardar.
Configure o Cloud Shell
-
In the Google Cloud console, 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.
- Encontre o ID da sua organização:
gcloud organizations list
- 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.
-
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 theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
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 theserviceusage.services.enable
permission. Learn how to grant roles. -
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 theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
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 theserviceusage.services.enable
permission. Learn how to grant roles. - Copie o número do projeto. Precisa do número do projeto para definir o recurso de destino ao implementar a postura.
gcloud projects describe PROJECT_ID
- Inicialize o Terraform:
terraform init
No Cloud Shell, inicie o editor do Cloud Shell. Para iniciar o editor, clique em
Abrir editor na barra de ferramentas da janela do Cloud Shell.
Crie um ficheiro YAML com o nome
example-standard.yaml
.Cole o seguinte código no ficheiro:
No Cloud Shell, crie a postura:
gcloud scc postures create organizations/ORGANIZATION_ID/locations/global/postures/example-standard --posture-from-file=example-standard.yaml
Copie o ID de revisão da postura que o comando gera.
Implemente a postura no seu 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 o seguinte:
ORGANIZATION_ID
: o ID da sua organização.POSTURE REVISION_ID
: o ID de revisão da sua postura que copiou.PROJECT_NUMBER
: o número do seu projeto.
No Cloud Shell, inicie o editor do Cloud Shell.
Crie um ficheiro do Terraform denominado
main.tf
.Cole o seguinte código no ficheiro:
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 criou.No Cloud Shell, crie o ficheiro de plano do Terraform e converta-o para o formato JSON:
terraform plan -out main.plan terraform show -json main.plan > mainplan.json
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
Este comando devolve um relatório de validação de IaC que descreve as seguintes violações:
- O valor
mtu
paraexample_network
não é 1000. - O valor
initial_node_count
paraexample_node_pool
não é 3. - O
example_bucket
não tem o acesso uniforme ao nível do contentor ativado. - O
example_bucket
não tem o registo ativado.
- O valor
No Cloud Shell, inicie o editor do Cloud Shell.
Atualize o ficheiro
main.tf
com as seguintes alterações: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 projeto que criou.No Cloud Shell, crie o ficheiro de plano do Terraform e converta-o para o formato JSON:
terraform plan -out main.plan terraform show -json main.plan > mainplan.json
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
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
- Reveja Valide a sua IaC relativamente às políticas da sua organização.
- Explore arquiteturas de referência, diagramas e práticas recomendadas sobre o Google Cloud. Consulte o nosso Centro de arquitetura na nuvem.
Prepare o ambiente
Crie e implemente uma postura
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
Substitua
ORGANIZATION_ID
pelo ID da sua organização.Crie o ficheiro Terraform e valide-o
Resolva violações
Limpar
Para evitar incorrer em custos na sua conta do Google Cloud pelos recursos usados neste tutorial, elimine o projeto que contém os recursos ou mantenha o projeto e elimine os recursos individuais.
Elimine o projeto
O que se segue?
-