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

provider/aws: Add resource_aws_volume_attachment #2050

Merged
merged 7 commits into from
May 28, 2015
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
1 change: 1 addition & 0 deletions builtin/providers/aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ func Provider() terraform.ResourceProvider {
"aws_sns_topic": resourceAwsSnsTopic(),
"aws_sns_topic_subscription": resourceAwsSnsTopicSubscription(),
"aws_subnet": resourceAwsSubnet(),
"aws_volume_attachment": resourceAwsVolumeAttachment(),
"aws_vpc_dhcp_options_association": resourceAwsVpcDhcpOptionsAssociation(),
"aws_vpc_dhcp_options": resourceAwsVpcDhcpOptions(),
"aws_vpc_peering_connection": resourceAwsVpcPeeringConnection(),
Expand Down
49 changes: 49 additions & 0 deletions builtin/providers/aws/resource_aws_ebs_volume.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ package aws

import (
"fmt"
"log"
"time"

"github.com/awslabs/aws-sdk-go/aws"
"github.com/awslabs/aws-sdk-go/aws/awserr"
"github.com/awslabs/aws-sdk-go/service/ec2"

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

Expand Down Expand Up @@ -91,9 +94,55 @@ func resourceAwsEbsVolumeCreate(d *schema.ResourceData, meta interface{}) error
if err != nil {
return fmt.Errorf("Error creating EC2 volume: %s", err)
}

log.Printf(
"[DEBUG] Waiting for Volume (%s) to become available",
d.Id())

stateConf := &resource.StateChangeConf{
Pending: []string{"creating"},
Target: "available",
Refresh: volumeStateRefreshFunc(conn, *result.VolumeID),
Timeout: 5 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}

_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for Volume (%s) to become available: %s",
*result.VolumeID, err)
}

return readVolume(d, result)
}

// volumeStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// a the state of a Volume. Returns successfully when volume is available
func volumeStateRefreshFunc(conn *ec2.EC2, volumeID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := conn.DescribeVolumes(&ec2.DescribeVolumesInput{
VolumeIDs: []*string{aws.String(volumeID)},
})

if err != nil {
if ec2err, ok := err.(awserr.Error); ok {
// Set this to nil as if we didn't find anything.
log.Printf("Error on Volume State Refresh: message: \"%s\", code:\"%s\"", ec2err.Message(), ec2err.Code())
resp = nil
return nil, "", err
} else {
log.Printf("Error on Volume State Refresh: %s", err)
return nil, "", err
}
}

v := resp.Volumes[0]
return v, *v.State, nil
}
}

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

Expand Down
36 changes: 36 additions & 0 deletions builtin/providers/aws/resource_aws_ebs_volume_test.go
Original file line number Diff line number Diff line change
@@ -1,23 +1,59 @@
package aws

import (
"fmt"
"testing"

"github.com/awslabs/aws-sdk-go/aws"
"github.com/awslabs/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSEBSVolume(t *testing.T) {
var v ec2.Volume
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAwsEbsVolumeConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckVolumeExists("aws_ebs_volume.test", &v),
),
},
},
})
}

func testAccCheckVolumeExists(n string, v *ec2.Volume) resource.TestCheckFunc {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Upgraded this test while I was here, since I needed a testAccCheckVolumeExists method

Copy link
Contributor

Choose a reason for hiding this comment

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

📈 👍

return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}

if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}

conn := testAccProvider.Meta().(*AWSClient).ec2conn

request := &ec2.DescribeVolumesInput{
VolumeIDs: []*string{aws.String(rs.Primary.ID)},
}

response, err := conn.DescribeVolumes(request)
if err == nil {
if response.Volumes != nil && len(response.Volumes) > 0 {
*v = *response.Volumes[0]
return nil
}
}
return fmt.Errorf("Error finding EC2 volume %s", rs.Primary.ID)
}
}

