github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/ns1/resource_datasource.go (about) 1 package ns1 2 3 import ( 4 "github.com/hashicorp/terraform/helper/schema" 5 6 ns1 "gopkg.in/ns1/ns1-go.v2/rest" 7 "gopkg.in/ns1/ns1-go.v2/rest/model/data" 8 ) 9 10 func dataSourceResource() *schema.Resource { 11 return &schema.Resource{ 12 Schema: map[string]*schema.Schema{ 13 "id": &schema.Schema{ 14 Type: schema.TypeString, 15 Computed: true, 16 }, 17 "name": &schema.Schema{ 18 Type: schema.TypeString, 19 Required: true, 20 }, 21 "sourcetype": &schema.Schema{ 22 Type: schema.TypeString, 23 Required: true, 24 ForceNew: true, 25 }, 26 "config": &schema.Schema{ 27 Type: schema.TypeMap, 28 Optional: true, 29 }, 30 }, 31 Create: DataSourceCreate, 32 Read: DataSourceRead, 33 Update: DataSourceUpdate, 34 Delete: DataSourceDelete, 35 } 36 } 37 38 func dataSourceToResourceData(d *schema.ResourceData, s *data.Source) { 39 d.SetId(s.ID) 40 d.Set("name", s.Name) 41 d.Set("sourcetype", s.Type) 42 d.Set("config", s.Config) 43 } 44 45 // DataSourceCreate creates an ns1 datasource 46 func DataSourceCreate(d *schema.ResourceData, meta interface{}) error { 47 client := meta.(*ns1.Client) 48 s := data.NewSource(d.Get("name").(string), d.Get("sourcetype").(string)) 49 s.Config = d.Get("config").(map[string]interface{}) 50 if _, err := client.DataSources.Create(s); err != nil { 51 return err 52 } 53 dataSourceToResourceData(d, s) 54 return nil 55 } 56 57 // DataSourceRead fetches info for the given datasource from ns1 58 func DataSourceRead(d *schema.ResourceData, meta interface{}) error { 59 client := meta.(*ns1.Client) 60 s, _, err := client.DataSources.Get(d.Id()) 61 if err != nil { 62 return err 63 } 64 dataSourceToResourceData(d, s) 65 return nil 66 } 67 68 // DataSourceDelete deteltes the given datasource from ns1 69 func DataSourceDelete(d *schema.ResourceData, meta interface{}) error { 70 client := meta.(*ns1.Client) 71 _, err := client.DataSources.Delete(d.Id()) 72 d.SetId("") 73 return err 74 } 75 76 // DataSourceUpdate updates the datasource with given parameters 77 func DataSourceUpdate(d *schema.ResourceData, meta interface{}) error { 78 client := meta.(*ns1.Client) 79 s := data.NewSource(d.Get("name").(string), d.Get("sourcetype").(string)) 80 s.ID = d.Id() 81 if _, err := client.DataSources.Update(s); err != nil { 82 return err 83 } 84 dataSourceToResourceData(d, s) 85 return nil 86 }