diff --git a/command/jsonconfig/config.go b/command/jsonconfig/config.go index ad9d473b5..416622e20 100644 --- a/command/jsonconfig/config.go +++ b/command/jsonconfig/config.go @@ -224,8 +224,15 @@ func marshalResources(resources map[string]*configs.Resource, schemas *terraform } } - schema, schemaVersion := schemas.ResourceTypeConfig(v.ProviderConfigAddr().String(), v.Mode, v.Type) - r.SchemaVersion = schemaVersion + schema, schemaVer := schemas.ResourceTypeConfig( + v.ProviderConfigAddr().StringCompact(), + v.Mode, + v.Type, + ) + if schema == nil { + return nil, fmt.Errorf("no schema found for %s", v.Addr().String()) + } + r.SchemaVersion = schemaVer r.Expressions = marshalExpressions(v.Config, schema) diff --git a/command/jsonconfig/expression_test.go b/command/jsonconfig/expression_test.go new file mode 100644 index 000000000..e454034e5 --- /dev/null +++ b/command/jsonconfig/expression_test.go @@ -0,0 +1,73 @@ +package jsonconfig + +import ( + "encoding/json" + "reflect" + "testing" + + "github.com/zclconf/go-cty/cty" + + "github.com/hashicorp/hcl2/hcl" + "github.com/hashicorp/hcl2/hcl/hclsyntax" + "github.com/hashicorp/terraform/configs/configschema" +) + +func TestMarshalExpressions(t *testing.T) { + tests := []struct { + Input hcl.Body + Schema *configschema.Block + Want expressions + }{ + { + &hclsyntax.Body{ + Attributes: hclsyntax.Attributes{ + "foo": &hclsyntax.Attribute{ + Expr: &hclsyntax.LiteralValueExpr{ + Val: cty.StringVal("bar"), + }, + }, + }, + }, + &configschema.Block{ + Attributes: map[string]*configschema.Attribute{ + "foo": { + Type: cty.String, + Optional: true, + }, + }, + }, + expressions{ + "foo": expression{ + ConstantValue: json.RawMessage([]byte(`"bar"`)), + References: []string(nil), + }, + }, + }, + } + + for _, test := range tests { + got := marshalExpressions(test.Input, test.Schema) + if !reflect.DeepEqual(got, test.Want) { + t.Fatalf("wrong result:\nGot: %#v\nWant: %#v\n", got, test.Want) + } + } +} + +func TestMarshalExpression(t *testing.T) { + tests := []struct { + Input hcl.Expression + Want expression + }{ + { + nil, + expression{}, + }, + } + + for _, test := range tests { + got := marshalExpression(test.Input) + if !reflect.DeepEqual(got, test.Want) { + t.Fatalf("wrong result:\nGot: %#v\nWant: %#v\n", got, test.Want) + } + } +} diff --git a/command/jsonplan/plan.go b/command/jsonplan/plan.go index 6e07f0b0e..f9fbc501d 100644 --- a/command/jsonplan/plan.go +++ b/command/jsonplan/plan.go @@ -176,9 +176,13 @@ func (p *plan) marshalResourceChanges(changes *plans.Changes, schemas *terraform }) } else { filteredAfter := omitUnknowns(changeV.After) - after, err = ctyjson.Marshal(filteredAfter, filteredAfter.Type()) - if err != nil { - return err + if filteredAfter.IsNull() { + after = nil + } else { + after, err = ctyjson.Marshal(filteredAfter, filteredAfter.Type()) + if err != nil { + return err + } } afterUnknown = unknownAsBool(changeV.After) }