github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/scaleway/data_source_scaleway_image.go (about)

     1  package scaleway
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/hashicorp/terraform/helper/schema"
     7  	"github.com/scaleway/scaleway-cli/pkg/api"
     8  )
     9  
    10  func dataSourceScalewayImage() *schema.Resource {
    11  	return &schema.Resource{
    12  		Read: dataSourceScalewayImageRead,
    13  
    14  		Schema: map[string]*schema.Schema{
    15  			"name": {
    16  				Type:     schema.TypeString,
    17  				Optional: true,
    18  				ForceNew: true,
    19  				Computed: true,
    20  			},
    21  			"name_filter": {
    22  				Type:     schema.TypeString,
    23  				Optional: true,
    24  				ForceNew: true,
    25  			},
    26  			"architecture": {
    27  				Type:     schema.TypeString,
    28  				Required: true,
    29  				ForceNew: true,
    30  			},
    31  			// Computed values.
    32  			"organization": {
    33  				Type:     schema.TypeString,
    34  				Computed: true,
    35  			},
    36  			"public": {
    37  				Type:     schema.TypeBool,
    38  				Computed: true,
    39  			},
    40  			"creation_date": {
    41  				Type:     schema.TypeString,
    42  				Computed: true,
    43  			},
    44  		},
    45  	}
    46  }
    47  
    48  func scalewayImageAttributes(d *schema.ResourceData, img *api.ScalewayImage) error {
    49  	d.Set("architecture", img.Arch)
    50  	d.Set("organization", img.Organization)
    51  	d.Set("public", img.Public)
    52  	d.Set("creation_date", img.CreationDate)
    53  	d.Set("name", img.Name)
    54  	d.SetId(img.Identifier)
    55  
    56  	return nil
    57  }
    58  
    59  func dataSourceScalewayImageRead(d *schema.ResourceData, meta interface{}) error {
    60  	scaleway := meta.(*Client).scaleway
    61  
    62  	var needle string
    63  	if name, ok := d.GetOk("name"); ok {
    64  		needle = name.(string)
    65  	} else if nameFilter, ok := d.GetOk("name_filter"); ok {
    66  		needle = nameFilter.(string)
    67  	}
    68  
    69  	images, err := scaleway.ResolveImage(needle)
    70  	if err != nil {
    71  		return err
    72  	}
    73  	images = api.FilterImagesByArch(images, d.Get("architecture").(string))
    74  	images = api.FilterImagesByRegion(images, scaleway.Region)
    75  
    76  	if len(images) > 1 {
    77  		return fmt.Errorf("The query returned more than one result. Please refine your query.")
    78  	}
    79  	if len(images) == 0 {
    80  		return fmt.Errorf("The query returned no result. Please refine your query.")
    81  	}
    82  
    83  	img, err := scaleway.GetImage(images[0].Identifier)
    84  	if err != nil {
    85  		return err
    86  	}
    87  
    88  	return scalewayImageAttributes(d, img)
    89  }