Skip to content
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

feat(instance): add support for snapshot #815

Merged
merged 3 commits into from
Apr 28, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
47 changes: 47 additions & 0 deletions docs/resources/instance_snapshot.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
page_title: "Scaleway: scaleway_instance_snapshot"
description: |-
Manages Scaleway Instance Snapshots.
---

# scaleway_instance_snapshot

Creates and manages Scaleway Compute Snapshots.
For more information, see [the documentation](https://developers.scaleway.com/en/products/instance/api/#snapshots-756fae).

## Example

```hcl
resource "scaleway_instance_snapshot" "main" {
name = "some-snapshot-name"
volume_id = "11111111-1111-1111-1111-111111111111"
}
```

## Arguments Reference

The following arguments are supported:

- `volume_id` - (Required) The ID of the volume to take a snapshot from.
- `name` - (Optional) The name of the snapshot. If not provided it will be randomly generated.
- `zone` - (Defaults to [provider](../index.md#zone) `zone`) The [zone](../guides/regions_and_zones.md#zones) in which the snapshot should be created.
- `project_id` - (Defaults to [provider](../index.md#project_id) `project_id`) The ID of the project the snapshot is associated with.

## Attributes Reference

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

- `id` - The ID of the snapshot.
- `size_in_gb` - (Optional) The size of the snapshot.
- `organization_id` - The organization ID the snapshot is associated with.
- `project_id` - The project ID the snapshot is associated with.
- `type` - The type of the snapshot. The possible values are: `b_ssd` (Block SSD), `l_ssd` (Local SSD).
- `created_at` - The snapshot creation time.

## Import

Snapshots can be imported using the `{zone}/{id}`, e.g.

```bash
$ terraform import scaleway_instance_snapshot.main fr-par-1/11111111-1111-1111-1111-111111111111
```
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ require (
github.com/google/go-cmp v0.5.5
github.com/hashicorp/go-retryablehttp v0.6.8
github.com/hashicorp/terraform-plugin-sdk/v2 v2.5.0
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.7.0.20210414083420-b36f019ca892
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.7.0.20210427131120-0f06a0676b46
github.com/stretchr/testify v1.7.0
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -276,8 +276,8 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.7.0.20210414083420-b36f019ca892 h1:8de9MJs8kRtUlc71A9+0wG5ToP9nk+Ujn/W03X/FGEg=
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.7.0.20210414083420-b36f019ca892/go.mod h1:CJJ5VAbozOl0yEw7nHB9+7BXTJbIn6h7W+f6Gau5IP8=
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.7.0.20210427131120-0f06a0676b46 h1:vo1Cwfn5es6jK9o5TvShDIdr8VWhYIHF9Q69LUxIpAg=
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.7.0.20210427131120-0f06a0676b46/go.mod h1:CJJ5VAbozOl0yEw7nHB9+7BXTJbIn6h7W+f6Gau5IP8=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
Expand Down
15 changes: 15 additions & 0 deletions scaleway/helpers_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ const (
defaultInstanceSecurityGroupRuleTimeout = 1 * time.Minute
defaultInstancePlacementGroupTimeout = 1 * time.Minute
defaultInstanceIPTimeout = 1 * time.Minute

defaultInstanceSnapshotWaitTimeout = 1 * time.Hour
)

// instanceAPIWithZone returns a new instance API and the zone for a Create request
Expand Down Expand Up @@ -133,6 +135,19 @@ func reachState(ctx context.Context, instanceAPI *instance.API, zone scw.Zone, s
return fmt.Errorf("don't know how to reach state %s from state %s for server %s", toState, fromState, serverID)
}

// We need to check that all volumes are ready
for _, volume := range response.Server.Volumes {
if volume.State != instance.VolumeStateAvailable {
_, err = instanceAPI.WaitForVolume(&instance.WaitForVolumeRequest{
Zone: zone,
VolumeID: volume.ID,
})
if err != nil {
return err
}
}
}

for _, a := range actions {
err = instanceAPI.ServerActionAndWait(&instance.ServerActionAndWaitRequest{
ServerID: serverID,
Expand Down
1 change: 1 addition & 0 deletions scaleway/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func Provider(config *ProviderConfig) plugin.ProviderFunc {
"scaleway_instance_security_group": resourceScalewayInstanceSecurityGroup(),
"scaleway_instance_security_group_rules": resourceScalewayInstanceSecurityGroupRules(),
"scaleway_instance_server": resourceScalewayInstanceServer(),
"scaleway_instance_snapshot": resourceScalewayInstanceSnapshot(),
"scaleway_instance_placement_group": resourceScalewayInstancePlacementGroup(),
"scaleway_instance_private_nic": resourceScalewayInstancePrivateNIC(),
"scaleway_iot_hub": resourceScalewayIotHub(),
Expand Down
157 changes: 157 additions & 0 deletions scaleway/resource_instance_snapshot.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
package scaleway

import (
"context"
"fmt"
"time"

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

func resourceScalewayInstanceSnapshot() *schema.Resource {
return &schema.Resource{
CreateContext: resourceScalewayInstanceSnapshotCreate,
ReadContext: resourceScalewayInstanceSnapshotRead,
UpdateContext: resourceScalewayInstanceSnapshotUpdate,
DeleteContext: resourceScalewayInstanceSnapshotDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Timeouts: &schema.ResourceTimeout{
Default: schema.DefaultTimeout(defaultInstanceSnapshotWaitTimeout),
},
SchemaVersion: 0,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The name of the snapshot",
},
"volume_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "ID of the volume to take a snapshot from",
ValidateFunc: validationUUIDorUUIDWithLocality(),
},
"type": {
Type: schema.TypeString,
Computed: true,
Description: "The volume type of the snapshot",
},
"size_in_gb": {
Type: schema.TypeInt,
Computed: true,
Description: "The size of the snapshot in gigabyte",
},
"created_at": {
Type: schema.TypeString,
Computed: true,
Description: "The date and time of the creation of the snapshot",
},
"zone": zoneSchema(),
"organization_id": organizationIDSchema(),
"project_id": projectIDSchema(),
},
}
}

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

req := &instance.CreateSnapshotRequest{
Zone: zone,
Project: expandStringPtr(d.Get("project_id")),
Name: expandOrGenerateString(d.Get("name"), "snap"),
VolumeID: expandZonedID(d.Get("volume_id").(string)).ID,
}

res, err := instanceAPI.CreateSnapshot(req, scw.WithContext(ctx))
if err != nil {
return diag.FromErr(err)
}

d.SetId(newZonedIDString(zone, res.Snapshot.ID))
return resourceScalewayInstanceSnapshotRead(ctx, d, meta)
}

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

snapshot, err := instanceAPI.GetSnapshot(&instance.GetSnapshotRequest{
SnapshotID: id,
Zone: zone,
}, scw.WithContext(ctx))
if err != nil {
if is404Error(err) {
d.SetId("")
return nil
}
return diag.FromErr(err)
}

_ = d.Set("name", snapshot.Snapshot.Name)
_ = d.Set("created_at", snapshot.Snapshot.CreationDate.Format(time.RFC3339))
_ = d.Set("type", snapshot.Snapshot.VolumeType.String())

return nil
}

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

if d.HasChange("name") {
newName := d.Get("name").(string)

_, err = instanceAPI.UpdateSnapshot(&instance.UpdateSnapshotRequest{
SnapshotID: id,
Zone: zone,
Name: &newName,
}, scw.WithContext(ctx))
if err != nil {
return diag.FromErr(fmt.Errorf("couldn't update snapshot: %s", err))
}
}

return resourceScalewayInstanceSnapshotRead(ctx, d, meta)
}

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

_, err = instanceAPI.WaitForSnapshot(&instance.WaitForSnapshotRequest{
SnapshotID: id,
Zone: zone,
})
if err != nil {
return diag.FromErr(err)
}

err = instanceAPI.DeleteSnapshot(&instance.DeleteSnapshotRequest{
SnapshotID: id,
Zone: zone,
}, scw.WithContext(ctx))
if err != nil {
if !is404Error(err) {
return diag.FromErr(err)
}
}

return nil
}
122 changes: 122 additions & 0 deletions scaleway/resource_instance_snapshot_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package scaleway

import (
"testing"

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

func TestAccScalewayInstanceSnapshot_BlockVolume(t *testing.T) {
tt := NewTestTools(t)
defer tt.Cleanup()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: tt.ProviderFactories,
CheckDestroy: testAccCheckScalewayInstanceVolumeDestroy(tt),
Steps: []resource.TestStep{
{
Config: `
resource "scaleway_instance_volume" "main" {
type = "b_ssd"
size_in_gb = 20
}

resource "scaleway_instance_snapshot" "main" {
volume_id = scaleway_instance_volume.main.id
}`,
},
},
})
}

func TestAccScalewayInstanceSnapshot_Server(t *testing.T) {
tt := NewTestTools(t)
defer tt.Cleanup()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: tt.ProviderFactories,
CheckDestroy: testAccCheckScalewayInstanceVolumeDestroy(tt),
Steps: []resource.TestStep{
{
Config: `
resource "scaleway_instance_server" "main" {
image = "ubuntu_focal"
type = "DEV1-S"
}

resource "scaleway_instance_snapshot" "main" {
volume_id = scaleway_instance_server.main.root_volume.0.volume_id
type = "l_ssd"
}`,
},
},
})
}

func TestAccScalewayInstanceSnapshot_ServerWithBlockVolume(t *testing.T) {
tt := NewTestTools(t)
defer tt.Cleanup()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: tt.ProviderFactories,
CheckDestroy: testAccCheckScalewayInstanceVolumeDestroy(tt),
Steps: []resource.TestStep{
{
Config: `
resource "scaleway_instance_volume" "block" {
type = "b_ssd"
size_in_gb = 10
}

resource "scaleway_instance_server" "main" {
image = "ubuntu_focal"
type = "DEV1-S"

additional_volume_ids = [
scaleway_instance_volume.block.id
]
}

resource "scaleway_instance_snapshot" "main" {
volume_id = scaleway_instance_volume.block.id
}`,
},
},
})
}

func TestAccScalewayInstanceSnapshot_RenameSnapshot(t *testing.T) {
tt := NewTestTools(t)
defer tt.Cleanup()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: tt.ProviderFactories,
CheckDestroy: testAccCheckScalewayInstanceVolumeDestroy(tt),
Steps: []resource.TestStep{
{
Config: `
resource "scaleway_instance_volume" "main" {
type = "b_ssd"
size_in_gb = 20
}

resource "scaleway_instance_snapshot" "main" {
volume_id = scaleway_instance_volume.main.id
name = "first_name"
}`,
},
{
Config: `
resource "scaleway_instance_volume" "main" {
type = "b_ssd"
size_in_gb = 20
}

resource "scaleway_instance_snapshot" "main" {
volume_id = scaleway_instance_volume.main.id
name = "second_name"
}`,
},
},
})
}
Loading