github.com/trawler/terraform@v0.10.8-0.20171106022149-4b1c7a1d9b48/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/ast" 13 "github.com/hashicorp/terraform/helper/hilmapstructure" 14 "github.com/hashicorp/terraform/plugin/discovery" 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 Locals []*Local 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 Version string 59 Providers map[string]string 60 RawConfig *RawConfig 61 } 62 63 // ProviderConfig is the configuration for a resource provider. 64 // 65 // For example, Terraform needs to set the AWS access keys for the AWS 66 // resource provider. 67 type ProviderConfig struct { 68 Name string 69 Alias string 70 Version string 71 RawConfig *RawConfig 72 73 // Path records where the Provider was declared in a module tree, so that 74 // it can be copied into child module providers yet still interpolated in 75 // the correct scope. 76 Path []string 77 78 // Inherited is used to skip validation of this config, since any 79 // interpolated variables won't be declared at this level. 80 Inherited bool 81 } 82 83 // A resource represents a single Terraform resource in the configuration. 84 // A Terraform resource is something that supports some or all of the 85 // usual "create, read, update, delete" operations, depending on 86 // the given Mode. 87 type Resource struct { 88 Mode ResourceMode // which operations the resource supports 89 Name string 90 Type string 91 RawCount *RawConfig 92 RawConfig *RawConfig 93 Provisioners []*Provisioner 94 Provider string 95 DependsOn []string 96 Lifecycle ResourceLifecycle 97 } 98 99 // Copy returns a copy of this Resource. Helpful for avoiding shared 100 // config pointers across multiple pieces of the graph that need to do 101 // interpolation. 102 func (r *Resource) Copy() *Resource { 103 n := &Resource{ 104 Mode: r.Mode, 105 Name: r.Name, 106 Type: r.Type, 107 RawCount: r.RawCount.Copy(), 108 RawConfig: r.RawConfig.Copy(), 109 Provisioners: make([]*Provisioner, 0, len(r.Provisioners)), 110 Provider: r.Provider, 111 DependsOn: make([]string, len(r.DependsOn)), 112 Lifecycle: *r.Lifecycle.Copy(), 113 } 114 for _, p := range r.Provisioners { 115 n.Provisioners = append(n.Provisioners, p.Copy()) 116 } 117 copy(n.DependsOn, r.DependsOn) 118 return n 119 } 120 121 // ResourceLifecycle is used to store the lifecycle tuning parameters 122 // to allow customized behavior 123 type ResourceLifecycle struct { 124 CreateBeforeDestroy bool `mapstructure:"create_before_destroy"` 125 PreventDestroy bool `mapstructure:"prevent_destroy"` 126 IgnoreChanges []string `mapstructure:"ignore_changes"` 127 } 128 129 // Copy returns a copy of this ResourceLifecycle 130 func (r *ResourceLifecycle) Copy() *ResourceLifecycle { 131 n := &ResourceLifecycle{ 132 CreateBeforeDestroy: r.CreateBeforeDestroy, 133 PreventDestroy: r.PreventDestroy, 134 IgnoreChanges: make([]string, len(r.IgnoreChanges)), 135 } 136 copy(n.IgnoreChanges, r.IgnoreChanges) 137 return n 138 } 139 140 // Provisioner is a configured provisioner step on a resource. 141 type Provisioner struct { 142 Type string 143 RawConfig *RawConfig 144 ConnInfo *RawConfig 145 146 When ProvisionerWhen 147 OnFailure ProvisionerOnFailure 148 } 149 150 // Copy returns a copy of this Provisioner 151 func (p *Provisioner) Copy() *Provisioner { 152 return &Provisioner{ 153 Type: p.Type, 154 RawConfig: p.RawConfig.Copy(), 155 ConnInfo: p.ConnInfo.Copy(), 156 When: p.When, 157 OnFailure: p.OnFailure, 158 } 159 } 160 161 // Variable is a module argument defined within the configuration. 162 type Variable struct { 163 Name string 164 DeclaredType string `mapstructure:"type"` 165 Default interface{} 166 Description string 167 } 168 169 // Local is a local value defined within the configuration. 170 type Local struct { 171 Name string 172 RawConfig *RawConfig 173 } 174 175 // Output is an output defined within the configuration. An output is 176 // resulting data that is highlighted by Terraform when finished. An 177 // output marked Sensitive will be output in a masked form following 178 // application, but will still be available in state. 179 type Output struct { 180 Name string 181 DependsOn []string 182 Description string 183 Sensitive bool 184 RawConfig *RawConfig 185 } 186 187 // VariableType is the type of value a variable is holding, and returned 188 // by the Type() function on variables. 189 type VariableType byte 190 191 const ( 192 VariableTypeUnknown VariableType = iota 193 VariableTypeString 194 VariableTypeList 195 VariableTypeMap 196 ) 197 198 func (v VariableType) Printable() string { 199 switch v { 200 case VariableTypeString: 201 return "string" 202 case VariableTypeMap: 203 return "map" 204 case VariableTypeList: 205 return "list" 206 default: 207 return "unknown" 208 } 209 } 210 211 // ProviderConfigName returns the name of the provider configuration in 212 // the given mapping that maps to the proper provider configuration 213 // for this resource. 214 func ProviderConfigName(t string, pcs []*ProviderConfig) string { 215 lk := "" 216 for _, v := range pcs { 217 k := v.Name 218 if strings.HasPrefix(t, k) && len(k) > len(lk) { 219 lk = k 220 } 221 } 222 223 return lk 224 } 225 226 // A unique identifier for this module. 227 func (r *Module) Id() string { 228 return fmt.Sprintf("%s", r.Name) 229 } 230 231 // Count returns the count of this resource. 232 func (r *Resource) Count() (int, error) { 233 raw := r.RawCount.Value() 234 count, ok := r.RawCount.Value().(string) 235 if !ok { 236 return 0, fmt.Errorf( 237 "expected count to be a string or int, got %T", raw) 238 } 239 240 v, err := strconv.ParseInt(count, 0, 0) 241 if err != nil { 242 return 0, err 243 } 244 245 return int(v), nil 246 } 247 248 // A unique identifier for this resource. 249 func (r *Resource) Id() string { 250 switch r.Mode { 251 case ManagedResourceMode: 252 return fmt.Sprintf("%s.%s", r.Type, r.Name) 253 case DataResourceMode: 254 return fmt.Sprintf("data.%s.%s", r.Type, r.Name) 255 default: 256 panic(fmt.Errorf("unknown resource mode %s", r.Mode)) 257 } 258 } 259 260 // ProviderFullName returns the full name of the provider for this resource, 261 // which may either be specified explicitly using the "provider" meta-argument 262 // or implied by the prefix on the resource type name. 263 func (r *Resource) ProviderFullName() string { 264 return ResourceProviderFullName(r.Type, r.Provider) 265 } 266 267 // ResourceProviderFullName returns the full (dependable) name of the 268 // provider for a hypothetical resource with the given resource type and 269 // explicit provider string. If the explicit provider string is empty then 270 // the provider name is inferred from the resource type name. 271 func ResourceProviderFullName(resourceType, explicitProvider string) string { 272 if explicitProvider != "" { 273 return explicitProvider 274 } 275 276 idx := strings.IndexRune(resourceType, '_') 277 if idx == -1 { 278 // If no underscores, the resource name is assumed to be 279 // also the provider name, e.g. if the provider exposes 280 // only a single resource of each type. 281 return resourceType 282 } 283 284 return resourceType[:idx] 285 } 286 287 // Validate does some basic semantic checking of the configuration. 288 func (c *Config) Validate() error { 289 if c == nil { 290 return nil 291 } 292 293 var errs []error 294 295 for _, k := range c.unknownKeys { 296 errs = append(errs, fmt.Errorf( 297 "Unknown root level key: %s", k)) 298 } 299 300 // Validate the Terraform config 301 if tf := c.Terraform; tf != nil { 302 errs = append(errs, c.Terraform.Validate()...) 303 } 304 305 vars := c.InterpolatedVariables() 306 varMap := make(map[string]*Variable) 307 for _, v := range c.Variables { 308 if _, ok := varMap[v.Name]; ok { 309 errs = append(errs, fmt.Errorf( 310 "Variable '%s': duplicate found. Variable names must be unique.", 311 v.Name)) 312 } 313 314 varMap[v.Name] = v 315 } 316 317 for k, _ := range varMap { 318 if !NameRegexp.MatchString(k) { 319 errs = append(errs, fmt.Errorf( 320 "variable %q: variable name must match regular expresion %s", 321 k, NameRegexp)) 322 } 323 } 324 325 for _, v := range c.Variables { 326 if v.Type() == VariableTypeUnknown { 327 errs = append(errs, fmt.Errorf( 328 "Variable '%s': must be a string or a map", 329 v.Name)) 330 continue 331 } 332 333 interp := false 334 fn := func(n ast.Node) (interface{}, error) { 335 // LiteralNode is a literal string (outside of a ${ ... } sequence). 336 // interpolationWalker skips most of these. but in particular it 337 // visits those that have escaped sequences (like $${foo}) as a 338 // signal that *some* processing is required on this string. For 339 // our purposes here though, this is fine and not an interpolation. 340 if _, ok := n.(*ast.LiteralNode); !ok { 341 interp = true 342 } 343 return "", nil 344 } 345 346 w := &interpolationWalker{F: fn} 347 if v.Default != nil { 348 if err := reflectwalk.Walk(v.Default, w); err == nil { 349 if interp { 350 errs = append(errs, fmt.Errorf( 351 "Variable '%s': cannot contain interpolations", 352 v.Name)) 353 } 354 } 355 } 356 } 357 358 // Check for references to user variables that do not actually 359 // exist and record those errors. 360 for source, vs := range vars { 361 for _, v := range vs { 362 uv, ok := v.(*UserVariable) 363 if !ok { 364 continue 365 } 366 367 if _, ok := varMap[uv.Name]; !ok { 368 errs = append(errs, fmt.Errorf( 369 "%s: unknown variable referenced: '%s'. define it with 'variable' blocks", 370 source, 371 uv.Name)) 372 } 373 } 374 } 375 376 // Check that all count variables are valid. 377 for source, vs := range vars { 378 for _, rawV := range vs { 379 switch v := rawV.(type) { 380 case *CountVariable: 381 if v.Type == CountValueInvalid { 382 errs = append(errs, fmt.Errorf( 383 "%s: invalid count variable: %s", 384 source, 385 v.FullKey())) 386 } 387 case *PathVariable: 388 if v.Type == PathValueInvalid { 389 errs = append(errs, fmt.Errorf( 390 "%s: invalid path variable: %s", 391 source, 392 v.FullKey())) 393 } 394 } 395 } 396 } 397 398 // Check that providers aren't declared multiple times and that their 399 // version constraints, where present, are syntactically valid. 400 providerSet := make(map[string]struct{}) 401 for _, p := range c.ProviderConfigs { 402 name := p.FullName() 403 if _, ok := providerSet[name]; ok { 404 errs = append(errs, fmt.Errorf( 405 "provider.%s: declared multiple times, you can only declare a provider once", 406 name)) 407 continue 408 } 409 410 if p.Version != "" { 411 _, err := discovery.ConstraintStr(p.Version).Parse() 412 if err != nil { 413 errs = append(errs, fmt.Errorf( 414 "provider.%s: invalid version constraint %q: %s", 415 name, p.Version, err, 416 )) 417 } 418 } 419 420 providerSet[name] = struct{}{} 421 } 422 423 // Check that all references to modules are valid 424 modules := make(map[string]*Module) 425 dupped := make(map[string]struct{}) 426 for _, m := range c.Modules { 427 // Check for duplicates 428 if _, ok := modules[m.Id()]; ok { 429 if _, ok := dupped[m.Id()]; !ok { 430 dupped[m.Id()] = struct{}{} 431 432 errs = append(errs, fmt.Errorf( 433 "%s: module repeated multiple times", 434 m.Id())) 435 } 436 437 // Already seen this module, just skip it 438 continue 439 } 440 441 modules[m.Id()] = m 442 443 // Check that the source has no interpolations 444 rc, err := NewRawConfig(map[string]interface{}{ 445 "root": m.Source, 446 }) 447 if err != nil { 448 errs = append(errs, fmt.Errorf( 449 "%s: module source error: %s", 450 m.Id(), err)) 451 } else if len(rc.Interpolations) > 0 { 452 errs = append(errs, fmt.Errorf( 453 "%s: module source cannot contain interpolations", 454 m.Id())) 455 } 456 457 // Check that the name matches our regexp 458 if !NameRegexp.Match([]byte(m.Name)) { 459 errs = append(errs, fmt.Errorf( 460 "%s: module name can only contain letters, numbers, "+ 461 "dashes, and underscores", 462 m.Id())) 463 } 464 465 // Check that the configuration can all be strings, lists or maps 466 raw := make(map[string]interface{}) 467 for k, v := range m.RawConfig.Raw { 468 var strVal string 469 if err := hilmapstructure.WeakDecode(v, &strVal); err == nil { 470 raw[k] = strVal 471 continue 472 } 473 474 var mapVal map[string]interface{} 475 if err := hilmapstructure.WeakDecode(v, &mapVal); err == nil { 476 raw[k] = mapVal 477 continue 478 } 479 480 var sliceVal []interface{} 481 if err := hilmapstructure.WeakDecode(v, &sliceVal); err == nil { 482 raw[k] = sliceVal 483 continue 484 } 485 486 errs = append(errs, fmt.Errorf( 487 "%s: variable %s must be a string, list or map value", 488 m.Id(), k)) 489 } 490 491 // Check for invalid count variables 492 for _, v := range m.RawConfig.Variables { 493 switch v.(type) { 494 case *CountVariable: 495 errs = append(errs, fmt.Errorf( 496 "%s: count variables are only valid within resources", m.Name)) 497 case *SelfVariable: 498 errs = append(errs, fmt.Errorf( 499 "%s: self variables are only valid within resources", m.Name)) 500 } 501 } 502 503 // Update the raw configuration to only contain the string values 504 m.RawConfig, err = NewRawConfig(raw) 505 if err != nil { 506 errs = append(errs, fmt.Errorf( 507 "%s: can't initialize configuration: %s", 508 m.Id(), err)) 509 } 510 } 511 dupped = nil 512 513 // Check that all variables for modules reference modules that 514 // exist. 515 for source, vs := range vars { 516 for _, v := range vs { 517 mv, ok := v.(*ModuleVariable) 518 if !ok { 519 continue 520 } 521 522 if _, ok := modules[mv.Name]; !ok { 523 errs = append(errs, fmt.Errorf( 524 "%s: unknown module referenced: %s", 525 source, 526 mv.Name)) 527 } 528 } 529 } 530 531 // Check that all references to resources are valid 532 resources := make(map[string]*Resource) 533 dupped = make(map[string]struct{}) 534 for _, r := range c.Resources { 535 if _, ok := resources[r.Id()]; ok { 536 if _, ok := dupped[r.Id()]; !ok { 537 dupped[r.Id()] = struct{}{} 538 539 errs = append(errs, fmt.Errorf( 540 "%s: resource repeated multiple times", 541 r.Id())) 542 } 543 } 544 545 resources[r.Id()] = r 546 } 547 dupped = nil 548 549 // Validate resources 550 for n, r := range resources { 551 // Verify count variables 552 for _, v := range r.RawCount.Variables { 553 switch v.(type) { 554 case *CountVariable: 555 errs = append(errs, fmt.Errorf( 556 "%s: resource count can't reference count variable: %s", 557 n, 558 v.FullKey())) 559 case *SimpleVariable: 560 errs = append(errs, fmt.Errorf( 561 "%s: resource count can't reference variable: %s", 562 n, 563 v.FullKey())) 564 565 // Good 566 case *ModuleVariable: 567 case *ResourceVariable: 568 case *TerraformVariable: 569 case *UserVariable: 570 case *LocalVariable: 571 572 default: 573 errs = append(errs, fmt.Errorf( 574 "Internal error. Unknown type in count var in %s: %T", 575 n, v)) 576 } 577 } 578 579 if !r.RawCount.couldBeInteger() { 580 errs = append(errs, fmt.Errorf( 581 "%s: resource count must be an integer", 582 n)) 583 } 584 r.RawCount.init() 585 586 // Validate DependsOn 587 errs = append(errs, c.validateDependsOn(n, r.DependsOn, resources, modules)...) 588 589 // Verify provisioners 590 for _, p := range r.Provisioners { 591 // This validation checks that there are no splat variables 592 // referencing ourself. This currently is not allowed. 593 594 for _, v := range p.ConnInfo.Variables { 595 rv, ok := v.(*ResourceVariable) 596 if !ok { 597 continue 598 } 599 600 if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name { 601 errs = append(errs, fmt.Errorf( 602 "%s: connection info cannot contain splat variable "+ 603 "referencing itself", n)) 604 break 605 } 606 } 607 608 for _, v := range p.RawConfig.Variables { 609 rv, ok := v.(*ResourceVariable) 610 if !ok { 611 continue 612 } 613 614 if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name { 615 errs = append(errs, fmt.Errorf( 616 "%s: connection info cannot contain splat variable "+ 617 "referencing itself", n)) 618 break 619 } 620 } 621 622 // Check for invalid when/onFailure values, though this should be 623 // picked up by the loader we check here just in case. 624 if p.When == ProvisionerWhenInvalid { 625 errs = append(errs, fmt.Errorf( 626 "%s: provisioner 'when' value is invalid", n)) 627 } 628 if p.OnFailure == ProvisionerOnFailureInvalid { 629 errs = append(errs, fmt.Errorf( 630 "%s: provisioner 'on_failure' value is invalid", n)) 631 } 632 } 633 634 // Verify ignore_changes contains valid entries 635 for _, v := range r.Lifecycle.IgnoreChanges { 636 if strings.Contains(v, "*") && v != "*" { 637 errs = append(errs, fmt.Errorf( 638 "%s: ignore_changes does not support using a partial string "+ 639 "together with a wildcard: %s", n, v)) 640 } 641 } 642 643 // Verify ignore_changes has no interpolations 644 rc, err := NewRawConfig(map[string]interface{}{ 645 "root": r.Lifecycle.IgnoreChanges, 646 }) 647 if err != nil { 648 errs = append(errs, fmt.Errorf( 649 "%s: lifecycle ignore_changes error: %s", 650 n, err)) 651 } else if len(rc.Interpolations) > 0 { 652 errs = append(errs, fmt.Errorf( 653 "%s: lifecycle ignore_changes cannot contain interpolations", 654 n)) 655 } 656 657 // If it is a data source then it can't have provisioners 658 if r.Mode == DataResourceMode { 659 if _, ok := r.RawConfig.Raw["provisioner"]; ok { 660 errs = append(errs, fmt.Errorf( 661 "%s: data sources cannot have provisioners", 662 n)) 663 } 664 } 665 } 666 667 for source, vs := range vars { 668 for _, v := range vs { 669 rv, ok := v.(*ResourceVariable) 670 if !ok { 671 continue 672 } 673 674 id := rv.ResourceId() 675 if _, ok := resources[id]; !ok { 676 errs = append(errs, fmt.Errorf( 677 "%s: unknown resource '%s' referenced in variable %s", 678 source, 679 id, 680 rv.FullKey())) 681 continue 682 } 683 } 684 } 685 686 // Check that all locals are valid 687 { 688 found := make(map[string]struct{}) 689 for _, l := range c.Locals { 690 if _, ok := found[l.Name]; ok { 691 errs = append(errs, fmt.Errorf( 692 "%s: duplicate local. local value names must be unique", 693 l.Name, 694 )) 695 continue 696 } 697 found[l.Name] = struct{}{} 698 699 for _, v := range l.RawConfig.Variables { 700 if _, ok := v.(*CountVariable); ok { 701 errs = append(errs, fmt.Errorf( 702 "local %s: count variables are only valid within resources", l.Name, 703 )) 704 } 705 } 706 } 707 } 708 709 // Check that all outputs are valid 710 { 711 found := make(map[string]struct{}) 712 for _, o := range c.Outputs { 713 // Verify the output is new 714 if _, ok := found[o.Name]; ok { 715 errs = append(errs, fmt.Errorf( 716 "%s: duplicate output. output names must be unique.", 717 o.Name)) 718 continue 719 } 720 found[o.Name] = struct{}{} 721 722 var invalidKeys []string 723 valueKeyFound := false 724 for k := range o.RawConfig.Raw { 725 if k == "value" { 726 valueKeyFound = true 727 continue 728 } 729 if k == "sensitive" { 730 if sensitive, ok := o.RawConfig.config[k].(bool); ok { 731 if sensitive { 732 o.Sensitive = true 733 } 734 continue 735 } 736 737 errs = append(errs, fmt.Errorf( 738 "%s: value for 'sensitive' must be boolean", 739 o.Name)) 740 continue 741 } 742 if k == "description" { 743 if desc, ok := o.RawConfig.config[k].(string); ok { 744 o.Description = desc 745 continue 746 } 747 748 errs = append(errs, fmt.Errorf( 749 "%s: value for 'description' must be string", 750 o.Name)) 751 continue 752 } 753 invalidKeys = append(invalidKeys, k) 754 } 755 if len(invalidKeys) > 0 { 756 errs = append(errs, fmt.Errorf( 757 "%s: output has invalid keys: %s", 758 o.Name, strings.Join(invalidKeys, ", "))) 759 } 760 if !valueKeyFound { 761 errs = append(errs, fmt.Errorf( 762 "%s: output is missing required 'value' key", o.Name)) 763 } 764 765 for _, v := range o.RawConfig.Variables { 766 if _, ok := v.(*CountVariable); ok { 767 errs = append(errs, fmt.Errorf( 768 "%s: count variables are only valid within resources", o.Name)) 769 } 770 } 771 } 772 } 773 774 // Validate the self variable 775 for source, rc := range c.rawConfigs() { 776 // Ignore provisioners. This is a pretty brittle way to do this, 777 // but better than also repeating all the resources. 778 if strings.Contains(source, "provision") { 779 continue 780 } 781 782 for _, v := range rc.Variables { 783 if _, ok := v.(*SelfVariable); ok { 784 errs = append(errs, fmt.Errorf( 785 "%s: cannot contain self-reference %s", source, v.FullKey())) 786 } 787 } 788 } 789 790 if len(errs) > 0 { 791 return &multierror.Error{Errors: errs} 792 } 793 794 return nil 795 } 796 797 // InterpolatedVariables is a helper that returns a mapping of all the interpolated 798 // variables within the configuration. This is used to verify references 799 // are valid in the Validate step. 800 func (c *Config) InterpolatedVariables() map[string][]InterpolatedVariable { 801 result := make(map[string][]InterpolatedVariable) 802 for source, rc := range c.rawConfigs() { 803 for _, v := range rc.Variables { 804 result[source] = append(result[source], v) 805 } 806 } 807 return result 808 } 809 810 // rawConfigs returns all of the RawConfigs that are available keyed by 811 // a human-friendly source. 812 func (c *Config) rawConfigs() map[string]*RawConfig { 813 result := make(map[string]*RawConfig) 814 for _, m := range c.Modules { 815 source := fmt.Sprintf("module '%s'", m.Name) 816 result[source] = m.RawConfig 817 } 818 819 for _, pc := range c.ProviderConfigs { 820 // this was an inherited config, so we don't validate it at this level. 821 if pc.Inherited { 822 continue 823 } 824 source := fmt.Sprintf("provider config '%s'", pc.Name) 825 result[source] = pc.RawConfig 826 } 827 828 for _, rc := range c.Resources { 829 source := fmt.Sprintf("resource '%s'", rc.Id()) 830 result[source+" count"] = rc.RawCount 831 result[source+" config"] = rc.RawConfig 832 833 for i, p := range rc.Provisioners { 834 subsource := fmt.Sprintf( 835 "%s provisioner %s (#%d)", 836 source, p.Type, i+1) 837 result[subsource] = p.RawConfig 838 } 839 } 840 841 for _, o := range c.Outputs { 842 source := fmt.Sprintf("output '%s'", o.Name) 843 result[source] = o.RawConfig 844 } 845 846 return result 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 validTypes := []string{} 1029 for k := range typeStringMap { 1030 validTypes = append(validTypes, k) 1031 } 1032 return fmt.Errorf( 1033 "Variable '%s' type must be one of [%s] - '%s' is not a valid type", 1034 v.Name, 1035 strings.Join(validTypes, ", "), 1036 v.DeclaredType, 1037 ) 1038 } 1039 } 1040 1041 if v.DeclaredType == "" || v.Default == nil { 1042 return nil 1043 } 1044 1045 if v.inferTypeFromDefault() != v.Type() { 1046 return fmt.Errorf("'%s' has a default value which is not of type '%s' (got '%s')", 1047 v.Name, v.DeclaredType, v.inferTypeFromDefault().Printable()) 1048 } 1049 1050 return nil 1051 } 1052 1053 func (v *Variable) mergerName() string { 1054 return v.Name 1055 } 1056 1057 func (v *Variable) mergerMerge(m merger) merger { 1058 return v.Merge(m.(*Variable)) 1059 } 1060 1061 // Required tests whether a variable is required or not. 1062 func (v *Variable) Required() bool { 1063 return v.Default == nil 1064 } 1065 1066 // inferTypeFromDefault contains the logic for the old method of inferring 1067 // variable types - we can also use this for validating that the declared 1068 // type matches the type of the default value 1069 func (v *Variable) inferTypeFromDefault() VariableType { 1070 if v.Default == nil { 1071 return VariableTypeString 1072 } 1073 1074 var s string 1075 if err := hilmapstructure.WeakDecode(v.Default, &s); err == nil { 1076 v.Default = s 1077 return VariableTypeString 1078 } 1079 1080 var m map[string]interface{} 1081 if err := hilmapstructure.WeakDecode(v.Default, &m); err == nil { 1082 v.Default = m 1083 return VariableTypeMap 1084 } 1085 1086 var l []interface{} 1087 if err := hilmapstructure.WeakDecode(v.Default, &l); err == nil { 1088 v.Default = l 1089 return VariableTypeList 1090 } 1091 1092 return VariableTypeUnknown 1093 } 1094 1095 func (m ResourceMode) Taintable() bool { 1096 switch m { 1097 case ManagedResourceMode: 1098 return true 1099 case DataResourceMode: 1100 return false 1101 default: 1102 panic(fmt.Errorf("unsupported ResourceMode value %s", m)) 1103 } 1104 }