-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathlaunchtemplate_target_terraform.go
331 lines (303 loc) · 13.9 KB
/
launchtemplate_target_terraform.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package awstasks
import (
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
"k8s.io/kops/upup/pkg/fi/cloudup/terraformWriter"
)
type terraformLaunchTemplateNetworkInterface struct {
// AssociatePublicIPAddress associates a public ip address with the network interface. Boolean value.
AssociatePublicIPAddress *bool `json:"associate_public_ip_address,omitempty" cty:"associate_public_ip_address"`
// DeleteOnTermination indicates whether the network interface should be destroyed on instance termination.
DeleteOnTermination *bool `json:"delete_on_termination,omitempty" cty:"delete_on_termination"`
// Ipv6AddressCount is the number of IPv6 addresses to assign with the primary network interface.
Ipv6AddressCount *int64 `json:"ipv6_address_count,omitempty" cty:"ipv6_address_count"`
// SecurityGroups is a list of security group ids.
SecurityGroups []*terraformWriter.Literal `json:"security_groups,omitempty" cty:"security_groups"`
}
type terraformLaunchTemplateMonitoring struct {
// Enabled indicates that monitoring is enabled
Enabled *bool `json:"enabled,omitempty" cty:"enabled"`
}
type terraformLaunchTemplatePlacement struct {
// Affinity is he affinity setting for an instance on a Dedicated Host.
Affinity *string `json:"affinity,omitempty" cty:"affinity"`
// AvailabilityZone is the Availability Zone for the instance.
AvailabilityZone *string `json:"availability_zone,omitempty" cty:"availability_zone"`
// GroupName is the name of the placement group for the instance.
GroupName *string `json:"group_name,omitempty" cty:"group_name"`
// HostID is the ID of the Dedicated Host for the instance.
HostID *string `json:"host_id,omitempty" cty:"host_id"`
// SpreadDomain are reserved for future use.
SpreadDomain *string `json:"spread_domain,omitempty" cty:"spread_domain"`
// Tenancy ist he tenancy of the instance. Can be default, dedicated, or host.
Tenancy *string `json:"tenancy,omitempty" cty:"tenancy"`
}
type terraformLaunchTemplateIAMProfile struct {
// Name is the name of the profile
Name *terraformWriter.Literal `json:"name,omitempty" cty:"name"`
}
type terraformLaunchTemplateMarketOptionsSpotOptions struct {
// BlockDurationMinutes is required duration in minutes. This value must be a multiple of 60.
BlockDurationMinutes *int64 `json:"block_duration_minutes,omitempty" cty:"block_duration_minutes"`
// InstanceInterruptionBehavior is the behavior when a Spot Instance is interrupted. Can be hibernate, stop, or terminate
InstanceInterruptionBehavior *string `json:"instance_interruption_behavior,omitempty" cty:"instance_interruption_behavior"`
// MaxPrice is the maximum hourly price you're willing to pay for the Spot Instances
MaxPrice *string `json:"max_price,omitempty" cty:"max_price"`
// SpotInstanceType is the Spot Instance request type. Can be one-time, or persistent
SpotInstanceType *string `json:"spot_instance_type,omitempty" cty:"spot_instance_type"`
// ValidUntil is the end date of the request
ValidUntil *string `json:"valid_until,omitempty" cty:"valid_until"`
}
type terraformLaunchTemplateMarketOptions struct {
// MarketType is the option type
MarketType *string `json:"market_type,omitempty" cty:"market_type"`
// SpotOptions are the set of options
SpotOptions []*terraformLaunchTemplateMarketOptionsSpotOptions `json:"spot_options,omitempty" cty:"spot_options"`
}
type terraformLaunchTemplateBlockDeviceEBS struct {
// VolumeType is the ebs type to use
VolumeType *string `json:"volume_type,omitempty" cty:"volume_type"`
// VolumeSize is the volume size
VolumeSize *int64 `json:"volume_size,omitempty" cty:"volume_size"`
// IOPS is the provisioned IOPS
IOPS *int64 `json:"iops,omitempty" cty:"iops"`
// Throughput is the gp3 volume throughput
Throughput *int64 `json:"throughput,omitempty" cty:"throughput"`
// DeleteOnTermination indicates the volume should die with the instance
DeleteOnTermination *bool `json:"delete_on_termination,omitempty" cty:"delete_on_termination"`
// Encrypted indicates the device should be encrypted
Encrypted *bool `json:"encrypted,omitempty" cty:"encrypted"`
// KmsKeyID is the encryption key identifier for the volume
KmsKeyID *string `json:"kms_key_id,omitempty" cty:"kms_key_id"`
}
type terraformLaunchTemplateBlockDevice struct {
// DeviceName is the name of the device
DeviceName *string `json:"device_name,omitempty" cty:"device_name"`
// VirtualName is used for the ephemeral devices
VirtualName *string `json:"virtual_name,omitempty" cty:"virtual_name"`
// EBS defines the ebs spec
EBS []*terraformLaunchTemplateBlockDeviceEBS `json:"ebs,omitempty" cty:"ebs"`
}
type terraformLaunchTemplateCreditSpecification struct {
CPUCredits *string `json:"cpu_credits,omitempty" cty:"cpu_credits"`
}
type terraformLaunchTemplateTagSpecification struct {
// ResourceType is the type of resource to tag.
ResourceType *string `json:"resource_type,omitempty" cty:"resource_type"`
// Tags are the tags to apply to the resource.
Tags map[string]string `json:"tags,omitempty" cty:"tags"`
}
type terraformLaunchTemplateInstanceMetadata struct {
// HTTPEndpoint enables or disables the HTTP metadata endpoint on instances.
HTTPEndpoint *string `json:"http_endpoint,omitempty" cty:"http_endpoint"`
// HTTPPutResponseHopLimit is the desired HTTP PUT response hop limit for instance metadata requests.
HTTPPutResponseHopLimit *int64 `json:"http_put_response_hop_limit,omitempty" cty:"http_put_response_hop_limit"`
// HTTPTokens is the state of token usage for your instance metadata requests.
HTTPTokens *string `json:"http_tokens,omitempty" cty:"http_tokens"`
// HTTPProtocolIPv6 enables the IPv6 instance metadata endpoint
HTTPProtocolIPv6 *string `json:"http_protocol_ipv6,omitempty" cty:"http_protocol_ipv6"`
}
type terraformLaunchTemplate struct {
// Name is the name of the launch template
Name *string `json:"name,omitempty" cty:"name"`
// Lifecycle is the terraform lifecycle
Lifecycle *terraform.Lifecycle `json:"lifecycle,omitempty" cty:"lifecycle"`
// BlockDeviceMappings is the device mappings
BlockDeviceMappings []*terraformLaunchTemplateBlockDevice `json:"block_device_mappings,omitempty" cty:"block_device_mappings"`
// CreditSpecification is the credit option for CPU Usage on some instance types
CreditSpecification *terraformLaunchTemplateCreditSpecification `json:"credit_specification,omitempty" cty:"credit_specification"`
// EBSOptimized indicates if the root device is ebs optimized
EBSOptimized *bool `json:"ebs_optimized,omitempty" cty:"ebs_optimized"`
// IAMInstanceProfile is the IAM profile to assign to the nodes
IAMInstanceProfile []*terraformLaunchTemplateIAMProfile `json:"iam_instance_profile,omitempty" cty:"iam_instance_profile"`
// ImageID is the ami to use for the instances
ImageID *string `json:"image_id,omitempty" cty:"image_id"`
// InstanceType is the type of instance
InstanceType *string `json:"instance_type,omitempty" cty:"instance_type"`
// KeyName is the ssh key to use
KeyName *terraformWriter.Literal `json:"key_name,omitempty" cty:"key_name"`
// MarketOptions are the spot pricing options
MarketOptions []*terraformLaunchTemplateMarketOptions `json:"instance_market_options,omitempty" cty:"instance_market_options"`
// MetadataOptions are the instance metadata options.
MetadataOptions *terraformLaunchTemplateInstanceMetadata `json:"metadata_options,omitempty" cty:"metadata_options"`
// Monitoring are the instance monitoring options
Monitoring []*terraformLaunchTemplateMonitoring `json:"monitoring,omitempty" cty:"monitoring"`
// NetworkInterfaces are the networking options
NetworkInterfaces []*terraformLaunchTemplateNetworkInterface `json:"network_interfaces,omitempty" cty:"network_interfaces"`
// Placement are the tenancy options
Placement []*terraformLaunchTemplatePlacement `json:"placement,omitempty" cty:"placement"`
// Tags is a map of tags applied to the launch template itself
Tags map[string]string `json:"tags,omitempty" cty:"tags"`
// TagSpecifications are the tags to apply to a resource when it is created.
TagSpecifications []*terraformLaunchTemplateTagSpecification `json:"tag_specifications,omitempty" cty:"tag_specifications"`
// UserData is the user data for the instances
UserData *terraformWriter.Literal `json:"user_data,omitempty" cty:"user_data"`
}
// TerraformLink returns the terraform reference
func (t *LaunchTemplate) TerraformLink() *terraformWriter.Literal {
return terraformWriter.LiteralProperty("aws_launch_template", fi.StringValue(t.Name), "id")
}
// VersionLink returns the terraform version reference
func (t *LaunchTemplate) VersionLink() *terraformWriter.Literal {
return terraformWriter.LiteralProperty("aws_launch_template", fi.StringValue(t.Name), "latest_version")
}
// RenderTerraform is responsible for rendering the terraform json
func (t *LaunchTemplate) RenderTerraform(target *terraform.TerraformTarget, a, e, changes *LaunchTemplate) error {
var err error
cloud := target.Cloud.(awsup.AWSCloud)
var image *string
if e.ImageID != nil {
im, err := cloud.ResolveImage(fi.StringValue(e.ImageID))
if err != nil {
return err
}
image = im.ImageId
}
tf := terraformLaunchTemplate{
Name: e.Name,
EBSOptimized: e.RootVolumeOptimization,
ImageID: image,
InstanceType: e.InstanceType,
Lifecycle: &terraform.Lifecycle{CreateBeforeDestroy: fi.Bool(true)},
MetadataOptions: &terraformLaunchTemplateInstanceMetadata{
// See issue https://github.com/hashicorp/terraform-provider-aws/issues/12564.
HTTPEndpoint: fi.String("enabled"),
HTTPTokens: e.HTTPTokens,
HTTPPutResponseHopLimit: e.HTTPPutResponseHopLimit,
HTTPProtocolIPv6: e.HTTPProtocolIPv6,
},
NetworkInterfaces: []*terraformLaunchTemplateNetworkInterface{
{
AssociatePublicIPAddress: e.AssociatePublicIP,
DeleteOnTermination: fi.Bool(true),
Ipv6AddressCount: e.IPv6AddressCount,
},
},
}
if fi.StringValue(e.SpotPrice) != "" {
marketSpotOptions := terraformLaunchTemplateMarketOptionsSpotOptions{MaxPrice: e.SpotPrice}
if e.SpotDurationInMinutes != nil {
marketSpotOptions.BlockDurationMinutes = e.SpotDurationInMinutes
}
if e.InstanceInterruptionBehavior != nil {
marketSpotOptions.InstanceInterruptionBehavior = e.InstanceInterruptionBehavior
}
tf.MarketOptions = []*terraformLaunchTemplateMarketOptions{
{
MarketType: fi.String("spot"),
SpotOptions: []*terraformLaunchTemplateMarketOptionsSpotOptions{&marketSpotOptions},
},
}
}
if fi.StringValue(e.CPUCredits) != "" {
tf.CreditSpecification = &terraformLaunchTemplateCreditSpecification{
CPUCredits: e.CPUCredits,
}
}
for _, x := range e.SecurityGroups {
tf.NetworkInterfaces[0].SecurityGroups = append(tf.NetworkInterfaces[0].SecurityGroups, x.TerraformLink())
}
if e.SSHKey != nil {
tf.KeyName = e.SSHKey.TerraformLink()
}
if e.Tenancy != nil {
tf.Placement = []*terraformLaunchTemplatePlacement{{Tenancy: e.Tenancy}}
}
if e.InstanceMonitoring != nil {
tf.Monitoring = []*terraformLaunchTemplateMonitoring{
{Enabled: e.InstanceMonitoring},
}
}
if e.IAMInstanceProfile != nil {
tf.IAMInstanceProfile = []*terraformLaunchTemplateIAMProfile{
{Name: e.IAMInstanceProfile.TerraformLink()},
}
}
if e.UserData != nil {
d, err := fi.ResourceAsBytes(e.UserData)
if err != nil {
return err
}
if d != nil {
tf.UserData, err = target.AddFileBytes("aws_launch_template", fi.StringValue(e.Name), "user_data", d, true)
if err != nil {
return err
}
}
}
devices, err := e.buildRootDevice(cloud)
if err != nil {
return err
}
for n, x := range devices {
tf.BlockDeviceMappings = append(tf.BlockDeviceMappings, &terraformLaunchTemplateBlockDevice{
DeviceName: fi.String(n),
EBS: []*terraformLaunchTemplateBlockDeviceEBS{
{
DeleteOnTermination: fi.Bool(true),
Encrypted: x.EbsEncrypted,
KmsKeyID: x.EbsKmsKey,
IOPS: x.EbsVolumeIops,
Throughput: x.EbsVolumeThroughput,
VolumeSize: x.EbsVolumeSize,
VolumeType: x.EbsVolumeType,
},
},
})
}
additionals, err := buildAdditionalDevices(e.BlockDeviceMappings)
if err != nil {
return err
}
for n, x := range additionals {
tf.BlockDeviceMappings = append(tf.BlockDeviceMappings, &terraformLaunchTemplateBlockDevice{
DeviceName: fi.String(n),
EBS: []*terraformLaunchTemplateBlockDeviceEBS{
{
DeleteOnTermination: fi.Bool(true),
Encrypted: x.EbsEncrypted,
IOPS: x.EbsVolumeIops,
Throughput: x.EbsVolumeThroughput,
KmsKeyID: x.EbsKmsKey,
VolumeSize: x.EbsVolumeSize,
VolumeType: x.EbsVolumeType,
},
},
})
}
devices, err = buildEphemeralDevices(cloud, fi.StringValue(e.InstanceType))
if err != nil {
return err
}
for n, x := range devices {
tf.BlockDeviceMappings = append(tf.BlockDeviceMappings, &terraformLaunchTemplateBlockDevice{
VirtualName: x.VirtualName,
DeviceName: fi.String(n),
})
}
if e.Tags != nil {
tf.TagSpecifications = append(tf.TagSpecifications, &terraformLaunchTemplateTagSpecification{
ResourceType: fi.String("instance"),
Tags: e.Tags,
})
tf.TagSpecifications = append(tf.TagSpecifications, &terraformLaunchTemplateTagSpecification{
ResourceType: fi.String("volume"),
Tags: e.Tags,
})
tf.Tags = e.Tags
}
return target.RenderResource("aws_launch_template", fi.StringValue(e.Name), tf)
}