10 "github.com/hashicorp/terraform/config"
11 "github.com/mitchellh/copystructure"
12 "github.com/mitchellh/reflectwalk"
15 // ResourceProvisionerConfig is used to pair a provisioner
16 // with its provided configuration. This allows us to use singleton
17 // instances of each ResourceProvisioner and to keep the relevant
18 // configuration instead of instantiating a new Provisioner for each
20 type ResourceProvisionerConfig struct {
22 Provisioner ResourceProvisioner
23 Config *ResourceConfig
24 RawConfig *config.RawConfig
25 ConnInfo *config.RawConfig
28 // Resource encapsulates a resource, its configuration, its provider,
29 // its current state, and potentially a desired diff from the state it
31 type Resource struct {
32 // These are all used by the new EvalNode stuff.
37 // These aren't really used anymore anywhere, but we keep them around
38 // since we haven't done a proper cleanup yet.
41 Config *ResourceConfig
44 Provider ResourceProvider
46 Provisioners []*ResourceProvisionerConfig
50 // ResourceKind specifies what kind of instance we're working with, whether
51 // its a primary instance, a tainted instance, or an orphan.
52 type ResourceFlag byte
54 // InstanceInfo is used to hold information about the instance and/or
55 // resource being modified.
56 type InstanceInfo struct {
57 // Id is a unique name to represent this instance. This is not related
58 // to InstanceState.ID in any way.
61 // ModulePath is the complete path of the module containing this
65 // Type is the resource type of this instance
68 // uniqueExtra is an internal field that can be populated to supply
69 // extra metadata that is used to identify a unique instance in
70 // the graph walk. This will be appended to HumanID when uniqueId
75 // HumanId is a unique Id that is human-friendly and useful for UI elements.
76 func (i *InstanceInfo) HumanId() string {
81 if len(i.ModulePath) <= 1 {
87 strings.Join(i.ModulePath[1:], "."),
91 // ResourceAddress returns the address of the resource that the receiver is describing.
92 func (i *InstanceInfo) ResourceAddress() *ResourceAddress {
93 // GROSS: for tainted and deposed instances, their status gets appended
94 // to i.Id to create a unique id for the graph node. Historically these
95 // ids were displayed to the user, so it's designed to be human-readable:
96 // "aws_instance.bar.0 (deposed #0)"
98 // So here we detect such suffixes and try to interpret them back to
99 // their original meaning so we can then produce a ResourceAddress
100 // with a suitable InstanceType.
102 instanceType := TypeInvalid
103 if idx := strings.Index(id, " ("); idx != -1 {
108 case strings.Contains(remain, "tainted"):
109 instanceType = TypeTainted
110 case strings.Contains(remain, "deposed"):
111 instanceType = TypeDeposed
115 addr, err := parseResourceAddressInternal(id)
117 // should never happen, since that would indicate a bug in the
118 // code that constructed this InstanceInfo.
119 panic(fmt.Errorf("InstanceInfo has invalid Id %s", id))
121 if len(i.ModulePath) > 1 {
122 addr.Path = i.ModulePath[1:] // trim off "root" prefix, which is implied
124 if instanceType != TypeInvalid {
125 addr.InstanceTypeSet = true
126 addr.InstanceType = instanceType
131 func (i *InstanceInfo) uniqueId() string {
132 prefix := i.HumanId()
133 if v := i.uniqueExtra; v != "" {
140 // ResourceConfig holds the configuration given for a resource. This is
141 // done instead of a raw `map[string]interface{}` type so that rich
142 // methods can be added to it to make dealing with it easier.
143 type ResourceConfig struct {
144 ComputedKeys []string
145 Raw map[string]interface{}
146 Config map[string]interface{}
148 raw *config.RawConfig
151 // NewResourceConfig creates a new ResourceConfig from a config.RawConfig.
152 func NewResourceConfig(c *config.RawConfig) *ResourceConfig {
153 result := &ResourceConfig{raw: c}
154 result.interpolateForce()
158 // DeepCopy performs a deep copy of the configuration. This makes it safe
159 // to modify any of the structures that are part of the resource config without
160 // affecting the original configuration.
161 func (c *ResourceConfig) DeepCopy() *ResourceConfig {
162 // DeepCopying a nil should return a nil to avoid panics
167 // Copy, this will copy all the exported attributes
168 copy, err := copystructure.Config{Lock: true}.Copy(c)
174 result := copy.(*ResourceConfig)
176 // For the raw configuration, we can just use its own copy method
177 result.raw = c.raw.Copy()
182 // Equal checks the equality of two resource configs.
183 func (c *ResourceConfig) Equal(c2 *ResourceConfig) bool {
184 // If either are nil, then they're only equal if they're both nil
185 if c == nil || c2 == nil {
189 // Sort the computed keys so they're deterministic
190 sort.Strings(c.ComputedKeys)
191 sort.Strings(c2.ComputedKeys)
193 // Two resource configs if their exported properties are equal.
194 // We don't compare "raw" because it is never used again after
195 // initialization and for all intents and purposes they are equal
196 // if the exported properties are equal.
197 check := [][2]interface{}{
198 {c.ComputedKeys, c2.ComputedKeys},
200 {c.Config, c2.Config},
202 for _, pair := range check {
203 if !reflect.DeepEqual(pair[0], pair[1]) {
211 // CheckSet checks that the given list of configuration keys is
212 // properly set. If not, errors are returned for each unset key.
214 // This is useful to be called in the Validate method of a ResourceProvider.
215 func (c *ResourceConfig) CheckSet(keys []string) []error {
218 for _, k := range keys {
220 errs = append(errs, fmt.Errorf("%s must be set", k))
227 // Get looks up a configuration value by key and returns the value.
229 // The second return value is true if the get was successful. Get will
230 // return the raw value if the key is computed, so you should pair this
232 func (c *ResourceConfig) Get(k string) (interface{}, bool) {
233 // We aim to get a value from the configuration. If it is computed,
234 // then we return the pure raw value.
240 return c.get(k, source)
243 // GetRaw looks up a configuration value by key and returns the value,
244 // from the raw, uninterpolated config.
246 // The second return value is true if the get was successful. Get will
247 // not succeed if the value is being computed.
248 func (c *ResourceConfig) GetRaw(k string) (interface{}, bool) {
249 return c.get(k, c.Raw)
252 // IsComputed returns whether the given key is computed or not.
253 func (c *ResourceConfig) IsComputed(k string) bool {
254 // The next thing we do is check the config if we get a computed
256 v, ok := c.get(k, c.Config)
261 // If value is nil, then it isn't computed
266 // Test if the value contains an unknown value
267 var w unknownCheckWalker
268 if err := reflectwalk.Walk(v, &w); err != nil {
275 // IsSet checks if the key in the configuration is set. A key is set if
276 // it has a value or the value is being computed (is unknown currently).
278 // This function should be used rather than checking the keys of the
279 // raw configuration itself, since a key may be omitted from the raw
280 // configuration if it is being computed.
281 func (c *ResourceConfig) IsSet(k string) bool {
290 if _, ok := c.Get(k); ok {
297 func (c *ResourceConfig) get(
298 k string, raw map[string]interface{}) (interface{}, bool) {
299 parts := strings.Split(k, ".")
300 if len(parts) == 1 && parts[0] == "" {
304 var current interface{} = raw
305 var previous interface{} = nil
306 for i, part := range parts {
311 cv := reflect.ValueOf(current)
315 v := cv.MapIndex(reflect.ValueOf(part))
317 if i > 0 && i != (len(parts)-1) {
318 tryKey := strings.Join(parts[i:], ".")
319 v := cv.MapIndex(reflect.ValueOf(tryKey))
324 return v.Interface(), true
330 current = v.Interface()
335 // If any value in a list is computed, this whole thing
336 // is computed and we can't read any part of it.
337 for i := 0; i < cv.Len(); i++ {
338 if v := cv.Index(i).Interface(); v == unknownValue() {
345 i, err := strconv.ParseInt(part, 0, 0)
349 if int(i) < 0 || int(i) >= cv.Len() {
352 current = cv.Index(int(i)).Interface()
355 // This happens when map keys contain "." and have a common
356 // prefix so were split as path components above.
357 actualKey := strings.Join(parts[i-1:], ".")
358 if prevMap, ok := previous.(map[string]interface{}); ok {
359 v, ok := prevMap[actualKey]
365 panic(fmt.Sprintf("Unknown kind: %s", cv.Kind()))
372 // interpolateForce is a temporary thing. We want to get rid of interpolate
373 // above and likewise this, but it can only be done after the f-ast-graph
374 // refactor is complete.
375 func (c *ResourceConfig) interpolateForce() {
378 c.raw, err = config.NewRawConfig(make(map[string]interface{}))
384 c.ComputedKeys = c.raw.UnknownKeys()
385 c.Raw = c.raw.RawMap()
386 c.Config = c.raw.Config()
389 // unknownCheckWalker
390 type unknownCheckWalker struct {
394 func (w *unknownCheckWalker) Primitive(v reflect.Value) error {
395 if v.Interface() == unknownValue() {