From 723dab2fe758cfb1db11ee1a0c849c978a5fcea0 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 | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index 129e9700..27606690 100644 --- a/main.go +++ b/main.go @@ -151,7 +151,12 @@ var ( Usage: "The comma separated list of ENVs which will be passed from controller to its managed modules during terraform run. " + "The values should be set on the controller.", }, - + &cli.BoolFlag{ + Name: "cleanup-temp-dir", + Value: false, + Usage: "If set, the OS temporary directory will be removed and re-created. This can help removing redundant terraform" + + "binaries and avoiding temp directory growing in size with every restart", + }, &cli.StringFlag{ Name: "module-label-selector", EnvVars: []string{"MODULE_LABEL_SELECTOR"}, @@ -411,6 +416,20 @@ preferences: {} } +func cleanupTmpDir() { + tmpDir := os.TempDir() + + err := os.RemoveAll(tmpDir) + if err != nil { + logger.Error("Error removing temporary directory:", err) + } + + err = os.Mkdir(tmpDir, 0700) + if err != nil { + logger.Error("Error creating temporary directory:", err) + } +} + func main() { app := &cli.App{ Name: "terraform-applier", @@ -482,6 +501,11 @@ func run(c *cli.Context) { } } + // Cleanup temp directory if the corresponding flag is set + if c.Bool("cleanup-temp-dir") { + cleanupTmpDir() + } + // Find the requested version of terraform and log the version // information execPath, cleanup, err := findTerraformExecPath(ctx, terraformPath, terraformVersion)