Skip to content

Commit

Permalink
Cloudflare LoadBalancer support for Pool Latitude and Longitude
Browse files Browse the repository at this point in the history
Removed duplicated float validation function replaced with standard
version from validation package.
  • Loading branch information
Timothy W Polich committed Jul 16, 2021
1 parent 0b519b4 commit 82b9c9c
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 22 deletions.
60 changes: 41 additions & 19 deletions cloudflare/resource_cloudflare_load_balancer_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log"
"math"
"strings"

"time"
Expand Down Expand Up @@ -52,6 +53,18 @@ func resourceCloudflareLoadBalancerPool() *schema.Resource {
Default: 1,
},

"latitude": {
Type: schema.TypeFloat,
Optional: true,
ValidateFunc: validation.FloatBetween(-90, 90),
},

"longitude": {
Type: schema.TypeFloat,
Optional: true,
ValidateFunc: validation.FloatBetween(-180, 180),
},

"check_regions": {
Type: schema.TypeSet,
Optional: true,
Expand Down Expand Up @@ -111,7 +124,7 @@ var originsElem = &schema.Resource{
Type: schema.TypeFloat,
Optional: true,
Default: 1.0,
ValidateFunc: floatBetween(0.0, 1.0),
ValidateFunc: validation.FloatBetween(0.0, 1.0),
},

"enabled": {
Expand Down Expand Up @@ -153,6 +166,15 @@ func resourceCloudflareLoadBalancerPoolCreate(d *schema.ResourceData, meta inter
MinimumOrigins: d.Get("minimum_origins").(int),
}

if lat, ok := d.GetOk("latitude"); ok {
f := float32(lat.(float64))
loadBalancerPool.Latitude = &f
}
if long, ok := d.GetOk("longitude"); ok {
f := float32(long.(float64))
loadBalancerPool.Longitude = &f
}

if checkRegions, ok := d.GetOk("check_regions"); ok {
loadBalancerPool.CheckRegions = expandInterfaceToStringList(checkRegions.(*schema.Set).List())
}
Expand Down Expand Up @@ -198,6 +220,15 @@ func resourceCloudflareLoadBalancerPoolUpdate(d *schema.ResourceData, meta inter
MinimumOrigins: d.Get("minimum_origins").(int),
}

if lat, ok := d.GetOk("latitude"); ok {
f := float32(lat.(float64))
loadBalancerPool.Latitude = &f
}
if long, ok := d.GetOk("longitude"); ok {
f := float32(long.(float64))
loadBalancerPool.Longitude = &f
}

if checkRegions, ok := d.GetOk("check_regions"); ok {
loadBalancerPool.CheckRegions = expandInterfaceToStringList(checkRegions.(*schema.Set).List())
}
Expand Down Expand Up @@ -290,6 +321,15 @@ func resourceCloudflareLoadBalancerPoolRead(d *schema.ResourceData, meta interfa
d.Set("created_on", loadBalancerPool.CreatedOn.Format(time.RFC3339Nano))
d.Set("modified_on", loadBalancerPool.ModifiedOn.Format(time.RFC3339Nano))

if lat := loadBalancerPool.Latitude; lat != nil {
f := math.Round(float64(*lat)*10000) / 10000 // set precision
d.Set("latitude", &f)
}
if long := loadBalancerPool.Longitude; long != nil {
f := math.Round(float64(*long)*10000) / 10000 // set precision
d.Set("longitude", &f)
}

if err := d.Set("origins", flattenLoadBalancerOrigins(d, loadBalancerPool.Origins)); err != nil {
log.Printf("[WARN] Error setting origins on load balancer pool %q: %s", d.Id(), err)
}
Expand Down Expand Up @@ -329,21 +369,3 @@ func resourceCloudflareLoadBalancerPoolDelete(d *schema.ResourceData, meta inter

return nil
}

// floatBetween returns a validate function that can be used in schema definitions.
func floatBetween(min, max float64) schema.SchemaValidateFunc {
return func(i interface{}, k string) (s []string, es []error) {
v, ok := i.(float64)
if !ok {
es = append(es, fmt.Errorf("expected type of %s to be float64", k))
return
}

if v < min || v > max {
es = append(es, fmt.Errorf("expected %s to be within %v and %v", k, min, max))
return
}

return
}
}
8 changes: 5 additions & 3 deletions cloudflare/resource_cloudflare_load_balancer_pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@ package cloudflare
import (
"context"
"fmt"
"github.com/pkg/errors"
"os"
"regexp"
"testing"

"time"

"github.com/cloudflare/cloudflare-go"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
"github.com/pkg/errors"
)

func TestAccCloudflareLoadBalancerPool_Basic(t *testing.T) {
Expand Down Expand Up @@ -65,7 +64,8 @@ func TestAccCloudflareLoadBalancerPool_FullySpecified(t *testing.T) {
resource.TestCheckResourceAttr(name, "description", "tfacc-fully-specified"),
resource.TestCheckResourceAttr(name, "check_regions.#", "1"),
resource.TestCheckResourceAttr(name, "minimum_origins", "2"),

resource.TestCheckResourceAttr(name, "latitude", "12.3"),
resource.TestCheckResourceAttr(name, "longitude", "55"),
func(state *terraform.State) error {
for _, rs := range state.RootModule().Resources {
for k, v := range rs.Primary.Attributes {
Expand Down Expand Up @@ -239,6 +239,8 @@ resource "cloudflare_load_balancer_pool" "%[1]s" {
values = ["test2.%[2]s"]
}
}
latitude = 12.3
longitude = 55
check_regions = ["WEU"]
description = "tfacc-fully-specified"
enabled = false
Expand Down
39 changes: 39 additions & 0 deletions cloudflare/resource_cloudflare_load_balancer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,33 @@ func TestAccCloudflareLoadBalancer_Rules(t *testing.T) {
})
}

func TestAccCloudflareLoadBalancer_LatitudeLongitude(t *testing.T) {
t.Parallel()
var loadBalancer cloudflare.LoadBalancer
zone := os.Getenv("CLOUDFLARE_DOMAIN")
zoneID := os.Getenv("CLOUDFLARE_ZONE_ID")
rnd := generateRandomResourceName()
name := "cloudflare_load_balancer." + rnd

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckCloudflareLoadBalancerDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckCloudflareLoadBalancerConfigLatitudeLongitude(zoneID, zone, rnd),
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudflareLoadBalancerExists(name, &loadBalancer),
testAccCheckCloudflareLoadBalancerIDIsValid(name, zoneID),
// checking our overrides of default values worked
resource.TestCheckResourceAttr(name, "latitude", "23.5"),
resource.TestCheckResourceAttr(name, "longitude", "-11.1"),
),
},
},
})
}

