forked from ivoronin/terraform-provider-netbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_prefix.go
89 lines (81 loc) · 2.2 KB
/
resource_prefix.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
package main
import (
"fmt"
"net/http"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/go-resty/resty/v2"
)
func resourcePrefix() *schema.Resource {
return &schema.Resource{
Create: resourcePrefixCreate,
Read: resourcePrefixRead,
Update: resourcePrefixUpdate,
Delete: resourcePrefixDelete,
Schema: map[string]*schema.Schema{
"prefix": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
},
}
}
type Prefix struct {
Id int `json:"id"`
Prefix string `json:"prefix"`
}
func resourcePrefixCreate(d *schema.ResourceData, m interface{}) error {
client := m.(*resty.Client)
resp, err := client.R().
SetBody(Prefix{Prefix: d.Get("prefix").(string)}).
SetResult(Prefix{}).
Post("/ipam/prefixes/")
if err != nil {
return err
}
if resp.StatusCode() != http.StatusCreated {
return fmt.Errorf("POST: Unexpected HTTP status: %s", resp.Status())
}
prefix := resp.Result().(*Prefix)
d.SetId(fmt.Sprintf("%d", prefix.Id))
return resourcePrefixRead(d, m)
}
func resourcePrefixRead(d *schema.ResourceData, m interface{}) error {
client := m.(*resty.Client)
resp, err := client.R().
SetResult(Prefix{}).
Get(fmt.Sprintf("/ipam/prefixes/%s/", d.Id()))
if err != nil {
return err
}
if resp.StatusCode() != http.StatusOK {
return fmt.Errorf("GET: Unexpected HTTP status: %s", resp.Status())
}
prefix := resp.Result().(*Prefix)
d.Set("prefix", prefix.Prefix)
return nil
}
func resourcePrefixUpdate(d *schema.ResourceData, m interface{}) error {
client := m.(*resty.Client)
resp, err := client.R().
SetBody(Prefix{Prefix: d.Get("prefix").(string)}).
Put(fmt.Sprintf("/ipam/prefixes/%s/", d.Id()))
if err != nil {
return err
}
if resp.StatusCode() != http.StatusOK {
return fmt.Errorf("PUT: Unexpected HTTP status: %s", resp.Status())
}
return resourcePrefixRead(d, m)
}
func resourcePrefixDelete(d *schema.ResourceData, m interface{}) error {
client := m.(*resty.Client)
resp, err := client.R().
Delete(fmt.Sprintf("/ipam/prefixes/%s/", d.Id()))
if err != nil {
return err
}
if resp.StatusCode() != http.StatusNoContent {
return fmt.Errorf("DELETE: Unexpected HTTP status: %s", resp.Status())
}
return nil
}