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