func TestAccCloudflareLoadBalancer_DuplicatePool(t *testing.T) {
t.Parallel()
zone := os.Getenv("CLOUDFLARE_DOMAIN")
Expand Down Expand Up @@ -506,3 +533,15 @@ resource "cloudflare_load_balancer" "%[3]s" {
}
}`, zoneID, zone, id)
}

func testAccCheckCloudflareLoadBalancerConfigLatitudeLongitude(zoneID, zone, id string) string {
return testAccCheckCloudflareLoadBalancerPoolConfigBasic(id) + fmt.Sprintf(`
resource "cloudflare_load_balancer" "%[3]s" {
zone_id = "%[1]s"
name = "tf-testacc-lb-latitude-longitude-%[3]s.%[2]s"
fallback_pool_id = "${cloudflare_load_balancer_pool.%[3]s.id}"
default_pool_ids = ["${cloudflare_load_balancer_pool.%[3]s.id}"]
latitude = 23.5
longitude = -11.1
}`, zoneID, zone, id)
}
4 changes: 4 additions & 0 deletions website/docs/r/load_balancer_pool.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ resource "cloudflare_load_balancer_pool" "foo" {
values = ["example-2"]
}
}
latitude = 55
longitude = -12
description = "example load balancer pool"
enabled = false
minimum_origins = 1
Expand All @@ -52,6 +54,8 @@ The following arguments are supported:
* `minimum_origins` - (Optional) The minimum number of origins that must be healthy for this pool to serve traffic. If the number of healthy origins falls below this number, the pool will be marked unhealthy and we will failover to the next available pool. Default: 1.
* `monitor` - (Optional) The ID of the Monitor to use for health checking origins within this pool.
* `notification_email` - (Optional) The email address to send health status notifications to. This can be an individual mailbox or a mailing list. Multiple emails can be supplied as a comma delimited list.
* `latitude` - (Optional) The latitude this pool is physically located at; used for proximity steering. Values should be between -90 and 90.
* `longitude` - (Optional) The longitude this pool is physically located at; used for proximity steering. Values should be between -180 and 180.

The **origins** block supports:

Expand Down

0 comments on commit 82b9c9c

Please sign in to comment.