Skip to content

Commit

Permalink
Auto allocate an IP address in resource
Browse files Browse the repository at this point in the history
  • Loading branch information
c0deaddict authored and Grendel7 committed May 9, 2022
1 parent 6d11699 commit 9cfa081
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
4 changes: 4 additions & 0 deletions plugin/providers/phpipam/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package phpipam

import (
"log"
"sync"

"github.com/pavel-z1/phpipam-sdk-go/controllers/addresses"
"github.com/pavel-z1/phpipam-sdk-go/controllers/sections"
Expand Down Expand Up @@ -49,6 +50,9 @@ type ProviderPHPIPAMClient struct {

// The client for the vlans controller.
vlansController *vlans.Controller

// Mutex for free IP address allocation.
addressAllocationLock sync.Mutex
}

// Client configures and returns a fully initialized PingdomClient.
Expand Down
24 changes: 23 additions & 1 deletion plugin/providers/phpipam/resource_phpipam_address.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,29 @@ func resourcePHPIPAMAddress() *schema.Resource {
}

func resourcePHPIPAMAddressCreate(d *schema.ResourceData, meta interface{}) error {
c := meta.(*ProviderPHPIPAMClient).addressesController
client := meta.(*ProviderPHPIPAMClient)
c := client.addressesController

// Get the next free address if no IP is specified.
if (d.Get("ip_address").(string) == "") {
// By default Terraform runs operations in parallel. Protect the
// GetFirstFreeAddress and CreateAddress operations with a lock so they are
// not run concurrently.
client.addressAllocationLock.Lock()
defer client.addressAllocationLock.Unlock()

subnet_c := client.subnetsController
out, err := subnet_c.GetFirstFreeAddress(d.Get("subnet_id").(int))
if err != nil {
return err
}
if out == "" {
return errors.New("Subnet has no free IP addresses")
}

d.Set("ip_address", out)
}

in := expandAddress(d)

// Assert the ID field here is empty. If this is not empty the request will fail.
Expand Down

0 comments on commit 9cfa081

Please sign in to comment.