2015-05-22 23:06:28 +02:00
|
|
|
package aws
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
2015-05-28 17:13:46 +02:00
|
|
|
"log"
|
2015-05-22 23:06:28 +02:00
|
|
|
"time"
|
|
|
|
|
2015-06-03 20:36:57 +02:00
|
|
|
"github.com/aws/aws-sdk-go/aws"
|
|
|
|
"github.com/aws/aws-sdk-go/aws/awserr"
|
|
|
|
"github.com/aws/aws-sdk-go/service/ec2"
|
2015-05-22 23:06:28 +02:00
|
|
|
"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{
|
2016-11-02 16:29:37 +01:00
|
|
|
"device_name": {
|
2015-05-22 23:06:28 +02:00
|
|
|
Type: schema.TypeString,
|
|
|
|
Required: true,
|
|
|
|
ForceNew: true,
|
|
|
|
},
|
|
|
|
|
2016-11-02 16:29:37 +01:00
|
|
|
"instance_id": {
|
2015-05-22 23:06:28 +02:00
|
|
|
Type: schema.TypeString,
|
|
|
|
Required: true,
|
|
|
|
ForceNew: true,
|
|
|
|
},
|
|
|
|
|
2016-11-02 16:29:37 +01:00
|
|
|
"volume_id": {
|
2015-05-22 23:06:28 +02:00
|
|
|
Type: schema.TypeString,
|
|
|
|
Required: true,
|
|
|
|
ForceNew: true,
|
|
|
|
},
|
|
|
|
|
2016-11-02 16:29:37 +01:00
|
|
|
"force_detach": {
|
|
|
|
Type: schema.TypeBool,
|
|
|
|
Optional: true,
|
|
|
|
Computed: true,
|
|
|
|
},
|
|
|
|
"skip_destroy": {
|
2015-05-22 23:06:28 +02:00
|
|
|
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)
|
|
|
|
|
Succeed creating aws_volume_attachment if identical attachment exists (#11060)
If an `aws_volume_attachment` is identical to one that already exists in
the API, don't attempt to re-create it (which fails), simply act as
though the creation command had already been run and continue.
This allows Terraform to cleanly recover from a situation where a volume
attachment action hangs indefinitely, possibly due to a bad instance
state, requiring manual intervention such as an instance reboot. In such
a situation, Terraform believes the attachment has failed, when in fact
it succeeded after the timeout had expired. On the subsequent retry run,
attempting to re-create the attachment will fail outright, due to the
AttachVolume API call being non-idempotent. This patch implements the
idempotency client-side by matching the (name, vID, iID) tuple.
Note that volume attachments are not assigned an ID by the API.
2017-02-01 16:41:53 +01:00
|
|
|
// Find out if the volume is already attached to the instance, in which case
|
|
|
|
// we have nothing to do
|
|
|
|
request := &ec2.DescribeVolumesInput{
|
|
|
|
VolumeIds: []*string{aws.String(vID)},
|
|
|
|
Filters: []*ec2.Filter{
|
|
|
|
&ec2.Filter{
|
|
|
|
Name: aws.String("attachment.instance-id"),
|
|
|
|
Values: []*string{aws.String(iID)},
|
|
|
|
},
|
|
|
|
&ec2.Filter{
|
|
|
|
Name: aws.String("attachment.device"),
|
|
|
|
Values: []*string{aws.String(name)},
|
|
|
|
},
|
|
|
|
},
|
2015-05-22 23:06:28 +02:00
|
|
|
}
|
|
|
|
|
Succeed creating aws_volume_attachment if identical attachment exists (#11060)
If an `aws_volume_attachment` is identical to one that already exists in
the API, don't attempt to re-create it (which fails), simply act as
though the creation command had already been run and continue.
This allows Terraform to cleanly recover from a situation where a volume
attachment action hangs indefinitely, possibly due to a bad instance
state, requiring manual intervention such as an instance reboot. In such
a situation, Terraform believes the attachment has failed, when in fact
it succeeded after the timeout had expired. On the subsequent retry run,
attempting to re-create the attachment will fail outright, due to the
AttachVolume API call being non-idempotent. This patch implements the
idempotency client-side by matching the (name, vID, iID) tuple.
Note that volume attachments are not assigned an ID by the API.
2017-02-01 16:41:53 +01:00
|
|
|
vols, err := conn.DescribeVolumes(request)
|
|
|
|
if (err != nil) || (len(vols.Volumes) == 0) {
|
2017-03-07 15:20:01 +01:00
|
|
|
// This handles the situation where the instance is created by
|
|
|
|
// a spot request and whilst the request has been fulfilled the
|
|
|
|
// instance is not running yet
|
|
|
|
stateConf := &resource.StateChangeConf{
|
|
|
|
Pending: []string{"pending"},
|
|
|
|
Target: []string{"running"},
|
2017-05-16 07:04:56 +02:00
|
|
|
Refresh: InstanceStateRefreshFunc(conn, iID, "terminated"),
|
2017-03-07 15:20:01 +01:00
|
|
|
Timeout: 10 * time.Minute,
|
|
|
|
Delay: 10 * time.Second,
|
|
|
|
MinTimeout: 3 * time.Second,
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = stateConf.WaitForState()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"Error waiting for instance (%s) to become ready: %s",
|
|
|
|
iID, err)
|
|
|
|
}
|
|
|
|
|
Succeed creating aws_volume_attachment if identical attachment exists (#11060)
If an `aws_volume_attachment` is identical to one that already exists in
the API, don't attempt to re-create it (which fails), simply act as
though the creation command had already been run and continue.
This allows Terraform to cleanly recover from a situation where a volume
attachment action hangs indefinitely, possibly due to a bad instance
state, requiring manual intervention such as an instance reboot. In such
a situation, Terraform believes the attachment has failed, when in fact
it succeeded after the timeout had expired. On the subsequent retry run,
attempting to re-create the attachment will fail outright, due to the
AttachVolume API call being non-idempotent. This patch implements the
idempotency client-side by matching the (name, vID, iID) tuple.
Note that volume attachments are not assigned an ID by the API.
2017-02-01 16:41:53 +01:00
|
|
|
// not attached
|
|
|
|
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
|
2015-05-28 00:07:34 +02:00
|
|
|
}
|
2015-05-22 23:06:28 +02:00
|
|
|
}
|
|
|
|
|
2015-05-28 17:13:46 +02:00
|
|
|
stateConf := &resource.StateChangeConf{
|
|
|
|
Pending: []string{"attaching"},
|
2016-01-21 02:20:41 +01:00
|
|
|
Target: []string{"attached"},
|
2015-05-28 17:13:46 +02:00
|
|
|
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(
|
2015-05-29 06:21:52 +02:00
|
|
|
"Error waiting for Volume (%s) to attach to Instance: %s, error: %s",
|
2015-05-28 17:13:46 +02:00
|
|
|
vID, iID, err)
|
|
|
|
}
|
|
|
|
|
2015-05-22 23:06:28 +02:00
|
|
|
d.SetId(volumeAttachmentID(name, vID, iID))
|
|
|
|
return resourceAwsVolumeAttachmentRead(d, meta)
|
|
|
|
}
|
|
|
|
|
2015-05-28 17:13:46 +02:00
|
|
|
func volumeAttachmentStateRefreshFunc(conn *ec2.EC2, volumeID, instanceID string) resource.StateRefreshFunc {
|
|
|
|
return func() (interface{}, string, error) {
|
|
|
|
|
|
|
|
request := &ec2.DescribeVolumesInput{
|
2015-08-17 20:27:16 +02:00
|
|
|
VolumeIds: []*string{aws.String(volumeID)},
|
2015-05-28 17:13:46 +02:00
|
|
|
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 {
|
2015-08-17 20:27:16 +02:00
|
|
|
if a.InstanceId != nil && *a.InstanceId == instanceID {
|
2015-05-28 17:13:46 +02:00
|
|
|
return a, *a.State, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// assume detached if volume count is 0
|
|
|
|
return 42, "detached", nil
|
|
|
|
}
|
|
|
|
}
|
2015-05-22 23:06:28 +02:00
|
|
|
func resourceAwsVolumeAttachmentRead(d *schema.ResourceData, meta interface{}) error {
|
|
|
|
conn := meta.(*AWSClient).ec2conn
|
|
|
|
|
|
|
|
request := &ec2.DescribeVolumesInput{
|
2015-08-17 20:27:16 +02:00
|
|
|
VolumeIds: []*string{aws.String(d.Get("volume_id").(string))},
|
2015-05-22 23:06:28 +02:00
|
|
|
Filters: []*ec2.Filter{
|
|
|
|
&ec2.Filter{
|
|
|
|
Name: aws.String("attachment.instance-id"),
|
|
|
|
Values: []*string{aws.String(d.Get("instance_id").(string))},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2016-09-30 20:09:35 +02:00
|
|
|
vols, err := conn.DescribeVolumes(request)
|
2015-05-22 23:06:28 +02:00
|
|
|
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)
|
|
|
|
}
|
2016-09-30 20:09:35 +02:00
|
|
|
|
|
|
|
if len(vols.Volumes) == 0 || *vols.Volumes[0].State == "available" {
|
2016-10-03 16:57:42 +02:00
|
|
|
log.Printf("[DEBUG] Volume Attachment (%s) not found, removing from state", d.Id())
|
2016-09-30 20:09:35 +02:00
|
|
|
d.SetId("")
|
|
|
|
}
|
|
|
|
|
2015-05-22 23:06:28 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func resourceAwsVolumeAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
|
|
|
|
conn := meta.(*AWSClient).ec2conn
|
|
|
|
|
2016-11-02 16:29:37 +01:00
|
|
|
if _, ok := d.GetOk("skip_destroy"); ok {
|
|
|
|
log.Printf("[INFO] Found skip_destroy to be true, removing attachment %q from state", d.Id())
|
|
|
|
d.SetId("")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-05-28 17:13:46 +02:00
|
|
|
vID := d.Get("volume_id").(string)
|
|
|
|
iID := d.Get("instance_id").(string)
|
2015-05-22 23:06:28 +02:00
|
|
|
|
|
|
|
opts := &ec2.DetachVolumeInput{
|
|
|
|
Device: aws.String(d.Get("device_name").(string)),
|
2015-08-17 20:27:16 +02:00
|
|
|
InstanceId: aws.String(iID),
|
|
|
|
VolumeId: aws.String(vID),
|
2015-07-28 22:29:46 +02:00
|
|
|
Force: aws.Bool(d.Get("force_detach").(bool)),
|
2015-05-22 23:06:28 +02:00
|
|
|
}
|
|
|
|
|
2015-05-28 17:13:46 +02:00
|
|
|
_, err := conn.DetachVolume(opts)
|
2016-08-25 20:46:46 +02:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Failed to detach Volume (%s) from Instance (%s): %s",
|
|
|
|
vID, iID, err)
|
|
|
|
}
|
2015-05-28 17:13:46 +02:00
|
|
|
stateConf := &resource.StateChangeConf{
|
|
|
|
Pending: []string{"detaching"},
|
2016-01-21 02:20:41 +01:00
|
|
|
Target: []string{"detached"},
|
2015-05-28 17:13:46 +02:00
|
|
|
Refresh: volumeAttachmentStateRefreshFunc(conn, vID, iID),
|
|
|
|
Timeout: 5 * time.Minute,
|
|
|
|
Delay: 10 * time.Second,
|
|
|
|
MinTimeout: 3 * time.Second,
|
|
|
|
}
|
2015-05-22 23:06:28 +02:00
|
|
|
|
2015-05-28 17:13:46 +02:00
|
|
|
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
|
2015-05-22 23:06:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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()))
|
|
|
|
}
|