github.com/adrian-bl/terraform@v0.7.0-rc2.0.20160705220747-de0a34fc3517/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 varMap[v.Name] = v 243 } 244 245 for _, v := range c.Variables { 246 if v.Type() == VariableTypeUnknown { 247 errs = append(errs, fmt.Errorf( 248 "Variable '%s': must be a string or a map", 249 v.Name)) 250 continue 251 } 252 253 interp := false 254 fn := func(ast.Node) (interface{}, error) { 255 interp = true 256 return "", nil 257 } 258 259 w := &interpolationWalker{F: fn} 260 if v.Default != nil { 261 if err := reflectwalk.Walk(v.Default, w); err == nil { 262 if interp { 263 errs = append(errs, fmt.Errorf( 264 "Variable '%s': cannot contain interpolations", 265 v.Name)) 266 } 267 } 268 } 269 } 270 271 // Check for references to user variables that do not actually 272 // exist and record those errors. 273 for source, vs := range vars { 274 for _, v := range vs { 275 uv, ok := v.(*UserVariable) 276 if !ok { 277 continue 278 } 279 280 if _, ok := varMap[uv.Name]; !ok { 281 errs = append(errs, fmt.Errorf( 282 "%s: unknown variable referenced: '%s'. define it with 'variable' blocks", 283 source, 284 uv.Name)) 285 } 286 } 287 } 288 289 // Check that all count variables are valid. 290 for source, vs := range vars { 291 for _, rawV := range vs { 292 switch v := rawV.(type) { 293 case *CountVariable: 294 if v.Type == CountValueInvalid { 295 errs = append(errs, fmt.Errorf( 296 "%s: invalid count variable: %s", 297 source, 298 v.FullKey())) 299 } 300 case *PathVariable: 301 if v.Type == PathValueInvalid { 302 errs = append(errs, fmt.Errorf( 303 "%s: invalid path variable: %s", 304 source, 305 v.FullKey())) 306 } 307 } 308 } 309 } 310 311 // Check that providers aren't declared multiple times. 312 providerSet := make(map[string]struct{}) 313 for _, p := range c.ProviderConfigs { 314 name := p.FullName() 315 if _, ok := providerSet[name]; ok { 316 errs = append(errs, fmt.Errorf( 317 "provider.%s: declared multiple times, you can only declare a provider once", 318 name)) 319 continue 320 } 321 322 providerSet[name] = struct{}{} 323 } 324 325 // Check that all references to modules are valid 326 modules := make(map[string]*Module) 327 dupped := make(map[string]struct{}) 328 for _, m := range c.Modules { 329 // Check for duplicates 330 if _, ok := modules[m.Id()]; ok { 331 if _, ok := dupped[m.Id()]; !ok { 332 dupped[m.Id()] = struct{}{} 333 334 errs = append(errs, fmt.Errorf( 335 "%s: module repeated multiple times", 336 m.Id())) 337 } 338 339 // Already seen this module, just skip it 340 continue 341 } 342 343 modules[m.Id()] = m 344 345 // Check that the source has no interpolations 346 rc, err := NewRawConfig(map[string]interface{}{ 347 "root": m.Source, 348 }) 349 if err != nil { 350 errs = append(errs, fmt.Errorf( 351 "%s: module source error: %s", 352 m.Id(), err)) 353 } else if len(rc.Interpolations) > 0 { 354 errs = append(errs, fmt.Errorf( 355 "%s: module source cannot contain interpolations", 356 m.Id())) 357 } 358 359 // Check that the name matches our regexp 360 if !NameRegexp.Match([]byte(m.Name)) { 361 errs = append(errs, fmt.Errorf( 362 "%s: module name can only contain letters, numbers, "+ 363 "dashes, and underscores", 364 m.Id())) 365 } 366 367 // Check that the configuration can all be strings, lists or maps 368 raw := make(map[string]interface{}) 369 for k, v := range m.RawConfig.Raw { 370 var strVal string 371 if err := hilmapstructure.WeakDecode(v, &strVal); err == nil { 372 raw[k] = strVal 373 continue 374 } 375 376 var mapVal map[string]interface{} 377 if err := hilmapstructure.WeakDecode(v, &mapVal); err == nil { 378 raw[k] = mapVal 379 continue 380 } 381 382 var sliceVal []interface{} 383 if err := hilmapstructure.WeakDecode(v, &sliceVal); err == nil { 384 raw[k] = sliceVal 385 continue 386 } 387 388 errs = append(errs, fmt.Errorf( 389 "%s: variable %s must be a string, list or map value", 390 m.Id(), k)) 391 } 392 393 // Check for invalid count variables 394 for _, v := range m.RawConfig.Variables { 395 switch v.(type) { 396 case *CountVariable: 397 errs = append(errs, fmt.Errorf( 398 "%s: count variables are only valid within resources", m.Name)) 399 case *SelfVariable: 400 errs = append(errs, fmt.Errorf( 401 "%s: self variables are only valid within resources", m.Name)) 402 } 403 } 404 405 // Update the raw configuration to only contain the string values 406 m.RawConfig, err = NewRawConfig(raw) 407 if err != nil { 408 errs = append(errs, fmt.Errorf( 409 "%s: can't initialize configuration: %s", 410 m.Id(), err)) 411 } 412 } 413 dupped = nil 414 415 // Check that all variables for modules reference modules that 416 // exist. 417 for source, vs := range vars { 418 for _, v := range vs { 419 mv, ok := v.(*ModuleVariable) 420 if !ok { 421 continue 422 } 423 424 if _, ok := modules[mv.Name]; !ok { 425 errs = append(errs, fmt.Errorf( 426 "%s: unknown module referenced: %s", 427 source, 428 mv.Name)) 429 } 430 } 431 } 432 433 // Check that all references to resources are valid 434 resources := make(map[string]*Resource) 435 dupped = make(map[string]struct{}) 436 for _, r := range c.Resources { 437 if _, ok := resources[r.Id()]; ok { 438 if _, ok := dupped[r.Id()]; !ok { 439 dupped[r.Id()] = struct{}{} 440 441 errs = append(errs, fmt.Errorf( 442 "%s: resource repeated multiple times", 443 r.Id())) 444 } 445 } 446 447 resources[r.Id()] = r 448 } 449 dupped = nil 450 451 // Validate resources 452 for n, r := range resources { 453 // Verify count variables 454 for _, v := range r.RawCount.Variables { 455 switch v.(type) { 456 case *CountVariable: 457 errs = append(errs, fmt.Errorf( 458 "%s: resource count can't reference count variable: %s", 459 n, 460 v.FullKey())) 461 case *ModuleVariable: 462 errs = append(errs, fmt.Errorf( 463 "%s: resource count can't reference module variable: %s", 464 n, 465 v.FullKey())) 466 case *ResourceVariable: 467 errs = append(errs, fmt.Errorf( 468 "%s: resource count can't reference resource variable: %s", 469 n, 470 v.FullKey())) 471 case *UserVariable: 472 // Good 473 default: 474 panic("Unknown type in count var: " + n) 475 } 476 } 477 478 // Interpolate with a fixed number to verify that its a number. 479 r.RawCount.interpolate(func(root ast.Node) (interface{}, error) { 480 // Execute the node but transform the AST so that it returns 481 // a fixed value of "5" for all interpolations. 482 result, err := hil.Eval( 483 hil.FixedValueTransform( 484 root, &ast.LiteralNode{Value: "5", Typex: ast.TypeString}), 485 nil) 486 if err != nil { 487 return "", err 488 } 489 490 return result.Value, nil 491 }) 492 _, err := strconv.ParseInt(r.RawCount.Value().(string), 0, 0) 493 if err != nil { 494 errs = append(errs, fmt.Errorf( 495 "%s: resource count must be an integer", 496 n)) 497 } 498 r.RawCount.init() 499 500 // Verify depends on points to resources that all exist 501 for _, d := range r.DependsOn { 502 // Check if we contain interpolations 503 rc, err := NewRawConfig(map[string]interface{}{ 504 "value": d, 505 }) 506 if err == nil && len(rc.Variables) > 0 { 507 errs = append(errs, fmt.Errorf( 508 "%s: depends on value cannot contain interpolations: %s", 509 n, d)) 510 continue 511 } 512 513 if _, ok := resources[d]; !ok { 514 errs = append(errs, fmt.Errorf( 515 "%s: resource depends on non-existent resource '%s'", 516 n, d)) 517 } 518 } 519 520 // Verify provider points to a provider that is configured 521 if r.Provider != "" { 522 if _, ok := providerSet[r.Provider]; !ok { 523 errs = append(errs, fmt.Errorf( 524 "%s: resource depends on non-configured provider '%s'", 525 n, r.Provider)) 526 } 527 } 528 529 // Verify provisioners don't contain any splats 530 for _, p := range r.Provisioners { 531 // This validation checks that there are now splat variables 532 // referencing ourself. This currently is not allowed. 533 534 for _, v := range p.ConnInfo.Variables { 535 rv, ok := v.(*ResourceVariable) 536 if !ok { 537 continue 538 } 539 540 if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name { 541 errs = append(errs, fmt.Errorf( 542 "%s: connection info cannot contain splat variable "+ 543 "referencing itself", n)) 544 break 545 } 546 } 547 548 for _, v := range p.RawConfig.Variables { 549 rv, ok := v.(*ResourceVariable) 550 if !ok { 551 continue 552 } 553 554 if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name { 555 errs = append(errs, fmt.Errorf( 556 "%s: connection info cannot contain splat variable "+ 557 "referencing itself", n)) 558 break 559 } 560 } 561 } 562 } 563 564 for source, vs := range vars { 565 for _, v := range vs { 566 rv, ok := v.(*ResourceVariable) 567 if !ok { 568 continue 569 } 570 571 id := rv.ResourceId() 572 if _, ok := resources[id]; !ok { 573 errs = append(errs, fmt.Errorf( 574 "%s: unknown resource '%s' referenced in variable %s", 575 source, 576 id, 577 rv.FullKey())) 578 continue 579 } 580 } 581 } 582 583 // Check that all outputs are valid 584 for _, o := range c.Outputs { 585 var invalidKeys []string 586 valueKeyFound := false 587 for k := range o.RawConfig.Raw { 588 if k == "value" { 589 valueKeyFound = true 590 continue 591 } 592 if k == "sensitive" { 593 if sensitive, ok := o.RawConfig.config[k].(bool); ok { 594 if sensitive { 595 o.Sensitive = true 596 } 597 continue 598 } 599 600 errs = append(errs, fmt.Errorf( 601 "%s: value for 'sensitive' must be boolean", 602 o.Name)) 603 continue 604 } 605 invalidKeys = append(invalidKeys, k) 606 } 607 if len(invalidKeys) > 0 { 608 errs = append(errs, fmt.Errorf( 609 "%s: output has invalid keys: %s", 610 o.Name, strings.Join(invalidKeys, ", "))) 611 } 612 if !valueKeyFound { 613 errs = append(errs, fmt.Errorf( 614 "%s: output is missing required 'value' key", o.Name)) 615 } 616 617 for _, v := range o.RawConfig.Variables { 618 if _, ok := v.(*CountVariable); ok { 619 errs = append(errs, fmt.Errorf( 620 "%s: count variables are only valid within resources", o.Name)) 621 } 622 } 623 } 624 625 // Check that all variables are in the proper context 626 for source, rc := range c.rawConfigs() { 627 walker := &interpolationWalker{ 628 ContextF: c.validateVarContextFn(source, &errs), 629 } 630 if err := reflectwalk.Walk(rc.Raw, walker); err != nil { 631 errs = append(errs, fmt.Errorf( 632 "%s: error reading config: %s", source, err)) 633 } 634 } 635 636 // Validate the self variable 637 for source, rc := range c.rawConfigs() { 638 // Ignore provisioners. This is a pretty brittle way to do this, 639 // but better than also repeating all the resources. 640 if strings.Contains(source, "provision") { 641 continue 642 } 643 644 for _, v := range rc.Variables { 645 if _, ok := v.(*SelfVariable); ok { 646 errs = append(errs, fmt.Errorf( 647 "%s: cannot contain self-reference %s", source, v.FullKey())) 648 } 649 } 650 } 651 652 if len(errs) > 0 { 653 return &multierror.Error{Errors: errs} 654 } 655 656 return nil 657 } 658 659 // InterpolatedVariables is a helper that returns a mapping of all the interpolated 660 // variables within the configuration. This is used to verify references 661 // are valid in the Validate step. 662 func (c *Config) InterpolatedVariables() map[string][]InterpolatedVariable { 663 result := make(map[string][]InterpolatedVariable) 664 for source, rc := range c.rawConfigs() { 665 for _, v := range rc.Variables { 666 result[source] = append(result[source], v) 667 } 668 } 669 return result 670 } 671 672 // rawConfigs returns all of the RawConfigs that are available keyed by 673 // a human-friendly source. 674 func (c *Config) rawConfigs() map[string]*RawConfig { 675 result := make(map[string]*RawConfig) 676 for _, m := range c.Modules { 677 source := fmt.Sprintf("module '%s'", m.Name) 678 result[source] = m.RawConfig 679 } 680 681 for _, pc := range c.ProviderConfigs { 682 source := fmt.Sprintf("provider config '%s'", pc.Name) 683 result[source] = pc.RawConfig 684 } 685 686 for _, rc := range c.Resources { 687 source := fmt.Sprintf("resource '%s'", rc.Id()) 688 result[source+" count"] = rc.RawCount 689 result[source+" config"] = rc.RawConfig 690 691 for i, p := range rc.Provisioners { 692 subsource := fmt.Sprintf( 693 "%s provisioner %s (#%d)", 694 source, p.Type, i+1) 695 result[subsource] = p.RawConfig 696 } 697 } 698 699 for _, o := range c.Outputs { 700 source := fmt.Sprintf("output '%s'", o.Name) 701 result[source] = o.RawConfig 702 } 703 704 return result 705 } 706 707 func (c *Config) validateVarContextFn( 708 source string, errs *[]error) interpolationWalkerContextFunc { 709 return func(loc reflectwalk.Location, node ast.Node) { 710 // If we're in a slice element, then its fine, since you can do 711 // anything in there. 712 if loc == reflectwalk.SliceElem { 713 return 714 } 715 716 // Otherwise, let's check if there is a splat resource variable 717 // at the top level in here. We do this by doing a transform that 718 // replaces everything with a noop node unless its a variable 719 // access or concat. This should turn the AST into a flat tree 720 // of Concat(Noop, ...). If there are any variables left that are 721 // multi-access, then its still broken. 722 node = node.Accept(func(n ast.Node) ast.Node { 723 // If it is a concat or variable access, we allow it. 724 switch n.(type) { 725 case *ast.Output: 726 return n 727 case *ast.VariableAccess: 728 return n 729 } 730 731 // Otherwise, noop 732 return &noopNode{} 733 }) 734 735 vars, err := DetectVariables(node) 736 if err != nil { 737 // Ignore it since this will be caught during parse. This 738 // actually probably should never happen by the time this 739 // is called, but its okay. 740 return 741 } 742 743 for _, v := range vars { 744 rv, ok := v.(*ResourceVariable) 745 if !ok { 746 return 747 } 748 749 if rv.Multi && rv.Index == -1 { 750 *errs = append(*errs, fmt.Errorf( 751 "%s: use of the splat ('*') operator must be wrapped in a list declaration", 752 source)) 753 } 754 } 755 } 756 } 757 758 func (m *Module) mergerName() string { 759 return m.Id() 760 } 761 762 func (m *Module) mergerMerge(other merger) merger { 763 m2 := other.(*Module) 764 765 result := *m 766 result.Name = m2.Name 767 result.RawConfig = result.RawConfig.merge(m2.RawConfig) 768 769 if m2.Source != "" { 770 result.Source = m2.Source 771 } 772 773 return &result 774 } 775 776 func (o *Output) mergerName() string { 777 return o.Name 778 } 779 780 func (o *Output) mergerMerge(m merger) merger { 781 o2 := m.(*Output) 782 783 result := *o 784 result.Name = o2.Name 785 result.RawConfig = result.RawConfig.merge(o2.RawConfig) 786 787 return &result 788 } 789 790 func (c *ProviderConfig) GoString() string { 791 return fmt.Sprintf("*%#v", *c) 792 } 793 794 func (c *ProviderConfig) FullName() string { 795 if c.Alias == "" { 796 return c.Name 797 } 798 799 return fmt.Sprintf("%s.%s", c.Name, c.Alias) 800 } 801 802 func (c *ProviderConfig) mergerName() string { 803 return c.Name 804 } 805 806 func (c *ProviderConfig) mergerMerge(m merger) merger { 807 c2 := m.(*ProviderConfig) 808 809 result := *c 810 result.Name = c2.Name 811 result.RawConfig = result.RawConfig.merge(c2.RawConfig) 812 813 return &result 814 } 815 816 func (r *Resource) mergerName() string { 817 return r.Id() 818 } 819 820 func (r *Resource) mergerMerge(m merger) merger { 821 r2 := m.(*Resource) 822 823 result := *r 824 result.Mode = r2.Mode 825 result.Name = r2.Name 826 result.Type = r2.Type 827 result.RawConfig = result.RawConfig.merge(r2.RawConfig) 828 829 if r2.RawCount.Value() != "1" { 830 result.RawCount = r2.RawCount 831 } 832 833 if len(r2.Provisioners) > 0 { 834 result.Provisioners = r2.Provisioners 835 } 836 837 return &result 838 } 839 840 // Merge merges two variables to create a new third variable. 841 func (v *Variable) Merge(v2 *Variable) *Variable { 842 // Shallow copy the variable 843 result := *v 844 845 // The names should be the same, but the second name always wins. 846 result.Name = v2.Name 847 848 if v2.Default != nil { 849 result.Default = v2.Default 850 } 851 if v2.Description != "" { 852 result.Description = v2.Description 853 } 854 855 return &result 856 } 857 858 var typeStringMap = map[string]VariableType{ 859 "string": VariableTypeString, 860 "map": VariableTypeMap, 861 "list": VariableTypeList, 862 } 863 864 // Type returns the type of variable this is. 865 func (v *Variable) Type() VariableType { 866 if v.DeclaredType != "" { 867 declaredType, ok := typeStringMap[v.DeclaredType] 868 if !ok { 869 return VariableTypeUnknown 870 } 871 872 return declaredType 873 } 874 875 return v.inferTypeFromDefault() 876 } 877 878 // ValidateTypeAndDefault ensures that default variable value is compatible 879 // with the declared type (if one exists), and that the type is one which is 880 // known to Terraform 881 func (v *Variable) ValidateTypeAndDefault() error { 882 // If an explicit type is declared, ensure it is valid 883 if v.DeclaredType != "" { 884 if _, ok := typeStringMap[v.DeclaredType]; !ok { 885 return fmt.Errorf("Variable '%s' must be of type string or map - '%s' is not a valid type", v.Name, v.DeclaredType) 886 } 887 } 888 889 if v.DeclaredType == "" || v.Default == nil { 890 return nil 891 } 892 893 if v.inferTypeFromDefault() != v.Type() { 894 return fmt.Errorf("'%s' has a default value which is not of type '%s' (got '%s')", 895 v.Name, v.DeclaredType, v.inferTypeFromDefault().Printable()) 896 } 897 898 return nil 899 } 900 901 func (v *Variable) mergerName() string { 902 return v.Name 903 } 904 905 func (v *Variable) mergerMerge(m merger) merger { 906 return v.Merge(m.(*Variable)) 907 } 908 909 // Required tests whether a variable is required or not. 910 func (v *Variable) Required() bool { 911 return v.Default == nil 912 } 913 914 // inferTypeFromDefault contains the logic for the old method of inferring 915 // variable types - we can also use this for validating that the declared 916 // type matches the type of the default value 917 func (v *Variable) inferTypeFromDefault() VariableType { 918 if v.Default == nil { 919 return VariableTypeString 920 } 921 922 var s string 923 if err := hilmapstructure.WeakDecode(v.Default, &s); err == nil { 924 v.Default = s 925 return VariableTypeString 926 } 927 928 var m map[string]interface{} 929 if err := hilmapstructure.WeakDecode(v.Default, &m); err == nil { 930 v.Default = m 931 return VariableTypeMap 932 } 933 934 var l []interface{} 935 if err := hilmapstructure.WeakDecode(v.Default, &l); err == nil { 936 v.Default = l 937 return VariableTypeList 938 } 939 940 return VariableTypeUnknown 941 } 942 943 func (m ResourceMode) Taintable() bool { 944 switch m { 945 case ManagedResourceMode: 946 return true 947 case DataResourceMode: 948 return false 949 default: 950 panic(fmt.Errorf("unsupported ResourceMode value %s", m)) 951 } 952 }