github.com/franklinhu/terraform@v0.6.9-0.20151202232446-81f7fb1e6f9e/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/terraform/config/lang" 13 "github.com/hashicorp/terraform/config/lang/ast" 14 "github.com/hashicorp/terraform/flatmap" 15 "github.com/mitchellh/mapstructure" 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(`\A[A-Za-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 Atlas *AtlasConfig 32 Modules []*Module 33 ProviderConfigs []*ProviderConfig 34 Resources []*Resource 35 Variables []*Variable 36 Outputs []*Output 37 38 // The fields below can be filled in by loaders for validation 39 // purposes. 40 unknownKeys []string 41 } 42 43 // AtlasConfig is the configuration for building in HashiCorp's Atlas. 44 type AtlasConfig struct { 45 Name string 46 Include []string 47 Exclude []string 48 } 49 50 // Module is a module used within a configuration. 51 // 52 // This does not represent a module itself, this represents a module 53 // call-site within an existing configuration. 54 type Module struct { 55 Name string 56 Source string 57 RawConfig *RawConfig 58 } 59 60 // ProviderConfig is the configuration for a resource provider. 61 // 62 // For example, Terraform needs to set the AWS access keys for the AWS 63 // resource provider. 64 type ProviderConfig struct { 65 Name string 66 Alias string 67 RawConfig *RawConfig 68 } 69 70 // A resource represents a single Terraform resource in the configuration. 71 // A Terraform resource is something that represents some component that 72 // can be created and managed, and has some properties associated with it. 73 type Resource struct { 74 Name string 75 Type string 76 RawCount *RawConfig 77 RawConfig *RawConfig 78 Provisioners []*Provisioner 79 Provider string 80 DependsOn []string 81 Lifecycle ResourceLifecycle 82 } 83 84 // ResourceLifecycle is used to store the lifecycle tuning parameters 85 // to allow customized behavior 86 type ResourceLifecycle struct { 87 CreateBeforeDestroy bool `mapstructure:"create_before_destroy"` 88 PreventDestroy bool `mapstructure:"prevent_destroy"` 89 IgnoreChanges []string `mapstructure:"ignore_changes"` 90 } 91 92 // Provisioner is a configured provisioner step on a resource. 93 type Provisioner struct { 94 Type string 95 RawConfig *RawConfig 96 ConnInfo *RawConfig 97 } 98 99 // Variable is a variable defined within the configuration. 100 type Variable struct { 101 Name string 102 Default interface{} 103 Description string 104 } 105 106 // Output is an output defined within the configuration. An output is 107 // resulting data that is highlighted by Terraform when finished. 108 type Output struct { 109 Name string 110 RawConfig *RawConfig 111 } 112 113 // VariableType is the type of value a variable is holding, and returned 114 // by the Type() function on variables. 115 type VariableType byte 116 117 const ( 118 VariableTypeUnknown VariableType = iota 119 VariableTypeString 120 VariableTypeMap 121 ) 122 123 // ProviderConfigName returns the name of the provider configuration in 124 // the given mapping that maps to the proper provider configuration 125 // for this resource. 126 func ProviderConfigName(t string, pcs []*ProviderConfig) string { 127 lk := "" 128 for _, v := range pcs { 129 k := v.Name 130 if strings.HasPrefix(t, k) && len(k) > len(lk) { 131 lk = k 132 } 133 } 134 135 return lk 136 } 137 138 // A unique identifier for this module. 139 func (r *Module) Id() string { 140 return fmt.Sprintf("%s", r.Name) 141 } 142 143 // Count returns the count of this resource. 144 func (r *Resource) Count() (int, error) { 145 v, err := strconv.ParseInt(r.RawCount.Value().(string), 0, 0) 146 if err != nil { 147 return 0, err 148 } 149 150 return int(v), nil 151 } 152 153 // A unique identifier for this resource. 154 func (r *Resource) Id() string { 155 return fmt.Sprintf("%s.%s", r.Type, r.Name) 156 } 157 158 // Validate does some basic semantic checking of the configuration. 159 func (c *Config) Validate() error { 160 if c == nil { 161 return nil 162 } 163 164 var errs []error 165 166 for _, k := range c.unknownKeys { 167 errs = append(errs, fmt.Errorf( 168 "Unknown root level key: %s", k)) 169 } 170 171 vars := c.InterpolatedVariables() 172 varMap := make(map[string]*Variable) 173 for _, v := range c.Variables { 174 varMap[v.Name] = v 175 } 176 177 for _, v := range c.Variables { 178 if v.Type() == VariableTypeUnknown { 179 errs = append(errs, fmt.Errorf( 180 "Variable '%s': must be string or mapping", 181 v.Name)) 182 continue 183 } 184 185 interp := false 186 fn := func(ast.Node) (string, error) { 187 interp = true 188 return "", nil 189 } 190 191 w := &interpolationWalker{F: fn} 192 if v.Default != nil { 193 if err := reflectwalk.Walk(v.Default, w); err == nil { 194 if interp { 195 errs = append(errs, fmt.Errorf( 196 "Variable '%s': cannot contain interpolations", 197 v.Name)) 198 } 199 } 200 } 201 } 202 203 // Check for references to user variables that do not actually 204 // exist and record those errors. 205 for source, vs := range vars { 206 for _, v := range vs { 207 uv, ok := v.(*UserVariable) 208 if !ok { 209 continue 210 } 211 212 if _, ok := varMap[uv.Name]; !ok { 213 errs = append(errs, fmt.Errorf( 214 "%s: unknown variable referenced: '%s'. define it with 'variable' blocks", 215 source, 216 uv.Name)) 217 } 218 } 219 } 220 221 // Check that all count variables are valid. 222 for source, vs := range vars { 223 for _, rawV := range vs { 224 switch v := rawV.(type) { 225 case *CountVariable: 226 if v.Type == CountValueInvalid { 227 errs = append(errs, fmt.Errorf( 228 "%s: invalid count variable: %s", 229 source, 230 v.FullKey())) 231 } 232 case *PathVariable: 233 if v.Type == PathValueInvalid { 234 errs = append(errs, fmt.Errorf( 235 "%s: invalid path variable: %s", 236 source, 237 v.FullKey())) 238 } 239 } 240 } 241 } 242 243 // Check that providers aren't declared multiple times. 244 providerSet := make(map[string]struct{}) 245 for _, p := range c.ProviderConfigs { 246 name := p.FullName() 247 if _, ok := providerSet[name]; ok { 248 errs = append(errs, fmt.Errorf( 249 "provider.%s: declared multiple times, you can only declare a provider once", 250 name)) 251 continue 252 } 253 254 providerSet[name] = struct{}{} 255 } 256 257 // Check that all references to modules are valid 258 modules := make(map[string]*Module) 259 dupped := make(map[string]struct{}) 260 for _, m := range c.Modules { 261 // Check for duplicates 262 if _, ok := modules[m.Id()]; ok { 263 if _, ok := dupped[m.Id()]; !ok { 264 dupped[m.Id()] = struct{}{} 265 266 errs = append(errs, fmt.Errorf( 267 "%s: module repeated multiple times", 268 m.Id())) 269 } 270 271 // Already seen this module, just skip it 272 continue 273 } 274 275 modules[m.Id()] = m 276 277 // Check that the source has no interpolations 278 rc, err := NewRawConfig(map[string]interface{}{ 279 "root": m.Source, 280 }) 281 if err != nil { 282 errs = append(errs, fmt.Errorf( 283 "%s: module source error: %s", 284 m.Id(), err)) 285 } else if len(rc.Interpolations) > 0 { 286 errs = append(errs, fmt.Errorf( 287 "%s: module source cannot contain interpolations", 288 m.Id())) 289 } 290 291 // Check that the name matches our regexp 292 if !NameRegexp.Match([]byte(m.Name)) { 293 errs = append(errs, fmt.Errorf( 294 "%s: module name can only contain letters, numbers, "+ 295 "dashes, and underscores", 296 m.Id())) 297 } 298 299 // Check that the configuration can all be strings 300 raw := make(map[string]interface{}) 301 for k, v := range m.RawConfig.Raw { 302 var strVal string 303 if err := mapstructure.WeakDecode(v, &strVal); err != nil { 304 errs = append(errs, fmt.Errorf( 305 "%s: variable %s must be a string value", 306 m.Id(), k)) 307 } 308 raw[k] = strVal 309 } 310 311 // Check for invalid count variables 312 for _, v := range m.RawConfig.Variables { 313 switch v.(type) { 314 case *CountVariable: 315 errs = append(errs, fmt.Errorf( 316 "%s: count variables are only valid within resources", m.Name)) 317 case *SelfVariable: 318 errs = append(errs, fmt.Errorf( 319 "%s: self variables are only valid within resources", m.Name)) 320 } 321 } 322 323 // Update the raw configuration to only contain the string values 324 m.RawConfig, err = NewRawConfig(raw) 325 if err != nil { 326 errs = append(errs, fmt.Errorf( 327 "%s: can't initialize configuration: %s", 328 m.Id(), err)) 329 } 330 } 331 dupped = nil 332 333 // Check that all variables for modules reference modules that 334 // exist. 335 for source, vs := range vars { 336 for _, v := range vs { 337 mv, ok := v.(*ModuleVariable) 338 if !ok { 339 continue 340 } 341 342 if _, ok := modules[mv.Name]; !ok { 343 errs = append(errs, fmt.Errorf( 344 "%s: unknown module referenced: %s", 345 source, 346 mv.Name)) 347 } 348 } 349 } 350 351 // Check that all references to resources are valid 352 resources := make(map[string]*Resource) 353 dupped = make(map[string]struct{}) 354 for _, r := range c.Resources { 355 if _, ok := resources[r.Id()]; ok { 356 if _, ok := dupped[r.Id()]; !ok { 357 dupped[r.Id()] = struct{}{} 358 359 errs = append(errs, fmt.Errorf( 360 "%s: resource repeated multiple times", 361 r.Id())) 362 } 363 } 364 365 resources[r.Id()] = r 366 } 367 dupped = nil 368 369 // Validate resources 370 for n, r := range resources { 371 // Verify count variables 372 for _, v := range r.RawCount.Variables { 373 switch v.(type) { 374 case *CountVariable: 375 errs = append(errs, fmt.Errorf( 376 "%s: resource count can't reference count variable: %s", 377 n, 378 v.FullKey())) 379 case *ModuleVariable: 380 errs = append(errs, fmt.Errorf( 381 "%s: resource count can't reference module variable: %s", 382 n, 383 v.FullKey())) 384 case *ResourceVariable: 385 errs = append(errs, fmt.Errorf( 386 "%s: resource count can't reference resource variable: %s", 387 n, 388 v.FullKey())) 389 case *UserVariable: 390 // Good 391 default: 392 panic("Unknown type in count var: " + n) 393 } 394 } 395 396 // Interpolate with a fixed number to verify that its a number. 397 r.RawCount.interpolate(func(root ast.Node) (string, error) { 398 // Execute the node but transform the AST so that it returns 399 // a fixed value of "5" for all interpolations. 400 out, _, err := lang.Eval( 401 lang.FixedValueTransform( 402 root, &ast.LiteralNode{Value: "5", Typex: ast.TypeString}), 403 nil) 404 if err != nil { 405 return "", err 406 } 407 408 return out.(string), nil 409 }) 410 _, err := strconv.ParseInt(r.RawCount.Value().(string), 0, 0) 411 if err != nil { 412 errs = append(errs, fmt.Errorf( 413 "%s: resource count must be an integer", 414 n)) 415 } 416 r.RawCount.init() 417 418 // Verify depends on points to resources that all exist 419 for _, d := range r.DependsOn { 420 // Check if we contain interpolations 421 rc, err := NewRawConfig(map[string]interface{}{ 422 "value": d, 423 }) 424 if err == nil && len(rc.Variables) > 0 { 425 errs = append(errs, fmt.Errorf( 426 "%s: depends on value cannot contain interpolations: %s", 427 n, d)) 428 continue 429 } 430 431 if _, ok := resources[d]; !ok { 432 errs = append(errs, fmt.Errorf( 433 "%s: resource depends on non-existent resource '%s'", 434 n, d)) 435 } 436 } 437 438 // Verify provider points to a provider that is configured 439 if r.Provider != "" { 440 if _, ok := providerSet[r.Provider]; !ok { 441 errs = append(errs, fmt.Errorf( 442 "%s: resource depends on non-configured provider '%s'", 443 n, r.Provider)) 444 } 445 } 446 447 // Verify provisioners don't contain any splats 448 for _, p := range r.Provisioners { 449 // This validation checks that there are now splat variables 450 // referencing ourself. This currently is not allowed. 451 452 for _, v := range p.ConnInfo.Variables { 453 rv, ok := v.(*ResourceVariable) 454 if !ok { 455 continue 456 } 457 458 if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name { 459 errs = append(errs, fmt.Errorf( 460 "%s: connection info cannot contain splat variable "+ 461 "referencing itself", n)) 462 break 463 } 464 } 465 466 for _, v := range p.RawConfig.Variables { 467 rv, ok := v.(*ResourceVariable) 468 if !ok { 469 continue 470 } 471 472 if rv.Multi && rv.Index == -1 && rv.Type == r.Type && rv.Name == r.Name { 473 errs = append(errs, fmt.Errorf( 474 "%s: connection info cannot contain splat variable "+ 475 "referencing itself", n)) 476 break 477 } 478 } 479 } 480 } 481 482 for source, vs := range vars { 483 for _, v := range vs { 484 rv, ok := v.(*ResourceVariable) 485 if !ok { 486 continue 487 } 488 489 id := fmt.Sprintf("%s.%s", rv.Type, rv.Name) 490 if _, ok := resources[id]; !ok { 491 errs = append(errs, fmt.Errorf( 492 "%s: unknown resource '%s' referenced in variable %s", 493 source, 494 id, 495 rv.FullKey())) 496 continue 497 } 498 } 499 } 500 501 // Check that all outputs are valid 502 for _, o := range c.Outputs { 503 invalid := false 504 for k, _ := range o.RawConfig.Raw { 505 if k != "value" { 506 invalid = true 507 break 508 } 509 } 510 if invalid { 511 errs = append(errs, fmt.Errorf( 512 "%s: output should only have 'value' field", o.Name)) 513 } 514 515 for _, v := range o.RawConfig.Variables { 516 if _, ok := v.(*CountVariable); ok { 517 errs = append(errs, fmt.Errorf( 518 "%s: count variables are only valid within resources", o.Name)) 519 } 520 } 521 } 522 523 // Check that all variables are in the proper context 524 for source, rc := range c.rawConfigs() { 525 walker := &interpolationWalker{ 526 ContextF: c.validateVarContextFn(source, &errs), 527 } 528 if err := reflectwalk.Walk(rc.Raw, walker); err != nil { 529 errs = append(errs, fmt.Errorf( 530 "%s: error reading config: %s", source, err)) 531 } 532 } 533 534 // Validate the self variable 535 for source, rc := range c.rawConfigs() { 536 // Ignore provisioners. This is a pretty brittle way to do this, 537 // but better than also repeating all the resources. 538 if strings.Contains(source, "provision") { 539 continue 540 } 541 542 for _, v := range rc.Variables { 543 if _, ok := v.(*SelfVariable); ok { 544 errs = append(errs, fmt.Errorf( 545 "%s: cannot contain self-reference %s", source, v.FullKey())) 546 } 547 } 548 } 549 550 if len(errs) > 0 { 551 return &multierror.Error{Errors: errs} 552 } 553 554 return nil 555 } 556 557 // InterpolatedVariables is a helper that returns a mapping of all the interpolated 558 // variables within the configuration. This is used to verify references 559 // are valid in the Validate step. 560 func (c *Config) InterpolatedVariables() map[string][]InterpolatedVariable { 561 result := make(map[string][]InterpolatedVariable) 562 for source, rc := range c.rawConfigs() { 563 for _, v := range rc.Variables { 564 result[source] = append(result[source], v) 565 } 566 } 567 return result 568 } 569 570 // rawConfigs returns all of the RawConfigs that are available keyed by 571 // a human-friendly source. 572 func (c *Config) rawConfigs() map[string]*RawConfig { 573 result := make(map[string]*RawConfig) 574 for _, m := range c.Modules { 575 source := fmt.Sprintf("module '%s'", m.Name) 576 result[source] = m.RawConfig 577 } 578 579 for _, pc := range c.ProviderConfigs { 580 source := fmt.Sprintf("provider config '%s'", pc.Name) 581 result[source] = pc.RawConfig 582 } 583 584 for _, rc := range c.Resources { 585 source := fmt.Sprintf("resource '%s'", rc.Id()) 586 result[source+" count"] = rc.RawCount 587 result[source+" config"] = rc.RawConfig 588 589 for i, p := range rc.Provisioners { 590 subsource := fmt.Sprintf( 591 "%s provisioner %s (#%d)", 592 source, p.Type, i+1) 593 result[subsource] = p.RawConfig 594 } 595 } 596 597 for _, o := range c.Outputs { 598 source := fmt.Sprintf("output '%s'", o.Name) 599 result[source] = o.RawConfig 600 } 601 602 return result 603 } 604 605 func (c *Config) validateVarContextFn( 606 source string, errs *[]error) interpolationWalkerContextFunc { 607 return func(loc reflectwalk.Location, node ast.Node) { 608 // If we're in a slice element, then its fine, since you can do 609 // anything in there. 610 if loc == reflectwalk.SliceElem { 611 return 612 } 613 614 // Otherwise, let's check if there is a splat resource variable 615 // at the top level in here. We do this by doing a transform that 616 // replaces everything with a noop node unless its a variable 617 // access or concat. This should turn the AST into a flat tree 618 // of Concat(Noop, ...). If there are any variables left that are 619 // multi-access, then its still broken. 620 node = node.Accept(func(n ast.Node) ast.Node { 621 // If it is a concat or variable access, we allow it. 622 switch n.(type) { 623 case *ast.Concat: 624 return n 625 case *ast.VariableAccess: 626 return n 627 } 628 629 // Otherwise, noop 630 return &noopNode{} 631 }) 632 633 vars, err := DetectVariables(node) 634 if err != nil { 635 // Ignore it since this will be caught during parse. This 636 // actually probably should never happen by the time this 637 // is called, but its okay. 638 return 639 } 640 641 for _, v := range vars { 642 rv, ok := v.(*ResourceVariable) 643 if !ok { 644 return 645 } 646 647 if rv.Multi && rv.Index == -1 { 648 *errs = append(*errs, fmt.Errorf( 649 "%s: multi-variable must be in a slice", source)) 650 } 651 } 652 } 653 } 654 655 func (m *Module) mergerName() string { 656 return m.Id() 657 } 658 659 func (m *Module) mergerMerge(other merger) merger { 660 m2 := other.(*Module) 661 662 result := *m 663 result.Name = m2.Name 664 result.RawConfig = result.RawConfig.merge(m2.RawConfig) 665 666 if m2.Source != "" { 667 result.Source = m2.Source 668 } 669 670 return &result 671 } 672 673 func (o *Output) mergerName() string { 674 return o.Name 675 } 676 677 func (o *Output) mergerMerge(m merger) merger { 678 o2 := m.(*Output) 679 680 result := *o 681 result.Name = o2.Name 682 result.RawConfig = result.RawConfig.merge(o2.RawConfig) 683 684 return &result 685 } 686 687 func (c *ProviderConfig) GoString() string { 688 return fmt.Sprintf("*%#v", *c) 689 } 690 691 func (c *ProviderConfig) FullName() string { 692 if c.Alias == "" { 693 return c.Name 694 } 695 696 return fmt.Sprintf("%s.%s", c.Name, c.Alias) 697 } 698 699 func (c *ProviderConfig) mergerName() string { 700 return c.Name 701 } 702 703 func (c *ProviderConfig) mergerMerge(m merger) merger { 704 c2 := m.(*ProviderConfig) 705 706 result := *c 707 result.Name = c2.Name 708 result.RawConfig = result.RawConfig.merge(c2.RawConfig) 709 710 return &result 711 } 712 713 func (r *Resource) mergerName() string { 714 return fmt.Sprintf("%s.%s", r.Type, r.Name) 715 } 716 717 func (r *Resource) mergerMerge(m merger) merger { 718 r2 := m.(*Resource) 719 720 result := *r 721 result.Name = r2.Name 722 result.Type = r2.Type 723 result.RawConfig = result.RawConfig.merge(r2.RawConfig) 724 725 if r2.RawCount.Value() != "1" { 726 result.RawCount = r2.RawCount 727 } 728 729 if len(r2.Provisioners) > 0 { 730 result.Provisioners = r2.Provisioners 731 } 732 733 return &result 734 } 735 736 // DefaultsMap returns a map of default values for this variable. 737 func (v *Variable) DefaultsMap() map[string]string { 738 if v.Default == nil { 739 return nil 740 } 741 742 n := fmt.Sprintf("var.%s", v.Name) 743 switch v.Type() { 744 case VariableTypeString: 745 return map[string]string{n: v.Default.(string)} 746 case VariableTypeMap: 747 result := flatmap.Flatten(map[string]interface{}{ 748 n: v.Default.(map[string]string), 749 }) 750 result[n] = v.Name 751 752 return result 753 default: 754 return nil 755 } 756 } 757 758 // Merge merges two variables to create a new third variable. 759 func (v *Variable) Merge(v2 *Variable) *Variable { 760 // Shallow copy the variable 761 result := *v 762 763 // The names should be the same, but the second name always wins. 764 result.Name = v2.Name 765 766 if v2.Default != nil { 767 result.Default = v2.Default 768 } 769 if v2.Description != "" { 770 result.Description = v2.Description 771 } 772 773 return &result 774 } 775 776 // Type returns the type of varialbe this is. 777 func (v *Variable) Type() VariableType { 778 if v.Default == nil { 779 return VariableTypeString 780 } 781 782 var strVal string 783 if err := mapstructure.WeakDecode(v.Default, &strVal); err == nil { 784 v.Default = strVal 785 return VariableTypeString 786 } 787 788 var m map[string]string 789 if err := mapstructure.WeakDecode(v.Default, &m); err == nil { 790 v.Default = m 791 return VariableTypeMap 792 } 793 794 return VariableTypeUnknown 795 } 796 797 func (v *Variable) mergerName() string { 798 return v.Name 799 } 800 801 func (v *Variable) mergerMerge(m merger) merger { 802 return v.Merge(m.(*Variable)) 803 } 804 805 // Required tests whether a variable is required or not. 806 func (v *Variable) Required() bool { 807 return v.Default == nil 808 }