1 // schema is a high-level framework for easily writing new providers
2 // for Terraform. Usage of schema is recommended over attempting to write
3 // to the low-level plugin interfaces manually.
5 // schema breaks down provider creation into simple CRUD operations for
6 // resources. The logic of diffing, destroying before creating, updating
7 // or creating, etc. is all handled by the framework. The plugin author
8 // only needs to implement a configuration schema and the CRUD operations and
9 // everything else is meant to just work.
11 // A good starting point is to view the Provider structure.
22 "github.com/hashicorp/terraform/terraform"
23 "github.com/mitchellh/mapstructure"
26 // type used for schema package context keys
27 type contextKey string
29 // Schema is used to describe the structure of a value.
31 // Read the documentation of the struct elements for important details.
33 // Type is the type of the value and must be one of the ValueType values.
35 // This type not only determines what type is expected/valid in configuring
36 // this value, but also what type is returned when ResourceData.Get is
37 // called. The types returned by Get are:
41 // TypeFloat - float64
42 // TypeString - string
43 // TypeList - []interface{}
44 // TypeMap - map[string]interface{}
45 // TypeSet - *schema.Set
49 // If one of these is set, then this item can come from the configuration.
50 // Both cannot be set. If Optional is set, the value is optional. If
51 // Required is set, the value is required.
53 // One of these must be set if the value is not computed. That is:
54 // value either comes from the config, is computed, or is both.
58 // If this is non-nil, the provided function will be used during diff
59 // of this field. If this is nil, a default diff for the type of the
60 // schema will be used.
62 // This allows comparison based on something other than primitive, list
63 // or map equality - for example SSH public keys may be considered
64 // equivalent regardless of trailing whitespace.
65 DiffSuppressFunc SchemaDiffSuppressFunc
67 // If this is non-nil, then this will be a default value that is used
68 // when this item is not set in the configuration.
70 // DefaultFunc can be specified to compute a dynamic default.
71 // Only one of Default or DefaultFunc can be set. If DefaultFunc is
72 // used then its return value should be stable to avoid generating
73 // confusing/perpetual diffs.
75 // Changing either Default or the return value of DefaultFunc can be
76 // a breaking change, especially if the attribute in question has
77 // ForceNew set. If a default needs to change to align with changing
78 // assumptions in an upstream API then it may be necessary to also use
79 // the MigrateState function on the resource to change the state to match,
80 // or have the Read function adjust the state value to align with the
83 // If Required is true above, then Default cannot be set. DefaultFunc
84 // can be set with Required. If the DefaultFunc returns nil, then there
85 // will be no default and the user will be asked to fill it in.
87 // If either of these is set, then the user won't be asked for input
88 // for this key if the default is not nil.
90 DefaultFunc SchemaDefaultFunc
92 // Description is used as the description for docs or asking for user
93 // input. It should be relatively short (a few sentences max) and should
94 // be formatted to fit a CLI.
97 // InputDefault is the default value to use for when inputs are requested.
98 // This differs from Default in that if Default is set, no input is
99 // asked for. If Input is asked, this will be the default value offered.
102 // The fields below relate to diffs.
104 // If Computed is true, then the result of this value is computed
105 // (unless specified by config) on creation.
107 // If ForceNew is true, then a change in this resource necessitates
108 // the creation of a new resource.
110 // StateFunc is a function called to change the value of this before
111 // storing it in the state (and likewise before comparing for diffs).
112 // The use for this is for example with large strings, you may want
113 // to simply store the hash of it.
116 StateFunc SchemaStateFunc
118 // The following fields are only set for a TypeList or TypeSet Type.
120 // Elem must be either a *Schema or a *Resource only if the Type is
121 // TypeList, and represents what the element type is. If it is *Schema,
122 // the element type is just a simple value. If it is *Resource, the
123 // element type is a complex structure, potentially with its own lifecycle.
125 // MaxItems defines a maximum amount of items that can exist within a
126 // TypeSet or TypeList. Specific use cases would be if a TypeSet is being
127 // used to wrap a complex structure, however more than one instance would
128 // cause instability.
130 // MinItems defines a minimum amount of items that can exist within a
131 // TypeSet or TypeList. Specific use cases would be if a TypeSet is being
132 // used to wrap a complex structure, however less than one instance would
133 // cause instability.
135 // PromoteSingle, if true, will allow single elements to be standalone
136 // and promote them to a list. For example "foo" would be promoted to
137 // ["foo"] automatically. This is primarily for legacy reasons and the
138 // ambiguity is not recommended for new usage. Promotion is only allowed
139 // for primitive element types.
145 // The following fields are only valid for a TypeSet type.
147 // Set defines a function to determine the unique ID of an item so that
148 // a proper set can be built.
151 // ComputedWhen is a set of queries on the configuration. Whenever any
152 // of these things is changed, it will require a recompute (this requires
153 // that Computed is set to true).
155 // NOTE: This currently does not work.
156 ComputedWhen []string
158 // ConflictsWith is a set of schema keys that conflict with this schema.
159 // This will only check that they're set in the _config_. This will not
160 // raise an error for a malfunctioning resource that sets a conflicting
162 ConflictsWith []string
164 // When Deprecated is set, this attribute is deprecated.
166 // A deprecated field still works, but will probably stop working in near
167 // future. This string is the message shown to the user with instructions on
168 // how to address the deprecation.
171 // When Removed is set, this attribute has been removed from the schema
173 // Removed attributes can be left in the Schema to generate informative error
174 // messages for the user when they show up in resource configurations.
175 // This string is the message shown to the user with instructions on
176 // what do to about the removed attribute.
179 // ValidateFunc allows individual fields to define arbitrary validation
180 // logic. It is yielded the provided config value as an interface{} that is
181 // guaranteed to be of the proper Schema type, and it can yield warnings or
182 // errors based on inspection of that value.
184 // ValidateFunc currently only works for primitive types.
185 ValidateFunc SchemaValidateFunc
187 // Sensitive ensures that the attribute's value does not get displayed in
188 // logs or regular output. It should be used for passwords or other
189 // secret fields. Future versions of Terraform may encrypt these
194 // SchemaDiffSuppresFunc is a function which can be used to determine
195 // whether a detected diff on a schema element is "valid" or not, and
196 // suppress it from the plan if necessary.
198 // Return true if the diff should be suppressed, false to retain it.
199 type SchemaDiffSuppressFunc func(k, old, new string, d *ResourceData) bool
201 // SchemaDefaultFunc is a function called to return a default value for
203 type SchemaDefaultFunc func() (interface{}, error)
205 // EnvDefaultFunc is a helper function that returns the value of the
206 // given environment variable, if one exists, or the default value
208 func EnvDefaultFunc(k string, dv interface{}) SchemaDefaultFunc {
209 return func() (interface{}, error) {
210 if v := os.Getenv(k); v != "" {
218 // MultiEnvDefaultFunc is a helper function that returns the value of the first
219 // environment variable in the given list that returns a non-empty value. If
220 // none of the environment variables return a value, the default value is
222 func MultiEnvDefaultFunc(ks []string, dv interface{}) SchemaDefaultFunc {
223 return func() (interface{}, error) {
224 for _, k := range ks {
225 if v := os.Getenv(k); v != "" {
233 // SchemaSetFunc is a function that must return a unique ID for the given
234 // element. This unique ID is used to store the element in a hash.
235 type SchemaSetFunc func(interface{}) int
237 // SchemaStateFunc is a function used to convert some type to a string
238 // to be stored in the state.
239 type SchemaStateFunc func(interface{}) string
241 // SchemaValidateFunc is a function used to validate a single field in the
243 type SchemaValidateFunc func(interface{}, string) ([]string, []error)
245 func (s *Schema) GoString() string {
246 return fmt.Sprintf("*%#v", *s)
249 // Returns a default value for this schema by either reading Default or
250 // evaluating DefaultFunc. If neither of these are defined, returns nil.
251 func (s *Schema) DefaultValue() (interface{}, error) {
252 if s.Default != nil {
253 return s.Default, nil
256 if s.DefaultFunc != nil {
257 defaultValue, err := s.DefaultFunc()
259 return nil, fmt.Errorf("error loading default: %s", err)
261 return defaultValue, nil
267 // Returns a zero value for the schema.
268 func (s *Schema) ZeroValue() interface{} {
269 // If it's a set then we'll do a bit of extra work to provide the
270 // right hashing function in our empty value.
271 if s.Type == TypeSet {
274 // Default set function uses the schema to hash the whole value
276 switch t := elem.(type) {
278 setFunc = HashSchema(t)
280 setFunc = HashResource(t)
282 panic("invalid set element type")
285 return &Set{F: setFunc}
291 func (s *Schema) finalizeDiff(
292 d *terraform.ResourceAttrDiff) *terraform.ResourceAttrDiff {
297 if s.Type == TypeBool {
298 normalizeBoolString := func(s string) string {
307 d.Old = normalizeBoolString(d.Old)
308 d.New = normalizeBoolString(d.New)
311 if s.Computed && !d.NewRemoved && d.New == "" {
312 // Computed attribute without a new value set
317 // ForceNew, mark that this field is requiring new under the
318 // following conditions, explained below:
320 // * Old != New - There is a change in value. This field
321 // is therefore causing a new resource.
323 // * NewComputed - This field is being computed, hence a
324 // potential change in value, mark as causing a new resource.
325 d.RequiresNew = d.Old != d.New || d.NewComputed
333 if d.Old != "" && d.New == "" {
334 // This is a computed value with an old value set already,
340 // Computed attribute without a new value set
346 // Set the Sensitive flag so output is hidden in the UI
353 // schemaMap is a wrapper that adds nice functions on top of schemas.
354 type schemaMap map[string]*Schema
356 // Data returns a ResourceData for the given schema, state, and diff.
358 // The diff is optional.
359 func (m schemaMap) Data(
360 s *terraform.InstanceState,
361 d *terraform.InstanceDiff) (*ResourceData, error) {
362 return &ResourceData{
369 // Diff returns the diff for a resource given the schema map,
370 // state, and configuration.
371 func (m schemaMap) Diff(
372 s *terraform.InstanceState,
373 c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) {
374 result := new(terraform.InstanceDiff)
375 result.Attributes = make(map[string]*terraform.ResourceAttrDiff)
377 // Make sure to mark if the resource is tainted
379 result.DestroyTainted = s.Tainted
388 for k, schema := range m {
389 err := m.diff(k, schema, result, d, false)
395 // If the diff requires a new resource, then we recompute the diff
396 // so we have the complete new resource diff, and preserve the
397 // RequiresNew fields where necessary so the user knows exactly what
399 if result.RequiresNew() {
400 // Create the new diff
401 result2 := new(terraform.InstanceDiff)
402 result2.Attributes = make(map[string]*terraform.ResourceAttrDiff)
404 // Preserve the DestroyTainted flag
405 result2.DestroyTainted = result.DestroyTainted
407 // Reset the data to not contain state. We have to call init()
408 // again in order to reset the FieldReaders.
412 // Perform the diff again
413 for k, schema := range m {
414 err := m.diff(k, schema, result2, d, false)
420 // Force all the fields to not force a new since we know what we
421 // want to force new.
422 for k, attr := range result2.Attributes {
427 if attr.RequiresNew {
428 attr.RequiresNew = false
432 attr.Old = s.Attributes[k]
436 // Now copy in all the requires new diffs...
437 for k, attr := range result.Attributes {
442 newAttr, ok := result2.Attributes[k]
447 if attr.RequiresNew {
448 newAttr.RequiresNew = true
451 result2.Attributes[k] = newAttr
458 // Remove any nil diffs just to keep things clean
459 for k, v := range result.Attributes {
461 delete(result.Attributes, k)
465 // Go through and detect all of the ComputedWhens now that we've
466 // finished the diff.
470 // If we don't have any diff elements, just return nil
477 // Input implements the terraform.ResourceProvider method by asking
478 // for input for required configuration keys that don't have a value.
479 func (m schemaMap) Input(
480 input terraform.UIInput,
481 c *terraform.ResourceConfig) (*terraform.ResourceConfig, error) {
482 keys := make([]string, 0, len(m))
483 for k, _ := range m {
484 keys = append(keys, k)
488 for _, k := range keys {
491 // Skip things that don't require config, if that is even valid
492 // for a provider schema.
493 // Required XOR Optional must always be true to validate, so we only
494 // need to check one.
499 // Deprecated fields should never prompt
500 if v.Deprecated != "" {
504 // Skip things that have a value of some sort already
505 if _, ok := c.Raw[k]; ok {
509 // Skip if it has a default value
510 defaultValue, err := v.DefaultValue()
512 return nil, fmt.Errorf("%s: error loading default: %s", k, err)
514 if defaultValue != nil {
518 var value interface{}
520 case TypeBool, TypeInt, TypeFloat, TypeSet, TypeList:
523 value, err = m.inputString(input, k, v)
525 panic(fmt.Sprintf("Unknown type for input: %#v", v.Type))
529 return nil, fmt.Errorf(
539 // Validate validates the configuration against this schema mapping.
540 func (m schemaMap) Validate(c *terraform.ResourceConfig) ([]string, []error) {
541 return m.validateObject("", m, c)
544 // InternalValidate validates the format of this schema. This should be called
545 // from a unit test (and not in user-path code) to verify that a schema
546 // is properly built.
547 func (m schemaMap) InternalValidate(topSchemaMap schemaMap) error {
548 if topSchemaMap == nil {
551 for k, v := range m {
552 if v.Type == TypeInvalid {
553 return fmt.Errorf("%s: Type must be specified", k)
556 if v.Optional && v.Required {
557 return fmt.Errorf("%s: Optional or Required must be set, not both", k)
560 if v.Required && v.Computed {
561 return fmt.Errorf("%s: Cannot be both Required and Computed", k)
564 if !v.Required && !v.Optional && !v.Computed {
565 return fmt.Errorf("%s: One of optional, required, or computed must be set", k)
568 if v.Computed && v.Default != nil {
569 return fmt.Errorf("%s: Default must be nil if computed", k)
572 if v.Required && v.Default != nil {
573 return fmt.Errorf("%s: Default cannot be set with Required", k)
576 if len(v.ComputedWhen) > 0 && !v.Computed {
577 return fmt.Errorf("%s: ComputedWhen can only be set with Computed", k)
580 if len(v.ConflictsWith) > 0 && v.Required {
581 return fmt.Errorf("%s: ConflictsWith cannot be set with Required", k)
584 if len(v.ConflictsWith) > 0 {
585 for _, key := range v.ConflictsWith {
586 parts := strings.Split(key, ".")
589 for _, part := range parts {
591 if _, err := strconv.Atoi(part); err == nil {
596 if target, ok = sm[part]; !ok {
597 return fmt.Errorf("%s: ConflictsWith references unknown attribute (%s)", k, key)
600 if subResource, ok := target.Elem.(*Resource); ok {
601 sm = schemaMap(subResource.Schema)
605 return fmt.Errorf("%s: ConflictsWith cannot find target attribute (%s), sm: %#v", k, key, sm)
608 return fmt.Errorf("%s: ConflictsWith cannot contain Required attribute (%s)", k, key)
611 if len(target.ComputedWhen) > 0 {
612 return fmt.Errorf("%s: ConflictsWith cannot contain Computed(When) attribute (%s)", k, key)
617 if v.Type == TypeList || v.Type == TypeSet {
619 return fmt.Errorf("%s: Elem must be set for lists", k)
622 if v.Default != nil {
623 return fmt.Errorf("%s: Default is not valid for lists or sets", k)
626 if v.Type != TypeSet && v.Set != nil {
627 return fmt.Errorf("%s: Set can only be set for TypeSet", k)
630 switch t := v.Elem.(type) {
632 if err := t.InternalValidate(topSchemaMap, true); err != nil {
636 bad := t.Computed || t.Optional || t.Required
639 "%s: Elem must have only Type set", k)
643 if v.MaxItems > 0 || v.MinItems > 0 {
644 return fmt.Errorf("%s: MaxItems and MinItems are only supported on lists or sets", k)
648 // Computed-only field
649 if v.Computed && !v.Optional {
650 if v.ValidateFunc != nil {
651 return fmt.Errorf("%s: ValidateFunc is for validating user input, "+
652 "there's nothing to validate on computed-only field", k)
654 if v.DiffSuppressFunc != nil {
655 return fmt.Errorf("%s: DiffSuppressFunc is for suppressing differences"+
656 " between config and state representation. "+
657 "There is no config for computed-only field, nothing to compare.", k)
661 if v.ValidateFunc != nil {
663 case TypeList, TypeSet:
664 return fmt.Errorf("ValidateFunc is not yet supported on lists or sets.")
672 func (m schemaMap) diff(
675 diff *terraform.InstanceDiff,
679 unsupressedDiff := new(terraform.InstanceDiff)
680 unsupressedDiff.Attributes = make(map[string]*terraform.ResourceAttrDiff)
684 case TypeBool, TypeInt, TypeFloat, TypeString:
685 err = m.diffString(k, schema, unsupressedDiff, d, all)
687 err = m.diffList(k, schema, unsupressedDiff, d, all)
689 err = m.diffMap(k, schema, unsupressedDiff, d, all)
691 err = m.diffSet(k, schema, unsupressedDiff, d, all)
693 err = fmt.Errorf("%s: unknown type %#v", k, schema.Type)
696 for attrK, attrV := range unsupressedDiff.Attributes {
697 if schema.DiffSuppressFunc != nil &&
699 schema.DiffSuppressFunc(attrK, attrV.Old, attrV.New, d) {
703 diff.Attributes[attrK] = attrV
709 func (m schemaMap) diffList(
712 diff *terraform.InstanceDiff,
715 o, n, _, computedList := d.diffChange(k)
721 // If we have an old value and no new value is set or will be
722 // computed once all variables can be interpolated and we're
723 // computed, then nothing has changed.
724 if o != nil && n == nil && !computedList && schema.Computed {
734 if s, ok := o.(*Set); ok {
737 if s, ok := n.(*Set); ok {
740 os := o.([]interface{})
741 vs := n.([]interface{})
743 // If the new value was set, and the two are equal, then we're done.
744 // We have to do this check here because sets might be NOT
745 // reflect.DeepEqual so we need to wait until we get the []interface{}
746 if !all && nSet && reflect.DeepEqual(os, vs) {
753 oldStr := strconv.FormatInt(int64(oldLen), 10)
755 // If the whole list is computed, then say that the # is computed
757 diff.Attributes[k+".#"] = &terraform.ResourceAttrDiff{
760 RequiresNew: schema.ForceNew,
765 // If the counts are not the same, then record that diff
766 changed := oldLen != newLen
767 computed := oldLen == 0 && newLen == 0 && schema.Computed
768 if changed || computed || all {
769 countSchema := &Schema{
771 Computed: schema.Computed,
772 ForceNew: schema.ForceNew,
777 newStr = strconv.FormatInt(int64(newLen), 10)
782 diff.Attributes[k+".#"] = countSchema.finalizeDiff(&terraform.ResourceAttrDiff{
788 // Figure out the maximum
794 switch t := schema.Elem.(type) {
796 // This is a complex resource
797 for i := 0; i < maxLen; i++ {
798 for k2, schema := range t.Schema {
799 subK := fmt.Sprintf("%s.%d.%s", k, i, k2)
800 err := m.diff(subK, schema, diff, d, all)
807 // Copy the schema so that we can set Computed/ForceNew from
808 // the parent schema (the TypeList).
810 t2.ForceNew = schema.ForceNew
812 // This is just a primitive element, so go through each and
814 for i := 0; i < maxLen; i++ {
815 subK := fmt.Sprintf("%s.%d", k, i)
816 err := m.diff(subK, &t2, diff, d, all)
822 return fmt.Errorf("%s: unknown element type (internal)", k)
828 func (m schemaMap) diffMap(
831 diff *terraform.InstanceDiff,
836 // First get all the values from the state
837 var stateMap, configMap map[string]string
838 o, n, _, nComputed := d.diffChange(k)
839 if err := mapstructure.WeakDecode(o, &stateMap); err != nil {
840 return fmt.Errorf("%s: %s", k, err)
842 if err := mapstructure.WeakDecode(n, &configMap); err != nil {
843 return fmt.Errorf("%s: %s", k, err)
846 // Keep track of whether the state _exists_ at all prior to clearing it
847 stateExists := o != nil
849 // Delete any count values, since we don't use those
850 delete(configMap, "%")
851 delete(stateMap, "%")
853 // Check if the number of elements has changed.
854 oldLen, newLen := len(stateMap), len(configMap)
855 changed := oldLen != newLen
856 if oldLen != 0 && newLen == 0 && schema.Computed {
860 // It is computed if we have no old value, no new value, the schema
861 // says it is computed, and it didn't exist in the state before. The
862 // last point means: if it existed in the state, even empty, then it
863 // has already been computed.
864 computed := oldLen == 0 && newLen == 0 && schema.Computed && !stateExists
866 // If the count has changed or we're computed, then add a diff for the
867 // count. "nComputed" means that the new value _contains_ a value that
868 // is computed. We don't do granular diffs for this yet, so we mark the
869 // whole map as computed.
870 if changed || computed || nComputed {
871 countSchema := &Schema{
873 Computed: schema.Computed || nComputed,
874 ForceNew: schema.ForceNew,
877 oldStr := strconv.FormatInt(int64(oldLen), 10)
879 if !computed && !nComputed {
880 newStr = strconv.FormatInt(int64(newLen), 10)
885 diff.Attributes[k+".%"] = countSchema.finalizeDiff(
886 &terraform.ResourceAttrDiff{
893 // If the new map is nil and we're computed, then ignore it.
894 if n == nil && schema.Computed {
898 // Now we compare, preferring values from the config map
899 for k, v := range configMap {
900 old, ok := stateMap[k]
903 if old == v && ok && !all {
907 diff.Attributes[prefix+k] = schema.finalizeDiff(&terraform.ResourceAttrDiff{
912 for k, v := range stateMap {
913 diff.Attributes[prefix+k] = schema.finalizeDiff(&terraform.ResourceAttrDiff{
922 func (m schemaMap) diffSet(
925 diff *terraform.InstanceDiff,
929 o, n, _, computedSet := d.diffChange(k)
935 // If we have an old value and no new value is set or will be
936 // computed once all variables can be interpolated and we're
937 // computed, then nothing has changed.
938 if o != nil && n == nil && !computedSet && schema.Computed {
943 o = schema.ZeroValue().(*Set)
946 n = schema.ZeroValue().(*Set)
951 // If the new value was set, compare the listCode's to determine if
952 // the two are equal. Comparing listCode's instead of the actual values
953 // is needed because there could be computed values in the set which
954 // would result in false positives while comparing.
955 if !all && nSet && reflect.DeepEqual(os.listCode(), ns.listCode()) {
962 oldStr := strconv.Itoa(oldLen)
963 newStr := strconv.Itoa(newLen)
965 // Build a schema for our count
966 countSchema := &Schema{
968 Computed: schema.Computed,
969 ForceNew: schema.ForceNew,
972 // If the set computed then say that the # is computed
973 if computedSet || schema.Computed && !nSet {
974 // If # already exists, equals 0 and no new set is supplied, there
975 // is nothing to record in the diff
976 count, ok := d.GetOk(k + ".#")
977 if ok && count.(int) == 0 && !nSet && !computedSet {
981 // Set the count but make sure that if # does not exist, we don't
982 // use the zeroed value
983 countStr := strconv.Itoa(count.(int))
988 diff.Attributes[k+".#"] = countSchema.finalizeDiff(&terraform.ResourceAttrDiff{
995 // If the counts are not the same, then record that diff
996 changed := oldLen != newLen
998 diff.Attributes[k+".#"] = countSchema.finalizeDiff(&terraform.ResourceAttrDiff{
1004 // Build the list of codes that will make up our set. This is the
1005 // removed codes as well as all the codes in the new codes.
1006 codes := make([][]string, 2)
1007 codes[0] = os.Difference(ns).listCode()
1008 codes[1] = ns.listCode()
1009 for _, list := range codes {
1010 for _, code := range list {
1011 switch t := schema.Elem.(type) {
1013 // This is a complex resource
1014 for k2, schema := range t.Schema {
1015 subK := fmt.Sprintf("%s.%s.%s", k, code, k2)
1016 err := m.diff(subK, schema, diff, d, true)
1022 // Copy the schema so that we can set Computed/ForceNew from
1023 // the parent schema (the TypeSet).
1025 t2.ForceNew = schema.ForceNew
1027 // This is just a primitive element, so go through each and
1029 subK := fmt.Sprintf("%s.%s", k, code)
1030 err := m.diff(subK, &t2, diff, d, true)
1035 return fmt.Errorf("%s: unknown element type (internal)", k)
1043 func (m schemaMap) diffString(
1046 diff *terraform.InstanceDiff,
1049 var originalN interface{}
1051 o, n, _, computed := d.diffChange(k)
1052 if schema.StateFunc != nil && n != nil {
1054 n = schema.StateFunc(n)
1057 if nraw == nil && o != nil {
1058 nraw = schema.Type.Zero()
1060 if err := mapstructure.WeakDecode(o, &os); err != nil {
1061 return fmt.Errorf("%s: %s", k, err)
1063 if err := mapstructure.WeakDecode(nraw, &ns); err != nil {
1064 return fmt.Errorf("%s: %s", k, err)
1067 if os == ns && !all {
1068 // They're the same value. If there old value is not blank or we
1069 // have an ID, then return right away since we're already setup.
1070 if os != "" || d.Id() != "" {
1074 // Otherwise, only continue if we're computed
1075 if !schema.Computed && !computed {
1081 if o != nil && n == nil {
1084 if removed && schema.Computed {
1088 diff.Attributes[k] = schema.finalizeDiff(&terraform.ResourceAttrDiff{
1091 NewExtra: originalN,
1092 NewRemoved: removed,
1093 NewComputed: computed,
1099 func (m schemaMap) inputString(
1100 input terraform.UIInput,
1102 schema *Schema) (interface{}, error) {
1103 result, err := input.Input(&terraform.InputOpts{
1106 Description: schema.Description,
1107 Default: schema.InputDefault,
1113 func (m schemaMap) validate(
1116 c *terraform.ResourceConfig) ([]string, []error) {
1118 if !ok && schema.DefaultFunc != nil {
1119 // We have a dynamic default. Check if we have a value.
1121 raw, err = schema.DefaultFunc()
1123 return nil, []error{fmt.Errorf(
1124 "%q, error loading default: %s", k, err)}
1127 // We're okay as long as we had a value set
1131 if schema.Required {
1132 return nil, []error{fmt.Errorf(
1133 "%q: required field is not set", k)}
1139 if !schema.Required && !schema.Optional {
1140 // This is a computed-only field
1141 return nil, []error{fmt.Errorf(
1142 "%q: this field cannot be set", k)}
1145 err := m.validateConflictingAttributes(k, schema, c)
1147 return nil, []error{err}
1150 return m.validateType(k, raw, schema, c)
1153 func (m schemaMap) validateConflictingAttributes(
1156 c *terraform.ResourceConfig) error {
1158 if len(schema.ConflictsWith) == 0 {
1162 for _, conflicting_key := range schema.ConflictsWith {
1163 if value, ok := c.Get(conflicting_key); ok {
1165 "%q: conflicts with %s (%#v)", k, conflicting_key, value)
1172 func (m schemaMap) validateList(
1176 c *terraform.ResourceConfig) ([]string, []error) {
1177 // We use reflection to verify the slice because you can't
1178 // case to []interface{} unless the slice is exactly that type.
1179 rawV := reflect.ValueOf(raw)
1181 // If we support promotion and the raw value isn't a slice, wrap
1182 // it in []interface{} and check again.
1183 if schema.PromoteSingle && rawV.Kind() != reflect.Slice {
1184 raw = []interface{}{raw}
1185 rawV = reflect.ValueOf(raw)
1188 if rawV.Kind() != reflect.Slice {
1189 return nil, []error{fmt.Errorf(
1190 "%s: should be a list", k)}
1194 if schema.MaxItems > 0 && rawV.Len() > schema.MaxItems {
1195 return nil, []error{fmt.Errorf(
1196 "%s: attribute supports %d item maximum, config has %d declared", k, schema.MaxItems, rawV.Len())}
1199 if schema.MinItems > 0 && rawV.Len() < schema.MinItems {
1200 return nil, []error{fmt.Errorf(
1201 "%s: attribute supports %d item as a minimum, config has %d declared", k, schema.MinItems, rawV.Len())}
1204 // Now build the []interface{}
1205 raws := make([]interface{}, rawV.Len())
1206 for i, _ := range raws {
1207 raws[i] = rawV.Index(i).Interface()
1212 for i, raw := range raws {
1213 key := fmt.Sprintf("%s.%d", k, i)
1215 // Reify the key value from the ResourceConfig.
1216 // If the list was computed we have all raw values, but some of these
1217 // may be known in the config, and aren't individually marked as Computed.
1218 if r, ok := c.Get(key); ok {
1224 switch t := schema.Elem.(type) {
1226 // This is a sub-resource
1227 ws2, es2 = m.validateObject(key, t.Schema, c)
1229 ws2, es2 = m.validateType(key, raw, t, c)
1233 ws = append(ws, ws2...)
1236 es = append(es, es2...)
1243 func (m schemaMap) validateMap(
1247 c *terraform.ResourceConfig) ([]string, []error) {
1248 // We use reflection to verify the slice because you can't
1249 // case to []interface{} unless the slice is exactly that type.
1250 rawV := reflect.ValueOf(raw)
1251 switch rawV.Kind() {
1252 case reflect.String:
1253 // If raw and reified are equal, this is a string and should
1255 reified, reifiedOk := c.Get(k)
1256 if reifiedOk && raw == reified && !c.IsComputed(k) {
1257 return nil, []error{fmt.Errorf("%s: should be a map", k)}
1259 // Otherwise it's likely raw is an interpolation.
1264 return nil, []error{fmt.Errorf("%s: should be a map", k)}
1267 // If it is not a slice, validate directly
1268 if rawV.Kind() != reflect.Slice {
1269 mapIface := rawV.Interface()
1270 if _, errs := validateMapValues(k, mapIface.(map[string]interface{}), schema); len(errs) > 0 {
1273 if schema.ValidateFunc != nil {
1274 return schema.ValidateFunc(mapIface, k)
1279 // It is a slice, verify that all the elements are maps
1280 raws := make([]interface{}, rawV.Len())
1281 for i, _ := range raws {
1282 raws[i] = rawV.Index(i).Interface()
1285 for _, raw := range raws {
1286 v := reflect.ValueOf(raw)
1287 if v.Kind() != reflect.Map {
1288 return nil, []error{fmt.Errorf(
1289 "%s: should be a map", k)}
1291 mapIface := v.Interface()
1292 if _, errs := validateMapValues(k, mapIface.(map[string]interface{}), schema); len(errs) > 0 {
1297 if schema.ValidateFunc != nil {
1298 validatableMap := make(map[string]interface{})
1299 for _, raw := range raws {
1300 for k, v := range raw.(map[string]interface{}) {
1301 validatableMap[k] = v
1305 return schema.ValidateFunc(validatableMap, k)
1311 func validateMapValues(k string, m map[string]interface{}, schema *Schema) ([]string, []error) {
1312 for key, raw := range m {
1313 valueType, err := getValueType(k, schema)
1315 return nil, []error{err}
1321 if err := mapstructure.WeakDecode(raw, &n); err != nil {
1322 return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)}
1326 if err := mapstructure.WeakDecode(raw, &n); err != nil {
1327 return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)}
1331 if err := mapstructure.WeakDecode(raw, &n); err != nil {
1332 return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)}
1336 if err := mapstructure.WeakDecode(raw, &n); err != nil {
1337 return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)}
1340 panic(fmt.Sprintf("Unknown validation type: %#v", schema.Type))
1346 func getValueType(k string, schema *Schema) (ValueType, error) {
1347 if schema.Elem == nil {
1348 return TypeString, nil
1350 if vt, ok := schema.Elem.(ValueType); ok {
1354 if s, ok := schema.Elem.(*Schema); ok {
1356 return TypeString, nil
1358 if vt, ok := s.Elem.(ValueType); ok {
1363 if _, ok := schema.Elem.(*Resource); ok {
1364 // TODO: We don't actually support this (yet)
1365 // but silently pass the validation, until we decide
1366 // how to handle nested structures in maps
1367 return TypeString, nil
1369 return 0, fmt.Errorf("%s: unexpected map value type: %#v", k, schema.Elem)
1372 func (m schemaMap) validateObject(
1374 schema map[string]*Schema,
1375 c *terraform.ResourceConfig) ([]string, []error) {
1377 if _, ok := raw.(map[string]interface{}); !ok && !c.IsComputed(k) {
1378 return nil, []error{fmt.Errorf(
1379 "%s: expected object, got %s",
1380 k, reflect.ValueOf(raw).Kind())}
1385 for subK, s := range schema {
1388 key = fmt.Sprintf("%s.%s", k, subK)
1391 ws2, es2 := m.validate(key, s, c)
1393 ws = append(ws, ws2...)
1396 es = append(es, es2...)
1400 // Detect any extra/unknown keys and report those as errors.
1401 if m, ok := raw.(map[string]interface{}); ok {
1402 for subk, _ := range m {
1403 if _, ok := schema[subk]; !ok {
1404 if subk == TimeoutsConfigKey {
1407 es = append(es, fmt.Errorf(
1408 "%s: invalid or unknown key: %s", k, subk))
1416 func (m schemaMap) validatePrimitive(
1420 c *terraform.ResourceConfig) ([]string, []error) {
1422 // Catch if the user gave a complex type where a primitive was
1423 // expected, so we can return a friendly error message that
1424 // doesn't contain Go type system terminology.
1425 switch reflect.ValueOf(raw).Type().Kind() {
1427 return nil, []error{
1428 fmt.Errorf("%s must be a single value, not a list", k),
1431 return nil, []error{
1432 fmt.Errorf("%s must be a single value, not a map", k),
1437 if c.IsComputed(k) {
1438 // If the key is being computed, then it is not an error as
1439 // long as it's not a slice or map.
1443 var decoded interface{}
1444 switch schema.Type {
1446 // Verify that we can parse this as the correct type
1448 if err := mapstructure.WeakDecode(raw, &n); err != nil {
1449 return nil, []error{fmt.Errorf("%s: %s", k, err)}
1453 // Verify that we can parse this as an int
1455 if err := mapstructure.WeakDecode(raw, &n); err != nil {
1456 return nil, []error{fmt.Errorf("%s: %s", k, err)}
1460 // Verify that we can parse this as an int
1462 if err := mapstructure.WeakDecode(raw, &n); err != nil {
1463 return nil, []error{fmt.Errorf("%s: %s", k, err)}
1467 // Verify that we can parse this as a string
1469 if err := mapstructure.WeakDecode(raw, &n); err != nil {
1470 return nil, []error{fmt.Errorf("%s: %s", k, err)}
1474 panic(fmt.Sprintf("Unknown validation type: %#v", schema.Type))
1477 if schema.ValidateFunc != nil {
1478 return schema.ValidateFunc(decoded, k)
1484 func (m schemaMap) validateType(
1488 c *terraform.ResourceConfig) ([]string, []error) {
1491 switch schema.Type {
1492 case TypeSet, TypeList:
1493 ws, es = m.validateList(k, raw, schema, c)
1495 ws, es = m.validateMap(k, raw, schema, c)
1497 ws, es = m.validatePrimitive(k, raw, schema, c)
1500 if schema.Deprecated != "" {
1501 ws = append(ws, fmt.Sprintf(
1502 "%q: [DEPRECATED] %s", k, schema.Deprecated))
1505 if schema.Removed != "" {
1506 es = append(es, fmt.Errorf(
1507 "%q: [REMOVED] %s", k, schema.Removed))
1513 // Zero returns the zero value for a type.
1514 func (t ValueType) Zero() interface{} {
1527 return []interface{}{}
1529 return map[string]interface{}{}
1533 return map[string]interface{}{}
1535 panic(fmt.Sprintf("unknown type %s", t))