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