-
Notifications
You must be signed in to change notification settings - Fork 0
/
ec2.go
73 lines (59 loc) · 1.88 KB
/
ec2.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
package aws
import (
"context"
"fmt"
"time"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/datawire/infra-actions/github-runner-provisioner/internal/aws/aws_runners"
"github.com/datawire/infra-actions/github-runner-provisioner/internal/utils"
log "github.com/sirupsen/logrus"
)
type InstanceDetails struct {
LaunchTime *time.Time
InstanceId *string
ActionRunnerLabel *string
}
func (c *Ec2Client) GetInstances(filter []types.Filter) ([]*InstanceDetails, error) {
var nextToken *string
instancesDetails := []*InstanceDetails{}
for {
params := ec2.DescribeInstancesInput{
Filters: filter,
NextToken: nextToken,
}
describeInstancesOutput, err := c.Client.DescribeInstances(context.Background(), ¶ms)
if err != nil {
err = fmt.Errorf("error getting EC2 instance information. %v", err)
return nil, err
}
for _, reservation := range describeInstancesOutput.Reservations {
for _, instance := range reservation.Instances {
label, err := getActionRunnerLabel(instance)
if err != nil {
log.Warningf("Error getting runner tag for instance %s: %v\n", *instance.InstanceId, err)
continue
}
instanceDetails := &InstanceDetails{
LaunchTime: instance.LaunchTime,
InstanceId: instance.InstanceId,
ActionRunnerLabel: utils.StrPtr(label),
}
instancesDetails = append(instancesDetails, instanceDetails)
}
}
if describeInstancesOutput.NextToken == nil {
break
}
nextToken = describeInstancesOutput.NextToken
}
return instancesDetails, nil
}
func getActionRunnerLabel(instance types.Instance) (string, error) {
for _, tag := range instance.Tags {
if *tag.Key == aws_runners.LabelTag {
return *tag.Value, nil
}
}
return "", fmt.Errorf("AWS instance %s does not contain tag %s", *instance.InstanceId, aws_runners.LabelTag)
}