arrow_back

Validating Policies for Terraform on Google Cloud

Acceder Unirse
Pon a prueba tus conocimientos y compártelos con nuestra comunidad
done
Obtén acceso a más de 700 labs prácticos, insignias de habilidad y cursos

Validating Policies for Terraform on Google Cloud

Lab 30 minutos universal_currency_alt 1 crédito show_chart Introductorio
info Es posible que este lab incorpore herramientas de IA para facilitar tu aprendizaje.
Pon a prueba tus conocimientos y compártelos con nuestra comunidad
done
Obtén acceso a más de 700 labs prácticos, insignias de habilidad y cursos

GSP1021

Google Cloud self-paced labs logo

Overview

In this lab, you will learn about the command gcloud beta terraform vet, referred as Validate through the rest of the lab. Validate is a tool for enforcing policy compliance as part of an infrastructure CI/CD pipeline. You can use Validate to detect policy violations and provide warnings or halt deployments before they reach production.

This lab will walk you through applying a constraint that enforces a domain restriction. You'll test that constraint and intentionally throw an error. You'll then modify the constraint so that your domain passes.

Objectives

In this lab, you will:

  • Apply a constraint that enforces a domain restriction
  • Test a constraint to intentionally throw a validation error
  • Modify the constraint so that it passes validation

Prerequisites

For this lab, you should have experience using Terraform. Check out the Automating Infrastructure on Google Cloud with Terraform skill badge quest for more hands-on practice with Terraform.

Setup and Requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Cloud console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details panel.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details panel.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To view a menu with a list of Google Cloud products and services, click the Navigation menu at the top-left. Navigation menu icon

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your Project_ID, . The output contains a line that declares the Project_ID for this session:

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

Output:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Validate a constraint

To see how a constraint is implemented, you'll copy an existing constraint, provide a test case that fails validation, and then modify the constraint so that it passes.

Copy the constraint

  1. Open a new Cloud Shell window and run the following command to clone the policy library repository.
git clone https://github.com/GoogleCloudPlatform/policy-library.git
  1. At the command prompt, enter the following to copy over the sample IAM domain restriction constraint:
cd policy-library/ cp samples/iam_service_accounts_only.yaml policies/constraints
  1. Examine the constraint you copied by printing it to the terminal.
cat policies/constraints/iam_service_accounts_only.yaml

The output looks like this:

# This constraint checks that all IAM policy members are in the # "gserviceaccount.com" domain. apiVersion: constraints.gatekeeper.sh/v1alpha1 kind: GCPIAMAllowedPolicyMemberDomainsConstraintV2 metadata: name: service_accounts_only annotations: description: Checks that members that have been granted IAM roles belong to allowlisted domains. spec: severity: high match: target: # {"$ref":"#/definitions/io.k8s.cli.setters.target"} - "organizations/**" parameters: domains: - gserviceaccount.com

Notice the highlighted section at the bottom. This specifies that only members from the gserviceaccount.com domain can be present in an IAM policy.

Test the constraint

  1. To verify that the policy works as expected, you'll create a Terraform file within the current directory.
touch main.tf
  1. On the Cloud Shell toolbar, click Open Editor. To switch between Cloud Shell and the code editor, click Open Editor or Open Terminal as required, or click Open in new window to leave the Editor open in a separate tab.

  2. Open the policy-library/main.tf file and copy the following code into it:

terraform { required_providers { google = { source = "hashicorp/google" version = "~> 3.84" } } } resource "google_project_iam_binding" "sample_iam_binding" { project = "<YOUR PROJECT ID>" role = "roles/viewer" members = [ "user:<USER>" ] }
  1. Replace <YOUR PROJECT ID> with .

  2. Replace <USER> with .

  3. Next, navigate back to the terminal and run the following command to initialize Terraform:

terraform init
  1. Run the following command to export the Terraform plan. If asked, click Authorize when prompted.
terraform plan -out=test.tfplan
  1. Convert the Terraform plan to JSON.
