From f800574be426574553e02bdf978cb6a24e8b490b Mon Sep 17 00:00:00 2001 From: DTLP Date: Mon, 9 Oct 2023 16:50:33 +0100 Subject: [PATCH] Add temp dir cleanup on startup Adding a reliable way of cleaning up the contents of temp dir to make sure it doesn't pile up terraform binaries and grow in size with every restart. --- main.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/main.go b/main.go index 129e9700..1eb78a93 100644 --- a/main.go +++ b/main.go @@ -411,6 +411,22 @@ preferences: {} } +func cleanupTmpDir() { + tmpDir := os.TempDir() + + files, err := os.ReadDir(tmpDir) + if err != nil { + logger.Error("Error reading directory: %v", err) + } + + for _, file := range files { + filePath := fmt.Sprintf("%s/%s", tmpDir, file.Name()) + if err := os.RemoveAll(filePath); err != nil { + logger.Error("Error deleting file %s: %v", filePath, err) + } + } +} + func main() { app := &cli.App{ Name: "terraform-applier", @@ -482,6 +498,8 @@ func run(c *cli.Context) { } } + cleanupTmpDir() + // Find the requested version of terraform and log the version // information execPath, cleanup, err := findTerraformExecPath(ctx, terraformPath, terraformVersion)