Skip to content

Instantly share code, notes, and snippets.

@bschaatsbergen
Last active October 8, 2024 15:14
Show Gist options
  • Save bschaatsbergen/5367cdc0f888dfca01758542e30d998a to your computer and use it in GitHub Desktop.
Save bschaatsbergen/5367cdc0f888dfca01758542e30d998a to your computer and use it in GitHub Desktop.
Profiling Terraform using pprof and FlameGraph

Build Terraform with some modifications in main.go:

diff --git a/main.go b/main.go
index cce3f5f998..d927fb7e8f 100644
--- a/main.go
+++ b/main.go
@@ -12,6 +12,7 @@ import (
        "os"
        "path/filepath"
        "runtime"
+       "runtime/pprof"
        "strings"

        "github.com/apparentlymart/go-shquot/shquot"
@@ -31,6 +32,8 @@ import (
        "go.opentelemetry.io/otel/trace"

        backendInit "github.com/hashicorp/terraform/internal/backend/init"
+
+       _ "net/http/pprof"
 )

 const (
@@ -61,7 +64,19 @@ func init() {
 }

 func main() {
-       os.Exit(realMain())
+       f, err := os.Create("terraform.prof")
+       if err != nil {
+               log.Fatal("could not create CPU profile: ", err)
+       }
+       defer f.Close()
+
+       if err := pprof.StartCPUProfile(f); err != nil {
+               log.Fatal("could not start CPU profile: ", err)
+       }
+       defer pprof.StopCPUProfile()
+       defer os.Exit(realMain())
+
+       pprof.StopCPUProfile()
 }

Compile it to your $GOPATH/bin directory by running the following command from the root of the repository:

$ go install

Run a plan or apply

$ "$GOPATH/bin/terraform" plan

This generates a terraform.prof file. We can convert it into a text-based file using:

$ go tool pprof -raw -output=terraform.txt terraform.prof

Next, to create a FlameGraph, use the tools from Brendan Gregg’s FlameGraph repository:

$ go tool pprof -raw -output=terraform.txt terraform.prof
$ stackcollapse-go.pl terraform.txt | flamegraph.pl > terraform.svg

Screenshot 2024-10-07 at 16 04 09

(Planning 20,000 random_pet resources).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment