Skip to content
This repository has been archived by the owner on Jun 29, 2022. It is now read-only.

Show logs when terraform fails in lokoctl cluster apply/destroy #323

Merged
merged 2 commits into from
Apr 27, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions pkg/terraform/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ const (
failFileSuffix = ".fail"

requiredVersion = ">= 0.12, < 0.13"

noOfLinesOnError = 20
)

// ErrBinaryNotFound denotes the fact that the Terraform binary could not be
Expand Down Expand Up @@ -211,22 +213,55 @@ func (ex *Executor) execute(verbose bool, args ...string) error {
wg.Add(1)

go tailFile(p, done, &wg)
} else {
fmt.Printf("\nYou can find the logs in %q\n", p)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not really sure if this is needed. Also, it uses else 😄

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But then that is one of the requirement from the issue. What is wrong with using else?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}

wg.Wait()

s, err := ex.Status(pid)
if err != nil {
if !verbose {
showError(p, noOfLinesOnError)
}
return fmt.Errorf("failed checking execution status: %w", err)
}

if s != ExecutionStatusSuccess {
if !verbose {
showError(p, noOfLinesOnError)
}
return fmt.Errorf("executing Terraform failed, check %s for details", p)
}

return nil
}

func showError(path string, noOfLines int) {
// nolint: gosec
data, err := ioutil.ReadFile(path)
surajssd marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
fmt.Printf("error reading file: %v", err)
return
}

text := string(data)
lines := strings.Split(text, "\n")

// Deletion by one is done here to adjust the difference between the user provided number which
// starts counting from 1 and array indices which start counting from 0.
// nolint: gomnd
offset := len(lines) - noOfLines - 1
surajssd marked this conversation as resolved.
Show resolved Hide resolved

if offset > 0 {
lines = lines[offset:]
}

for _, line := range lines {
fmt.Println(line)
}
}

// LoadVars is a convenience function to load the tfvars file into memory
// as a JSON object.
func (ex *Executor) LoadVars() (map[string]interface{}, error) {
Expand Down