github.com/richardbowden/terraform@v0.6.12-0.20160901200758-30ea22c25211/builtin/providers/scaleway/resource_scaleway_ip.go (about) 1 package scaleway 2 3 import ( 4 "log" 5 6 "github.com/hashicorp/terraform/helper/schema" 7 "github.com/scaleway/scaleway-cli/pkg/api" 8 ) 9 10 func resourceScalewayIP() *schema.Resource { 11 return &schema.Resource{ 12 Create: resourceScalewayIPCreate, 13 Read: resourceScalewayIPRead, 14 Update: resourceScalewayIPUpdate, 15 Delete: resourceScalewayIPDelete, 16 Schema: map[string]*schema.Schema{ 17 "server": &schema.Schema{ 18 Type: schema.TypeString, 19 Optional: true, 20 }, 21 "ip": &schema.Schema{ 22 Type: schema.TypeString, 23 Computed: true, 24 }, 25 }, 26 } 27 } 28 29 func resourceScalewayIPCreate(d *schema.ResourceData, m interface{}) error { 30 scaleway := m.(*Client).scaleway 31 resp, err := scaleway.NewIP() 32 if err != nil { 33 return err 34 } 35 36 d.SetId(resp.IP.ID) 37 return resourceScalewayIPUpdate(d, m) 38 } 39 40 func resourceScalewayIPRead(d *schema.ResourceData, m interface{}) error { 41 scaleway := m.(*Client).scaleway 42 log.Printf("[DEBUG] Reading IP\n") 43 44 resp, err := scaleway.GetIP(d.Id()) 45 if err != nil { 46 log.Printf("[DEBUG] Error reading ip: %q\n", err) 47 if serr, ok := err.(api.ScalewayAPIError); ok { 48 if serr.StatusCode == 404 { 49 d.SetId("") 50 return nil 51 } 52 } 53 return err 54 } 55 56 d.Set("ip", resp.IP.Address) 57 if resp.IP.Server != nil { 58 d.Set("server", resp.IP.Server.Identifier) 59 } 60 return nil 61 } 62 63 func resourceScalewayIPUpdate(d *schema.ResourceData, m interface{}) error { 64 scaleway := m.(*Client).scaleway 65 if d.HasChange("server") { 66 if d.Get("server").(string) != "" { 67 log.Printf("[DEBUG] Attaching IP %q to server %q\n", d.Id(), d.Get("server").(string)) 68 if err := scaleway.AttachIP(d.Id(), d.Get("server").(string)); err != nil { 69 return err 70 } 71 } else { 72 log.Printf("[DEBUG] Detaching IP %q\n", d.Id()) 73 return DetachIP(scaleway, d.Id()) 74 } 75 } 76 77 return resourceScalewayIPRead(d, m) 78 } 79 80 func resourceScalewayIPDelete(d *schema.ResourceData, m interface{}) error { 81 scaleway := m.(*Client).scaleway 82 err := scaleway.DeleteIP(d.Id()) 83 if err != nil { 84 return err 85 } 86 d.SetId("") 87 return nil 88 }