forked from TritonDataCenter/terraform-provider-triton
-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_source_image.go
128 lines (111 loc) · 2.58 KB
/
data_source_image.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
package triton
import (
"context"
"fmt"
"log"
"github.com/hashicorp/terraform/helper/schema"
"github.com/joyent/triton-go/compute"
)
func dataSourceImage() *schema.Resource {
return &schema.Resource{
Read: dataSourceImageRead,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"os": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"public": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"state": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"owner": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"most_recent": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
},
}
}
func mostRecentImages(images []*compute.Image) *compute.Image {
return sortImages(images)[0]
}
func dataSourceImageRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Client)
c, err := client.Compute()
if err != nil {
return err
}
input := &compute.ListImagesInput{}
if name, hasName := d.GetOk("name"); hasName {
input.Name = name.(string)
}
if os, hasOS := d.GetOk("os"); hasOS {
input.OS = os.(string)
}
if version, hasVersion := d.GetOk("version"); hasVersion {
input.Version = version.(string)
}
if public, hasPublic := d.GetOk("public"); hasPublic {
input.Public = public.(bool)
}
if state, hasState := d.GetOk("state"); hasState {
input.State = state.(string)
}
if owner, hasOwner := d.GetOk("owner"); hasOwner {
input.Owner = owner.(string)
}
if imageType, hasImageType := d.GetOk("type"); hasImageType {
input.Type = imageType.(string)
}
images, err := c.Images().List(context.Background(), input)
if err != nil {
return err
}
var image *compute.Image
if len(images) == 0 {
return fmt.Errorf("Your query returned no results. Please change " +
"your search criteria and try again.")
}
if len(images) > 1 {
recent := d.Get("most_recent").(bool)
log.Printf("[DEBUG] triton_image - multiple results found and `most_recent` is set to: %t", recent)
if recent {
image = mostRecentImages(images)
} else {
return fmt.Errorf("Your query returned more than one result. " +
"Please try a more specific search criteria.")
}
} else {
image = images[0]
}
d.SetId(image.ID)
return nil
}