-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
81 lines (61 loc) · 1.59 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"log"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func main() {
if len(os.Args) != 3 {
log.Fatalf("usage: associate-ebs <volume-id> </dev/xvd*>")
}
volumeID, deviceName := os.Args[1], os.Args[2]
if exists(deviceName) {
log.Printf("Device %q already present, exiting", deviceName)
return
}
s := session.New()
meta := ec2metadata.New(s)
region, err := meta.Region()
if err != nil {
log.Fatalf("associate-ebs: unable to determine region failed: %v", err)
}
instanceID, err := meta.GetMetadata("instance-id")
if err != nil {
log.Fatalf("associate-ebs: unable to determine instance id: %v", err)
}
svc := ec2.New(s, &aws.Config{Region: aws.String(region)})
args := &ec2.AttachVolumeInput{
InstanceId: aws.String(instanceID),
VolumeId: aws.String(volumeID),
Device: aws.String(deviceName),
}
attachment, err := svc.AttachVolume(args)
if err != nil {
log.Fatalf("associate-ebs: AttachVolume failed: %v", err)
}
log.Printf("Attachment State: %q", *attachment.State)
tick := time.NewTicker(100 * time.Millisecond).C
timeout := 1 * time.Minute
deadline := time.After(timeout)
start := time.Now()
for {
select {
case <-tick:
case <-deadline:
log.Fatalf("associate-ebs: device did not attach after %v", timeout)
}
if exists(deviceName) {
log.Printf("Attached in %v", time.Since(start))
// Success
return
}
}
}
func exists(path string) bool {
_, err := os.Stat(path)
return err == nil
}