-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathami.go
87 lines (76 loc) · 2.02 KB
/
ami.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
package rhcos
import (
"context"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/pkg/errors"
)
const (
// DefaultChannel is the default RHCOS channel for the cluster.
DefaultChannel = "tested"
)
// AMI calculates a Red Hat CoreOS AMI.
func AMI(ctx context.Context, channel, region string) (ami string, err error) {
if channel != DefaultChannel {
return "", errors.Errorf("channel %q is not yet supported", channel)
}
ssn := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
Config: aws.Config{
Region: aws.String(region),
},
}))
svc := ec2.New(ssn)
result, err := svc.DescribeImagesWithContext(ctx, &ec2.DescribeImagesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("name"),
Values: aws.StringSlice([]string{"rhcos*"}),
},
{
Name: aws.String("architecture"),
Values: aws.StringSlice([]string{"x86_64"}),
},
{
Name: aws.String("virtualization-type"),
Values: aws.StringSlice([]string{"hvm"}),
},
{
Name: aws.String("image-type"),
Values: aws.StringSlice([]string{"machine"}),
},
{
Name: aws.String("owner-id"),
Values: aws.StringSlice([]string{"531415883065"}),
},
{
Name: aws.String("state"),
Values: aws.StringSlice([]string{"available"}),
},
},
})
if err != nil {
return "", errors.Wrap(err, "failed to describe AMIs")
}
var image *ec2.Image
var created time.Time
for _, nextImage := range result.Images {
if nextImage.ImageId == nil || nextImage.CreationDate == nil {
continue
}
nextCreated, err := time.Parse(time.RFC3339, *nextImage.CreationDate)
if err != nil {
return "", errors.Wrap(err, "failed to parse AMIs CreationDate to time.RFC3339")
}
if image == nil || nextCreated.After(created) {
image = nextImage
created = nextCreated
}
}
if image == nil {
return "", errors.Errorf("no RHCOS AMIs found in %s", region)
}
return *image.ImageId, nil
}