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