DSL: Closures & Scopes

Question

Generate TimePeriod objects in a loop, and use the loop iterator for object attributes.

It doesn’t work like this, s is undefined inside the object definition.

for (s in a) {
  //loop scope

  object TimePeriod "tp-" + s {
    //object scope
  }
}

Answer

That’s a problem with scopes. The variable s is available in the for loop scope, but not within the object’s scope.

for (s in a) {
  //loop scope

  object TimePeriod "tp-" + s {
    //object scope, does not inherit parent scope
  }
}

In order to solve this, you need to use closures and bind the variable into the current scope.

for (s in a) {                                                                                                                                                                            
  object TimePeriod "tp-" + s use (s) { //after this bracket, the object scope differs from the loop scope
    includes = [ "24x7" ]
    excludes = [ "no-tp" + s ]
                                                                                                                                                                                      
    display_name = "Downtime in " + s
    prefer_includes = false
  }
}

We do that in our example config in the Vagrant boxes too :wink:

Cheers,
Michael

2 Likes