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

New Resource: aws_storagegateway_working_storage #5285

Merged
merged 2 commits into from
Jul 27, 2018
Merged
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
76 changes: 76 additions & 0 deletions aws/data_source_aws_storagegateway_local_disk.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package aws

import (
"errors"
"fmt"
"log"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/storagegateway"
"github.com/hashicorp/terraform/helper/schema"
)

func dataSourceAwsStorageGatewayLocalDisk() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsStorageGatewayLocalDiskRead,

Schema: map[string]*schema.Schema{
"disk_id": {
Type: schema.TypeString,
Computed: true,
},
"disk_path": {
Type: schema.TypeString,
Required: true,
},
"gateway_arn": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateArn,
},
},
}
}

func dataSourceAwsStorageGatewayLocalDiskRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).storagegatewayconn

input := &storagegateway.ListLocalDisksInput{
GatewayARN: aws.String(d.Get("gateway_arn").(string)),
}

log.Printf("[DEBUG] Reading Storage Gateway Local Disk: %s", input)
output, err := conn.ListLocalDisks(input)
if err != nil {
return fmt.Errorf("error reading Storage Gateway Local Disk: %s", err)
}

if output == nil || len(output.Disks) == 0 {
return errors.New("no results found for query, try adjusting your search criteria")
}

diskPath := d.Get("disk_path").(string)
var matchingDisks []*storagegateway.Disk

for _, disk := range output.Disks {
if aws.StringValue(disk.DiskPath) == diskPath {
matchingDisks = append(matchingDisks, disk)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It appears finding more than 1 disk is an error? Perhaps refactor to single match and break when you find it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A disk path is a unique identifier on a system, e.g. /dev/sdb

}
}

if len(matchingDisks) == 0 {
return errors.New("no results found for query, try adjusting your search criteria")
}

if len(matchingDisks) > 1 {
return errors.New("multiple results found for query, try adjusting your search criteria")
}

disk := matchingDisks[0]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

again do we foresee multiple matches being something that comes later?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We would create a separate pluralized data source (e.g. aws_storagegateway_local_disks) in that case


d.SetId(aws.StringValue(disk.DiskId))
d.Set("disk_id", disk.DiskId)
d.Set("disk_path", disk.DiskPath)

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

import (
"fmt"
"regexp"
"testing"

"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSStorageGatewayLocalDiskDataSource_DiskPath(t *testing.T) {
rName := acctest.RandomWithPrefix("tf-acc-test")
dataSourceName := "data.aws_storagegateway_local_disk.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccAWSStorageGatewayLocalDiskDataSourceConfig_DiskPath_NonExistent(rName),
ExpectError: regexp.MustCompile(`no results found`),
},
{
Config: testAccAWSStorageGatewayLocalDiskDataSourceConfig_DiskPath(rName),
Check: resource.ComposeTestCheckFunc(
testAccAWSStorageGatewayLocalDiskDataSourceExists(dataSourceName),
resource.TestCheckResourceAttrSet(dataSourceName, "disk_id"),
),
},
},
})
}

func testAccAWSStorageGatewayLocalDiskDataSourceExists(dataSourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[dataSourceName]
if !ok {
return fmt.Errorf("not found: %s", dataSourceName)
}

return nil
}
}

func testAccAWSStorageGatewayLocalDiskDataSourceConfig_DiskPath(rName string) string {
return testAccAWSStorageGatewayGatewayConfig_GatewayType_FileS3(rName) + fmt.Sprintf(`
resource "aws_ebs_volume" "test" {
availability_zone = "${aws_instance.test.availability_zone}"
size = "10"
type = "gp2"

tags {
Name = %q
}
}

resource "aws_volume_attachment" "test" {
device_name = "/dev/xvdb"
force_detach = true
instance_id = "${aws_instance.test.id}"
volume_id = "${aws_ebs_volume.test.id}"
}

data "aws_storagegateway_local_disk" "test" {
disk_path = "${aws_volume_attachment.test.device_name}"
gateway_arn = "${aws_storagegateway_gateway.test.arn}"
}
`, rName)
}

