Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Dokumen ini memberikan panduan dan rekomendasi untuk menguji Terraform untuk modul dan konfigurasi Google Cloud .
Pengujian modul dan konfigurasi Terraform terkadang mengikuti pola dan konvensi
yang berbeda dari pengujian kode aplikasi. Meskipun menguji
kode aplikasi paling banyak melibatkan pengujian logika bisnis aplikasi
itu sendiri, pengujian kode infrastruktur secara menyeluruh memerlukan deployment resource cloud
nyata untuk meminimalkan risiko kegagalan produksi. Ada beberapa
pertimbangan saat menjalankan pengujian Terraform:
Menjalankan pengujian Terraform akan menciptakan, mengubah, dan menghancurkan infrastruktur
nyata, sehingga pengujian Anda berpotensi memerlukan waktu yang lama dan biaya yang mahal.
Anda tidak bisa hanya menguji unit arsitektur menyeluruh. Pendekatan
terbaik adalah dengan membagi arsitektur Anda menjadi beberapa modul dan mengujinya
satu per satu. Manfaat pendekatan ini mencakup pengembangan
iteratif yang lebih cepat karena runtime pengujian yang lebih cepat, pengurangan biaya untuk setiap pengujian, dan
penurunan peluang kegagalan uji dari faktor-faktor di luar kendali Anda.
Hindari menggunakan kembali status jika memungkinkan. Mungkin ada situasi saat Anda
melakukan pengujian dengan konfigurasi yang memiliki data yang sama seperti konfigurasi lain,
tetapi idealnya setiap pengujian harus dilakukan terpisah dan tidak boleh menggunakan kembali status
di seluruh pengujian.
Menggunakan metode pengujian yang lebih murah terlebih dahulu
Ada beberapa metode yang dapat Anda gunakan untuk menguji Terraform. Dalam urutan
biaya, waktu proses, dan kedalaman dari atas ke bawah, metrik tersebut meliputi:
Analisis statis: Menguji sintaksis dan struktur konfigurasi
tanpa men-deploy resource apa pun menggunakan alat seperti compiler, linter,
dan uji coba. Untuk melakukannya, gunakan
terraform validate
Pengujian integrasi modul: Untuk memastikan bahwa modul berfungsi dengan benar, uji
setiap modul secara terpisah. Pengujian integrasi untuk modul
melibatkan deployment modul ke dalam lingkungan pengujian dan memverifikasi bahwa
resource yang diharapkan telah dibuat. Ada beberapa framework pengujian yang
memudahkan penulisan pengujian sebagai berikut:
Pengujian menyeluruh: Dengan memperluas pendekatan pengujian integrasi ke
seluruh lingkungan, Anda dapat mengonfirmasi bahwa beberapa modul dapat berfungsi bersama.
Dalam pendekatan ini, deploy semua modul yang membentuk arsitektur di
lingkungan pengujian baru. Idealnya, lingkungan pengujian harus semirip
mungkin dengan lingkungan produksi Anda. Meskipun biayanya mahal, tetapi memberikan
keyakinan besar bahwa perubahan tidak merusak lingkungan produksi Anda.
Memulai dari yang kecil
Pastikan pengujian Anda saling melengkapi satu sama lain secara iteratif. Sebaiknya jalankan
pengujian yang lebih kecil terlebih dahulu, lalu lanjutkan ke pengujian yang lebih kompleks, menggunakan
pendekatan fail fast.
Mengacak project ID dan nama resource
Untuk menghindari konflik penamaan, pastikan konfigurasi Anda memiliki project ID
yang unik secara global dan nama resource yang tidak tumpang-tindih dalam setiap project. Untuk
melakukannya, gunakan namespace untuk resource Anda. Terraform memiliki
penyedia acak
bawaan untuk ini.
Menggunakan lingkungan terpisah untuk pengujian
Selama pengujian, banyak resource yang dibuat dan dihapus. Pastikan
lingkungan diisolasi dari project pengembangan atau produksi untuk menghindari
penghapusan yang tidak disengaja selama pembersihan resource. Pendekatan terbaik adalah meminta setiap
pengujian membuat project atau folder baru. Untuk menghindari kesalahan konfigurasi, pertimbangkan
untuk membuat akun layanan khusus untuk setiap eksekusi uji.
Membersihkan semua resource
Menguji kode infrastruktur berarti Anda men-deploy resource yang sebenarnya.
Agar tidak dikenai biaya, pertimbangkan untuk menerapkan langkah pembersihan.
Untuk menghancurkan semua objek jarak jauh yang dikelola oleh konfigurasi tertentu, gunakan
perintah terraform destroy. Beberapa framework pengujian memiliki langkah pembersihan
bawaan untuk Anda. Misalnya, jika Anda menggunakan Terratest, tambahkan
defer terraform.Destroy(t, terraformOptions) ke pengujian. Jika menggunakan
Kitchen-Terraform, hapus ruang kerja Anda menggunakan
terraform kitchen delete WORKSPACE_NAME.
Setelah menjalankan perintah terraform destroy, jalankan juga prosedur pembersihan
tambahan untuk menghapus resource yang gagal dihancurkan Terraform. Lakukan hal ini dengan
menghapus project yang digunakan untuk eksekusi uji atau menggunakan alat seperti
modul project_cleanup.
Mengoptimalkan waktu proses pengujian
Untuk mengoptimalkan waktu eksekusi uji, gunakan pendekatan berikut:
Jalankan pengujian secara paralel. Beberapa framework pengujian mendukung pengoperasian
beberapa pengujian Terraform secara bersamaan.
Misalnya, dengan Terratest, Anda dapat melakukannya dengan menambahkan
t.Parallel() setelah definisi fungsi pengujian.
Uji secara bertahap. Pisahkan pengujian Anda ke dalam konfigurasi independen
yang dapat diuji secara terpisah. Dengan pendekatan ini, Anda tidak perlu melalui
semua tahap saat menjalankan pengujian dan siklus pengembangan
iteratif juga menjadi lebih cepat.
Misalnya, di Kitchen-Terraform, bagi pengujian dalam
suite terpisah. Saat melakukan iterasi, jalankan setiap suite secara terpisah.
Demikian pula, dengan menggunakan Terratest, gabungkan setiap tahap pengujian Anda dengan
stage(t, STAGE_NAME, CORRESPONDING_TESTFUNCTION).
Menetapkan variabel lingkungan yang menunjukkan pengujian yang akan dijalankan. Misalnya,
SKIPSTAGE_NAME="true".
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 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)."]]