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