Vérifiez que gcloud CLI est installé en exécutant la commande suivante :
gcloudbetaterraformvet--help
Obtenir les autorisations requises
Le compte Google Cloud que vous utilisez pour la validation doit disposer des autorisations suivantes :
getIamPolicy : gcloud beta terraform vet doit obtenir des stratégies Identity and Access Management (IAM) complètes, et les fusionner avec les membres et les liaisons pour disposer d'un état final précis à valider.
resourcemanager.projects.get : gcloud beta terraform vet doit obtenir l'ancêtre du projet depuis l'API afin de créer avec précision un nom d'élément CAI complet pour tous les projets auxquels des ressources validées sont associées.
resourcemanager.folders.get : gcloud beta terraform vet doit obtenir l'ancêtre du dossier auprès de l'API afin de créer avec précision un nom d'élément CAI complet si les ressources validées contiennent des ressources liées au dossier.
gcloud beta terraform vet est compatible avec Terraform 0.12 et les versions ultérieures. gcloud beta terraform vet accepte comme entrée l'objet JSON terraform plan. Vous pouvez générer le fichier JSON en exécutant les commandes suivantes dans le répertoire Terraform :
terraform plan -out=tfplan.tfplan
terraform show -json ./tfplan.tfplan > ./tfplan.json
2. Exécuter gcloud beta terraform vet
gcloud beta terraform vet vous permet de valider votre fichier JSON terraform plan par rapport au POLICY_LIBRARY_REPO de votre organisation. Exemple :
git clone POLICY_LIBRARY_REPOPOLICY_LIBRARY_DIR
gcloud beta terraform vet tfplan.json --policy-library=POLICY_LIBRARY_DIR
Lorsque vous exécutez cette commande, gcloud beta terraform vet récupère les données du projet en utilisant les API Google Cloud nécessaires à une validation précise de votre plan.
Options
--policy-library=POLICY_LIBRARY_DIR : répertoire contenant une bibliothèque de règles
--project=PROJECT_ID - gcloud beta terraform vet accepte une option --project facultative. Cette option spécifie le projet par défaut lors de la création de l'ancêtre (à partir de la hiérarchie des ressources Google Cloud) pour toute ressource dans laquelle aucun projet n'est explicitement défini.
--format=FORMAT : le format par défaut est yaml. Les formats acceptés sont les suivants : default, json, none, text, yaml. Pour en savoir plus, exécutez $ gcloud topic formats.
Code de sortie et résultat
Si toutes les contraintes sont validées, la commande renvoie le code de sortie 0 et n'affiche aucune violation.
Si des problèmes de non-respect sont détectés, gcloud beta terraform vet renvoie le code de sortie 2 et affiche la liste des cas de non-respect. Par exemple, la sortie JSON peut ressembler à ceci :
[
{
"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/PROJECT_ID contains member from unexpected domain: user:me@example.com",
"metadata": {
"ancestry_path": "organizations/ORG_ID/projects/PROJECT_ID",
"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:me@example.com",
"resource": "//cloudresourcemanager.googleapis.com/projects/PROJECT_ID"
}
},
"resource": "//cloudresourcemanager.googleapis.com/projects/PROJECT_ID",
"severity": "high"
}
]
Exemple CI/CD
Un script bash permettant d'utiliser gcloud beta terraform vet dans un pipeline CI/CD peut se présenter comme suit :
terraformplan-out=tfplan.tfplan
terraformshow-json./tfplan.tfplan>./tfplan.json
gitclonePOLICY_LIBRARY_REPOPOLICY_LIBRARY_DIRVIOLATIONS=$(gcloudbetaterraformvettfplan.json--policy-library=POLICY_LIBRARY_DIR--format=json)retVal=$?if[$retVal-eq2];then# Optional: parse the VIOLATIONS variable as json and check the severity levelecho"$VIOLATIONS"echo"Violations found; not proceeding with terraform apply"exit1fiif[$retVal-ne0];thenecho"Error during gcloud beta terraform vet; not proceeding with terraform apply"exit1fiecho"No policy violations detected; proceeding with terraform apply"
terraformapply
Les développeurs peuvent également utiliser gcloud beta terraform vet en local pour tester les modifications Terraform avant d'exécuter le pipeline CI/CD.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/03 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/03 (UTC)."],[[["\u003cp\u003e\u003ccode\u003egcloud beta terraform vet\u003c/code\u003e is a tool for validating Terraform plan JSON against a defined policy library to ensure compliance.\u003c/p\u003e\n"],["\u003cp\u003eThe tool requires the installation of Google Cloud CLI, including the \u003ccode\u003eterraform-tools\u003c/code\u003e component, and specific IAM permissions for the validating account.\u003c/p\u003e\n"],["\u003cp\u003eA policy library must be created and configured to define the constraints and rules against which the Terraform plan will be evaluated.\u003c/p\u003e\n"],["\u003cp\u003eThe validation process involves generating a Terraform plan in JSON format, then running \u003ccode\u003egcloud beta terraform vet\u003c/code\u003e with the JSON plan and the policy library directory as input, then an exit code of 2 indicates policy violations.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003egcloud beta terraform vet\u003c/code\u003e can be integrated into CI/CD pipelines to automatically check for policy violations before applying Terraform changes, and developers can also use it locally to test their changes.\u003c/p\u003e\n"]]],[],null,["# Validate policies\n\n| **Preview**\n|\n|\n| This product or feature is subject to the \"Pre-GA Offerings Terms\" in the General Service Terms section\n| of the [Service Specific Terms](/terms/service-terms#1).\n|\n| Pre-GA products and features are available \"as is\" and might have limited support.\n|\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n\nBefore you begin\n----------------\n\n### Install `Google Cloud CLI`\n\nTo use `gcloud beta terraform vet` you must first install Google Cloud CLI:\n\n1. Install Google Cloud CLI but skip the `gcloud init` command.\n\n2. Run the following commands to install the terraform-tools component:\n\n gcloud components update\n gcloud components install terraform-tools\n\n3. Verify that the gcloud CLI is installed by running the following command:\n\n gcloud beta terraform vet --help\n\n### Get required permissions\n\nThe Google Cloud account that you use for validation must have the following permissions:\n\n- `getIamPolicy`: `gcloud beta terraform vet` needs to get full Identity and Access Management (IAM) policies and merge them with members and bindings to get an accurate end state to validate.\n- `resourcemanager.projects.get`: `gcloud beta terraform vet` needs to get project ancestry from the API in order to accurately construct a full CAI Asset Name for any projects that validated resources are related to.\n- `resourcemanager.folders.get`: `gcloud beta terraform vet` needs to get folder ancestry from the API in order to accurately construct a full CAI Asset Name if the validated resources contain any folder-related resources.\n\n### Set up a policy library\n\nYou need to [create a policy library](/docs/terraform/policy_validation/create_policy_library) to use this tool.\n\nValidate policies\n-----------------\n\n### 1. Generate a Terraform plan\n\n`gcloud beta terraform vet` is compatible with Terraform 0.12+. `gcloud beta terraform vet` takes `terraform plan` JSON as its input. You can generate the JSON file by running the following commands in your Terraform directory: \n\n```\nterraform plan -out=tfplan.tfplan\nterraform show -json ./tfplan.tfplan \u003e ./tfplan.json\n```\n\n### 2. Run `gcloud beta terraform vet`\n\n`gcloud beta terraform vet` lets you validate your `terraform plan` JSON against your organization's \u003cvar translate=\"no\"\u003ePOLICY_LIBRARY_REPO\u003c/var\u003e. For example: \n\n```\ngit clone POLICY_LIBRARY_REPO POLICY_LIBRARY_DIR\ngcloud beta terraform vet tfplan.json --policy-library=POLICY_LIBRARY_DIR\n```\n\nWhen you execute this command, `gcloud beta terraform vet` retrieves project data by using Google Cloud APIs that are necessary for an accurate validation of your plan.\n\n#### Flags\n\n- `--policy-library=`\u003cvar translate=\"no\"\u003ePOLICY_LIBRARY_DIR\u003c/var\u003e - Directory that contains a policy library.\n- `--project=`\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e - `gcloud beta terraform vet` accepts an optional `--project` flag. This flag specifies the [default project](/sdk/gcloud/reference/config/set) when building the ancestry (from the Google Cloud resource hierarchy) for any resource that doesn't have an explicit project set.\n- `--format=`\u003cvar translate=\"no\"\u003eFORMAT\u003c/var\u003e - The default is yaml. The supported formats are: `default`, `json`, `none`, `text`, `yaml`. For more details run $ [gcloud topic formats](/sdk/gcloud/reference/topic/formats).\n\n#### Exit code and output\n\n- If all constraints are validated, the command returns exit code 0 and does not display violations.\n- If violations are found, `gcloud beta terraform vet` returns exit code 2, and displays a list of violations. For example, JSON output might look like:\n\n```\n[\n {\n \"constraint\": \"GCPIAMAllowedPolicyMemberDomainsConstraintV2.service_accounts_only\",\n \"constraint_config\": {\n \"api_version\": \"constraints.gatekeeper.sh/v1alpha1\",\n \"kind\": \"GCPIAMAllowedPolicyMemberDomainsConstraintV2\",\n \"metadata\": {\n \"annotations\": {\n \"description\": \"Checks that members that have been granted IAM roles belong to allowlisted domains.\",\n \"validation.gcp.forsetisecurity.org/originalName\": \"service_accounts_only\",\n \"validation.gcp.forsetisecurity.org/yamlpath\": \"policies/constraints/iam_service_accounts_only.yaml\"\n },\n \"name\": \"service-accounts-only\"\n },\n \"spec\": {\n \"match\": {\n \"target\": [\n \"organizations/**\"\n ]\n },\n \"parameters\": {\n \"domains\": [\n \"gserviceaccount.com\"\n ]\n },\n \"severity\": \"high\"\n }\n },\n \"message\": \"IAM policy for //cloudresourcemanager.googleapis.com/projects/PROJECT_ID contains member from unexpected domain: user:me@example.com\",\n \"metadata\": {\n \"ancestry_path\": \"organizations/ORG_ID/projects/PROJECT_ID\",\n \"constraint\": {\n \"annotations\": {\n \"description\": \"Checks that members that have been granted IAM roles belong to allowlisted domains.\",\n \"validation.gcp.forsetisecurity.org/originalName\": \"service_accounts_only\",\n \"validation.gcp.forsetisecurity.org/yamlpath\": \"policies/constraints/iam_service_accounts_only.yaml\"\n },\n \"labels\": {},\n \"parameters\": {\n \"domains\": [\n \"gserviceaccount.com\"\n ]\n }\n },\n \"details\": {\n \"member\": \"user:me@example.com\",\n \"resource\": \"//cloudresourcemanager.googleapis.com/projects/PROJECT_ID\"\n }\n },\n \"resource\": \"//cloudresourcemanager.googleapis.com/projects/PROJECT_ID\",\n \"severity\": \"high\"\n }\n]\n```\n\nCI/CD example\n-------------\n\nA bash script for using `gcloud beta terraform vet` in a CI/CD pipeline might look like\nthis: \n\n```bash\nterraform plan -out=tfplan.tfplan\nterraform show -json ./tfplan.tfplan \u003e ./tfplan.json\ngit clone POLICY_LIBRARY_REPO POLICY_LIBRARY_DIR\nVIOLATIONS=$(gcloud beta terraform vet tfplan.json --policy-library=POLICY_LIBRARY_DIR --format=json)\nretVal=$?\nif [ $retVal -eq 2 ]; then\n # Optional: parse the VIOLATIONS variable as json and check the severity level\n echo \"$VIOLATIONS\"\n echo \"Violations found; not proceeding with terraform apply\"\n exit 1\nfi\nif [ $retVal -ne 0]; then\n echo \"Error during gcloud beta terraform vet; not proceeding with terraform apply\"\n exit 1\nfi\n\necho \"No policy violations detected; proceeding with terraform apply\"\n\nterraform apply\n```\n\nDevelopers can also use `gcloud beta terraform vet` locally to test Terraform changes\nprior to running your CI/CD pipeline."]]