-
Notifications
You must be signed in to change notification settings - Fork 31
/
data_source.go
86 lines (78 loc) · 1.76 KB
/
data_source.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package locations
import (
"github.com/dtcookie/hcl"
"github.com/dtcookie/opt"
"github.com/dynatrace-oss/terraform-provider-dynatrace/config"
"github.com/dynatrace-oss/terraform-provider-dynatrace/hcl2sdk"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func DataSource() *schema.Resource {
return &schema.Resource{
Read: DataSourceRead,
Schema: hcl2sdk.Convert(map[string]*hcl.Schema{
"id": {
Type: hcl.TypeString,
Optional: true,
},
"name": {
Type: hcl.TypeString,
Optional: true,
},
"locations": {
Type: hcl.TypeList,
MaxItems: 1,
Elem: &hcl.Resource{Schema: new(Locations).Schema()},
Optional: true,
Computed: true,
},
}),
}
}
func DataSourceRead(d *schema.ResourceData, m interface{}) error {
var id *string
var name *string
if v, ok := d.GetOk("id"); ok {
d.SetId(v.(string))
id = opt.NewString(v.(string))
} else {
d.SetId(uuid.New().String())
}
if v, ok := d.GetOk("name"); ok {
name = opt.NewString(v.(string))
}
conf := m.(*config.ProviderConfiguration)
apiService := NewService(conf.DTNonConfigEnvURL, conf.APIToken)
locationList, err := apiService.List()
if err != nil {
return err
}
locs := Locations{}
for _, location := range locationList.Locations {
if id != nil {
if *id != location.ID {
continue
}
}
if name != nil {
if *name != location.Name {
continue
}
}
locs = append(locs, &Location{
ID: location.ID,
Name: location.Name,
Type: LocationType(string(location.Type)),
})
}
marshalled, err := locs.MarshalHCL()
if err != nil {
return err
}
them := map[string]interface{}{}
for k, v := range marshalled {
them[k] = v
}
d.Set("locations", []interface{}{them})
return nil
}