/
data_source_ibm_compute_image_template.go
71 lines (59 loc) · 1.93 KB
/
data_source_ibm_compute_image_template.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
package ibm
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/softlayer/softlayer-go/filter"
"github.com/softlayer/softlayer-go/services"
)
func dataSourceIBMComputeImageTemplate() *schema.Resource {
return &schema.Resource{
Read: dataSourceIBMComputeImageTemplateRead,
// TODO: based on need add properties for visibility, type of image,
// notes, size, shared on accounts if needed
Schema: map[string]*schema.Schema{
"id": {
Description: "The internal id of the image template",
Type: schema.TypeInt,
Computed: true,
},
"name": {
Description: "The name of this image template",
Type: schema.TypeString,
Required: true,
},
},
}
}
func dataSourceIBMComputeImageTemplateRead(d *schema.ResourceData, meta interface{}) error {
sess := meta.(ClientSession).SoftLayerSession()
service := services.GetAccountService(sess)
name := d.Get("name").(string)
imageTemplates, err := service.
Mask("id,name").
GetBlockDeviceTemplateGroups()
if err != nil {
return fmt.Errorf("Error looking up image template [%s]: %s", name, err)
}
for _, imageTemplate := range imageTemplates {
if imageTemplate.Name != nil && *imageTemplate.Name == name {
d.SetId(fmt.Sprintf("%d", *imageTemplate.Id))
return nil
}
}
// Image not found among private nor shared images in the account.
// Looking up in the public images
templateService := services.GetVirtualGuestBlockDeviceTemplateGroupService(sess)
pubImageTemplates, err := templateService.
Mask("id,name").
Filter(filter.Path("name").Eq(name).Build()).
GetPublicImages()
if err != nil {
return fmt.Errorf("Error looking up image template [%s] among the public images: %s", name, err)
}
if len(pubImageTemplates) > 0 {
imageTemplate := pubImageTemplates[0]
d.SetId(fmt.Sprintf("%d", *imageTemplate.Id))
return nil
}
return fmt.Errorf("Could not find image template with name [%s]", name)
}