Feature Friday #29: Variable class expressions

Posted by Nick Anderson
September 27, 2024

Did you know you can use variables in class expressions?

If you are reading this, you probably are already familiar with the ability to use class expressions to restrict the context of multiple promises. For example, here we have three reports type promises, all guarded by the class expression linux::.

bundle agent __main__
{
  reports:

    linux::
      "Only hosts with the linux class";

      "Will have these promises";

      "In context";

}

And, if you are tracking this series, you know that you can restrict the context of a single promise using if or unless.1 However, you can also use variables in class expressions. Let’s take a look.

Let’s modify the previous policy to use a variable class expression.

bundle agent __main__
{
  vars:
      "state" string => "disabled";

  classes:
      "state_enabled" expression => "any";

  reports:

    "linux.state_$(state)"::

      "Only hosts with the linux class";

      "Will have these promises";

      "In context";
}

Now we have a variable state, which is currently set to disabled. Furthermore, a class state_enabled which is defined in any context. Lastly, the class expression guarding our reports has been quoted and includes a variable expansion. No output is generated if you run this policy since all the reports are out of context. However, if you change state to enabled:

/tmp/feature-friday-29.cf
bundle agent __main__
{
  vars:
      "state" string => "enabled";

  classes:
      "state_enabled" expression => "any";

  reports:

    "linux.state_$(state)"::

      "Only hosts with the linux class";

      "Will have these promises";

      "In context";
}
command
cf-agent -Kf /tmp/feature-friday-29.cf
output
R: Only hosts with the linux class
R: Will have these promises
R: In context

Running the policy on a Linux host, we see that all three reports are emitted. Hence, if you have multiple promises that need to be guarded based on some variable class name, then this can be easier to maintain than explicitly constraining each promise with if attributes.

Happy Friday! 🎉


  1. In case you missed it, Feature Friday #28: Restricting individual promises using if and unless. ↩︎