arrow_back

Validating Policies for Terraform on Google Cloud

登录 加入
访问 700 多个实验和课程

Validating Policies for Terraform on Google Cloud

实验 30 分钟 universal_currency_alt 1 个积分 show_chart 入门级
info 此实验可能会提供 AI 工具来支持您学习。
访问 700 多个实验和课程

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 Build Infrastructure with Terraform on Google Cloud course 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 are made available to you.

This hands-on lab lets you do the lab activities in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials 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 (recommended) or private browser window to run this lab. This prevents 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: Use only the student account for this lab. If you use a different Google Cloud account, you may incur charges to that 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 dialog opens for you to select your payment method. On the left is the Lab Details pane 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 pane.

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

  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 access Google Cloud products and services, click the Navigation menu or type the service or product name in the Search field. Navigation menu icon and Search field

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.

  2. Click through the following windows:

    • Continue through the Cloud Shell information window.
    • Authorize Cloud Shell to use your credentials to make Google Cloud API calls.

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.

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

Task 2. 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 November 29, 2024

Lab Last Tested November 29, 2024

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

准备工作

  1. 实验会创建一个 Google Cloud 项目和一些资源,供您使用限定的一段时间
  2. 实验有时间限制,并且没有暂停功能。如果您中途结束实验,则必须重新开始。
  3. 在屏幕左上角,点击开始实验即可开始

使用无痕浏览模式

  1. 复制系统为实验提供的用户名密码
  2. 在无痕浏览模式下,点击打开控制台

登录控制台

  1. 使用您的实验凭证登录。使用其他凭证可能会导致错误或产生费用。
  2. 接受条款,并跳过恢复资源页面
  3. 除非您已完成此实验或想要重新开始,否则请勿点击结束实验,因为点击后系统会清除您的工作并移除该项目

此内容目前不可用

一旦可用,我们会通过电子邮件告知您

太好了!

一旦可用,我们会通过电子邮件告知您

一次一个实验

确认结束所有现有实验并开始此实验

使用无痕浏览模式运行实验

请使用无痕模式或无痕式浏览器窗口运行此实验。这可以避免您的个人账号与学生账号之间发生冲突,这种冲突可能导致您的个人账号产生额外费用。