github.com/darmach/terratest@v0.34.8-0.20210517103231-80931f95e3ff/docs/_docs/02_testing-best-practices/cleanup.md (about)

     1  ---
     2  layout: collection-browser-doc
     3  title: Cleanup
     4  category: testing-best-practices
     5  excerpt: >-
     6    Since automated tests with Terratest deploy real resources into real environments, you'll want to make sure your tests
     7    always cleanup after themselves.
     8  tags: ["testing-best-practices", "clean", "terraform-destroy", "terraform-apply"]
     9  order: 204
    10  nav_title: Documentation
    11  nav_title_link: /docs/
    12  ---
    13  
    14  Since automated tests with Terratest deploy real resources into real environments, you'll want to make sure your tests
    15  always cleanup after themselves so you don't leave a bunch of resources lying around. Typically, you should use Go's
    16  `defer` keyword to ensure that the cleanup code always runs, even if the test hits an error along the way.
    17  
    18  For example, if your test runs `terraform apply`, you should run `terraform destroy` at the end to clean up:
    19  
    20  ```go
    21  // Ensure cleanup always runs
    22  defer terraform.Destroy(t, options)
    23  
    24  // Deploy
    25  terraform.Apply(t, options)
    26  
    27  // Validate
    28  checkServerWorks(t, options)
    29  ```
    30  
    31  Of course, despite your best efforts, occasionally cleanup will fail, perhaps due to the CI server going down, or a bug
    32  in your code, or a temporary network outage. To handle those cases, we run a tool called
    33  [cloud-nuke](https://github.com/gruntwork-io/cloud-nuke) in our test AWS account on a nightly basis to clean up any
    34  leftover resources.