Merge pull request #3748 from stack72/do-floatingips

provider/digitalocean : New Resource for Floating IPs
This commit is contained in:
James Nugent 2015-11-24 13:16:24 +02:00
commit 1cde2e64a0
5 changed files with 333 additions and 4 deletions

View File

@ -18,10 +18,11 @@ func Provider() terraform.ResourceProvider {
},
ResourcesMap: map[string]*schema.Resource{
"digitalocean_domain": resourceDigitalOceanDomain(),
"digitalocean_droplet": resourceDigitalOceanDroplet(),
"digitalocean_record": resourceDigitalOceanRecord(),
"digitalocean_ssh_key": resourceDigitalOceanSSHKey(),
"digitalocean_domain": resourceDigitalOceanDomain(),
"digitalocean_droplet": resourceDigitalOceanDroplet(),
"digitalocean_floating_ip": resourceDigitalOceanFloatingIp(),
"digitalocean_record": resourceDigitalOceanRecord(),
"digitalocean_ssh_key": resourceDigitalOceanSSHKey(),
},
ConfigureFunc: providerConfigure,

View File

@ -0,0 +1,159 @@
package digitalocean
import (
"fmt"
"log"
"time"
"github.com/digitalocean/godo"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceDigitalOceanFloatingIp() *schema.Resource {
return &schema.Resource{
Create: resourceDigitalOceanFloatingIpCreate,
Read: resourceDigitalOceanFloatingIpRead,
Delete: resourceDigitalOceanFloatingIpDelete,
Schema: map[string]*schema.Schema{
"ip_address": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"region": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"droplet_id": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceDigitalOceanFloatingIpCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*godo.Client)
log.Printf("[INFO] Create a FloatingIP In a Region")
regionOpts := &godo.FloatingIPCreateRequest{
Region: d.Get("region").(string),
}
log.Printf("[DEBUG] FloatingIP Create: %#v", regionOpts)
floatingIp, _, err := client.FloatingIPs.Create(regionOpts)
if err != nil {
return fmt.Errorf("Error creating FloatingIP: %s", err)
}
d.SetId(floatingIp.IP)
if v, ok := d.GetOk("droplet_id"); ok {
log.Printf("[INFO] Assigning the Floating IP to the Droplet %s", v.(int))
action, _, err := client.FloatingIPActions.Assign(d.Id(), v.(int))
if err != nil {
return fmt.Errorf(
"Error Assigning FloatingIP (%s) to the droplet: %s", d.Id(), err)
}
_, unassignedErr := waitForFloatingIPReady(d, "completed", []string{"new", "in-progress"}, "status", meta, action.ID)
if unassignedErr != nil {
return fmt.Errorf(
"Error waiting for FloatingIP (%s) to be Assigned: %s", d.Id(), unassignedErr)
}
}
return resourceDigitalOceanFloatingIpRead(d, meta)
}
func resourceDigitalOceanFloatingIpRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*godo.Client)
log.Printf("[INFO] Reading the details of the FloatingIP %s", d.Id())
floatingIp, _, err := client.FloatingIPs.Get(d.Id())
if err != nil {
return fmt.Errorf("Error retrieving FloatingIP: %s", err)
}
if _, ok := d.GetOk("droplet_id"); ok {
log.Printf("[INFO] The region of the Droplet is %s", floatingIp.Droplet.Region)
d.Set("region", floatingIp.Droplet.Region.Slug)
} else {
d.Set("region", floatingIp.Region.Slug)
}
d.Set("ip_address", floatingIp.IP)
return nil
}
func resourceDigitalOceanFloatingIpDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*godo.Client)
if _, ok := d.GetOk("droplet_id"); ok {
log.Printf("[INFO] Unassigning the Floating IP from the Droplet")
action, _, err := client.FloatingIPActions.Unassign(d.Id())
if err != nil {
return fmt.Errorf(
"Error Unassigning FloatingIP (%s) from the droplet: %s", d.Id(), err)
}
_, unassignedErr := waitForFloatingIPReady(d, "completed", []string{"new", "in-progress"}, "status", meta, action.ID)
if unassignedErr != nil {
return fmt.Errorf(
"Error waiting for FloatingIP (%s) to be unassigned: %s", d.Id(), unassignedErr)
}
}
log.Printf("[INFO] Deleting FloatingIP: %s", d.Id())
_, err := client.FloatingIPs.Delete(d.Id())
if err != nil {
return fmt.Errorf("Error deleting FloatingIP: %s", err)
}
d.SetId("")
return nil
}
func waitForFloatingIPReady(
d *schema.ResourceData, target string, pending []string, attribute string, meta interface{}, actionId int) (interface{}, error) {
log.Printf(
"[INFO] Waiting for FloatingIP (%s) to have %s of %s",
d.Id(), attribute, target)
stateConf := &resource.StateChangeConf{
Pending: pending,
Target: target,
Refresh: newFloatingIPStateRefreshFunc(d, attribute, meta, actionId),
Timeout: 60 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
NotFoundChecks: 60,
}
return stateConf.WaitForState()
}
func newFloatingIPStateRefreshFunc(
d *schema.ResourceData, attribute string, meta interface{}, actionId int) resource.StateRefreshFunc {
client := meta.(*godo.Client)
return func() (interface{}, string, error) {
log.Printf("[INFO] Assigning the Floating IP to the Droplet")
action, _, err := client.FloatingIPActions.Get(d.Id(), actionId)
if err != nil {
return nil, "", fmt.Errorf("Error retrieving FloatingIP (%s) ActionId (%d): %s", d.Id(), actionId, err)
}
log.Printf("[INFO] The FloatingIP Action Status is %s", action.Status)
return &action, action.Status, nil
}
}

