/
data_source_ip_space.go
95 lines (79 loc) · 2.7 KB
/
data_source_ip_space.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
package solidserver
import (
"context"
"encoding/json"
"fmt"
"github.com/MakeNowJust/heredoc/v2"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"net/url"
)
func dataSourceipspace() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceipspaceRead,
Description: heredoc.Doc(`
Space data-source allows to retrieve information about reserved IP spaces, including meta-data.
Spaces are the highest level objets in the SOLIDserver's IPAM module organization,
the entry point of any IPv4 or IPv6 addressing plan. It allows to manage unique ranges
of IP addresses.
`),
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Description: "The name of the IP space.",
Required: true,
},
"class": {
Type: schema.TypeString,
Description: "The class associated to the IP space.",
Computed: true,
},
"class_parameters": {
Type: schema.TypeMap,
Description: "The class parameters associated to IP space.",
Computed: true,
},
},
}
}
func dataSourceipspaceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
s := meta.(*SOLIDserver)
d.SetId("")
// Building parameters
parameters := url.Values{}
parameters.Add("WHERE", "site_name='"+d.Get("name").(string)+"'")
// Sending the read request
resp, body, err := s.Request("get", "rest/ip_site_list", ¶meters)
if err == nil {
var buf [](map[string]interface{})
json.Unmarshal([]byte(body), &buf)
// Checking the answer
if resp.StatusCode == 200 && len(buf) > 0 {
d.SetId(buf[0]["site_id"].(string))
d.Set("name", buf[0]["site_name"].(string))
d.Set("class", buf[0]["site_class_name"].(string))
// Updating local class_parameters
retrievedClassParameters, _ := url.ParseQuery(buf[0]["site_class_parameters"].(string))
computedClassParameters := map[string]string{}
for ck := range retrievedClassParameters {
computedClassParameters[ck] = retrievedClassParameters[ck][0]
}
d.Set("class_parameters", computedClassParameters)
return nil
}
if len(buf) > 0 {
if errMsg, errExist := buf[0]["errmsg"].(string); errExist {
// Log the error
tflog.Debug(ctx, fmt.Sprintf("Unable to read information from IP space: %s (%s)\n", d.Get("name").(string), errMsg))
}
} else {
// Log the error
tflog.Debug(ctx, fmt.Sprintf("Unable to read information from IP space: %s\n", d.Get("name").(string)))
}
// Reporting a failure
return diag.Errorf("Unable to find IP space: %s\n", d.Get("name").(string))
}
// Reporting a failure
return diag.FromErr(err)
}