func testAccAWSStorageGatewayLocalDiskDataSourceConfig_DiskPath_NonExistent(rName string) string {
return testAccAWSStorageGatewayGatewayConfig_GatewayType_FileS3(rName) + fmt.Sprintf(`
resource "aws_ebs_volume" "test" {
availability_zone = "${aws_instance.test.availability_zone}"
size = "10"
type = "gp2"

tags {
Name = %q
}
}

resource "aws_volume_attachment" "test" {
device_name = "/dev/xvdb"
force_detach = true
instance_id = "${aws_instance.test.id}"
volume_id = "${aws_ebs_volume.test.id}"
}

data "aws_storagegateway_local_disk" "test" {
disk_path = "/dev/xvdz"
gateway_arn = "${aws_storagegateway_gateway.test.arn}"
}
`, rName)
}
2 changes: 2 additions & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ func Provider() terraform.ResourceProvider {
"aws_sns_topic": dataSourceAwsSnsTopic(),
"aws_sqs_queue": dataSourceAwsSqsQueue(),
"aws_ssm_parameter": dataSourceAwsSsmParameter(),
"aws_storagegateway_local_disk": dataSourceAwsStorageGatewayLocalDisk(),
"aws_subnet": dataSourceAwsSubnet(),
"aws_subnet_ids": dataSourceAwsSubnetIDs(),
"aws_vpcs": dataSourceAwsVpcs(),
Expand Down Expand Up @@ -586,6 +587,7 @@ func Provider() terraform.ResourceProvider {
"aws_ssm_resource_data_sync": resourceAwsSsmResourceDataSync(),
"aws_storagegateway_gateway": resourceAwsStorageGatewayGateway(),
"aws_storagegateway_nfs_file_share": resourceAwsStorageGatewayNfsFileShare(),
"aws_storagegateway_working_storage": resourceAwsStorageGatewayWorkingStorage(),
"aws_spot_datafeed_subscription": resourceAwsSpotDataFeedSubscription(),
"aws_spot_instance_request": resourceAwsSpotInstanceRequest(),
"aws_spot_fleet_request": resourceAwsSpotFleetRequest(),
Expand Down
131 changes: 131 additions & 0 deletions aws/resource_aws_storagegateway_working_storage.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package aws

import (
"fmt"
"log"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/service/storagegateway"
"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsStorageGatewayWorkingStorage() *schema.Resource {
return &schema.Resource{
Create: resourceAwsStorageGatewayWorkingStorageCreate,
Read: resourceAwsStorageGatewayWorkingStorageRead,
Delete: schema.Noop,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"disk_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"gateway_arn": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateArn,
},
},
}
}

func resourceAwsStorageGatewayWorkingStorageCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).storagegatewayconn

diskID := d.Get("disk_id").(string)
gatewayARN := d.Get("gateway_arn").(string)

input := &storagegateway.AddWorkingStorageInput{
DiskIds: []*string{aws.String(diskID)},
GatewayARN: aws.String(gatewayARN),
}

log.Printf("[DEBUG] Adding Storage Gateway working storage: %s", input)
_, err := conn.AddWorkingStorage(input)
if err != nil {
return fmt.Errorf("error adding Storage Gateway working storage: %s", err)
}

d.SetId(fmt.Sprintf("%s:%s", gatewayARN, diskID))

return resourceAwsStorageGatewayWorkingStorageRead(d, meta)
}

func resourceAwsStorageGatewayWorkingStorageRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).storagegatewayconn

gatewayARN, diskID, err := decodeStorageGatewayWorkingStorageID(d.Id())
if err != nil {
return err
}

input := &storagegateway.DescribeWorkingStorageInput{
GatewayARN: aws.String(gatewayARN),
}

log.Printf("[DEBUG] Reading Storage Gateway working storage: %s", input)
output, err := conn.DescribeWorkingStorage(input)
if err != nil {
if isAWSErrStorageGatewayGatewayNotFound(err) {
log.Printf("[WARN] Storage Gateway working storage %q not found - removing from state", d.Id())
d.SetId("")
return nil
}
return fmt.Errorf("error reading Storage Gateway working storage: %s", err)
}

if output == nil || len(output.DiskIds) == 0 {
log.Printf("[WARN] Storage Gateway working storage %q not found - removing from state", d.Id())
d.SetId("")
return nil
}

found := false
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick var found bool would begin false... I'm okay either way :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Go newcomers might be confused by variable type zero-value behavior -- explicit > implicit IMO since it doesn't cost any extra lines of code. 👍

for _, existingDiskID := range output.DiskIds {
if aws.StringValue(existingDiskID) == diskID {
found = true
break
}
}

if !found {
log.Printf("[WARN] Storage Gateway working storage %q not found - removing from state", d.Id())
d.SetId("")
return nil
}

d.Set("disk_id", diskID)
d.Set("gateway_arn", gatewayARN)

return nil
}

func decodeStorageGatewayWorkingStorageID(id string) (string, string, error) {
// id = arn:aws:storagegateway:us-east-1:123456789012:gateway/sgw-12345678:pci-0000:03:00.0-scsi-0:0:0:0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remnant from development?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm showing these for future travelers since the logic might be seen as non-trivial

idFormatErr := fmt.Errorf("expected ID in form of GatewayARN:DiskId, received: %s", id)
gatewayARNAndDisk, err := arn.Parse(id)
if err != nil {
return "", "", idFormatErr
}
// gatewayARNAndDisk.Resource = gateway/sgw-12345678:pci-0000:03:00.0-scsi-0:0:0:0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

development remnant?

resourceParts := strings.SplitN(gatewayARNAndDisk.Resource, ":", 2)
if len(resourceParts) != 2 {
return "", "", idFormatErr
}
// resourceParts = ["gateway/sgw-12345678", "pci-0000:03:00.0-scsi-0:0:0:0"]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remnant?

gatewayARN := &arn.ARN{
AccountID: gatewayARNAndDisk.AccountID,
Partition: gatewayARNAndDisk.Partition,
Region: gatewayARNAndDisk.Region,
Service: gatewayARNAndDisk.Service,
Resource: resourceParts[0],
}
return gatewayARN.String(), resourceParts[1], nil
}
Loading