This repository has been archived by the owner on Aug 10, 2022. It is now read-only.
forked from kubernetes/kops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
instance.go
268 lines (221 loc) · 6.89 KB
/
instance.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package awstasks
import (
"fmt"
"encoding/base64"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/golang/glog"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
"strings"
)
const MaxUserDataSize = 16384
type Instance struct {
ID *string
UserData fi.Resource
Subnet *Subnet
PrivateIPAddress *string
Name *string
Tags map[string]string
ImageID *string
InstanceType *string
SSHKey *SSHKey
SecurityGroups []*SecurityGroup
AssociatePublicIP *bool
IAMInstanceProfile *IAMInstanceProfile
}
var _ fi.CompareWithID = &Instance{}
func (s *Instance) CompareWithID() *string {
return s.ID
}
func (e *Instance) Find(c *fi.Context) (*Instance, error) {
cloud := c.Cloud.(*awsup.AWSCloud)
filters := cloud.BuildFilters(e.Name)
filters = append(filters, awsup.NewEC2Filter("instance-state-name", "pending", "running", "stopping", "stopped"))
request := &ec2.DescribeInstancesInput{
Filters: filters,
}
response, err := cloud.EC2.DescribeInstances(request)
if err != nil {
return nil, fmt.Errorf("error listing instances: %v", err)
}
instances := []*ec2.Instance{}
if response != nil {
for _, reservation := range response.Reservations {
for _, instance := range reservation.Instances {
instances = append(instances, instance)
}
}
}
if len(instances) == 0 {
return nil, nil
}
if len(instances) != 1 {
return nil, fmt.Errorf("found multiple Instances with name: %s", *e.Name)
}
glog.V(2).Info("found existing instance")
i := instances[0]
if i.InstanceId == nil {
return nil, fmt.Errorf("found instance, but InstanceId was nil")
}
actual := &Instance{
ID: i.InstanceId,
PrivateIPAddress: i.PrivateIpAddress,
InstanceType: i.InstanceType,
ImageID: i.ImageId,
Name: findNameTag(i.Tags),
}
// Fetch instance UserData
{
request := &ec2.DescribeInstanceAttributeInput{}
request.InstanceId = i.InstanceId
request.Attribute = aws.String("userData")
response, err := cloud.EC2.DescribeInstanceAttribute(request)
if err != nil {
return nil, fmt.Errorf("error querying EC2 for user metadata for instance %q: %v", *i.InstanceId, err)
}
if response.UserData != nil {
b, err := base64.StdEncoding.DecodeString(aws.StringValue(response.UserData.Value))
if err != nil {
return nil, fmt.Errorf("error decoding EC2 UserData: %v", err)
}
actual.UserData = fi.NewBytesResource(b)
}
}
if i.SubnetId != nil {
actual.Subnet = &Subnet{ID: i.SubnetId}
}
if i.KeyName != nil {
actual.SSHKey = &SSHKey{Name: i.KeyName}
}
for _, sg := range i.SecurityGroups {
actual.SecurityGroups = append(actual.SecurityGroups, &SecurityGroup{ID: sg.GroupId})
}
associatePublicIpAddress := false
for _, ni := range i.NetworkInterfaces {
if aws.StringValue(ni.Association.PublicIp) != "" {
associatePublicIpAddress = true
}
}
actual.AssociatePublicIP = &associatePublicIpAddress
if i.IamInstanceProfile != nil {
actual.IAMInstanceProfile = &IAMInstanceProfile{Name: nameFromIAMARN(i.IamInstanceProfile.Arn)}
}
actual.Tags = mapEC2TagsToMap(i.Tags)
e.ID = actual.ID
// Avoid spurious changes on ImageId
if e.ImageID != nil && actual.ImageID != nil && *actual.ImageID != *e.ImageID {
image, err := cloud.ResolveImage(*e.ImageID)
if err != nil {
glog.Warningf("unable to resolve image: %q: %v", *e.ImageID, err)
} else if image == nil {
glog.Warningf("unable to resolve image: %q: not found", *e.ImageID)
} else if aws.StringValue(image.ImageId) == *actual.ImageID {
glog.V(4).Infof("Returning matching ImageId as expected name: %q -> %q", *actual.ImageID, *e.ImageID)
actual.ImageID = e.ImageID
}
}
return actual, nil
}
func nameFromIAMARN(arn *string) *string {
if arn == nil {
return nil
}
tokens := strings.Split(*arn, ":")
last := tokens[len(tokens)-1]
if !strings.HasPrefix(last, "instance-profile/") {
glog.Warningf("Unexpected ARN for instance profile: %q", *arn)
}
name := strings.TrimPrefix(last, "instance-profile/")
return &name
}
func (e *Instance) Run(c *fi.Context) error {
cloud := c.Cloud.(*awsup.AWSCloud)
cloud.AddTags(e.Name, e.Tags)
return fi.DefaultDeltaRunMethod(e, c)
}
func (_ *Instance) CheckChanges(a, e, changes *Instance) error {
if a != nil {
if e.Name == nil {
return fi.RequiredField("Name")
}
}
return nil
}
func (_ *Instance) RenderAWS(t *awsup.AWSAPITarget, a, e, changes *Instance) error {
if a == nil {
if e.ImageID == nil {
return fi.RequiredField("ImageID")
}
image, err := t.Cloud.ResolveImage(*e.ImageID)
if err != nil {
return err
}
glog.V(2).Infof("Creating Instance with Name:%q", *e.Name)
request := &ec2.RunInstancesInput{
ImageId: image.ImageId,
InstanceType: e.InstanceType,
MinCount: aws.Int64(1),
MaxCount: aws.Int64(1),
}
if e.SSHKey != nil {
request.KeyName = e.SSHKey.Name
}
securityGroupIDs := []*string{}
for _, sg := range e.SecurityGroups {
securityGroupIDs = append(securityGroupIDs, sg.ID)
}
request.NetworkInterfaces = []*ec2.InstanceNetworkInterfaceSpecification{
{
DeviceIndex: aws.Int64(0),
AssociatePublicIpAddress: e.AssociatePublicIP,
SubnetId: e.Subnet.ID,
PrivateIpAddress: e.PrivateIPAddress,
Groups: securityGroupIDs,
},
}
// Build up the actual block device mappings
// TODO: Support RootVolumeType & RootVolumeSize (see launchconfiguration)
blockDeviceMappings, err := buildEphemeralDevices(e.InstanceType)
if err != nil {
return err
}
if len(blockDeviceMappings) != 0 {
request.BlockDeviceMappings = []*ec2.BlockDeviceMapping{}
for deviceName, bdm := range blockDeviceMappings {
request.BlockDeviceMappings = append(request.BlockDeviceMappings, bdm.ToEC2(deviceName))
}
}
if e.UserData != nil {
d, err := fi.ResourceAsBytes(e.UserData)
if err != nil {
return fmt.Errorf("error rendering Instance UserData: %v", err)
}
if len(d) > MaxUserDataSize {
// TODO: Re-enable gzip?
// But it exposes some bugs in the AWS console, so if we can avoid it, we should
//d, err = fi.GzipBytes(d)
//if err != nil {
// return fmt.Errorf("error while gzipping UserData: %v", err)
//}
return fmt.Errorf("Instance UserData was too large (%d bytes)", len(d))
}
request.UserData = aws.String(base64.StdEncoding.EncodeToString(d))
}
if e.IAMInstanceProfile != nil {
request.IamInstanceProfile = &ec2.IamInstanceProfileSpecification{
Name: e.IAMInstanceProfile.Name,
}
}
response, err := t.Cloud.EC2.RunInstances(request)
if err != nil {
return fmt.Errorf("error creating Instance: %v", err)
}
e.ID = response.Instances[0].InstanceId
}
return t.AddAWSTags(*e.ID, e.Tags)
}
func (e *Instance) TerraformLink() *terraform.Literal {
return terraform.LiteralSelfLink("aws_instance", *e.Name)
}