Skip to content

feat(lb): add private network resource #3153

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions docs/resources/lb_private_network.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
---
subcategory: "Load Balancers"
page_title: "Scaleway: scaleway_lb_private_network"
---

# Resource: scaleway_lb_private_network

Creates and manages Scaleway Load Balancer Private Network attachments.

For more information, see the [main documentation](https://www.scaleway.com/en/docs/load-balancer/how-to/use-with-private-network/).

## Example Usage

### Basic

```terraform
resource "scaleway_vpc" "vpc01" {
name = "my vpc"
}

resource "scaleway_vpc_private_network" "pn01" {
vpc_id = scaleway_vpc.vpc01.id
ipv4_subnet {
subnet = "172.16.32.0/22"
}
}

resource "scaleway_ipam_ip" "ip01" {
address = "172.16.32.7"
source {
private_network_id = scaleway_vpc_private_network.pn01.id
}
}

resource "scaleway_lb" "lb01" {
name = "test-lb-private-network"
type = "LB-S"
}

resource "scaleway_lb_private_network" "lbpn01" {
lb_id = scaleway_lb.lb01.id
private_network_id = scaleway_vpc_private_network.pn01.id
ipam_ip_ids = [scaleway_ipam_ip.ip01.id]
}
```

## Argument Reference

The following arguments are supported:

- `zone` - (Defaults to [provider](../index.md#zone) `zone`) The [zone](../guides/regions_and_zones.md#zones) in which the Private Network should be attached.
- `project_id` - (Defaults to [provider](../index.md#project_id) `project_id`) The ID of the Project the Private Network attachment is associated with.
- `lb_id` - (Required) The load-balancer ID to attach the private network to.
- `private_network_id` - (Required) The private network ID to attach.
- `ipam_ip_ids` - (Required) The IPAM ID of a pre-reserved IP address to assign to the Load Balancer on this Private Network.

## Attributes Reference

In addition to all arguments above, the following attributes are exported:

- `id` - The ID of the Private Network attachment, which is of the form `{zone}/{lb-id}/{private-network-id}` e.g. `fr-par-1/11111111-1111-1111-1111-111111111111/11111111-1111-1111-1111-111111111111`
- `status` - The status of the Private Network attachment.
- `created_at` - The date and time of the creation of the Private Network attachment (RFC 3339 format).
- `updated_at` - The date and time of the last update of the Private Network attachment (RFC 3339 format).

## Import

Private Network attachments can be imported using `{zone}/{lb-id}/{private-network-id}`, e.g.

```bash
terraform import scaleway_lb_private_network.lbpn01 fr-par-1/11111111-1111-1111-1111-111111111111/11111111-1111-1111-1111-111111111111
```
1 change: 1 addition & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ func Provider(config *Config) plugin.ProviderFunc {
"scaleway_lb_certificate": lb.ResourceCertificate(),
"scaleway_lb_frontend": lb.ResourceFrontend(),
"scaleway_lb_ip": lb.ResourceIP(),
"scaleway_lb_private_network": lb.ResourcePrivateNetwork(),
"scaleway_lb_route": lb.ResourceRoute(),
"scaleway_mnq_nats_account": mnq.ResourceNatsAccount(),
"scaleway_mnq_nats_credentials": mnq.ResourceNatsCredentials(),
Expand Down
9 changes: 9 additions & 0 deletions internal/services/lb/helpers_lb.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,3 +226,12 @@ func customizeDiffAssignFlexibleIPv6(_ context.Context, diff *schema.ResourceDif

return nil
}

func ResourceLBPrivateNetworkParseID(resourceID string) (zone scw.Zone, lbID string, pnID string, err error) {
idParts := strings.Split(resourceID, "/")
if len(idParts) != 3 {
return "", "", "", fmt.Errorf("can't parse user resource id: %s", resourceID)
}

return scw.Zone(idParts[0]), idParts[1], idParts[2], nil
}
1 change: 1 addition & 0 deletions internal/services/lb/lb.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ func ResourceLb() *schema.Resource {
"private_network": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
MaxItems: 8,
Set: lbPrivateNetworkSetHash,
Description: "List of private network to connect with your load balancer",
Expand Down
211 changes: 211 additions & 0 deletions internal/services/lb/private_network.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
package lb

import (
"context"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
lb "github.com/scaleway/scaleway-sdk-go/api/lb/v1"
"github.com/scaleway/scaleway-sdk-go/scw"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/cdf"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/httperrors"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/locality"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/locality/regional"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/locality/zonal"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/services/account"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/types"
)

func ResourcePrivateNetwork() *schema.Resource {
return &schema.Resource{
CreateContext: resourceLbPrivateNetworkCreate,
ReadContext: resourceLbPrivateNetworkRead,
DeleteContext: resourceLbPrivateNetworkDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Timeouts: &schema.ResourceTimeout{
Read: schema.DefaultTimeout(defaultLbLbTimeout),
Update: schema.DefaultTimeout(defaultLbLbTimeout),
Delete: schema.DefaultTimeout(defaultLbLbTimeout),
Default: schema.DefaultTimeout(defaultLbLbTimeout),
},
SchemaVersion: 0,
Schema: map[string]*schema.Schema{
"lb_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The load-balancer ID to attach the private network to",
},
"private_network_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The private network ID to attach",
},
"ipam_ip_ids": {
Type: schema.TypeList,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MaxItems: 1,
Optional: true,
Computed: true,
ForceNew: true,
Description: "IPAM ID of a pre-reserved IP address to assign to the Load Balancer on this Private Network",
},
"zone": zonal.Schema(),
// Computed
"status": {
Type: schema.TypeString,
Computed: true,
Description: "The status of private network connection",
},
"created_at": {
Type: schema.TypeString,
Computed: true,
Description: "The date and time of the creation of the private network connection",
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
Description: "The date and time of the last update of the private network connection",
},
"project_id": account.ProjectIDSchema(),
},
CustomizeDiff: cdf.LocalityCheck("lb_id", "private_network_id"),
}
}

func resourceLbPrivateNetworkCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
lbAPI, zone, err := lbAPIWithZone(d, m)
if err != nil {
return diag.FromErr(err)
}

lbID := zonal.ExpandID(d.Get("lb_id").(string)).ID

_, err = waitForLB(ctx, lbAPI, zone, lbID, d.Timeout(schema.TimeoutCreate))
if err != nil {
return diag.FromErr(err)
}

attach, err := lbAPI.AttachPrivateNetwork(&lb.ZonedAPIAttachPrivateNetworkRequest{
Zone: zone,
LBID: lbID,
PrivateNetworkID: regional.ExpandID(d.Get("private_network_id").(string)).ID,
IpamIDs: locality.ExpandIDs(d.Get("ipam_ip_ids")),
}, scw.WithContext(ctx))
if err != nil {
return diag.FromErr(err)
}

_, err = waitForLB(ctx, lbAPI, zone, lbID, d.Timeout(schema.TimeoutUpdate))
if err != nil && !httperrors.Is404(err) {
return diag.FromErr(err)
}

_, err = waitForPrivateNetworks(ctx, lbAPI, zone, lbID, d.Timeout(schema.TimeoutUpdate))
if err != nil && !httperrors.Is404(err) {
return diag.FromErr(err)
}

d.SetId(
zonal.NewNestedIDString(
zone,
attach.LB.ID,
attach.PrivateNetworkID,
),
)

return resourceLbPrivateNetworkRead(ctx, d, m)
}

func resourceLbPrivateNetworkRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
lbAPI, _, err := lbAPIWithZone(d, m)
if err != nil {
return diag.FromErr(err)
}

zone, LBID, PNID, err := ResourceLBPrivateNetworkParseID(d.Id())
if err != nil {
return diag.FromErr(err)
}

privateNetworks, err := waitForPrivateNetworks(ctx, lbAPI, zone, LBID, d.Timeout(schema.TimeoutRead))
if err != nil {
if httperrors.Is404(err) {
d.SetId("")

return nil
}

return diag.FromErr(err)
}

var foundPN *lb.PrivateNetwork

for _, pn := range privateNetworks {
if pn.PrivateNetworkID == PNID {
foundPN = pn

break
}
}

if foundPN == nil {
d.SetId("")

return nil
}

region, err := zone.Region()
if err != nil {
return diag.FromErr(err)
}

_ = d.Set("private_network_id", regional.NewIDString(region, foundPN.PrivateNetworkID))
_ = d.Set("lb_id", zonal.NewIDString(zone, foundPN.LB.ID))
_ = d.Set("ipam_ip_ids", regional.NewRegionalIDs(region, foundPN.IpamIDs))
_ = d.Set("status", foundPN.Status.String())
_ = d.Set("created_at", types.FlattenTime(foundPN.CreatedAt))
_ = d.Set("updated_at", types.FlattenTime(foundPN.UpdatedAt))
_ = d.Set("zone", zone)
_ = d.Set("project_id", foundPN.LB.ProjectID)

return nil
}

func resourceLbPrivateNetworkDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
lbAPI, _, err := lbAPIWithZone(d, m)
if err != nil {
return diag.FromErr(err)
}

zone, LBID, PNID, err := ResourceLBPrivateNetworkParseID(d.Id())
if err != nil {
return diag.FromErr(err)
}

err = lbAPI.DetachPrivateNetwork(&lb.ZonedAPIDetachPrivateNetworkRequest{
Zone: zone,
LBID: LBID,
PrivateNetworkID: PNID,
}, scw.WithContext(ctx))
if err != nil && !httperrors.Is404(err) {
return diag.FromErr(err)
}

_, err = waitForLB(ctx, lbAPI, zone, LBID, d.Timeout(schema.TimeoutUpdate))
if err != nil && !httperrors.Is404(err) {
return diag.FromErr(err)
}

_, err = waitForPrivateNetworks(ctx, lbAPI, zone, LBID, d.Timeout(schema.TimeoutUpdate))
if err != nil && !httperrors.Is404(err) {
return diag.FromErr(err)
}

return nil
}
64 changes: 64 additions & 0 deletions internal/services/lb/private_network_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package lb_test

import (
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/acctest"
lbchecks "github.com/scaleway/terraform-provider-scaleway/v2/internal/services/lb/testfuncs"
)

func TestAccLBPrivateNetwork_Basic(t *testing.T) {
tt := acctest.NewTestTools(t)
defer tt.Cleanup()
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ProviderFactories: tt.ProviderFactories,
CheckDestroy: lbchecks.IsIPDestroyed(tt),
Steps: []resource.TestStep{
{
Config: `
resource "scaleway_vpc" "vpc01" {
name = "my vpc"
}

resource "scaleway_vpc_private_network" "pn01" {
vpc_id = scaleway_vpc.vpc01.id
ipv4_subnet {
subnet = "172.16.32.0/22"
}
}

resource "scaleway_ipam_ip" "ip01" {
address = "172.16.32.7"
source {
private_network_id = scaleway_vpc_private_network.pn01.id
}
}

resource "scaleway_lb" "lb01" {
name = "test-lb-private-network"
type = "LB-S"
}

resource "scaleway_lb_private_network" "lbpn01" {
lb_id = scaleway_lb.lb01.id
private_network_id = scaleway_vpc_private_network.pn01.id
ipam_ip_ids = [scaleway_ipam_ip.ip01.id]
}
`,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrPair(
"scaleway_lb.lb01", "id",
"scaleway_lb_private_network.lbpn01", "lb_id"),
resource.TestCheckResourceAttrPair(
"scaleway_vpc_private_network.pn01", "id",
"scaleway_lb_private_network.lbpn01", "private_network_id"),
resource.TestCheckResourceAttrPair(
"scaleway_ipam_ip.ip01", "id",
"scaleway_lb_private_network.lbpn01", "ipam_ip_ids.0"),
),
},
},
})
}
Loading
Loading