genelet / determined

Build customized JSON and HCL Unmarshaler with Determined
https://medium.com/@peterbi_91340/decoding-of-dynamic-json-data-1d4e67318661
MIT License
19 stars 3 forks source link

JSON to HCL is not working properly #3

Closed tqindia closed 4 months ago

tqindia commented 4 months ago

Currently, we are using the convert package to convert JSON to HCL, which works well for modules and inputs but generates problematic HCL code for providers and outputs. The issue is similar to the problem discussed in a blog about handling arrays and maps in HCL.

Examples of the Problem

Example 1: Providers in provider.tf

{
  "terraform": {
    "required_providers": {
      "gcp": {
        "source": "hashicorp/gcp",
        "version": "4.27.0"
      },
      "helm": {
        "source": "hashicorp/helm",
        "version": "2.6.0"
      }
    },
    "backend": {
      "local": {
        "path": "./tfstate/cops.tfstate"
      }
    }
  }
}

Generated HCL Output (Incorrect):


 terraform  "backend"  {
    local = {
      path = "./tfstate/cops.tfstate"
    }
  }
  terraform "required_providers" "gcp"  {
    source = "hashicorp/gcp"
    version = "4.27.0"
  }
  terraform "required_providers" "helm"  {
    source = "hashicorp/helm"
    version = "2.6.0"
  }

The convert package generates incorrect HCL code where terraform "required_providers" and terraform "backend" are mixed up and not properly structured.

My Code

package terraform

import (
    v1 "saas/pkg/gen/cops/v1"

    "github.com/genelet/determined/convert"
)

// ParseTerraform formats and beautifies the given Terraform content.
func ParseTerraform(content string, file, key string, cloud *v1.Cloud) ([]byte, error) {
    // Convert JSON content to HCL if it's neither "terraform.tf" nor "output.tf"
    hcl, err := convert.JSONToHCL([]byte(content))
    if err != nil {
        return []byte(""), err
    }
    return hcl, nil
}
tqindia commented 4 months ago

Mine Json issue