const testAccAwsEbsVolumeConfig = `
resource "aws_ebs_volume" "test" {
availability_zone = "us-west-2a"
Expand Down
191 changes: 191 additions & 0 deletions builtin/providers/aws/resource_aws_volume_attachment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
package aws

import (
"bytes"
"fmt"
"log"
"time"

"github.com/awslabs/aws-sdk-go/aws"
"github.com/awslabs/aws-sdk-go/aws/awserr"
"github.com/awslabs/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsVolumeAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAwsVolumeAttachmentCreate,
Read: resourceAwsVolumeAttachmentRead,
Delete: resourceAwsVolumeAttachmentDelete,

Schema: map[string]*schema.Schema{
"device_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"instance_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"volume_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"force_detach": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
}
}

func resourceAwsVolumeAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
name := d.Get("device_name").(string)
iID := d.Get("instance_id").(string)
vID := d.Get("volume_id").(string)

opts := &ec2.AttachVolumeInput{
Device: aws.String(name),
InstanceID: aws.String(iID),
VolumeID: aws.String(vID),
}

log.Printf("[DEBUG] Attaching Volume (%s) to Instance (%s)", vID, iID)
_, err := conn.AttachVolume(opts)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
return fmt.Errorf("[WARN] Error attaching volume (%s) to instance (%s), message: \"%s\", code: \"%s\"",
vID, iID, awsErr.Message(), awsErr.Code())
}
return err
}
Copy link
Contributor

Choose a reason for hiding this comment

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

So now that we loop above, there's no eventual consistency here? No need to loop and wait for "attached" or anything?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

added polling for attached9329073 , JUST FOR YOU @phinze


stateConf := &resource.StateChangeConf{
Pending: []string{"attaching"},
Target: "attached",
Refresh: volumeAttachmentStateRefreshFunc(conn, vID, iID),
Timeout: 5 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}

_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for Volume (%s) to attach to Instance: %s, error:",
vID, iID, err)
}

d.SetId(volumeAttachmentID(name, vID, iID))
return resourceAwsVolumeAttachmentRead(d, meta)
}

func volumeAttachmentStateRefreshFunc(conn *ec2.EC2, volumeID, instanceID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {

request := &ec2.DescribeVolumesInput{
VolumeIDs: []*string{aws.String(volumeID)},
Filters: []*ec2.Filter{
&ec2.Filter{
Name: aws.String("attachment.instance-id"),
Values: []*string{aws.String(instanceID)},
},
},
}

resp, err := conn.DescribeVolumes(request)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
return nil, "failed", fmt.Errorf("code: %s, message: %s", awsErr.Code(), awsErr.Message())
}
return nil, "failed", err
}

if len(resp.Volumes) > 0 {
v := resp.Volumes[0]
for _, a := range v.Attachments {
if a.InstanceID != nil && *a.InstanceID == instanceID {
return a, *a.State, nil
}
}
}
// assume detached if volume count is 0
return 42, "detached", nil
}
}
func resourceAwsVolumeAttachmentRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn

request := &ec2.DescribeVolumesInput{
VolumeIDs: []*string{aws.String(d.Get("volume_id").(string))},
Filters: []*ec2.Filter{
&ec2.Filter{
Name: aws.String("attachment.instance-id"),
Values: []*string{aws.String(d.Get("instance_id").(string))},
},
},
}

_, err := conn.DescribeVolumes(request)
if err != nil {
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVolume.NotFound" {
d.SetId("")
return nil
}
return fmt.Errorf("Error reading EC2 volume %s for instance: %s: %#v", d.Get("volume_id").(string), d.Get("instance_id").(string), err)
}
return nil
}

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

vID := d.Get("volume_id").(string)
iID := d.Get("instance_id").(string)

opts := &ec2.DetachVolumeInput{
Device: aws.String(d.Get("device_name").(string)),
InstanceID: aws.String(iID),
VolumeID: aws.String(vID),
Force: aws.Boolean(d.Get("force_detach").(bool)),
}

_, err := conn.DetachVolume(opts)
stateConf := &resource.StateChangeConf{
Pending: []string{"detaching"},
Target: "detached",
Refresh: volumeAttachmentStateRefreshFunc(conn, vID, iID),
Timeout: 5 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}

log.Printf("[DEBUG] Detaching Volume (%s) from Instance (%s)", vID, iID)
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for Volume (%s) to detach from Instance: %s",
vID, iID)
}
d.SetId("")
return nil
}

func volumeAttachmentID(name, volumeID, instanceID string) string {
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("%s-", name))
buf.WriteString(fmt.Sprintf("%s-", instanceID))
buf.WriteString(fmt.Sprintf("%s-", volumeID))

return fmt.Sprintf("vai-%d", hashcode.String(buf.String()))
}
Loading