[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-05-15。"],[[["\u003cp\u003eTesting Terraform requires deploying real cloud resources, which can be time-consuming and costly, therefore it's recommended to break down architectures into smaller modules for individual testing.\u003c/p\u003e\n"],["\u003cp\u003eStart with less expensive testing methods like static analysis and module integration testing before moving to end-to-end testing, using a fail-fast approach to catch errors quickly.\u003c/p\u003e\n"],["\u003cp\u003eUtilize unique project IDs and resource names, employing the Terraform random provider to avoid conflicts, and use isolated test environments separate from development or production.\u003c/p\u003e\n"],["\u003cp\u003eImplement cleanup procedures, including \u003ccode\u003eterraform destroy\u003c/code\u003e and other tools, to remove all resources created during testing to avoid unnecessary costs.\u003c/p\u003e\n"],["\u003cp\u003eOptimize test runtime by running tests in parallel and separating tests into stages for faster iteration, using frameworks like Terratest or Kitchen-Terraform for efficient test management.\u003c/p\u003e\n"]]],[],null,["# Best practices for testing\n\nThis document provides guidelines and recommendations for testing\nTerraform for Google Cloud modules and configurations.\n\nTesting Terraform modules and configurations sometimes follows different\npatterns and conventions from testing application code. While testing\napplication code primarily involves testing the business logic of applications\nthemselves, fully testing infrastructure code requires deploying real cloud\nresources to minimize the risk of production failures. There are a few\nconsiderations when running Terraform tests:\n\n- Running a Terraform test creates, modifies, and destroys real infrastructure, so your tests can potentially be time-consuming and expensive.\n- *You cannot purely unit test an end-to-end architecture*. The best approach is to break up your architecture into modules and test those individually. The benefits of this approach include faster iterative development due to faster test runtime, reduced costs for each test, and reduced chances of test failures from factors beyond your control.\n- *Avoid reusing state if possible*. There may be situations where you are testing with configurations that share data with other configurations, but ideally each test should be independent and should not reuse state across tests.\n\nUse less expensive test methods first\n-------------------------------------\n\nThere are multiple methods that you can use to test Terraform. In ascending\norder of cost, run time, and depth, they include the following:\n\n- **Static analysis:** Testing the syntax and structure of your configuration without deploying any resources, using tools such as compilers, linters, and dry runs. To do so, use [`terraform validate`](https://www.terraform.io/cli/commands/validate)\n- **Module integration testing** : To ensure that modules work correctly, test individual modules in isolation. Integration testing for modules involves deploying the module into a test environment and verifying that expected resources are created. There are several testing frameworks that make it easier to write tests, as follows:\n - [Google's blueprint testing framework](https://pkg.go.dev/github.com/GoogleCloudPlatform/cloud-foundation-toolkit/infra/blueprint-test)\n - [Terratest](https://terratest.gruntwork.io/)\n - [Kitchen-Terraform](https://newcontext-oss.github.io/kitchen-terraform/)\n - [InSpec](https://github.com/inspec/inspec-gcp)\n - [tftest](https://pypi.org/project/tftest/)\n- **End-to-end testing:** By extending the integration testing approach to an entire environment, you can confirm that multiple modules work together. In this approach, deploy all modules that make up the architecture in a fresh test environment. Ideally, the test environment is as similar as possible to your production environment. This is costly but provides the greatest confidence that changes don't break your production environment.\n\nStart small\n-----------\n\nMake sure that your tests iteratively build on each other. Consider running\nsmaller tests first and then working up to more complex tests, using a\n*fail fast* approach.\n\nRandomize project IDs and resource names\n----------------------------------------\n\nTo avoid naming conflicts, make sure that your configurations have a globally\nunique project ID and non-overlapping resource names within each project. To do\nthis, use namespaces for your resources. Terraform has a built-in\n[random provider](https://registry.terraform.io/providers/hashicorp/random/latest/docs)\nfor this.\n\nUse a separate environment for testing\n--------------------------------------\n\nDuring testing, many resources are created and deleted. Ensure that the\nenvironment is isolated from development or production projects to avoid\naccidental deletions during resource cleanup. The best approach is to have each\ntest create a fresh project or folder. To avoid misconfiguration, consider\ncreating service accounts specifically for each test execution.\n\nClean up all resources\n----------------------\n\nTesting infrastructure code means that you are deploying actual resources.\nTo avoid incurring charges, consider implementing a clean-up step.\n\nTo destroy all remote objects managed by a particular configuration, use the\n`terraform destroy` command. Some testing frameworks have a built-in cleanup\nstep for you. For example, if you are using Terratest, add\n`defer terraform.Destroy(t, terraformOptions)` to your test. If you're using\nKitchen-Terraform, delete your workspace using\n`terraform kitchen delete `\u003cvar translate=\"no\"\u003eWORKSPACE_NAME\u003c/var\u003e.\n\nAfter you run the `terraform destroy` command, also run additional clean-up\nprocedures to remove any resources that Terraform failed to destroy. Do this by\ndeleting any projects used for test execution or by using a tool like the\n[`project_cleanup`](https://github.com/terraform-google-modules/terraform-google-scheduled-function/tree/master/modules/project_cleanup) module.\n| **Warning:** Don't use such tools in a production environment.\n\nOptimize test runtime\n---------------------\n\nTo optimize your test execution time, use the following approaches:\n\n- **Run tests in parallel.** Some testing frameworks support running multiple Terraform tests simultaneously.\n - For example, with Terratest you can do this by adding `t.Parallel()` after the test function definition.\n- **Test in stages.** Separate your tests into independent configurations that can be tested separately. This approach removes the need to go through all stages when running a test, and accelerates the iterative development cycle.\n - For example, in Kitchen-Terraform, split tests into separate suites. When iterating, execute each suite independently.\n - Similarly, using Terratest, wrap each stage of your test with `stage(t, `\u003cvar translate=\"no\"\u003eSTAGE_NAME\u003c/var\u003e`, `\u003cvar translate=\"no\"\u003eCORRESPONDING_TEST\u003cem\u003eFUNCTION\u003c/em\u003e\u003c/var\u003e*)**.\n Set environment variables that indicate which tests to run. For example,\n `SKIP`* \u003cvar translate=\"no\"\u003eSTAGE_NAME\u003c/var\u003e`=\"true\"`.\n - The [blueprint testing framework](https://pkg.go.dev/github.com/GoogleCloudPlatform/cloud-foundation-toolkit/infra/blueprint-test) supports staged execution.\n\nWhat's next\n-----------\n\n- Learn about [general style and structure best practices for Terraform on Google Cloud](/docs/terraform/best-practices/general-style-structure).\n- Learn about [best practices when using Terraform root modules](/docs/terraform/best-practices/root-modules)."]]