restructure JSON terraform config block AST

When configuration is read out of JSON, HCL assumes that empty levels of
objects can be flattened, but this removes too much to decode into a
config.Terraform struct.

Reconstruct the appropriate AST to decode the config struct.
This commit is contained in:
James Bardin 2017-03-21 18:04:19 -04:00
parent 7729949ef4
commit 8bcb9e19ca
3 changed files with 48 additions and 0 deletions

View File

@ -209,6 +209,19 @@ func loadTerraformHcl(list *ast.ObjectList) (*Terraform, error) {
// Get our one item
item := list.Items[0]
// This block should have an empty top level ObjectItem. If there are keys
// here, it's likely because we have a flattened JSON object, and we can
// lift this into a nested ObjectList to decode properly.
if len(item.Keys) > 0 {
item = &ast.ObjectItem{
Val: &ast.ObjectType{
List: &ast.ObjectList{
Items: []*ast.ObjectItem{item},
},
},
}
}
// We need the item value as an ObjectList
var listVal *ast.ObjectList
if ot, ok := item.Val.(*ast.ObjectType); ok {

View File

@ -384,6 +384,32 @@ backend (s3)
}
}
// test that the alternate, more obvious JSON format also decodes properly
func TestLoadFile_terraformBackendJSON2(t *testing.T) {
c, err := LoadFile(filepath.Join(fixtureDir, "terraform-backend-2.tf.json"))
if err != nil {
t.Fatalf("err: %s", err)
}
if c == nil {
t.Fatal("config should not be nil")
}
if c.Dir != "" {
t.Fatalf("bad: %#v", c.Dir)
}
{
actual := terraformStr(c.Terraform)
expected := strings.TrimSpace(`
backend (s3)
foo`)
if actual != expected {
t.Fatalf("bad:\n%s", actual)
}
}
}
func TestLoadFile_terraformBackendMulti(t *testing.T) {
_, err := LoadFile(filepath.Join(fixtureDir, "terraform-backend-multi.tf"))
if err == nil {

View File

@ -0,0 +1,9 @@
{
"terraform": {
"backend": {
"s3": {
"foo": "bar"
}
}
}
}