Feature Friday #3: execresult_as_data()

Posted by Nick Anderson
March 29, 2024

When you want to inspect both the return code and output from a command execresult_as_data() might be the function you are searching for.

Most CFEngine policy writers have used execresult() and returnszero(). They are useful when you want to do something based on the output of a command or based on its successful execution (returning zero). For example:

/tmp/feature-friday-3.cf
bundle agent __main__
{
  vars:
    "hostname"
      string => execresult( "$(paths.hostname)", "useshell" );

  classes:
    "my_command_returned_zero"
      expression => returnszero( "$(paths.hostname)", "noshell" );

  reports:

    "$(hostname)";

    my_command_returned_zero::
      "$(paths.hostname) returned 0";
}
command
cf-agent --no-lock --log-level info --file /tmp/feature-friday-3.cf
output
precision-5570
R: precision-5570
R: /bin/hostname returned 0

But, sometimes, you care about specific return codes. However, you might also want to consider the output from a command. execresult_as_data() facilitates inspecting both output and return code from a command’s execution, by returning a data structure. Let’s take a look.

/tmp/feature-friday-3-1.cf
bundle agent __main__
{
  vars:
    "i_got"
      data => execresult_as_data( "$(paths.hostname)", "useshell" );

  reports:
      "$(paths.hostname) emitted '$(i_got[output])' and returned '$(i_got[exit_code])'";
}
command
cf-agent --no-lock --log-level info --file /tmp/feature-friday-3-1.cf
output
R: /bin/hostname emitted 'precision-5570' and returned '0'

Happy Friday! 🎉