diff --git a/internal/cli/root.go b/internal/cli/root.go index 978ff80c..4c7a4569 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -163,6 +163,7 @@ func (c *Client) Format() outputPkg.Format { case "": break case outputPkg.FormatTable, + outputPkg.FormatTerraform, outputPkg.FormatJSON, outputPkg.FormatYAML: format = f diff --git a/internal/outputs/outputs.go b/internal/outputs/outputs.go index 53386c35..e5c18fe7 100644 --- a/internal/outputs/outputs.go +++ b/internal/outputs/outputs.go @@ -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 { @@ -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 { @@ -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) diff --git a/internal/outputs/terraform/format.go b/internal/outputs/terraform/format.go new file mode 100644 index 00000000..7651ece3 --- /dev/null +++ b/internal/outputs/terraform/format.go @@ -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 +}