/
snap.go
106 lines (88 loc) · 2.35 KB
/
snap.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package snap
import (
// "flag"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func CreateSnapshot(s *session.Session, instance string, device string, mount string, volumeId string, expires int) error {
// Set up the expiration time
startingTime := time.Now().UTC()
expireTag := fmt.Sprintf("%v", startingTime.AddDate(0, 0, expires).Round(time.Second))
if Verbose() {
println("Expiration time set to", expireTag)
}
// old autosnap uses hostname instead of instance-id
// maybe we should find that...
snapDesc := fmt.Sprintf("ebs-snap %s:%s:%s", instance, device, mount)
snapId, err := EC2Snapshot(s, volumeId, snapDesc)
if err != nil {
fmt.Printf("error creating snapshot for volume %s: %s\n", volumeId, err.Error())
return err
}
if Verbose() {
println("Created snapshot with id: ", snapId)
} else {
println(snapId)
}
err = TagSnapshot(s, snapId, volumeId, expireTag)
if err != nil {
println("error in tagging:", err)
// delete here on error, if we can...
return err
}
return nil
}
func EC2Snapshot(s *session.Session, volumeId string, desc string) (string, error) {
svc := ec2.New(s)
params := &ec2.CreateSnapshotInput{
VolumeId: aws.String(volumeId),
Description: aws.String(desc),
}
resp, err := svc.CreateSnapshot(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return "", err
}
return *resp.SnapshotId, nil
}
func TagSnapshot(s *session.Session, snapId string, volumeId string, expires string) error {
svc := ec2.New(s)
dparams := &ec2.DescribeTagsInput{
DryRun: aws.Bool(false),
Filters: []*ec2.Filter{
{
Name: aws.String("resource-id"),
Values: []*string{
aws.String(volumeId),
},
},
},
}
res, err := svc.DescribeTags(dparams)
if err != nil {
fmt.Printf("error reading tags from volume %s: %v", volumeId, err)
// forge on, we're just tagging
}
tags := []*ec2.Tag{
{
Key: aws.String("Expires"),
Value: aws.String(expires),
},
}
for _, v := range res.Tags {
tags = append(tags, &ec2.Tag{Key: aws.String(*v.Key), Value: aws.String(*v.Value)})
}
cparams := &ec2.CreateTagsInput{
Resources: []*string{
aws.String(snapId),
},
Tags: tags,
}
_, err = svc.CreateTags(cparams)
return err
}