chanzuckerberg / fogg

Manage Infrastructure as Code with less pain.
https://chanzuckerberg.github.io/fogg/
MIT License
294 stars 20 forks source link

feat: Use hclwriter in gotemplates #936

Open vincenthsh opened 1 year ago

vincenthsh commented 1 year ago

Example Implementation writing a foo = {} assignment

Example Implementation writing a provider "foo" {} block

Usage in go templates:

terraform {
  required_version = "={{ .TerraformVersion }}"
  {{ template "backend" .Backend }}
  required_providers {
    {{- range $k, $v := .ProviderVersions }}
    {{ toHclAssignment $k $v }}
    {{- end }}
  }
}

Result:

terraform {
  required_version = "=1.5.7"
  backend "s3" {
    # snip
    ...
  }
  required_providers {
    archive = {
      source  = "hashicorp/archive"
      version = "~> 2.0"
    }
    assert = {
      source  = "bwoznicki/assert"
      version = "0.0.1"
    }
    ...

Caveat: requires json tags on the golang structs as zclconf/go-cty only supports UnmarshalJSON

// json tags required for toHCLAssignment function
// in util/template.go
type ProviderVersion struct {
  Source  string  `yaml:"source" json:"source"`
  Version *string `yaml:"version" json:"version"`
}

Inspiration from:

vincenthsh commented 1 year ago

Just noticed github.com/zclconf/go-cty-yaml - may not need json tags 🤦‍♂️