Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Questo documento fornisce linee guida e consigli per testare Terraform per Google Cloud moduli e configurazioni.
A volte, i test dei moduli e delle configurazioni di Terraform seguono schemi e convenzioni diversi rispetto al test del codice dell'applicazione. Sebbene il test del codice dell'applicazione riguardi principalmente la logica di business delle applicazioni stesse, il test completo del codice dell'infrastruttura richiede il dispiegamento di risorse cloud reali per ridurre al minimo il rischio di errori di produzione. Esistono alcune considerazioni da tenere presenti quando esegui i test di Terraform:
L'esecuzione di un test Terraform crea, modifica ed elimina l'infrastruttura reale, pertanto i test possono essere potenzialmente lunghi e costosi.
Non puoi eseguire test di unità puramente su un'architettura end-to-end. L'approccio migliore è suddividere l'architettura in moduli e testarli singolarmente. I vantaggi di questo approccio includono uno sviluppo iterativo più rapido grazie a un tempo di esecuzione dei test più breve, costi ridotti per ogni test e probabilità ridotte di errori di test dovuti a fattori non sotto il tuo controllo.
Se possibile, evita di riutilizzare lo stato. Potrebbero verificarsi situazioni in cui
esegui test con configurazioni che condividono dati con altre configurazioni,
ma idealmente ogni test dovrebbe essere indipendente e non riutilizzare lo stato
tra i test.
Utilizza prima i metodi di test meno costosi
Esistono diversi metodi che puoi utilizzare per testare Terraform. In ordine crescente di costo, tempo di esecuzione e profondità, includono quanto segue:
Analisi statica: test della sintassi e della struttura della configurazione
senza eseguire il deployment di risorse, utilizzando strumenti come compilatori, lint e
prove a vuoto. Per farlo, utilizza
terraform validate
Test di integrazione dei moduli: per assicurarti che i moduli funzionino correttamente, testa i singoli moduli singolarmente. I test di integrazione per i moduli
prevedono il deployment del modulo in un ambiente di test e la verifica della creazione delle risorse previste. Esistono diversi framework di test che facilitano la scrittura dei test, come segue:
Test end-to-end: estendendo l'approccio di test di integrazione a un intero ambiente, puoi verificare che più moduli funzionino insieme.
In questo approccio, esegui il deployment di tutti i moduli che compongono l'architettura in un nuovo ambiente di test. Idealmente, l'ambiente di test deve essere il più simile possibile all'ambiente di produzione. Questa operazione è costosa, ma offre la massima certezza che le modifiche non danneggino l'ambiente di produzione.
Inizia in piccolo
Assicurati che i test si fondino l'uno sull'altro in modo iterativo. Valuta la possibilità di eseguire prima test più piccoli e poi passare a test più complessi, utilizzando un approccio fail fast.
Generare ID progetto e nomi delle risorse in modo casuale
Per evitare conflitti di denominazione, assicurati che le configurazioni abbiano un ID progetto univoco a livello mondiale e nomi di risorse non sovrapposti all'interno di ogni progetto. Per farlo, utilizza gli spazi dei nomi per le risorse. Terraform ha un
provider casuale
integrato per questo.
Utilizza un ambiente separato per i test
Durante i test, vengono create ed eliminate molte risorse. Assicurati che l'ambiente sia isolato dai progetti di sviluppo o di produzione per evitare eliminazioni accidentali durante la pulizia delle risorse. L'approccio migliore è fare in modo che ogni
test crei un nuovo progetto o una nuova cartella. Per evitare una configurazione errata, valuta la possibilità di creare account di servizio specifici per ogni esecuzione del test.
Ripulire tutte le risorse
Testare il codice dell'infrastruttura significa che stai eseguendo il deployment di risorse effettive.
Per evitare addebiti, valuta la possibilità di implementare un passaggio di pulizia.
Per eliminare tutti gli oggetti remoti gestiti da una determinata configurazione, utilizza il comando terraform destroy. Alcuni framework di test hanno un
passaggio di pulizia integrato. Ad esempio, se utilizzi Terratest, aggiungi
defer terraform.Destroy(t, terraformOptions) al test. Se utilizzi
Kitchen-Terraform, elimina lo spazio di lavoro utilizzando
terraform kitchen delete WORKSPACE_NAME.
Dopo aver eseguito il comando terraform destroy, esegui anche procedure di pulizia aggiuntive per rimuovere le risorse che Terraform non è riuscito a eliminare. Per farlo,
elimina i progetti utilizzati per l'esecuzione dei test o utilizza uno strumento come il
modulo project_cleanup.
Ottimizza il tempo di esecuzione del test
Per ottimizzare il tempo di esecuzione del test, utilizza i seguenti approcci:
Esegui i test in parallelo. Alcuni framework di test supportano l'esecuzione di più test Terraform contemporaneamente.
Ad esempio, con Terratest puoi farlo aggiungendo
t.Parallel() dopo la definizione della funzione di test.
Esegui il test in più fasi. Separa i test in configurazioni indipendenti
che possono essere testate separatamente. Questo approccio elimina la necessità di eseguire tutte le fasi durante l'esecuzione di un test e accelera il ciclo di sviluppo iterativo.
Ad esempio, in Kitchen-Terraform, suddividi i test in suite separate. Durante l'iterazione, esegui ogni suite in modo indipendente.
Analogamente, utilizzando Terratest, racchiudi ogni fase del test con
stage(t, STAGE_NAME, CORRESPONDING_TESTFUNCTION).
Imposta le variabili di ambiente che indicano quali test eseguire. Ad esempio,
SKIPSTAGE_NAME="true".
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-04 UTC."],[[["\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)."]]