forked from hashicorp/terraform-provider-aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_source_aws_ami.go
442 lines (414 loc) · 11.8 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
package aws
import (
"bytes"
"fmt"
"log"
"regexp"
"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"
"github.com/hashicorp/terraform/helper/validation"
)
func dataSourceAwsAmi() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsAmiRead,
Schema: map[string]*schema.Schema{
"filter": dataSourceFiltersSchema(),
"executable_users": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateRegexp,
},
"most_recent": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"owners": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values.
"architecture": {
Type: schema.TypeString,
Computed: true,
},
"creation_date": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"hypervisor": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"image_location": {
Type: schema.TypeString,
Computed: true,
},
"image_owner_alias": {
Type: schema.TypeString,
Computed: true,
},
"image_type": {
Type: schema.TypeString,
Computed: true,
},
"kernel_id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"owner_id": {
Type: schema.TypeString,
Computed: true,
},
"platform": {
Type: schema.TypeString,
Computed: true,
},
"public": {
Type: schema.TypeBool,
Computed: true,
},
"ramdisk_id": {
Type: schema.TypeString,
Computed: true,
},
"root_device_name": {
Type: schema.TypeString,
Computed: true,
},
"root_device_type": {
Type: schema.TypeString,
Computed: true,
},
"root_snapshot_id": {
Type: schema.TypeString,
Computed: true,
},
"sriov_net_support": {
Type: schema.TypeString,
Computed: true,
},
"state": {
Type: schema.TypeString,
Computed: true,
},
"virtualization_type": {
Type: schema.TypeString,
Computed: true,
},
// Complex computed values
"block_device_mappings": {
Type: schema.TypeSet,
Computed: true,
Set: amiBlockDeviceMappingHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"device_name": {
Type: schema.TypeString,
Computed: true,
},
"no_device": {
Type: schema.TypeString,
Computed: true,
},
"virtual_name": {
Type: schema.TypeString,
Computed: true,
},
"ebs": {
Type: schema.TypeMap,
Computed: true,
},
},
},
},
"product_codes": {
Type: schema.TypeSet,
Computed: true,
Set: amiProductCodesHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"product_code_id": {
Type: schema.TypeString,
Computed: true,
},
"product_code_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"state_reason": {
Type: schema.TypeMap,
Computed: true,
},
"tags": tagsSchemaComputed(),
},
}
}
// 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")
nameRegex, nameRegexOk := d.GetOk("name_regex")
owners, ownersOk := d.GetOk("owners")
if !executableUsersOk && !filtersOk && !nameRegexOk && !ownersOk {
return fmt.Errorf("One of executable_users, filters, name_regex, or owners must be assigned")
}
params := &ec2.DescribeImagesInput{}
if executableUsersOk {
params.ExecutableUsers = expandStringList(executableUsers.([]interface{}))
}
if filtersOk {
params.Filters = buildAwsDataSourceFilters(filters.(*schema.Set))
}
if ownersOk {
o := expandStringList(owners.([]interface{}))
if len(o) > 0 {
params.Owners = o
}
}
// Deprecated: pre-2.0.0 warning logging
if !ownersOk {
log.Print("[WARN] The \"owners\" argument will become required in the next major version.")
log.Print("[WARN] Documentation can be found at: https://www.terraform.io/docs/providers/aws/d/ami.html#owners")
missingOwnerFilter := true
if filtersOk {
for _, filter := range params.Filters {
if aws.StringValue(filter.Name) == "owner-alias" || aws.StringValue(filter.Name) == "owner-id" {
missingOwnerFilter = false
break
}
}
}
if missingOwnerFilter {
log.Print("[WARN] Potential security issue: missing \"owners\" filtering for AMI. Check AMI to ensure it came from trusted source.")
}
}
log.Printf("[DEBUG] Reading AMI: %s", params)
resp, err := conn.DescribeImages(params)
if err != nil {
return err
}
var filteredImages []*ec2.Image
if nameRegexOk {
r := regexp.MustCompile(nameRegex.(string))
for _, image := range resp.Images {
// Check for a very rare case where the response would include no
// image name. No name means nothing to attempt a match against,
// therefore we are skipping such image.
if image.Name == nil || *image.Name == "" {
log.Printf("[WARN] Unable to find AMI name to match against "+
"for image ID %q owned by %q, nothing to do.",
*image.ImageId, *image.OwnerId)
continue
}
if r.MatchString(*image.Name) {
filteredImages = append(filteredImages, image)
}
}
} else {
filteredImages = resp.Images[:]
}
if len(filteredImages) < 1 {
return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
}
if len(filteredImages) > 1 {
if !d.Get("most_recent").(bool) {
return fmt.Errorf("Your query returned more than one result. Please try a more " +
"specific search criteria, or set `most_recent` attribute to true.")
}
sort.Slice(filteredImages, func(i, j int) bool {
itime, _ := time.Parse(time.RFC3339, aws.StringValue(filteredImages[i].CreationDate))
jtime, _ := time.Parse(time.RFC3339, aws.StringValue(filteredImages[j].CreationDate))
return itime.Unix() > jtime.Unix()
})
}
return amiDescriptionAttributes(d, filteredImages[0])
}
// 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)
d.Set("root_snapshot_id", amiRootSnapshotId(image))
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", tagsToMap(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": aws.StringValue(v.DeviceName),
"virtual_name": aws.StringValue(v.VirtualName),
}
if v.Ebs != nil {
ebs := map[string]interface{}{
"delete_on_termination": fmt.Sprintf("%t", aws.BoolValue(v.Ebs.DeleteOnTermination)),
"encrypted": fmt.Sprintf("%t", aws.BoolValue(v.Ebs.Encrypted)),
"iops": fmt.Sprintf("%d", aws.Int64Value(v.Ebs.Iops)),
"volume_size": fmt.Sprintf("%d", aws.Int64Value(v.Ebs.VolumeSize)),
"snapshot_id": aws.StringValue(v.Ebs.SnapshotId),
"volume_type": aws.StringValue(v.Ebs.VolumeType),
}
mapping["ebs"] = ebs
}
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": aws.StringValue(v.ProductCodeId),
"product_code_type": aws.StringValue(v.ProductCodeType),
}
s.Add(code)
}
return s
}
// Returns the root snapshot ID for an image, if it has one
func amiRootSnapshotId(image *ec2.Image) string {
if image.RootDeviceName == nil {
return ""
}
for _, bdm := range image.BlockDeviceMappings {
if bdm.DeviceName == nil || *bdm.DeviceName != *image.RootDeviceName {
continue
}
if bdm.Ebs != nil && bdm.Ebs.SnapshotId != nil {
return *bdm.Ebs.SnapshotId
}
}
return ""
}
// Returns the state reason.
func amiStateReason(m *ec2.StateReason) map[string]interface{} {
s := make(map[string]interface{})
if m != nil {
s["code"] = aws.StringValue(m.Code)
s["message"] = aws.StringValue(m.Message)
} else {
s["code"] = "UNSET"
s["message"] = "UNSET"
}
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())
}