github.com/recobe182/terraform@v0.8.5-0.20170117231232-49ab22a935b7/helper/schema/field_reader_config.go (about)

     1  package schema
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"strings"
     7  	"sync"
     8  
     9  	"github.com/hashicorp/terraform/terraform"
    10  	"github.com/mitchellh/mapstructure"
    11  )
    12  
    13  // ConfigFieldReader reads fields out of an untyped map[string]string to the
    14  // best of its ability. It also applies defaults from the Schema. (The other
    15  // field readers do not need default handling because they source fully
    16  // populated data structures.)
    17  type ConfigFieldReader struct {
    18  	Config *terraform.ResourceConfig
    19  	Schema map[string]*Schema
    20  
    21  	indexMaps map[string]map[string]int
    22  	once      sync.Once
    23  }
    24  
    25  func (r *ConfigFieldReader) ReadField(address []string) (FieldReadResult, error) {
    26  	r.once.Do(func() { r.indexMaps = make(map[string]map[string]int) })
    27  	return r.readField(address, false)
    28  }
    29  
    30  func (r *ConfigFieldReader) readField(
    31  	address []string, nested bool) (FieldReadResult, error) {
    32  	schemaList := addrToSchema(address, r.Schema)
    33  	if len(schemaList) == 0 {
    34  		return FieldReadResult{}, nil
    35  	}
    36  
    37  	if !nested {
    38  		// If we have a set anywhere in the address, then we need to
    39  		// read that set out in order and actually replace that part of
    40  		// the address with the real list index. i.e. set.50 might actually
    41  		// map to set.12 in the config, since it is in list order in the
    42  		// config, not indexed by set value.
    43  		for i, v := range schemaList {
    44  			// Sets are the only thing that cause this issue.
    45  			if v.Type != TypeSet {
    46  				continue
    47  			}
    48  
    49  			// If we're at the end of the list, then we don't have to worry
    50  			// about this because we're just requesting the whole set.
    51  			if i == len(schemaList)-1 {
    52  				continue
    53  			}
    54  
    55  			// If we're looking for the count, then ignore...
    56  			if address[i+1] == "#" {
    57  				continue
    58  			}
    59  
    60  			indexMap, ok := r.indexMaps[strings.Join(address[:i+1], ".")]
    61  			if !ok {
    62  				// Get the set so we can get the index map that tells us the
    63  				// mapping of the hash code to the list index
    64  				_, err := r.readSet(address[:i+1], v)
    65  				if err != nil {
    66  					return FieldReadResult{}, err
    67  				}
    68  				indexMap = r.indexMaps[strings.Join(address[:i+1], ".")]
    69  			}
    70  
    71  			index, ok := indexMap[address[i+1]]
    72  			if !ok {
    73  				return FieldReadResult{}, nil
    74  			}
    75  
    76  			address[i+1] = strconv.FormatInt(int64(index), 10)
    77  		}
    78  	}
    79  
    80  	k := strings.Join(address, ".")
    81  	schema := schemaList[len(schemaList)-1]
    82  	switch schema.Type {
    83  	case TypeBool, TypeFloat, TypeInt, TypeString:
    84  		return r.readPrimitive(k, schema)
    85  	case TypeList:
    86  		return readListField(&nestedConfigFieldReader{r}, address, schema)
    87  	case TypeMap:
    88  		return r.readMap(k, schema)
    89  	case TypeSet:
    90  		return r.readSet(address, schema)
    91  	case typeObject:
    92  		return readObjectField(
    93  			&nestedConfigFieldReader{r},
    94  			address, schema.Elem.(map[string]*Schema))
    95  	default:
    96  		panic(fmt.Sprintf("Unknown type: %s", schema.Type))
    97  	}
    98  }
    99  
   100  func (r *ConfigFieldReader) readMap(k string, schema *Schema) (FieldReadResult, error) {
   101  	// We want both the raw value and the interpolated. We use the interpolated
   102  	// to store actual values and we use the raw one to check for
   103  	// computed keys. Actual values are obtained in the switch, depending on
   104  	// the type of the raw value.
   105  	mraw, ok := r.Config.GetRaw(k)
   106  	if !ok {
   107  		// check if this is from an interpolated field by seeing if it exists
   108  		// in the config
   109  		_, ok := r.Config.Get(k)
   110  		if !ok {
   111  			// this really doesn't exist
   112  			return FieldReadResult{}, nil
   113  		}
   114  
   115  		// We couldn't fetch the value from a nested data structure, so treat the
   116  		// raw value as an interpolation string. The mraw value is only used
   117  		// for the type switch below.
   118  		mraw = "${INTERPOLATED}"
   119  	}
   120  
   121  	result := make(map[string]interface{})
   122  	computed := false
   123  	switch m := mraw.(type) {
   124  	case string:
   125  		// This is a map which has come out of an interpolated variable, so we
   126  		// can just get the value directly from config. Values cannot be computed
   127  		// currently.
   128  		v, _ := r.Config.Get(k)
   129  
   130  		// If this isn't a map[string]interface, it must be computed.
   131  		mapV, ok := v.(map[string]interface{})
   132  		if !ok {
   133  			return FieldReadResult{
   134  				Exists:   true,
   135  				Computed: true,
   136  			}, nil
   137  		}
   138  
   139  		// Otherwise we can proceed as usual.
   140  		for i, iv := range mapV {
   141  			result[i] = iv
   142  		}
   143  	case []interface{}:
   144  		for i, innerRaw := range m {
   145  			for ik := range innerRaw.(map[string]interface{}) {
   146  				key := fmt.Sprintf("%s.%d.%s", k, i, ik)
   147  				if r.Config.IsComputed(key) {
   148  					computed = true
   149  					break
   150  				}
   151  
   152  				v, _ := r.Config.Get(key)
   153  				result[ik] = v
   154  			}
   155  		}
   156  	case []map[string]interface{}:
   157  		for i, innerRaw := range m {
   158  			for ik := range innerRaw {
   159  				key := fmt.Sprintf("%s.%d.%s", k, i, ik)
   160  				if r.Config.IsComputed(key) {
   161  					computed = true
   162  					break
   163  				}
   164  
   165  				v, _ := r.Config.Get(key)
   166  				result[ik] = v
   167  			}
   168  		}
   169  	case map[string]interface{}:
   170  		for ik := range m {
   171  			key := fmt.Sprintf("%s.%s", k, ik)
   172  			if r.Config.IsComputed(key) {
   173  				computed = true
   174  				break
   175  			}
   176  
   177  			v, _ := r.Config.Get(key)
   178  			result[ik] = v
   179  		}
   180  	default:
   181  		panic(fmt.Sprintf("unknown type: %#v", mraw))
   182  	}
   183  
   184  	err := mapValuesToPrimitive(result, schema)
   185  	if err != nil {
   186  		return FieldReadResult{}, nil
   187  	}
   188  
   189  	var value interface{}
   190  	if !computed {
   191  		value = result
   192  	}
   193  
   194  	return FieldReadResult{
   195  		Value:    value,
   196  		Exists:   true,
   197  		Computed: computed,
   198  	}, nil
   199  }
   200  
   201  func (r *ConfigFieldReader) readPrimitive(
   202  	k string, schema *Schema) (FieldReadResult, error) {
   203  	raw, ok := r.Config.Get(k)
   204  	if !ok {
   205  		// Nothing in config, but we might still have a default from the schema
   206  		var err error
   207  		raw, err = schema.DefaultValue()
   208  		if err != nil {
   209  			return FieldReadResult{}, fmt.Errorf("%s, error loading default: %s", k, err)
   210  		}
   211  
   212  		if raw == nil {
   213  			return FieldReadResult{}, nil
   214  		}
   215  	}
   216  
   217  	var result string
   218  	if err := mapstructure.WeakDecode(raw, &result); err != nil {
   219  		return FieldReadResult{}, err
   220  	}
   221  
   222  	computed := r.Config.IsComputed(k)
   223  	returnVal, err := stringToPrimitive(result, computed, schema)
   224  	if err != nil {
   225  		return FieldReadResult{}, err
   226  	}
   227  
   228  	return FieldReadResult{
   229  		Value:    returnVal,
   230  		Exists:   true,
   231  		Computed: computed,
   232  	}, nil
   233  }
   234  
   235  func (r *ConfigFieldReader) readSet(
   236  	address []string, schema *Schema) (FieldReadResult, error) {
   237  	indexMap := make(map[string]int)
   238  	// Create the set that will be our result
   239  	set := schema.ZeroValue().(*Set)
   240  
   241  	raw, err := readListField(&nestedConfigFieldReader{r}, address, schema)
   242  	if err != nil {
   243  		return FieldReadResult{}, err
   244  	}
   245  	if !raw.Exists {
   246  		return FieldReadResult{Value: set}, nil
   247  	}
   248  
   249  	// If the list is computed, the set is necessarilly computed
   250  	if raw.Computed {
   251  		return FieldReadResult{
   252  			Value:    set,
   253  			Exists:   true,
   254  			Computed: raw.Computed,
   255  		}, nil
   256  	}
   257  
   258  	// Build up the set from the list elements
   259  	for i, v := range raw.Value.([]interface{}) {
   260  		// Check if any of the keys in this item are computed
   261  		computed := r.hasComputedSubKeys(
   262  			fmt.Sprintf("%s.%d", strings.Join(address, "."), i), schema)
   263  
   264  		code := set.add(v, computed)
   265  		indexMap[code] = i
   266  	}
   267  
   268  	r.indexMaps[strings.Join(address, ".")] = indexMap
   269  
   270  	return FieldReadResult{
   271  		Value:  set,
   272  		Exists: true,
   273  	}, nil
   274  }
   275  
   276  // hasComputedSubKeys walks through a schema and returns whether or not the
   277  // given key contains any subkeys that are computed.
   278  func (r *ConfigFieldReader) hasComputedSubKeys(key string, schema *Schema) bool {
   279  	prefix := key + "."
   280  
   281  	switch t := schema.Elem.(type) {
   282  	case *Resource:
   283  		for k, schema := range t.Schema {
   284  			if r.Config.IsComputed(prefix + k) {
   285  				return true
   286  			}
   287  
   288  			if r.hasComputedSubKeys(prefix+k, schema) {
   289  				return true
   290  			}
   291  		}
   292  	}
   293  
   294  	return false
   295  }
   296  
   297  // nestedConfigFieldReader is a funny little thing that just wraps a
   298  // ConfigFieldReader to call readField when ReadField is called so that
   299  // we don't recalculate the set rewrites in the address, which leads to
   300  // an infinite loop.
   301  type nestedConfigFieldReader struct {
   302  	Reader *ConfigFieldReader
   303  }
   304  
   305  func (r *nestedConfigFieldReader) ReadField(
   306  	address []string) (FieldReadResult, error) {
   307  	return r.Reader.readField(address, true)
   308  }