Skip to content

Commit

Permalink
feat(instance): Adding the datasource for instance ip (scaleway#870)
Browse files Browse the repository at this point in the history
* feat(instance): Adding the datasource for instance ip

* refactoring: using ParseIP to validate the IP

* fix: use proper validation

* minor fixes

* style(tfproviderlint): S019: schema should omit Computed, Optional, or Required set to false

* fix: avoiding one api call if the ID is passed

Co-authored-by: Rémy Léone <rleone@scaleway.com>
Co-authored-by: jaime Bernabe <jbernabe@student.42.fr>
  • Loading branch information
3 people authored Sep 15, 2021
1 parent 8ea9492 commit 0ef5457
Show file tree
Hide file tree
Showing 6 changed files with 839 additions and 0 deletions.
44 changes: 44 additions & 0 deletions docs/data-sources/instance_ip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
page_title: "Scaleway: scaleway_instance_ip"
description: |-
Gets information about an instance IP.
---

# scaleway_instance_ip

Gets information about an instance IP.

## Example Usage

```hcl
# Get info by IP address
data "scaleway_instance_ip" "my_ip" {
address = "0.0.0.0"
}
# Get info by ID
data "scaleway_instance_ip" "my_ip" {
id = "fr-par-1/11111111-1111-1111-1111-111111111111"
}
```

## Argument Reference

- `address` - (Optional) The IPv4 address to retrieve
Only one of `address` and `id` should be specified.

- `id` - (Optional) The ID of the IP address to retrieve
Only one of `address` and `id` should be specified.

- `zone` - (Defaults to [provider](../index.md#zone) `zone`) The [zone](../guides/regions_and_zones.md#zones) in which the IP should be reserved.

- `project_id` - (Defaults to [provider](../index.md#project_id) `project_id`) The ID of the project the IP is associated with.

## Attributes Reference

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

- `id` - The ID of the IP.
- `address` - The IP address.
- `reverse` - The reverse dns attached to this IP
- `organization_id` - The organization ID the IP is associated with.
67 changes: 67 additions & 0 deletions scaleway/data_source_instance_ip.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package scaleway

import (
"context"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/scaleway/scaleway-sdk-go/api/instance/v1"
"github.com/scaleway/scaleway-sdk-go/scw"
)

func dataSourceScalewayInstanceIP() *schema.Resource {
// Generate datasource schema from resource
dsSchema := datasourceSchemaFromResourceSchema(resourceScalewayInstanceIP().Schema)

dsSchema["id"] = &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "The ID of the IP address",
ValidateFunc: validationUUIDorUUIDWithLocality(),
ConflictsWith: []string{"address"},
}
dsSchema["address"] = &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "The IP address",
ConflictsWith: []string{"id"},
ValidateFunc: validation.IsIPv4Address,
}

return &schema.Resource{
ReadContext: dataSourceScalewayInstanceIPRead,

Schema: dsSchema,
}
}

func dataSourceScalewayInstanceIPRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
instanceAPI, zone, err := instanceAPIWithZone(d, meta)
if err != nil {
return diag.FromErr(err)
}

id, ok := d.GetOk("id")
var ID string
if !ok {
res, err := instanceAPI.GetIP(&instance.GetIPRequest{
IP: d.Get("address").(string),
Zone: zone,
}, scw.WithContext(ctx))
if err != nil {
// We check for 403 because instance API returns 403 for a deleted IP
if is404Error(err) || is403Error(err) {
d.SetId("")
return nil
}
return diag.FromErr(err)
}
ID = res.IP.ID
} else {
_, ID, _ = parseLocalizedID(id.(string))
}
d.SetId(newZonedIDString(zone, ID))

return resourceScalewayInstanceIPRead(ctx, d, meta)
}
42 changes: 42 additions & 0 deletions scaleway/data_source_instance_ip_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package scaleway

import (
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccScalewayDataSourceInstanceIP_Basic(t *testing.T) {
tt := NewTestTools(t)
defer tt.Cleanup()
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: tt.ProviderFactories,
CheckDestroy: testAccCheckScalewayInstanceServerDestroy(tt),
Steps: []resource.TestStep{
{
Config: `resource "scaleway_instance_ip" "ip" {}`,
},
{
Config: `
resource "scaleway_instance_ip" "ip" {}
data "scaleway_instance_ip" "ip-from-address" {
address = "${scaleway_instance_ip.ip.address}"
}
data "scaleway_instance_ip" "ip-from-id" {
id = "${scaleway_instance_ip.ip.id}"
}
`,
Check: resource.ComposeTestCheckFunc(
testCheckResourceAttrIP("scaleway_instance_ip.ip", "address"),
testCheckResourceAttrIP("data.scaleway_instance_ip.ip-from-address", "address"),
testCheckResourceAttrIP("data.scaleway_instance_ip.ip-from-id", "address"),
resource.TestCheckResourceAttrPair("scaleway_instance_ip.ip", "address", "data.scaleway_instance_ip.ip-from-address", "address"),
resource.TestCheckResourceAttrPair("scaleway_instance_ip.ip", "address", "data.scaleway_instance_ip.ip-from-id", "address"),
),
},
},
})
}
10 changes: 10 additions & 0 deletions scaleway/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,13 @@ func testCheckResourceAttrIPv6(name string, key string) resource.TestCheckFunc {
return nil
})
}

func testCheckResourceAttrIP(name string, key string) resource.TestCheckFunc {
return testCheckResourceAttrFunc(name, key, func(value string) error {
ip := net.ParseIP(value)
if ip == nil {
return fmt.Errorf("%s is not a valid IP", value)
}
return nil
})
}
1 change: 1 addition & 0 deletions scaleway/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ func Provider(config *ProviderConfig) plugin.ProviderFunc {

DataSourcesMap: map[string]*schema.Resource{
"scaleway_account_ssh_key": dataSourceScalewayAccountSSHKey(),
"scaleway_instance_ip": dataSourceScalewayInstanceIP(),
"scaleway_instance_security_group": dataSourceScalewayInstanceSecurityGroup(),
"scaleway_instance_server": dataSourceScalewayInstanceServer(),
"scaleway_instance_image": dataSourceScalewayInstanceImage(),
Expand Down
Loading

0 comments on commit 0ef5457

Please sign in to comment.