...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package krmtotf
16
17 import (
18 "encoding/json"
19 "fmt"
20 "strings"
21
22 "github.com/hashicorp/go-cty/cty"
23 ctyjson "github.com/hashicorp/go-cty/cty/json"
24 "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
25 "github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
26 )
27
28
29
30
31
32
33
34
35 var terraformIDReplacer = strings.NewReplacer("-", "_", ".", "_")
36
37
38
39 func InstanceStateToMap(r *schema.Resource, state *terraform.InstanceState) map[string]interface{} {
40 ctyType := ctyTypeForResource(r)
41 stateVal, err := state.AttrsAsObjectValue(ctyType)
42 if err != nil {
43 panic(fmt.Errorf("error parsing instance state as cty.Value: %v", err))
44 }
45 return CtyValToMap(stateVal, ctyType)
46 }
47
48 func MapToInstanceState(r *schema.Resource, m map[string]interface{}) *terraform.InstanceState {
49 state := terraform.NewInstanceStateShimmedFromValue(MapToCtyVal(m, r.CoreConfigSchema().ImpliedType()), r.SchemaVersion)
50
51 state.Meta["schema_version"] = fmt.Sprintf("%v", r.SchemaVersion)
52 return state
53 }
54
55 func ResourceConfigToMap(config *terraform.ResourceConfig) map[string]interface{} {
56 return config.Raw
57 }
58
59 func MapToResourceConfig(r *schema.Resource, m map[string]interface{}) *terraform.ResourceConfig {
60 schema := r.CoreConfigSchema()
61 return terraform.NewResourceConfigShimmed(MapToCtyVal(m, schema.ImpliedType()), schema)
62 }
63
64 func CtyValToMap(val cty.Value, t cty.Type) map[string]interface{} {
65 b, err := ctyjson.Marshal(val, t)
66 if err != nil {
67 panic(fmt.Errorf("error marshaling cty.Value as JSON: %v", err))
68 }
69 var ret map[string]interface{}
70 if err := json.Unmarshal(b, &ret); err != nil {
71 panic(fmt.Errorf("error unmarshaling JSON as map[string]interface{}: %v", err))
72 }
73 return ret
74 }
75
76 func MapToCtyVal(m map[string]interface{}, t cty.Type) cty.Value {
77 b, err := json.Marshal(&m)
78 if err != nil {
79 panic(fmt.Errorf("error marshaling map as JSON: %v", err))
80 }
81 ret, err := ctyjson.Unmarshal(b, t)
82 if err != nil {
83 panic(fmt.Errorf("error unmarshaling JSON as cty.Value: %v", err))
84 }
85 return ret
86 }
87
88 func MapToCtyValWithSchema(m map[string]interface{}, s map[string]*schema.Schema) cty.Value {
89 b, err := json.Marshal(&m)
90 if err != nil {
91 panic(fmt.Errorf("error marshaling map as JSON: %v", err))
92 }
93 ret, err := ctyjson.Unmarshal(b, schema.InternalMap(s).CoreConfigSchema().ImpliedType())
94 if err != nil {
95 panic(fmt.Errorf("error unmarshaling JSON as cty.Value: %v", err))
96 }
97 return ret
98 }
99
100 func ctyTypeForResource(r *schema.Resource) cty.Type {
101 return r.CoreConfigSchema().ImpliedType()
102 }
103
104
105
106 func KRMNameToTerraformID(name string) string {
107 return terraformIDReplacer.Replace(name)
108 }
109
View as plain text