[DSL] best practice to override object attributes from variables in apply rule

How could I override some object attributes (eg. Service.enable_active_checks) in an apply rule based on the presence or absence of a variable?

Example, I want to follow the documentation “apply Service for” pattern to define services and I want to customise display names and turn off active checks for a specific one:

object Host "myhost" {
  import "generic-host"
  address = "127.0.1.4"
  vars.interfaces["eth0"] = {
     vlan = "internal"
     display_name = "LAN interface"
  }
  vars.interfaces["eth1"] = {
     vlan = "remote"
     display_name = "WAN interface"
     enable_active_checks = false
  }
}

The best I came up with is standardising my apply for rules to use a common config name and checking its keys for variable presence, then explicitly handling them one by one:

template Service "custom-vars-service" {
  if ( "display_name" in keys(config) ) { display_name = config.display_name }
  if ( "enable_active_checks" in keys(config) ) { enable_active_checks = config.enable_active_checks }
  if ( "enable_passive_checks" in keys(config) ) { enable_passive_checks = config.enable_passive_checks }
  if ( "notes" in keys(config) ) { notes = config.notes }
}
apply Service for (my_svc => config in host.vars.my_svc) {
  import "custom-vars-service"
  # ....
}

Is there any better way?
Is there any downside to my approach that I’m not seeing right now?

thanks for feedback

To apply a service depending the presence of a variable, you could
use something like:

apply Service .... {
...
  assign where host.vars.your_special_variable != ""
...
}

Well, this should be optimized but may give you an idea.

Hi,

the proposed solution looks good to me. Although do keep in mind that it might get overly complicated. The approach suggested by @homerjay with creating multiple apply for rules for better readability also is a good thing.

Cheers,
Michael

@homerjay sorry but I wasn’t asking for a way to conditionally define services or not.
The service must be defined, what I want is to override its attributes.

@lesinigo
Sorry, I should have been a little more specific.

The idea was to create different apply rules, depending on the existence of the variable or not, and to assign the preferred display_name value.
Just as an idea.

Thank you @homerjay , now I understood what you meant.

My problem with this approach is that having multiple conditionals for different parameters to customize would lead to an explosion to the number of apply rules, so I’m gonna stick with my proposed approach.