Creating an Apply For rule across multiple variables

Scopes

checkname is a scoped variable. It exists inside the for loop, but not inside other inner scopes, like an object or an apply rule.

for (c in [ "c1", "c2" ]) {
  object Host c { //this works, the declaration of the object is in the parent scope
    check_command = "dummy"
    vars.cv = c //this doesn't work, c is not available inside the object scope
  }
}

The DSL is very strict with scopes, this is to avoid accidental overrides from upper layers. One would not expect that a variable defined somewhere above would actually be global. Or - which source wins with many wrapped scopes?

Note

These loops might not be handy for production though. For developers and tests, they are pretty awesome, since we can generate many objects just with the DSL. The famous “many.conf” also exists inside the Vagrant boxes for that purpose :slight_smile:

I have an advanced example in progress for IcingaDB tests which also renders zone/endpoint memberships, but you know … time.

Global constants vs local variables

In contrast to that, a global variable or constant can be used, since globals is implicitly bound into an object/apply rule. this and locals isn’t.

Try that:

var c = "c1"

object Host c {
  check_command = "dummy"
  vars.cv = c
}
[2019-05-29 19:18:44 +0200] critical/config: Error: Error while evaluating expression: Tried to access undefined script variable 'c'
Location: in /etc/icinga2/tests/scope.conf: 5:13-5:13
/etc/icinga2/tests/scope.conf(3): object Host c {
/etc/icinga2/tests/scope.conf(4):   check_command = "dummy"
/etc/icinga2/tests/scope.conf(5):   vars.cv = c
                                              ^
/etc/icinga2/tests/scope.conf(6): }
/etc/icinga2/tests/scope.conf(7): 

[2019-05-29 19:18:44 +0200] critical/config: 1 error

vs

const c = "c1"

object Host c {
  check_command = "dummy"
  vars.cv = c
}
<works>

Agreed, the docs are a bit sparse on this … but you know, I cannot do everything :kissing_heart:

Imho one can only learn these advances techniques by discussing them here on the forums. I think it really is very hard to explain in the docs - if you look at the loop unrolling which tries to explain the apply for loop iterations … well, not happy with it, but at least something.

Cheers,
Michael

2 Likes