SDK - schema.Resource to HCL

Greetings,
I have a use case for generating Terraform files from code for certain resources. I thought I could use those resource’s provider to achieve that in the following fashion:

func main() {
	dummyProvider := &schema.Provider{
		ResourcesMap: map[string]*schema.Resource{
			"dummy_resource": {
				Schema: map[string]*schema.Schema{
					"name": {
						Type: schema.TypeString,
					},
				},
				Read: func(rd *schema.ResourceData, _ interface{}) error {
					rd.Set("name", "harvey_dent")
					return nil
				},
			},
		},
	}

	dummyResource := dummyProvider.ResourcesMap["dummy_resource"]
	dummyResourceData := dummyResource.Data(nil)
	err := dummyResource.Read(dummyResourceData, nil)
	if err != nil {
		panic(err)
	}

	fmt.Println(dummyResourceData.Get("name"))
}

At this point I have data in dummyResourceData, but how can I translate that to an actual HCL representation/terraform file?

1 Like

Have you had any luck with this?

You may marshal “dummyResourceData” using package like “gohcl” from GitHub - hashicorp/hcl: HCL is the HashiCorp configuration language., or GitHub - genelet/determined: Build customized JSON and HCL Unmarshaler with Determined .