Skip to content

Commit

Permalink
add terraform outputter format (with basic device support)
Browse files Browse the repository at this point in the history
Signed-off-by: Marques Johansson <[email protected]>
  • Loading branch information
displague committed Jul 23, 2021
1 parent 97ef14c commit 47cc2c8
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 3 deletions.
1 change: 1 addition & 0 deletions internal/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ func (c *Client) Format() outputPkg.Format {
case "":
break
case outputPkg.FormatTable,
outputPkg.FormatTerraform,
outputPkg.FormatJSON,
outputPkg.FormatYAML:
format = f
Expand Down
20 changes: 17 additions & 3 deletions internal/outputs/outputs.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@ import (

"github.com/olekukonko/tablewriter"
"sigs.k8s.io/yaml"

"github.com/equinix/metal-cli/internal/outputs/terraform"
)

type Format string

const (
FormatTable Format = "table"
FormatJSON Format = "json"
FormatYAML Format = "yaml"
FormatTable Format = "table"
FormatJSON Format = "json"
FormatYAML Format = "yaml"
FormatTerraform Format = "tf"
)

type Outputer interface {
Expand All @@ -26,6 +29,15 @@ type Standard struct {
Format Format
}

func outputTerraform(in interface{}) error {
output, err := terraform.Marshal(in)
if err != nil {
return err
}
fmt.Println(string(output))
return nil
}

func outputJSON(in interface{}) error {
output, err := json.MarshalIndent(in, "", " ")
if err != nil {
Expand All @@ -49,6 +61,8 @@ func (o *Standard) Output(in interface{}, header []string, data *[][]string) err
return outputJSON(in)
} else if o.Format == FormatYAML {
return outputYAML(in)
} else if o.Format == FormatTerraform {
return outputTerraform(in)
} else {
table := tablewriter.NewWriter(os.Stdout)
table.SetAutoWrapText(false)
Expand Down
45 changes: 45 additions & 0 deletions internal/outputs/terraform/format.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package terraform

import (
"bytes"
"html/template"

"github.com/packethost/packngo"
)

const deviceFormat = `
# terraform import metal_device.{{.Hostname}} {{.ID}}
resource "metal_device" "{{.Hostname}}" {
plan = "{{.Plan.Slug}}"
hostname = "{{.Hostname}}"
billing_cycle = "{{.BillingCycle}}"
metro = "{{.Metro.Code}}"
operating_system = "{{.OS.Slug}}"
project_id = "{{.Project.ID}}"
tags = {{.Tags}}
}
`

func many(s string) string {
return `{{range .}}` + s + `{{end}}`
}
func Marshal(i interface{}) ([]byte, error) {
var f = ""
switch i.(type) {
case *packngo.Device:
f = deviceFormat
case []packngo.Device:
f = many(deviceFormat)
}
tmpl, err := template.New("terraform").Parse(f)
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
err = tmpl.Execute(buf, i)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}

0 comments on commit 47cc2c8

Please sign in to comment.