Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En este documento, se proporcionan lineamientos y recomendaciones a fin de probar los módulos y parámetros de configuración de
Terraform para Google Cloud.
La prueba de módulos y configuraciones de Terraform a veces sigue diferentes patrones y convenciones a partir de la prueba del código de la aplicación. Si bien probar el código de la aplicación implica principalmente probar la lógica empresarial de las aplicaciones en sí, para probar el código de la infraestructura en su totalidad es necesario implementar recursos en la nube reales para minimizar el riesgo de errores de producción. Ten en cuenta las siguientes consideraciones cuando ejecutes pruebas de Terraform:
La ejecución de una prueba de Terraform crea, modifica y destruye la infraestructura real, por lo que las pruebas pueden llevar mucho tiempo y ser costosas.
No puedes probar la unidad solo de una arquitectura de extremo a extremo. El mejor enfoque consiste en dividir la arquitectura en módulos y probarlos de forma individual. Los beneficios de este enfoque incluyen un desarrollo iterativo más rápido debido al tiempo de ejecución de prueba más rápido, la reducción de costos para cada prueba y la reducción de las posibilidades de pruebas fallidas a partir de factores más allá de tu control.
Evita la reutilización del estado, si es posible. Puede haber situaciones en las que realices pruebas con configuraciones que compartan datos con otras opciones de configuración, pero idealmente cada prueba debería ser independiente y no debería reutilizar el estado en todas las pruebas.
Usa primero métodos de prueba menos costosos
Existen varios métodos que puedes usar para probar Terraform. En orden ascendente según el costo, el tiempo de ejecución y la profundidad, incluyen lo siguiente:
Análisis estático: prueba la sintaxis y la estructura de tu configuración sin implementar ningún recurso mediante herramientas, como compiladores, lints y pruebas de validación. Para hacerlo, usa
terraform validate.
Prueba de integración del módulo: para garantizar que los módulos funcionen de forma correcta, prueba los módulos individuales de forma aislada. La prueba de integración para los módulos implican implementar el módulo en un entorno de pruebas y verificar que se creen los recursos esperados. Hay varios frameworks de prueba que facilitan la escritura de pruebas, de la siguiente manera:
Prueba de extremo a extremo: si extiendes el enfoque de prueba de integración a un entorno completo, puedes confirmar que varios módulos funcionen juntos.
En este enfoque, implementa todos los módulos que conforman la arquitectura en un entorno de pruebas nuevo. Lo ideal es que el entorno de pruebas sea lo más similar posible a tu entorno de producción. Esto es costoso, pero proporciona la mayor confianza de que los cambios no interrumpen tu entorno de producción.
Empieza de a poco
Asegúrate de que las pruebas se compilen de forma iterativa entre sí. Considera ejecutar primero pruebas más pequeñas y, luego, trabajar en pruebas más complejas mediante un enfoque de falla rápida.
Aleatoriza ID de proyectos y nombres de recursos
Para evitar conflictos de nombres, asegúrate de que tus opciones de configuración tengan un ID del proyecto único a nivel global y nombres de recursos no superpuestos en cada proyecto. Para hacerlo, utiliza espacios de nombres en tus recursos. Terraform tiene un proveedor aleatorio integrado para esto.
Usa un entorno independiente para realizar pruebas
Durante la prueba, se crean y borran muchos recursos. Asegúrate de que el entorno esté aislado de los proyectos de desarrollo o producción para evitar las eliminaciones accidentales durante la limpieza de los recursos. El mejor enfoque es hacer que cada prueba cree un proyecto o una carpeta nuevos. A fin de evitar una configuración incorrecta, considera crear cuentas de servicio específicas para cada ejecución de prueba.
Limpia todos los recursos
Probar el código de infraestructura significa que estás implementando recursos reales.
Para evitar que se apliquen cargos, considera implementar un paso de limpieza.
Para destruir todos los objetos remotos que administra una configuración específica, usa el comando terraform destroy. Algunos frameworks de prueba tienen un paso de limpieza integrado. Por ejemplo, si usas Terratest, agrega defer terraform.Destroy(t, terraformOptions) a tu prueba. Si usas Kitchen-Terraform, borra tu lugar de trabajo con terraform kitchen delete WORKSPACE_NAME.
Después de ejecutar el comando terraform destroy, también ejecuta procedimientos de limpieza adicionales para quitar cualquier recurso que Terraform no haya destruido. Para eso, borra los proyectos que se usaron en la ejecución de prueba o con una herramienta como el módulo project_cleanup.
Optimiza el entorno de ejecución de pruebas
Para optimizar el tiempo de ejecución de prueba, usa los siguientes enfoques:
Ejecuta pruebas en paralelo. Algunos frameworks de prueba admiten la ejecución de varias pruebas de Terraform de forma simultánea.
Por ejemplo, con Terratest, puedes agregar t.Parallel() después de la definición de la función de prueba.
Realiza pruebas en etapas. Separa tus pruebas en configuraciones independientes que se pueden probar por separado. Este enfoque quita la necesidad de pasar por todas las etapas cuando se ejecuta una prueba y acelera el ciclo de desarrollo iterativo.
Por ejemplo, en Kitchen-Terraform, divide las pruebas en conjuntos separados. Cuando iteras, ejecuta cada conjunto de forma independiente.
Del mismo modo, mediante Terratest, une cada etapa de la prueba con stage(t, STAGE_NAME, CORRESPONDING_TESTFUNCTION).
Configura variables de entorno que indiquen qué pruebas ejecutar. Por ejemplo,
SKIPSTAGE_NAME="true".
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2024-12-22 (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)."]]