github.com/hs0210/hashicorp-terraform@v0.11.12-beta1/helper/schema/backend.go (about) 1 package schema 2 3 import ( 4 "context" 5 6 "github.com/hashicorp/terraform/terraform" 7 ) 8 9 // Backend represents a partial backend.Backend implementation and simplifies 10 // the creation of configuration loading and validation. 11 // 12 // Unlike other schema structs such as Provider, this struct is meant to be 13 // embedded within your actual implementation. It provides implementations 14 // only for Input and Configure and gives you a method for accessing the 15 // configuration in the form of a ResourceData that you're expected to call 16 // from the other implementation funcs. 17 type Backend struct { 18 // Schema is the schema for the configuration of this backend. If this 19 // Backend has no configuration this can be omitted. 20 Schema map[string]*Schema 21 22 // ConfigureFunc is called to configure the backend. Use the 23 // FromContext* methods to extract information from the context. 24 // This can be nil, in which case nothing will be called but the 25 // config will still be stored. 26 ConfigureFunc func(context.Context) error 27 28 config *ResourceData 29 } 30 31 var ( 32 backendConfigKey = contextKey("backend config") 33 ) 34 35 // FromContextBackendConfig extracts a ResourceData with the configuration 36 // from the context. This should only be called by Backend functions. 37 func FromContextBackendConfig(ctx context.Context) *ResourceData { 38 return ctx.Value(backendConfigKey).(*ResourceData) 39 } 40 41 func (b *Backend) Input( 42 input terraform.UIInput, 43 c *terraform.ResourceConfig) (*terraform.ResourceConfig, error) { 44 if b == nil { 45 return c, nil 46 } 47 48 return schemaMap(b.Schema).Input(input, c) 49 } 50 51 func (b *Backend) Validate(c *terraform.ResourceConfig) ([]string, []error) { 52 if b == nil { 53 return nil, nil 54 } 55 56 return schemaMap(b.Schema).Validate(c) 57 } 58 59 func (b *Backend) Configure(c *terraform.ResourceConfig) error { 60 if b == nil { 61 return nil 62 } 63 64 sm := schemaMap(b.Schema) 65 66 // Get a ResourceData for this configuration. To do this, we actually 67 // generate an intermediary "diff" although that is never exposed. 68 diff, err := sm.Diff(nil, c, nil, nil) 69 if err != nil { 70 return err 71 } 72 73 data, err := sm.Data(nil, diff) 74 if err != nil { 75 return err 76 } 77 b.config = data 78 79 if b.ConfigureFunc != nil { 80 err = b.ConfigureFunc(context.WithValue( 81 context.Background(), backendConfigKey, data)) 82 if err != nil { 83 return err 84 } 85 } 86 87 return nil 88 } 89 90 // Config returns the configuration. This is available after Configure is 91 // called. 92 func (b *Backend) Config() *ResourceData { 93 return b.config 94 }