-
Notifications
You must be signed in to change notification settings - Fork 134
/
data_source_datacenters.go
101 lines (84 loc) · 2.55 KB
/
data_source_datacenters.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package fastly
import (
"context"
"encoding/json"
"log"
"strconv"
gofastly "github.com/fastly/go-fastly/v6/fastly"
"github.com/fastly/terraform-provider-fastly/fastly/hashcode"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func dataSourceFastlyDatacenters() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceFastlyDatacentersRead,
Schema: map[string]*schema.Schema{
"pops": {
Type: schema.TypeList,
Computed: true,
Description: "A list of all Fastly POPs.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"code": {
Type: schema.TypeString,
Computed: true,
Description: "A code representing the POP location.",
},
"name": {
Type: schema.TypeString,
Computed: true,
Description: "The name of the POP.",
},
"group": {
Type: schema.TypeString,
Computed: true,
Description: "A code representing the general region of the world in which the POP location resides.",
},
"shield": {
Type: schema.TypeString,
Computed: true,
Description: "A code representing the shielding name of the POP. The value may be empty if the POP is not available for shielding.",
},
},
},
},
},
}
}
func dataSourceFastlyDatacentersRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*FastlyClient).conn
log.Printf("[DEBUG] Reading datacenters")
datacenters, err := conn.AllDatacenters()
if err != nil {
return diag.Errorf("error fetching datacenters: %s", err)
}
hashBase, _ := json.Marshal(datacenters)
hashString := strconv.Itoa(hashcode.String(string(hashBase)))
d.SetId(hashString)
if err := d.Set("pops", flattenDatacenters(datacenters)); err != nil {
return diag.Errorf("error setting datacenters: %s", err)
}
return nil
}
func flattenDatacenters(datacenters []gofastly.Datacenter) []map[string]interface{} {
pops := make([]map[string]interface{}, len(datacenters))
if len(datacenters) == 0 {
return pops
}
for i, pop := range datacenters {
datacentersMapString := map[string]interface{}{
"code": pop.Code,
"name": pop.Name,
"group": pop.Group,
"shield": pop.Shield,
}
// Prune any empty values that come from the default string value in structs.
for k, v := range datacentersMapString {
if v == "" {
delete(datacentersMapString, k)
}
}
pops[i] = datacentersMapString
}
return pops
}