github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/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  		Importer: &schema.ResourceImporter{
    17  			State: schema.ImportStatePassthrough,
    18  		},
    19  
    20  		Schema: map[string]*schema.Schema{
    21  			"server": &schema.Schema{
    22  				Type:     schema.TypeString,
    23  				Optional: true,
    24  			},
    25  			"ip": &schema.Schema{
    26  				Type:     schema.TypeString,
    27  				Computed: true,
    28  			},
    29  		},
    30  	}
    31  }
    32  
    33  func resourceScalewayIPCreate(d *schema.ResourceData, m interface{}) error {
    34  	scaleway := m.(*Client).scaleway
    35  	resp, err := scaleway.NewIP()
    36  	if err != nil {
    37  		return err
    38  	}
    39  
    40  	d.SetId(resp.IP.ID)
    41  	return resourceScalewayIPUpdate(d, m)
    42  }
    43  
    44  func resourceScalewayIPRead(d *schema.ResourceData, m interface{}) error {
    45  	scaleway := m.(*Client).scaleway
    46  	log.Printf("[DEBUG] Reading IP\n")
    47  
    48  	resp, err := scaleway.GetIP(d.Id())
    49  	if err != nil {
    50  		log.Printf("[DEBUG] Error reading ip: %q\n", err)
    51  		if serr, ok := err.(api.ScalewayAPIError); ok {
    52  			if serr.StatusCode == 404 {
    53  				d.SetId("")
    54  				return nil
    55  			}
    56  		}
    57  		return err
    58  	}
    59  
    60  	d.Set("ip", resp.IP.Address)
    61  	if resp.IP.Server != nil {
    62  		d.Set("server", resp.IP.Server.Identifier)
    63  	}
    64  	return nil
    65  }
    66  
    67  func resourceScalewayIPUpdate(d *schema.ResourceData, m interface{}) error {
    68  	scaleway := m.(*Client).scaleway
    69  	if d.HasChange("server") {
    70  		if d.Get("server").(string) != "" {
    71  			log.Printf("[DEBUG] Attaching IP %q to server %q\n", d.Id(), d.Get("server").(string))
    72  			if err := scaleway.AttachIP(d.Id(), d.Get("server").(string)); err != nil {
    73  				return err
    74  			}
    75  		} else {
    76  			log.Printf("[DEBUG] Detaching IP %q\n", d.Id())
    77  			return scaleway.DetachIP(d.Id())
    78  		}
    79  	}
    80  
    81  	return resourceScalewayIPRead(d, m)
    82  }
    83  
    84  func resourceScalewayIPDelete(d *schema.ResourceData, m interface{}) error {
    85  	scaleway := m.(*Client).scaleway
    86  	err := scaleway.DeleteIP(d.Id())
    87  	if err != nil {
    88  		return err
    89  	}
    90  	d.SetId("")
    91  	return nil
    92  }