forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 7
/
resource_scaleway_ip.go
88 lines (77 loc) · 1.98 KB
/
resource_scaleway_ip.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
package scaleway
import (
"log"
"github.com/hashicorp/terraform/helper/schema"
"github.com/scaleway/scaleway-cli/pkg/api"
)
func resourceScalewayIP() *schema.Resource {
return &schema.Resource{
Create: resourceScalewayIPCreate,
Read: resourceScalewayIPRead,
Update: resourceScalewayIPUpdate,
Delete: resourceScalewayIPDelete,
Schema: map[string]*schema.Schema{
"server": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"ip": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceScalewayIPCreate(d *schema.ResourceData, m interface{}) error {
scaleway := m.(*Client).scaleway
resp, err := scaleway.NewIP()
if err != nil {
return err
}
d.SetId(resp.IP.ID)
return resourceScalewayIPUpdate(d, m)
}
func resourceScalewayIPRead(d *schema.ResourceData, m interface{}) error {
scaleway := m.(*Client).scaleway
log.Printf("[DEBUG] Reading IP\n")
resp, err := scaleway.GetIP(d.Id())
if err != nil {
log.Printf("[DEBUG] Error reading ip: %q\n", err)
if serr, ok := err.(api.ScalewayAPIError); ok {
if serr.StatusCode == 404 {
d.SetId("")
return nil
}
}
return err
}
d.Set("ip", resp.IP.Address)
if resp.IP.Server != nil {
d.Set("server", resp.IP.Server.Identifier)
}
return nil
}
func resourceScalewayIPUpdate(d *schema.ResourceData, m interface{}) error {
scaleway := m.(*Client).scaleway
if d.HasChange("server") {
if d.Get("server").(string) != "" {
log.Printf("[DEBUG] Attaching IP %q to server %q\n", d.Id(), d.Get("server").(string))
if err := scaleway.AttachIP(d.Id(), d.Get("server").(string)); err != nil {
return err
}
} else {
log.Printf("[DEBUG] Detaching IP %q\n", d.Id())
return DetachIP(scaleway, d.Id())
}
}
return resourceScalewayIPRead(d, m)
}
func resourceScalewayIPDelete(d *schema.ResourceData, m interface{}) error {
scaleway := m.(*Client).scaleway
err := scaleway.DeleteIP(d.Id())
if err != nil {
return err
}
d.SetId("")
return nil
}