github.com/tomaszheflik/terraform@v0.7.3-0.20160827060421-32f990b41594/config/config.go (about) 1 // The config package is responsible for loading and validating the 2 // configuration. 3 package config 4 5 import ( 6 "fmt" 7 "regexp" 8 "strconv" 9 "strings" 10 11 "github.com/hashicorp/go-multierror" 12 "github.com/hashicorp/hil" 13 "github.com/hashicorp/hil/ast" 14 "github.com/hashicorp/terraform/helper/hilmapstructure" 15 "github.com/mitchellh/reflectwalk" 16 ) 17 18 // NameRegexp is the regular expression that all names (modules, providers, 19 // resources, etc.) must follow. 20 var NameRegexp = regexp.MustCompile(`\A[A-Za-z0-9\-\_]+\z`) 21 22 // Config is the configuration that comes from loading a collection 23 // of Terraform templates. 24 type Config struct { 25 // Dir is the path to the directory where this configuration was 26 // loaded from. If it is blank, this configuration wasn't loaded from 27 // any meaningful directory. 28 Dir string 29 30 Atlas *AtlasConfig 31 Modules []*Module 32 ProviderConfigs []*ProviderConfig 33 Resources []*Resource 34 Variables []*Variable 35 Outputs []*Output 36 37 // The fields below can be filled in by loaders for validation 38 // purposes. 39 unknownKeys []string 40 } 41 42 // AtlasConfig is the configuration for building in HashiCorp's Atlas. 43 type AtlasConfig struct { 44 Name string 45 Include []string 46 Exclude []string 47 } 48 49 // Module is a module used within a configuration. 50 // 51 // This does not represent a module itself, this represents a module 52 // call-site within an existing configuration. 53 type Module struct { 54 Name string 55 Source string 56 RawConfig *RawConfig 57 } 58 59 // ProviderConfig is the configuration for a resource provider. 60 // 61 // For example, Terraform needs to set the AWS access keys for the AWS 62 // resource provider. 63 type ProviderConfig struct { 64 Name string 65 Alias string 66 RawConfig *RawConfig 67 } 68 69 // A resource represents a single Terraform resource in the configuration. 70 // A Terraform resource is something that supports some or all of the 71 // usual "create, read, update, delete" operations, depending on 72 // the given Mode. 73 type Resource struct { 74 Mode ResourceMode // which operations the resource supports 75 Name string 76 Type string 77 RawCount *RawConfig 78 RawConfig *RawConfig 79 Provisioners []*Provisioner 80 Provider string 81 DependsOn []string 82 Lifecycle ResourceLifecycle 83 } 84 85 // Copy returns a copy of this Resource. Helpful for avoiding shared 86 // config pointers across multiple pieces of the graph that need to do 87 // interpolation. 88 func (r *Resource) Copy() *Resource { 89 n := &Resource{ 90 Mode: r.Mode, 91 Name: r.Name, 92 Type: r.Type, 93 RawCount: r.RawCount.Copy(), 94 RawConfig: r.RawConfig.Copy(), 95 Provisioners: make([]*Provisioner, 0, len(r.Provisioners)), 96 Provider: r.Provider, 97 DependsOn: make([]string, len(r.DependsOn)), 98 Lifecycle: *r.Lifecycle.Copy(), 99 } 100 for _, p := range r.Provisioners { 101 n.Provisioners = append(n.Provisioners, p.Copy()) 102 } 103 copy(n.DependsOn, r.DependsOn) 104 return n 105 } 106 107 // ResourceLifecycle is used to store the lifecycle tuning parameters 108 // to allow customized behavior 109 type ResourceLifecycle struct { 110 CreateBeforeDestroy bool `mapstructure:"create_before_destroy"` 111 PreventDestroy bool `mapstructure:"prevent_destroy"` 112 IgnoreChanges []string `mapstructure:"ignore_changes"` 113 } 114 115 // Copy returns a copy of this ResourceLifecycle 116 func (r *ResourceLifecycle) Copy() *ResourceLifecycle { 117 n := &ResourceLifecycle{ 118 CreateBeforeDestroy: r.CreateBeforeDestroy, 119 PreventDestroy: r.PreventDestroy, 120 IgnoreChanges: make([]string, len(r.IgnoreChanges)), 121 } 122 copy(n.IgnoreChanges, r.IgnoreChanges) 123 return n 124 } 125 126 // Provisioner is a configured provisioner step on a resource. 127 type Provisioner struct { 128 Type string 129 RawConfig *RawConfig 130 ConnInfo *RawConfig 131 } 132 133 // Copy returns a copy of this Provisioner 134 func (p *Provisioner) Copy() *Provisioner { 135 return &Provisioner{ 136 Type: p.Type, 137 RawConfig: p.RawConfig.Copy(), 138 ConnInfo: p.ConnInfo.Copy(), 139 } 140 } 141 142 // Variable is a variable defined within the configuration. 143 type Variable struct { 144 Name string 145 DeclaredType string `mapstructure:"type"` 146 Default interface{} 147 Description string 148 } 149 150 // Output is an output defined within the configuration. An output is 151 // resulting data that is highlighted by Terraform when finished. An 152 // output marked Sensitive will be output in a masked form following 153 // application, but will still be available in state. 154 type Output struct { 155 Name string 156 Sensitive bool 157 RawConfig *RawConfig 158 } 159 160 // VariableType is the type of value a variable is holding, and returned 161 // by the Type() function on variables. 162 type VariableType byte 163 164 const ( 165 VariableTypeUnknown VariableType = iota 166 VariableTypeString 167 VariableTypeList 168 VariableTypeMap 169 ) 170 171 func (v VariableType) Printable() string { 172 switch v { 173 case VariableTypeString: 174 return "string" 175 case VariableTypeMap: 176 return "map" 177 case VariableTypeList: 178 return "list" 179 default: 180 return "unknown" 181 } 182 } 183 184 // ProviderConfigName returns the name of the provider configuration in 185 // the given mapping that maps to the proper provider configuration 186 // for this resource. 187 func ProviderConfigName(t string, pcs []*ProviderConfig) string { 188 lk := "" 189 for _, v := range pcs { 190 k := v.Name 191 if strings.HasPrefix(t, k) && len(k) > len(lk) { 192 lk = k 193 } 194 } 195 196 return lk 197 } 198 199 // A unique identifier for this module. 200 func (r *Module) Id() string { 201 return fmt.Sprintf("%s", r.Name) 202 } 203 204 // Count returns the count of this resource. 205 func (r *Resource) Count() (int, error) { 206 v, err := strconv.ParseInt(r.RawCount.Value().(string), 0, 0) 207 if err != nil { 208 return 0, err 209 } 210 211 return int(v), nil 212 } 213 214 // A unique identifier for this resource. 215 func (r *Resource) Id() string { 216 switch r.Mode { 217 case ManagedResourceMode: 218 return fmt.Sprintf("%s.%s", r.Type, r.Name) 219 case DataResourceMode: 220 return fmt.Sprintf("data.%s.%s", r.Type, r.Name) 221 default: 222 panic(fmt.Errorf("unknown resource mode %s", r.Mode)) 223 } 224 } 225 226 // Validate does some basic semantic checking of the configuration. 227 func (c *Config) Validate() error { 228 if c == nil { 229 return nil 230 } 231 232 var errs []error 233 234 for _, k := range c.unknownKeys { 235 errs = append(errs, fmt.Errorf( 236 "Unknown root level key: %s", k)) 237 } 238 239 vars := c.InterpolatedVariables() 240 varMap := make(map[string]*Variable) 241 for _, v := range c.Variables { 242 if _, ok := varMap[v.Name]; ok { 243 errs = append(errs, fmt.Errorf( 244 "Variable '%s': duplicate found. Variable names must be unique.", 245 v.Name)) 246 } 247 248 varMap[v.Name] = v 249 } 250 251 for _, v := range c.Variables { 252 if v.Type() == VariableTypeUnknown { 253 errs = append(errs, fmt.Errorf( 254 "Variable '%s': must be a string or a map", 255 v.Name)) 256 continue 257 } 258 259 interp := false 260 fn := func(ast.Node) (interface{}, error) { 261 interp = true 262 return "", nil 263 } 264 265 w := &interpolationWalker{F: fn} 266 if v.Default != nil { 267 if err := reflectwalk.Walk(v.Default, w); err == nil { 268 if interp { 269 errs = append(errs, fmt.Errorf( 270 "Variable '%s': cannot contain interpolations", 271 v.Name)) 272 } 273 } 274 } 275 } 276 277 // Check for references to user variables that do not actually 278 // exist and record those errors. 279 for source, vs := range vars { 280 for _, v := range vs { 281 uv, ok := v.(*UserVariable) 282 if !ok { 283 continue 284 } 285 286 if _, ok := varMap[uv.Name]; !ok { 287 errs = append(errs, fmt.Errorf( 288 "%s: unknown variable referenced: '%s'. define it with 'variable' blocks", 289 source, 290 uv.Name)) 291 } 292 } 293 } 294 295 // Check that all count variables are valid. 296 for source, vs := range vars { 297 for _, rawV := range vs { 298 switch v := rawV.(type) { 299 case *CountVariable: 300 if v.Type == CountValueInvalid { 301 errs = append(errs, fmt.Errorf( 302 "%s: invalid count variable: %s", 303 source, 304 v.FullKey())) 305 } 306 case *PathVariable: 307 if v.Type == PathValueInvalid { 308 errs = append(errs, fmt.Errorf( 309 "%s: invalid path variable: %s", 310 source, 311 v.FullKey())) 312 } 313 } 314 } 315 } 316 317 // Check that providers aren't declared multiple times. 318 providerSet := make(map[string]struct{}) 319 for _, p := range c.ProviderConfigs { 320 name := p.FullName() 321 if _, ok := providerSet[name]; ok { 322 errs = append(errs, fmt.Errorf( 323 "provider.%s: declared multiple times, you can only declare a provider once", 324 name)) 325 continue 326 } 327 328 providerSet[name] = struct{}{} 329 } 330 331 // Check that all references to modules are valid 332 modules := make(map[string]*Module) 333 dupped := make(map[string]struct{}) 334 for _, m := range c.Modules { 335 // Check for duplicates 336 if _, ok := modules[m.Id()]; ok { 337 if _, ok := dupped[m.Id()]; !ok { 338 dupped[m.Id()] = struct{}{} 339 340 errs = append(errs, fmt.Errorf( 341 "%s: module repeated multiple times", 342 m.Id())) 343 } 344 345 // Already seen this module, just skip it 346 continue 347 } 348 349 modules[m.Id()] = m 350 351 // Check that the source has no interpolations 352 rc, err := NewRawConfig(map[string]interface{}{ 353 "root": m.Source, 354 }) 355 if err != nil { 356 errs = append(errs, fmt.Errorf( 357 "%s: module source error: %s", 358 m.Id(), err)) 359 } else if len(rc.Interpolations) > 0 { 360 errs = append(errs, fmt.Errorf( 361 "%s: module source cannot contain interpolations", 362 m.Id())) 363 } 364 365 // Check that the name matches our regexp 366 if !NameRegexp.Match([]byte(m.Name)) { 367 errs = append(errs, fmt.Errorf( 368 "%s: module name can only contain letters, numbers, "+ 369 "dashes, and underscores", 370 m.Id())) 371 } 372 373 // Check that the configuration can all be strings, lists or maps 374 raw := make(map[string]interface{}) 375 for k, v := range m.RawConfig.Raw { 376 var strVal string 377 if err := hilmapstructure.WeakDecode(v, &strVal); err == nil { 378 raw[k] = strVal 379 continue 380 } 381 382 var mapVal map[string]interface{} 383 if err := hilmapstructure.WeakDecode(v, &mapVal); err == nil { 384 raw[k] = mapVal 385 continue 386 } 387 388 var sliceVal []interface{} 389 if err := hilmapstructure.WeakDecode(v, &sliceVal); err == nil { 390 raw[k] = sliceVal 391 continue 392 } 393 394 errs = append(errs, fmt.Errorf( 395 "%s: variable %s must be a string, list or map value", 396 m.Id(), k)) 397 } 398 399 // Check for invalid count variables 400 for _, v := range m.RawConfig.Variables { 401 switch v.(type) { 402 case *CountVariable: 403 errs = append(errs, fmt.Errorf( 404 "%s: count variables are only valid within resources", m.Name)) 405 case *SelfVariable: 406 errs = append(errs, fmt.Errorf( 407 "%s: self variables are only valid within resources", m.Name)) 408 } 409 } 410 411 // Update the raw configuration to only contain the string values 412 m.RawConfig, err = NewRawConfig(raw) 413 if err != nil { 414 errs = append(errs, fmt.Errorf( 415 "%s: can't initialize configuration: %s", 416 m.Id(), err)) 417 } 418 } 419 dupped = nil 420 421 // Check that all variables for modules reference modules that 422 // exist. 423 for source, vs := range vars { 424 for _, v := range vs { 425 mv, ok := v.(*ModuleVariable) 426 if !ok { 427 continue 428 } 429 430 if _, ok := modules[mv.Name]; !ok { 431 errs = append(errs, fmt.Errorf( 432 "%s: unknown module referenced: %s", 433 source, 434 mv.Name)) 435 } 436 } 437 } 438 439 // Check that all references to resources are valid 440 resources := make(map[string]*Resource) 441 dupped = make(map[string]struct{}) 442 for _, r := range c.Resources { 443 if _, ok := resources[r.Id()]; ok { 444 if _, ok := dupped[r.Id()]; !ok { 445 dupped[r.Id()] = struct{}{} 446 447 errs = append(errs, fmt.Errorf( 448 "%s: resource repeated multiple times", 449 r.Id())) 450 } 451 } 452 453 resources[r.Id()] = r 454 } 455 dupped = nil 456 457 // Validate resources 458 for n, r := range resources { 459 // Verify count variables 460 for _, v := range r.RawCount.Variables { 461 switch v.(type) { 462 case *CountVariable: 463 errs = append(errs, fmt.Errorf( 464 "%s: resource count can't reference count variable: %s", 465 n, 466 v.FullKey())) 467 case *ModuleVariable: 468 errs = append(errs, fmt.Errorf( 469 "%s: resource count can't reference module variable: %s", 470 n, 471 v.FullKey())) 472 case *ResourceVariable: 473 errs = append(errs, fmt.Errorf( 474 "%s: resource count can't reference resource variable: %s", 475 n, 476 v.FullKey())) 477 case *SimpleVariable: 478 errs = append(errs, fmt.Errorf( 479 "%s: resource count can't reference variable: %s", 480 n, 481 v.FullKey())) 482 case *UserVariable: 483 // Good 484 default: 485 panic(fmt.Sprintf("Unknown type in count var in %s: %T", n, v)) 486 } 487 } 488 489 // Interpolate with a fixed number to verify that its a number. 490 r.RawCount.interpolate(func(root ast.Node) (interface{}, error) { 491 // Execute the node but transform the AST so that it returns 492 // a fixed value of "5" for all interpolations. 493 result, err := hil.Eval( 494 hil.FixedValueTransform( 495 root, &ast.LiteralNode{Value: "5", Typex: ast.TypeString}), 496 nil) 497 if err != nil { 498 return "", err 499 } 500 501 return result.Value, nil 502 }) 503 _, err := strconv.ParseInt(r.RawCount.Value().(string), 0, 0) 504 if err != nil { 505 errs = append(errs, fmt.Errorf( 506 "%s: resource count must be an integer", 507 n)) 508 } 509 r.RawCount.init() 510 511 // Verify depends on points to resources that all exist 512 for _, d := range r.DependsOn { 513 // Check if we contain interpolations 514 rc, err := NewRawConfig(map[string]interface{}{ 515 "value": d, 516 }) 517 if err == nil && len(rc.Variables) > 0 { 518 errs = append(errs, fmt.Errorf( 519 "%s: depends on value cannot contain interpolations: %s", 520 n, d)) 521 continue 522 } 523 524 if _, ok := resources[d]; !ok { 525 errs = append(errs, fmt.Errorf( 526 "%s: resource depends on non-existent resource '%s'", 527 n, d)) 528 } 529 } 530 531 // Verify provider points to a provider that is configured 532 if r.Provider != "" { 533 if _, ok := providerSet[r.Provider]; !ok { 534 errs = append(errs, fmt.Errorf( 535 "%s: resource depends on non-configured provider '%s'", 536 n, r.Provider)) 537 } 538 } 539 540 // Verify provisioners don't contain any splats 541 for _, p := range r.Provisioners { 542 // This validation checks that there are now splat variables 543 // referencing ourself. This currently is not allowed. 544 545 for _, v := range p.ConnInfo.Variables { 546 rv, ok := v.(*ResourceVariable) 547 if !ok { 548 continue 549 } 550 551 if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name { 552 errs = append(errs, fmt.Errorf( 553 "%s: connection info cannot contain splat variable "+ 554 "referencing itself", n)) 555 break 556 } 557 } 558 559 for _, v := range p.RawConfig.Variables { 560 rv, ok := v.(*ResourceVariable) 561 if !ok { 562 continue 563 } 564 565 if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name { 566 errs = append(errs, fmt.Errorf( 567 "%s: connection info cannot contain splat variable "+ 568 "referencing itself", n)) 569 break 570 } 571 } 572 } 573 } 574 575 for source, vs := range vars { 576 for _, v := range vs { 577 rv, ok := v.(*ResourceVariable) 578 if !ok { 579 continue 580 } 581 582 id := rv.ResourceId() 583 if _, ok := resources[id]; !ok { 584 errs = append(errs, fmt.Errorf( 585 "%s: unknown resource '%s' referenced in variable %s", 586 source, 587 id, 588 rv.FullKey())) 589 continue 590 } 591 } 592 } 593 594 // Check that all outputs are valid 595 { 596 found := make(map[string]struct{}) 597 for _, o := range c.Outputs { 598 // Verify the output is new 599 if _, ok := found[o.Name]; ok { 600 errs = append(errs, fmt.Errorf( 601 "%s: duplicate output. output names must be unique.", 602 o.Name)) 603 continue 604 } 605 found[o.Name] = struct{}{} 606 607 var invalidKeys []string 608 valueKeyFound := false 609 for k := range o.RawConfig.Raw { 610 if k == "value" { 611 valueKeyFound = true 612 continue 613 } 614 if k == "sensitive" { 615 if sensitive, ok := o.RawConfig.config[k].(bool); ok { 616 if sensitive { 617 o.Sensitive = true 618 } 619 continue 620 } 621 622 errs = append(errs, fmt.Errorf( 623 "%s: value for 'sensitive' must be boolean", 624 o.Name)) 625 continue 626 } 627 invalidKeys = append(invalidKeys, k) 628 } 629 if len(invalidKeys) > 0 { 630 errs = append(errs, fmt.Errorf( 631 "%s: output has invalid keys: %s", 632 o.Name, strings.Join(invalidKeys, ", "))) 633 } 634 if !valueKeyFound { 635 errs = append(errs, fmt.Errorf( 636 "%s: output is missing required 'value' key", o.Name)) 637 } 638 639 for _, v := range o.RawConfig.Variables { 640 if _, ok := v.(*CountVariable); ok { 641 errs = append(errs, fmt.Errorf( 642 "%s: count variables are only valid within resources", o.Name)) 643 } 644 } 645 } 646 } 647 648 // Check that all variables are in the proper context 649 for source, rc := range c.rawConfigs() { 650 walker := &interpolationWalker{ 651 ContextF: c.validateVarContextFn(source, &errs), 652 } 653 if err := reflectwalk.Walk(rc.Raw, walker); err != nil { 654 errs = append(errs, fmt.Errorf( 655 "%s: error reading config: %s", source, err)) 656 } 657 } 658 659 // Validate the self variable 660 for source, rc := range c.rawConfigs() { 661 // Ignore provisioners. This is a pretty brittle way to do this, 662 // but better than also repeating all the resources. 663 if strings.Contains(source, "provision") { 664 continue 665 } 666 667 for _, v := range rc.Variables { 668 if _, ok := v.(*SelfVariable); ok { 669 errs = append(errs, fmt.Errorf( 670 "%s: cannot contain self-reference %s", source, v.FullKey())) 671 } 672 } 673 } 674 675 if len(errs) > 0 { 676 return &multierror.Error{Errors: errs} 677 } 678 679 return nil 680 } 681 682 // InterpolatedVariables is a helper that returns a mapping of all the interpolated 683 // variables within the configuration. This is used to verify references 684 // are valid in the Validate step. 685 func (c *Config) InterpolatedVariables() map[string][]InterpolatedVariable { 686 result := make(map[string][]InterpolatedVariable) 687 for source, rc := range c.rawConfigs() { 688 for _, v := range rc.Variables { 689 result[source] = append(result[source], v) 690 } 691 } 692 return result 693 } 694 695 // rawConfigs returns all of the RawConfigs that are available keyed by 696 // a human-friendly source. 697 func (c *Config) rawConfigs() map[string]*RawConfig { 698 result := make(map[string]*RawConfig) 699 for _, m := range c.Modules { 700 source := fmt.Sprintf("module '%s'", m.Name) 701 result[source] = m.RawConfig 702 } 703 704 for _, pc := range c.ProviderConfigs { 705 source := fmt.Sprintf("provider config '%s'", pc.Name) 706 result[source] = pc.RawConfig 707 } 708 709 for _, rc := range c.Resources { 710 source := fmt.Sprintf("resource '%s'", rc.Id()) 711 result[source+" count"] = rc.RawCount 712 result[source+" config"] = rc.RawConfig 713 714 for i, p := range rc.Provisioners { 715 subsource := fmt.Sprintf( 716 "%s provisioner %s (#%d)", 717 source, p.Type, i+1) 718 result[subsource] = p.RawConfig 719 } 720 } 721 722 for _, o := range c.Outputs { 723 source := fmt.Sprintf("output '%s'", o.Name) 724 result[source] = o.RawConfig 725 } 726 727 return result 728 } 729 730 func (c *Config) validateVarContextFn( 731 source string, errs *[]error) interpolationWalkerContextFunc { 732 return func(loc reflectwalk.Location, node ast.Node) { 733 // If we're in a slice element, then its fine, since you can do 734 // anything in there. 735 if loc == reflectwalk.SliceElem { 736 return 737 } 738 739 // Otherwise, let's check if there is a splat resource variable 740 // at the top level in here. We do this by doing a transform that 741 // replaces everything with a noop node unless its a variable 742 // access or concat. This should turn the AST into a flat tree 743 // of Concat(Noop, ...). If there are any variables left that are 744 // multi-access, then its still broken. 745 node = node.Accept(func(n ast.Node) ast.Node { 746 // If it is a concat or variable access, we allow it. 747 switch n.(type) { 748 case *ast.Output: 749 return n 750 case *ast.VariableAccess: 751 return n 752 } 753 754 // Otherwise, noop 755 return &noopNode{} 756 }) 757 758 vars, err := DetectVariables(node) 759 if err != nil { 760 // Ignore it since this will be caught during parse. This 761 // actually probably should never happen by the time this 762 // is called, but its okay. 763 return 764 } 765 766 for _, v := range vars { 767 rv, ok := v.(*ResourceVariable) 768 if !ok { 769 return 770 } 771 772 if rv.Multi && rv.Index == -1 { 773 *errs = append(*errs, fmt.Errorf( 774 "%s: use of the splat ('*') operator must be wrapped in a list declaration", 775 source)) 776 } 777 } 778 } 779 } 780 781 func (m *Module) mergerName() string { 782 return m.Id() 783 } 784 785 func (m *Module) mergerMerge(other merger) merger { 786 m2 := other.(*Module) 787 788 result := *m 789 result.Name = m2.Name 790 result.RawConfig = result.RawConfig.merge(m2.RawConfig) 791 792 if m2.Source != "" { 793 result.Source = m2.Source 794 } 795 796 return &result 797 } 798 799 func (o *Output) mergerName() string { 800 return o.Name 801 } 802 803 func (o *Output) mergerMerge(m merger) merger { 804 o2 := m.(*Output) 805 806 result := *o 807 result.Name = o2.Name 808 result.RawConfig = result.RawConfig.merge(o2.RawConfig) 809 810 return &result 811 } 812 813 func (c *ProviderConfig) GoString() string { 814 return fmt.Sprintf("*%#v", *c) 815 } 816 817 func (c *ProviderConfig) FullName() string { 818 if c.Alias == "" { 819 return c.Name 820 } 821 822 return fmt.Sprintf("%s.%s", c.Name, c.Alias) 823 } 824 825 func (c *ProviderConfig) mergerName() string { 826 return c.Name 827 } 828 829 func (c *ProviderConfig) mergerMerge(m merger) merger { 830 c2 := m.(*ProviderConfig) 831 832 result := *c 833 result.Name = c2.Name 834 result.RawConfig = result.RawConfig.merge(c2.RawConfig) 835 836 return &result 837 } 838 839 func (r *Resource) mergerName() string { 840 return r.Id() 841 } 842 843 func (r *Resource) mergerMerge(m merger) merger { 844 r2 := m.(*Resource) 845 846 result := *r 847 result.Mode = r2.Mode 848 result.Name = r2.Name 849 result.Type = r2.Type 850 result.RawConfig = result.RawConfig.merge(r2.RawConfig) 851 852 if r2.RawCount.Value() != "1" { 853 result.RawCount = r2.RawCount 854 } 855 856 if len(r2.Provisioners) > 0 { 857 result.Provisioners = r2.Provisioners 858 } 859 860 return &result 861 } 862 863 // Merge merges two variables to create a new third variable. 864 func (v *Variable) Merge(v2 *Variable) *Variable { 865 // Shallow copy the variable 866 result := *v 867 868 // The names should be the same, but the second name always wins. 869 result.Name = v2.Name 870 871 if v2.Default != nil { 872 result.Default = v2.Default 873 } 874 if v2.Description != "" { 875 result.Description = v2.Description 876 } 877 878 return &result 879 } 880 881 var typeStringMap = map[string]VariableType{ 882 "string": VariableTypeString, 883 "map": VariableTypeMap, 884 "list": VariableTypeList, 885 } 886 887 // Type returns the type of variable this is. 888 func (v *Variable) Type() VariableType { 889 if v.DeclaredType != "" { 890 declaredType, ok := typeStringMap[v.DeclaredType] 891 if !ok { 892 return VariableTypeUnknown 893 } 894 895 return declaredType 896 } 897 898 return v.inferTypeFromDefault() 899 } 900 901 // ValidateTypeAndDefault ensures that default variable value is compatible 902 // with the declared type (if one exists), and that the type is one which is 903 // known to Terraform 904 func (v *Variable) ValidateTypeAndDefault() error { 905 // If an explicit type is declared, ensure it is valid 906 if v.DeclaredType != "" { 907 if _, ok := typeStringMap[v.DeclaredType]; !ok { 908 return fmt.Errorf("Variable '%s' must be of type string or map - '%s' is not a valid type", v.Name, v.DeclaredType) 909 } 910 } 911 912 if v.DeclaredType == "" || v.Default == nil { 913 return nil 914 } 915 916 if v.inferTypeFromDefault() != v.Type() { 917 return fmt.Errorf("'%s' has a default value which is not of type '%s' (got '%s')", 918 v.Name, v.DeclaredType, v.inferTypeFromDefault().Printable()) 919 } 920 921 return nil 922 } 923 924 func (v *Variable) mergerName() string { 925 return v.Name 926 } 927 928 func (v *Variable) mergerMerge(m merger) merger { 929 return v.Merge(m.(*Variable)) 930 } 931 932 // Required tests whether a variable is required or not. 933 func (v *Variable) Required() bool { 934 return v.Default == nil 935 } 936 937 // inferTypeFromDefault contains the logic for the old method of inferring 938 // variable types - we can also use this for validating that the declared 939 // type matches the type of the default value 940 func (v *Variable) inferTypeFromDefault() VariableType { 941 if v.Default == nil { 942 return VariableTypeString 943 } 944 945 var s string 946 if err := hilmapstructure.WeakDecode(v.Default, &s); err == nil { 947 v.Default = s 948 return VariableTypeString 949 } 950 951 var m map[string]interface{} 952 if err := hilmapstructure.WeakDecode(v.Default, &m); err == nil { 953 v.Default = m 954 return VariableTypeMap 955 } 956 957 var l []interface{} 958 if err := hilmapstructure.WeakDecode(v.Default, &l); err == nil { 959 v.Default = l 960 return VariableTypeList 961 } 962 963 return VariableTypeUnknown 964 } 965 966 func (m ResourceMode) Taintable() bool { 967 switch m { 968 case ManagedResourceMode: 969 return true 970 case DataResourceMode: 971 return false 972 default: 973 panic(fmt.Errorf("unsupported ResourceMode value %s", m)) 974 } 975 }