Feature Friday #31: Seeing a data structure with storejson()

Posted by Nick Anderson
October 11, 2024

Ever need to visualize the data your working with? storejson() to the rescue!

Let’s re-visit our example for sys.os_release from Feature Friday #12: Special variables:

bundle agent __main__
{
  reports:
    "My custom key 'NORTHERN_TECH_OWNER' contains $(sys.os_release[NORTHERN_TECH_OWNER])";
}
R: My custom key 'NORTHERN_TECH_OWNER' contains Nick Anderson

So, we saw the value of a single key, but if we don’t know what keys are available it can be useful to render the JSON representation. The with attribute in combination with storejson() provides a convenient way to visualize the JSON representation of structured data in CFEngine. Let’s adjust the policy:

bundle agent __main__
{
  reports:
    "My custom key 'NORTHERN_TECH_OWNER' contains $(sys.os_release[NORTHERN_TECH_OWNER])";
    "The JSON representation of sys.os_release:$(const.n)$(with)"
      with => storejson( "sys.os_release" );
}

Running the policy we can see all of the keys and values:

R: My custom key 'NORTHERN_TECH_OWNER' contains Nick Anderson
R: The JSON representation of sys.os_release:
{
  "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/",
  "HOME_URL": "https://www.ubuntu.com/",
  "ID": "ubuntu",
  "ID_LIKE": "debian",
  "NAME": "Ubuntu",
  "NORTHERN_TECH_OWNER": "Nick Anderson",
  "PRETTY_NAME": "Ubuntu 22.04.4 LTS",
  "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy",
  "SUPPORT_URL": "https://help.ubuntu.com/",
  "UBUNTU_CODENAME": "jammy",
  "VERSION": "22.04.4 LTS (Jammy Jellyfish)",
  "VERSION_CODENAME": "jammy",
  "VERSION_ID": "22.04"
}

Happy Friday! 🎉