forked from hashicorp/terraform
/
data_source_aws_ami.go
465 lines (442 loc) · 12.4 KB
/
data_source_aws_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
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
package aws
import (
"bytes"
"fmt"
"log"
"sort"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema"
)
func dataSourceAwsAmi() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsAmiRead,
Schema: map[string]*schema.Schema{
"executable_users": &schema.Schema{
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"filter": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"values": &schema.Schema{
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"most_recent": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"owners": &schema.Schema{
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values.
"architecture": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"creation_date": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"description": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"hypervisor": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"image_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"image_location": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"image_owner_alias": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"image_type": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"kernel_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"owner_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"platform": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"public": &schema.Schema{
Type: schema.TypeBool,
Computed: true,
},
"ramdisk_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"root_device_name": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"root_device_type": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"sriov_net_support": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"state": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"virtualization_type": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
// Complex computed values
"block_device_mappings": &schema.Schema{
Type: schema.TypeSet,
Computed: true,
Set: amiBlockDeviceMappingHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"device_name": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"no_device": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"virtual_name": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"ebs": &schema.Schema{
Type: schema.TypeMap,
Computed: true,
},
},
},
},
"product_codes": &schema.Schema{
Type: schema.TypeSet,
Computed: true,
Set: amiProductCodesHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"product_code_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"product_code_type": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
},
},
"state_reason": &schema.Schema{
Type: schema.TypeMap,
Computed: true,
},
"tags": &schema.Schema{
Type: schema.TypeSet,
Computed: true,
Set: amiTagsHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"value": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
// dataSourceAwsAmiDescriptionRead performs the AMI lookup.
func dataSourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
executableUsers, executableUsersOk := d.GetOk("executable_users")
filters, filtersOk := d.GetOk("filter")
owners, ownersOk := d.GetOk("owners")
if executableUsersOk == false && filtersOk == false && ownersOk == false {
return fmt.Errorf("One of executable_users, filters, or owners must be assigned")
}
params := &ec2.DescribeImagesInput{}
if executableUsersOk {
params.ExecutableUsers = expandStringList(executableUsers.([]interface{}))
}
if filtersOk {
params.Filters = buildAmiFilters(filters.(*schema.Set))
}
if ownersOk {
params.Owners = expandStringList(owners.([]interface{}))
}
resp, err := conn.DescribeImages(params)
if err != nil {
return err
}
var image *ec2.Image
if len(resp.Images) < 1 {
return fmt.Errorf("Your query returned no results. Please change your filters and try again.")
} else if len(resp.Images) > 1 {
if (d.Get("most_recent").(bool)) == true {
log.Printf("[DEBUG] aws_ami - multiple results found and most_recent is set")
image = mostRecentAmi(resp.Images)
} else {
log.Printf("[DEBUG] aws_ami - multiple results found and most_recent not set")
return fmt.Errorf("Your query returned more than one result. Please try a more specific search, or set most_recent to true.")
}
} else {
log.Printf("[DEBUG] aws_ami - Single AMI found: %s", *resp.Images[0].ImageId)
image = resp.Images[0]
}
return amiDescriptionAttributes(d, image)
}
// Build a slice of AMI filter options from the filters provided.
func buildAmiFilters(set *schema.Set) []*ec2.Filter {
var filters []*ec2.Filter
for _, v := range set.List() {
m := v.(map[string]interface{})
var filterValues []*string
for _, e := range m["values"].([]interface{}) {
filterValues = append(filterValues, aws.String(e.(string)))
}
filters = append(filters, &ec2.Filter{
Name: aws.String(m["name"].(string)),
Values: filterValues,
})
}
return filters
}
type imageSort []*ec2.Image
func (a imageSort) Len() int { return len(a) }
func (a imageSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a imageSort) Less(i, j int) bool {
itime, _ := time.Parse(time.RFC3339, *a[i].CreationDate)
jtime, _ := time.Parse(time.RFC3339, *a[j].CreationDate)
return itime.Unix() < jtime.Unix()
}
// Returns the most recent AMI out of a slice of images.
func mostRecentAmi(images []*ec2.Image) *ec2.Image {
sortedImages := images
sort.Sort(imageSort(sortedImages))
return sortedImages[len(sortedImages)-1]
}
// populate the numerous fields that the image description returns.
func amiDescriptionAttributes(d *schema.ResourceData, image *ec2.Image) error {
// Simple attributes first
d.SetId(*image.ImageId)
d.Set("architecture", *image.Architecture)
d.Set("creation_date", *image.CreationDate)
if image.Description != nil {
d.Set("description", *image.Description)
}
d.Set("hypervisor", *image.Hypervisor)
d.Set("image_id", *image.ImageId)
d.Set("image_location", *image.ImageLocation)
if image.ImageOwnerAlias != nil {
d.Set("image_owner_alias", *image.ImageOwnerAlias)
}
d.Set("image_type", *image.ImageType)
if image.KernelId != nil {
d.Set("kernel_id", *image.KernelId)
}
d.Set("name", *image.Name)
d.Set("owner_id", *image.OwnerId)
if image.Platform != nil {
d.Set("platform", *image.Platform)
}
d.Set("public", *image.Public)
if image.RamdiskId != nil {
d.Set("ramdisk_id", *image.RamdiskId)
}
if image.RootDeviceName != nil {
d.Set("root_device_name", *image.RootDeviceName)
}
d.Set("root_device_type", *image.RootDeviceType)
if image.SriovNetSupport != nil {
d.Set("sriov_net_support", *image.SriovNetSupport)
}
d.Set("state", *image.State)
d.Set("virtualization_type", *image.VirtualizationType)
// Complex types get their own functions
if err := d.Set("block_device_mappings", amiBlockDeviceMappings(image.BlockDeviceMappings)); err != nil {
return err
}
if err := d.Set("product_codes", amiProductCodes(image.ProductCodes)); err != nil {
return err
}
if err := d.Set("state_reason", amiStateReason(image.StateReason)); err != nil {
return err
}
if err := d.Set("tags", amiTags(image.Tags)); err != nil {
return err
}
return nil
}
// Returns a set of block device mappings.
func amiBlockDeviceMappings(m []*ec2.BlockDeviceMapping) *schema.Set {
s := &schema.Set{
F: amiBlockDeviceMappingHash,
}
for _, v := range m {
mapping := map[string]interface{}{
"device_name": *v.DeviceName,
}
if v.Ebs != nil {
ebs := map[string]interface{}{
"delete_on_termination": fmt.Sprintf("%t", *v.Ebs.DeleteOnTermination),
"encrypted": fmt.Sprintf("%t", *v.Ebs.Encrypted),
"volume_size": fmt.Sprintf("%d", *v.Ebs.VolumeSize),
"volume_type": *v.Ebs.VolumeType,
}
// Iops is not always set
if v.Ebs.Iops != nil {
ebs["iops"] = fmt.Sprintf("%d", *v.Ebs.Iops)
} else {
ebs["iops"] = "0"
}
// snapshot id may not be set
if v.Ebs.SnapshotId != nil {
ebs["snapshot_id"] = *v.Ebs.SnapshotId
}
mapping["ebs"] = ebs
}
if v.VirtualName != nil {
mapping["virtual_name"] = *v.VirtualName
}
log.Printf("[DEBUG] aws_ami - adding block device mapping: %v", mapping)
s.Add(mapping)
}
return s
}
// Returns a set of product codes.
func amiProductCodes(m []*ec2.ProductCode) *schema.Set {
s := &schema.Set{
F: amiProductCodesHash,
}
for _, v := range m {
code := map[string]interface{}{
"product_code_id": *v.ProductCodeId,
"product_code_type": *v.ProductCodeType,
}
s.Add(code)
}
return s
}
// Returns the state reason.
func amiStateReason(m *ec2.StateReason) map[string]interface{} {
s := make(map[string]interface{})
if m != nil {
s["code"] = *m.Code
s["message"] = *m.Message
} else {
s["code"] = "UNSET"
s["message"] = "UNSET"
}
return s
}
// Returns a set of tags.
func amiTags(m []*ec2.Tag) *schema.Set {
s := &schema.Set{
F: amiTagsHash,
}
for _, v := range m {
tag := map[string]interface{}{
"key": *v.Key,
"value": *v.Value,
}
s.Add(tag)
}
return s
}
// Generates a hash for the set hash function used by the block_device_mappings
// attribute.
func amiBlockDeviceMappingHash(v interface{}) int {
var buf bytes.Buffer
// All keys added in alphabetical order.
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["device_name"].(string)))
if d, ok := m["ebs"]; ok {
if len(d.(map[string]interface{})) > 0 {
e := d.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", e["delete_on_termination"].(string)))
buf.WriteString(fmt.Sprintf("%s-", e["encrypted"].(string)))
buf.WriteString(fmt.Sprintf("%s-", e["iops"].(string)))
buf.WriteString(fmt.Sprintf("%s-", e["volume_size"].(string)))
buf.WriteString(fmt.Sprintf("%s-", e["volume_type"].(string)))
}
}
if d, ok := m["no_device"]; ok {
buf.WriteString(fmt.Sprintf("%s-", d.(string)))
}
if d, ok := m["virtual_name"]; ok {
buf.WriteString(fmt.Sprintf("%s-", d.(string)))
}
if d, ok := m["snapshot_id"]; ok {
buf.WriteString(fmt.Sprintf("%s-", d.(string)))
}
return hashcode.String(buf.String())
}
// Generates a hash for the set hash function used by the product_codes
// attribute.
func amiProductCodesHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
// All keys added in alphabetical order.
buf.WriteString(fmt.Sprintf("%s-", m["product_code_id"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["product_code_type"].(string)))
return hashcode.String(buf.String())
}
// Generates a hash for the set hash function used by the tags
// attribute.
func amiTagsHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
// All keys added in alphabetical order.
buf.WriteString(fmt.Sprintf("%s-", m["key"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["value"].(string)))
return hashcode.String(buf.String())
}