github.com/richardmarshall/terraform@v0.9.5-0.20170429023105-15704cc6ee35/helper/schema/data_source_resource_shim.go (about) 1 package schema 2 3 import ( 4 "fmt" 5 ) 6 7 // DataSourceResourceShim takes a Resource instance describing a data source 8 // (with a Read implementation and a Schema, at least) and returns a new 9 // Resource instance with additional Create and Delete implementations that 10 // allow the data source to be used as a resource. 11 // 12 // This is a backward-compatibility layer for data sources that were formerly 13 // read-only resources before the data source concept was added. It should not 14 // be used for any *new* data sources. 15 // 16 // The Read function for the data source *must* call d.SetId with a non-empty 17 // id in order for this shim to function as expected. 18 // 19 // The provided Resource instance, and its schema, will be modified in-place 20 // to make it suitable for use as a full resource. 21 func DataSourceResourceShim(name string, dataSource *Resource) *Resource { 22 // Recursively, in-place adjust the schema so that it has ForceNew 23 // on any user-settable resource. 24 dataSourceResourceShimAdjustSchema(dataSource.Schema) 25 26 dataSource.Create = CreateFunc(dataSource.Read) 27 dataSource.Delete = func(d *ResourceData, meta interface{}) error { 28 d.SetId("") 29 return nil 30 } 31 dataSource.Update = nil // should already be nil, but let's make sure 32 33 // FIXME: Link to some further docs either on the website or in the 34 // changelog, once such a thing exists. 35 dataSource.deprecationMessage = fmt.Sprintf( 36 "using %s as a resource is deprecated; consider using the data source instead", 37 name, 38 ) 39 40 return dataSource 41 } 42 43 func dataSourceResourceShimAdjustSchema(schema map[string]*Schema) { 44 for _, s := range schema { 45 // If the attribute is configurable then it must be ForceNew, 46 // since we have no Update implementation. 47 if s.Required || s.Optional { 48 s.ForceNew = true 49 } 50 51 // If the attribute is a nested resource, we need to recursively 52 // apply these same adjustments to it. 53 if s.Elem != nil { 54 if r, ok := s.Elem.(*Resource); ok { 55 dataSourceResourceShimAdjustSchema(r.Schema) 56 } 57 } 58 } 59 }