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