@@ -2,8 +2,10 @@ package types
2
2
3
3
import (
4
4
"context"
5
+ "fmt"
5
6
6
7
"github.com/hashicorp/terraform-plugin-framework/attr"
8
+ "github.com/hashicorp/terraform-plugin-framework/internal/reflect"
7
9
"github.com/hashicorp/terraform-plugin-go/tftypes"
8
10
)
9
11
@@ -80,6 +82,37 @@ type Object struct {
80
82
AttributeTypes map [string ]attr.Type
81
83
}
82
84
85
+ // As populates `target` with the data in the Object, throwing an error if the
86
+ // data cannot be stored in `target`.
87
+ func (o * Object ) ElementsAs (ctx context.Context , target interface {}, allowUnhandled bool ) error {
88
+ // we need a tftypes.Value for this Object to be able to use it with
89
+ // our reflection code
90
+ values := map [string ]tftypes.Value {}
91
+ types := map [string ]tftypes.Type {}
92
+ for key , attr := range o .Attributes {
93
+ val , err := attr .ToTerraformValue (ctx )
94
+ if err != nil {
95
+ return fmt .Errorf ("error getting Terraform value for attribute %q: %w" , key , err )
96
+ }
97
+ typ , ok := o .AttributeTypes [key ]
98
+ if ! ok {
99
+ return fmt .Errorf ("no AttributeType defined for attribute %q: %w" , key , err )
100
+ }
101
+ types [key ] = typ .TerraformType (ctx )
102
+ err = tftypes .ValidateValue (typ .TerraformType (ctx ), val )
103
+ if err != nil {
104
+ return fmt .Errorf ("error using created Terraform value for element %q: %w" , key , err )
105
+ }
106
+ values [key ] = tftypes .NewValue (typ .TerraformType (ctx ), val )
107
+ }
108
+ return reflect .Into (ctx , tftypes .NewValue (tftypes.Object {
109
+ AttributeTypes : types ,
110
+ }, values ), target , reflect.Options {
111
+ UnhandledNullAsEmpty : allowUnhandled ,
112
+ UnhandledUnknownAsEmpty : allowUnhandled ,
113
+ })
114
+ }
115
+
83
116
// ToTerraformValue returns the data contained in the AttributeValue as
84
117
// a Go type that tftypes.NewValue will accept.
85
118
func (o * Object ) ToTerraformValue (ctx context.Context ) (interface {}, error ) {
0 commit comments