View File

@ -0,0 +1,121 @@
package digitalocean
import (
"fmt"
"testing"
"github.com/digitalocean/godo"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccDigitalOceanFloatingIP_Region(t *testing.T) {
var floatingIP godo.FloatingIP
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckDigitalOceanFloatingIPDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccCheckDigitalOceanFloatingIPConfig_region,
Check: resource.ComposeTestCheckFunc(
testAccCheckDigitalOceanFloatingIPExists("digitalocean_floating_ip.foobar", &floatingIP),
resource.TestCheckResourceAttr(
"digitalocean_floating_ip.foobar", "region", "nyc3"),
),
},
},
})
}
func TestAccDigitalOceanFloatingIP_Droplet(t *testing.T) {
var floatingIP godo.FloatingIP
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckDigitalOceanFloatingIPDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccCheckDigitalOceanFloatingIPConfig_droplet,
Check: resource.ComposeTestCheckFunc(
testAccCheckDigitalOceanFloatingIPExists("digitalocean_floating_ip.foobar", &floatingIP),
resource.TestCheckResourceAttr(
"digitalocean_floating_ip.foobar", "region", "sgp1"),
),
},
},
})
}
func testAccCheckDigitalOceanFloatingIPDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*godo.Client)
for _, rs := range s.RootModule().Resources {
if rs.Type != "digitalocean_floating_ip" {
continue
}
// Try to find the key
_, _, err := client.FloatingIPs.Get(rs.Primary.ID)
if err == nil {
fmt.Errorf("Floating IP still exists")
}
}
return nil
}
func testAccCheckDigitalOceanFloatingIPExists(n string, floatingIP *godo.FloatingIP) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No Record ID is set")
}
client := testAccProvider.Meta().(*godo.Client)
// Try to find the FloatingIP
foundFloatingIP, _, err := client.FloatingIPs.Get(rs.Primary.ID)
if err != nil {
return err
}
if foundFloatingIP.IP != rs.Primary.ID {
return fmt.Errorf("Record not found")
}
*floatingIP = *foundFloatingIP
return nil
}
}
var testAccCheckDigitalOceanFloatingIPConfig_region = `
resource "digitalocean_floating_ip" "foobar" {
region = "nyc3"
}`
var testAccCheckDigitalOceanFloatingIPConfig_droplet = `
resource "digitalocean_droplet" "foobar" {
name = "baz"
size = "1gb"
image = "centos-5-8-x32"
region = "sgp1"
ipv6 = true
private_networking = true
}
resource "digitalocean_floating_ip" "foobar" {
droplet_id = "${digitalocean_droplet.foobar.id}"
region = "${digitalocean_droplet.foobar.region}"
}`

View File

@ -0,0 +1,44 @@
---
layout: "digitalocean"
page_title: "DigitalOcean: digitalocean_floating_ip"
sidebar_current: "docs-do-resource-floating-ip"
description: |-
Provides a DigitalOcean Floating IP resource.
---
# digitalocean\_floating_ip
Provides a DigitalOcean Floating IP to represent a publicly-accessible static IP addresses that can be mapped to one of your Droplets.
## Example Usage
```
resource "digitalocean_droplet" "foobar" {
name = "baz"
size = "1gb"
image = "centos-5-8-x32"
region = "sgp1"
ipv6 = true
private_networking = true
}
resource "digitalocean_floating_ip" "foobar" {
droplet_id = "${digitalocean_droplet.foobar.id}"
region = "${digitalocean_droplet.foobar.region}"
}
```
## Argument Reference
The following arguments are supported:
* `region` - (Required) The region that the Floating IP is reserved to.
* `droplet_id` - (Optional) The ID of Droplet that the Floating IP will be assigned to.
~> **NOTE:** A Floating IP can be assigned to a region OR a droplet_id. If both region AND droplet_id are specified, then the Floating IP will be assigned to the droplet and use that region
## Attributes Reference
The following attributes are exported:
* `ip_address` - The IP Address of the resource

View File

@ -21,6 +21,10 @@
<a href="/docs/providers/do/r/droplet.html">digitalocean_droplet</a>
</li>
<li<%= sidebar_current("docs-do-resource-floating-ip") %>>
<a href="/docs/providers/do/r/floating_ip.html">digitalocean_floating_ip</a>
</li>
<li<%= sidebar_current("docs-do-resource-record") %>>
<a href="/docs/providers/do/r/record.html">digitalocean_record</a>
</li>