Skip to content

Commit

Permalink
Merge pull request GoogleCloudPlatform#2759 from mr0re1/better_version
Browse files Browse the repository at this point in the history
Add terraform version to `ghpc --version`
  • Loading branch information
mr0re1 authored Jul 16, 2024
2 parents 19416ae + 4225bbd commit 9fe323e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
13 changes: 11 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"fmt"
"hpc-toolkit/pkg/config"
"hpc-toolkit/pkg/logging"
"hpc-toolkit/pkg/shell"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -79,13 +80,21 @@ func Execute() error {
if len(GitBranch) == 0 {
GitBranch = "detached HEAD"
}

annotation["version"] = GitTagVersion
annotation["branch"] = GitBranch
annotation["commitInfo"] = GitCommitInfo
rootCmd.SetVersionTemplate(`ghpc version {{index .Annotations "version"}}
tmpl := `ghpc version {{index .Annotations "version"}}
Built from '{{index .Annotations "branch"}}' branch.
Commit info: {{index .Annotations "commitInfo"}}
`)
`
tfVersion, _ := shell.TfVersion()
if tfVersion != "" {
annotation["tfVersion"] = tfVersion
tmpl += `Terraform version: {{index .Annotations "tfVersion"}}
`
}
rootCmd.SetVersionTemplate(tmpl)
}

return rootCmd.Execute()
Expand Down
38 changes: 33 additions & 5 deletions pkg/shell/terraform.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,21 @@ type outputValue struct {
Value cty.Value
}

// ConfigureTerraform returns a Terraform object used to execute commands
func ConfigureTerraform(workingDir string) (*tfexec.Terraform, error) {
func tfExecPath() (string, error) {
path, err := exec.LookPath("terraform")
if err != nil {
return nil, config.HintError{
return "", config.HintError{
Hint: "must have a copy of terraform installed in PATH (obtain at https://terraform.io)",
Err: err,
}
Err: err}
}
return path, nil
}

// ConfigureTerraform returns a Terraform object used to execute commands
func ConfigureTerraform(workingDir string) (*tfexec.Terraform, error) {
path, err := tfExecPath()
if err != nil {
return nil, err
}
return tfexec.NewTerraform(workingDir, path)
}
Expand Down Expand Up @@ -424,3 +431,24 @@ func ImportInputs(groupDir string, artifactsDir string, bp config.Blueprint) err
func Destroy(tf *tfexec.Terraform, b ApplyBehavior) error {
return applyOrDestroy(tf, b, true)
}

func TfVersion() (string, error) {
path, err := tfExecPath()
if err != nil {
return "", err
}

out, err := exec.Command(path, "version", "--json").Output()
if err != nil {
return "", err
}

var version struct {
TerraformVersion string `json:"terraform_version"`
}
if err := json.Unmarshal(out, &version); err != nil {
return "", err
}

return version.TerraformVersion, nil
}

0 comments on commit 9fe323e

Please sign in to comment.