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