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