terraform show -json ./test.tfplan > ./tfplan.json
  1. Install the Terraform Tools component.
sudo apt-get install google-cloud-sdk-terraform-tools
  1. Run the following command to validate that your Terraform plan complies with your policies.
gcloud beta terraform vet tfplan.json --policy-library=. Note: you can ignore any warnings about retrieving your Project ID.

Since the email address you provided in the IAM policy binding does not belong to a service account, the plan violates the constraint you set up. Your output should resemble the following:

constraint: GCPIAMAllowedPolicyMemberDomainsConstraintV2.service_accounts_only constraint_config: api_version: constraints.gatekeeper.sh/v1alpha1 kind: GCPIAMAllowedPolicyMemberDomainsConstraintV2 metadata: annotations: description: Checks that members that have been granted IAM roles belong to allowlisted domains. validation.gcp.forsetisecurity.org/originalName: service_accounts_only validation.gcp.forsetisecurity.org/yamlpath: policies/constraints/iam_service_accounts_only.yaml name: service-accounts-only spec: match: target: - organizations/** parameters: domains: - gserviceaccount.com severity: high message: 'IAM policy for //cloudresourcemanager.googleapis.com/projects/qwiklabs-gcp-02-ec89de7c9f9d contains member from unexpected domain: user:student-02-0edcb8aed69f@qwiklabs.net' metadata: ancestry_path: organizations/616463121992/folders/365352270458/folders/474147567761/folders/125430737939/projects/qwiklabs-gcp-02-ec89de7c9f9d constraint: annotations: description: Checks that members that have been granted IAM roles belong to allowlisted domains. validation.gcp.forsetisecurity.org/originalName: service_accounts_only validation.gcp.forsetisecurity.org/yamlpath: policies/constraints/iam_service_accounts_only.yaml labels: {} parameters: domains: - gserviceaccount.com details: member: user:student-02-0edcb8aed69f@qwiklabs.net resource: //cloudresourcemanager.googleapis.com/projects/qwiklabs-gcp-02-ec89de7c9f9d resource: //cloudresourcemanager.googleapis.com/projects/qwiklabs-gcp-02-ec89de7c9f9d severity: high Troubleshooting: If you receive the following error, "Error 403: The caller does not have permission, forbidden," then you either didn't replace the project_id argument in policy-library/main.tf, or you don't have the necessary permissions on the project you specified.

Modify the constraint

The constraint works as intended, but let's say you want to modify this so you can allow other email addresses in your domain.

  1. From the Editor, navigate to the policy-library/policies/constraints/iam_service_accounts_only.yaml file.

  2. Under the domains section, append the qwiklabs.net email domain to the domains allowlist:

apiVersion: constraints.gatekeeper.sh/v1alpha1 kind: GCPIAMAllowedPolicyMemberDomainsConstraintV1 metadata: name: service_accounts_only spec: severity: high match: target: ["organizations/**"] parameters: domains: - gserviceaccount.com - qwiklabs.net
  1. Navigate back to the Cloud Shell window and export a new JSON Terraform plan.
terraform plan -out=test.tfplan
  1. Now validate your Terraform plan again, and this should result in no violations found.
gcloud beta terraform vet tfplan.json --policy-library=.

Output:

Validating resources...done.
  1. Lastly, apply the Terraform plan for the IAM policy to grant a role to the member.
terraform apply test.tfplan

Click Check my progress to verify the objective. Modify the constraint

Congratulations!

In this lab you applied a constraint that enforces a domain restriction. You tested that constraint, which threw an error. Then you modified the constraint so that domains you define can pass validation.

Next Steps / Learn More

Be sure to check out the following resources for more practice with Validator and Terraform:

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated September 28, 2023
Lab Last Tested September 28, 2023

Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

Este contenido no está disponible en este momento

Te enviaremos una notificación por correo electrónico cuando esté disponible

¡Genial!

Nos comunicaremos contigo por correo electrónico si está disponible