The Policy Framework

Table of Contents

The CFEngine policy framework is called the masterfiles because the files live in /var/cfengine/masterfiles on the policy server (on the clients, and note the policy server is typically also a client, they are cached in /var/cfengine/inputs).

The following configuration files are part of the default CFEngine installation in /var/cfengine/masterfiles, and have special roles.

Setting up

First, review update.cf and def.cf. Most settings you need to change will live here.

update.cf

Synchronizing clients with the policy server happens here, in update.cf. Its main job is to copy all the files on the policy server (usually the hub) under $(sys.masterdir) (usually /var/cfengine/masterfiles) to the local host into $(sys.inputdir) (usually /var/cfengine/inputs).

This file should rarely if ever change. Should you ever change it (or when you upgrade CFEngine), take special care to ensure the old and the new CFEngine can parse and execute this file successfully. If not, you risk losing control of your system (that is, if CFEngine cannot successfully execute update.cf, it has no mechanism for distributing new policy files).

By default, the policy defined in update.cf is executed from two sets of promise bodies. The "usual" one (defined in the bundlesequence in promises.cf) and another in the backup/failsafe bundlesequence (defined in failsafe.cf).

This is a standalone policy file. You can actually run it with cf-agent -KI -f ./update.cf but if you don't understand what that command does, please hold off until you've gone through the CFEngine documentation. The contents of update.cf duplicate other things under lib sometimes, in order to be completely standalone.

To repeat, when update.cf is broken, things go bonkers. CFEngine will try to run a backup failsafe.cf you can find in the C core under libpromises/failsafe.cf (that .cf file is written into the C code and can't be modified). If things get to that point, you probably have to look at why corrupted policies made it into production.

As is typical for CFEngine, the policy and the configuration are mixed. In update.cf you'll find some very useful settings. Keep referring to update.cf as you read this. We are skipping the nonessential ones.

How it works

There are 4 stages in update.cf. See the bundlesequence: after loading the configuration from update_def, we take these steps in order.

cfe_internal_dc_workflow

This step implements the auto-deployment of policies. See Version Control and Configuration Policy and cfengine_internal_masterfiles_update below for details.

cfe_internal_update_policy

This step updates the policy files themselves. Basically it's a check step that looks at $(sys.inputdir)/cf_promises_validated and compares it with the policy server's $(sys.masterdir)/cf_promises_validated. Then there's the actual copy, which happens only if the cf_promises_validated file was updated in the check step.

Implementation (warning: advanced usage):

bundle agent cfe_internal_update_policy
{
  vars:
    !(cfengine_3_5||cfengine_3_4)::
      "inputs_dir"         string => translatepath("$(sys.inputdir)"),
      comment => "Directory containing CFEngine policies",
      handle => "cfe_internal_update_policy_vars_inputs_dir";

      "dir_bin"         string => translatepath("$(sys.bindir)"),
      comment => "Directory containing CFEngine binaries",
      handle => "cfe_internal_update_policy_vars_dir_bin";

    (cfengine_3_5||cfengine_3_4)::
      "inputs_dir"         string => translatepath("$(sys.workdir)/inputs"),
      comment => "Directory containing CFEngine policies",
      handle => "cfe_internal_update_policy_vars_inputs_dir_backport";

      "dir_bin"         string => translatepath("$(sys.workdir)/bin"),
      comment => "Directory containing CFEngine binaries",
      handle => "cfe_internal_update_policy_vars_dir_bin_backport";

    windows::

      "master_location"    string => "/var/cfengine/masterfiles",  # NB! NOT $(sys.workdir) on Windows !
      comment => "The master CFEngine policy directory on the policy host",
      handle => "cfe_internal_update_policy_vars_master_location_windows";

      "modules_dir"        string => "/var/cfengine/modules",      # NB! NOT $(sys.workdir) on Windows !
      comment => "Directory containing CFEngine modules",
      handle => "cfe_internal_update_policy_vars_modules_dir_windows";

      "plugins_dir"        string => "/var/cfengine/plugins",      # NB! NOT $(sys.workdir) on Windows !
      comment => "Directory containing CFEngine plugins",
      handle => "cfe_internal_update_policy_vars_plugins_dir_windows";

    !windows.!(cfengine_3_5||cfengine_3_4)::
      "master_location"    string => "$(sys.masterdir)",
      comment => "The master CFEngine policy directory on the policy host",
      handle => "cfe_internal_update_policy_vars_master_location";

    !windows.(cfengine_3_5||cfengine_3_4)::
      "master_location"    string => "$(sys.workdir)/masterfiles",
      comment => "The master CFEngine policy directory on the policy host",
      handle => "cfe_internal_update_policy_vars_master_location_backport";

    !windows::
      "modules_dir"        string => translatepath("$(sys.workdir)/modules"),
      comment => "Directory containing CFEngine modules",
      handle => "cfe_internal_update_policy_vars_modules_dir";

      "plugins_dir"        string => translatepath("$(sys.workdir)/plugins"),
      comment => "Directory containing CFEngine plugins",
      handle => "cfe_internal_update_policy_vars_plugins_dir";

    any::

      "file_check"         string => translatepath("$(inputs_dir)/promises.cf"),
      comment => "Path to a policy file",
      handle => "cfe_internal_update_vars_file_check";

      "ppkeys_file"        string => translatepath("$(sys.workdir)/ppkeys/localhost.pub"),
      comment => "Path to public key file",
      handle => "cfe_internal_update_policy_vars_ppkeys_file";

      "postgresdb_dir"        string => "$(sys.workdir)/state/pg/data",
      comment => "Directory where Postgres database files will be stored on hub -",
      handle => "cfe_internal_update_policy_postgresdb_dir";

      "postgresdb_log"        string => "/var/log/postgresql.log",
      comment => "File where Postgres database files will be logging -",
      handle => "cfe_internal_update_policy_postgresdb_log_file";

      "redis_conf_file"  string => translatepath("$(sys.workdir)/config/redis.conf"),
      comment => "Path to Redis configuration file",
      handle => "cfe_internal_update_policy_redis_conf_file";

      "agents" slist => {
              "cf-agent",
              "cf-execd",
              "cf-key",
              "cf-monitord",
              "cf-promises",
              "cf-runagent",
              "cf-serverd",
      },
      comment => "List of CFEngine binaries",
      handle => "cfe_internal_update_policy_vars_agents";

      "optional_agents" slist => {
                       "cf-consumer",
                       "cf-hub",
      },
      comment => "List of optional CFEngine binaries",
      handle => "cfe_internal_update_policy_vars_optional_agents";
      #

  classes:

      "have_bindir_$(optional_agents)" expression => fileexists("$(dir_bin)/$(optional_agents)");

    any::

      "have_ppkeys"   expression => fileexists("$(ppkeys_file)"),
      comment => "Check for $(sys.workdir)/ppkeys/localhost.pub",
      handle => "cfe_internal_update_policy_classes_have_ppkeys";

      "local_files_ok" expression => fileexists("$(file_check)"),
      comment => "Check for $(sys.masterdir)/promises.cf",
      handle => "cfe_internal_update_classes_files_ok";

      # create a global files_ok class
      "cfe_internal_trigger" expression => "local_files_ok",
      classes => u_if_else("files_ok", "files_ok");

      #

  commands:

    !have_ppkeys::

      "$(sys.cf_key)"
      comment => "Generate cfengine encryption keys if necessary",
      classes => u_kept_successful_command,
      handle => "cfe_internal_update_policy_commands_generate_keys";

    am_policy_hub.update_report::

      "$(sys.cf_promises) -r"
         contain => u_in_shell_and_silent,
         comment => "Generate config knowledge format after update",
         classes => u_kept_successful_command,
         handle => "cfe_internal_update_policy_commands_run_cf_promises_r";

      #

  files:

    !am_policy_hub::  # policy hub should not alter inputs/ uneccessary

      "$(inputs_dir)/cf_promises_validated"
      comment => "Check whether a validation stamp is available for a new policy update to reduce the distributed load",
      handle => "cfe_internal_update_policy_check_valid_update",
      copy_from => u_rcp("$(master_location)/cf_promises_validated", @(update_def.policy_servers)),
      action => u_immediate,
      classes => u_if_repaired("validated_updates_ready");

    !am_policy_hub.!windows::

      "$(modules_dir)"
      comment => "Always update modules files on client side",
      handle => "cfe_internal_update_policy_files_update_modules",
      copy_from => u_rcp("$(modules_dir)", @(update_def.policy_servers)),
      depth_search => u_recurse("inf"),
      perms => u_m("755"),
      action => u_immediate;

      "$(plugins_dir)"
      comment => "Always update plugins files on client side",
      handle => "cfe_internal_update_policy_files_update_plugins",
      copy_from => u_rcp("$(plugins_dir)", @(update_def.policy_servers)),
      depth_search => u_recurse("inf"),
      perms => u_m("755"),
      action => u_immediate;

    !am_policy_hub.windows::

      "$(sys.workdir)\modules"
      comment => "Always update modules files on client side (Windows)",
      handle => "cfe_internal_update_policy_files_update_modules_windows",
      copy_from => u_rcp("$(modules_dir)", @(update_def.policy_servers)),
      depth_search => u_recurse("inf"),
      perms => u_m("755"),
      action => u_immediate;

      "$(sys.workdir)\plugins"
      comment => "Always update plugins files on client side (Windows)",
      handle => "cfe_internal_update_policy_files_update_plugins_windows",
      copy_from => u_rcp("$(plugins_dir)", @(update_def.policy_servers)),
      depth_search => u_recurse("inf"),
      perms => u_m("755"),
      action => u_immediate;

    am_policy_hub|validated_updates_ready::  # policy hub should always put masterfiles in inputs in order to check new policy

      "$(inputs_dir)"
      comment => "Copy policy updates from master source on policy server if a new validation was acquired",
      handle => "cfe_internal_update_policy_files_inputs_dir",
      copy_from => u_rcp("$(master_location)", @(update_def.policy_servers)),
      depth_search => u_recurse("inf"),
      file_select  => u_input_files,
      action => u_immediate,
      classes => u_if_repaired("update_report");

    !policy_server.enable_cfengine_enterprise_hub_ha::
      "$(sys.workdir)/policy_server.dat"
      comment => "Copy policy_server.dat file from server",
      handle => "cfe_internal_update_ha_policy_server",
      copy_from => u_rcp("$(sys.workdir)/state/master_hub.dat", @(update_def.policy_servers)),
      action => u_immediate,
      classes => u_if_repaired("replica_failover");  # not needed ?

    !windows::

      "$(dir_bin)/$(agents)"
      comment => "Make sure cfengine binaries have right file permissions",
      handle => "cfe_internal_update_policy_files_dir_bin_agents",
      perms => u_m("755"),
      action => u_immediate;

      "$(dir_bin)/$(optional_agents)"
      comment => "Make sure the optional cfengine binaries have right file permissions",
      handle => "cfe_internal_update_policy_files_sys_workdir_bin_optional",
      perms => u_m("755"),
      action => u_immediate,
      ifvarclass => canonify("have_bindir_$(optional_agents)");

      "$(sys.workdir)/bin"
      comment => "Make sure cfengine binaries have right file permissions",
      handle => "cfe_internal_update_policy_files_sys_workdir_bin",
      perms => u_m("755"),
      depth_search => u_recurse_basedir("inf"),
      ifvarclass => and(strcmp($(sys.workdir), "/var/cfengine")),
      action => u_immediate;

      "$(sys.workdir)/lib"
      comment => "Make sure cfengine libraries have right file permissions",
      handle => "cfe_internal_update_policy_files_sys_workdir_lib",
      perms => u_shared_lib_perms,
      depth_search => u_recurse_basedir("inf"),
      action => u_immediate;

      "/usr/local/sbin/$(agents)"
      comment => "Create symlinks of CFE binaries in /usr/local/sbin",
      handle => canonify("cfe_internal_update_policy_files_sbin_$(agents)"),
      move_obstructions => "true",
      link_from => u_ln_s("$(sys.workdir)/bin/$(agents)");

      "/usr/local/sbin/$(agents).cfsaved"
      comment => "Remove all .cfsaved file extension",
      handle => canonify("cfe_internal_update_policy_files_remove_$(agent)_cfsaved"),
      delete => u_tidy;

    am_policy_hub::

      "$(master_location)/."
      comment => "Make sure masterfiles folder has right file permissions",
      handle => "cfe_internal_update_policy_files_sys_workdir_masterfiles",
      perms => u_m($(update_def.masterfiles_perms_mode)),
      depth_search => u_recurse_basedir("inf"),
      action => u_immediate;

}


body perms u_m(p)
{
      mode  => "$(p)";
}


body perms u_mo(p,o)
{
      mode   => "$(p)";
      owners => {"$(o)"};
}


body perms u_shared_lib_perms
{
    !hpux::
      mode => "0644";
    hpux::
      mode => "0755"; # Mantis 1114, Redmine 1179
}


body file_select u_cf3_files
{
      leaf_name => { "cf-.*" };
      file_result => "leaf_name";
}


body file_select u_input_files
{
      leaf_name => { @(update_def.input_name_patterns) };
      file_result => "leaf_name";
}


body copy_from u_rcp(from,server)
{
      source      => "$(from)";
      compare     => "digest";
      trustkey    => "false";

    !am_policy_hub::

      servers => { "$(server)" };

    cfengine_internal_encrypt_transfers::
      encrypt => "true";

    cfengine_internal_purge_policies::
      purge => "true";
}


body copy_from u_cp(from)
{
      source  => "$(from)";
      compare => "digest";
}


body copy_from u_cp_nobck(from)
{
      source      => "$(from)";
      compare     => "digest";
      copy_backup => "false";
}


body action u_immediate
{
      ifelapsed => "0";
}


body depth_search u_recurse(d)
{
      depth => "$(d)";
      exclude_dirs => { "\.svn", "\.git", "git-core" };
}


body depth_search u_recurse_basedir(d)
{
      include_basedir => "true";
      depth => "$(d)";
      exclude_dirs => { "\.svn", "\.git", "git-core" };
}


body classes u_if_repaired(x)
{
      promise_repaired => { "$(x)" };
}


body classes u_if_repaired_then_cancel(y)
{
      cancel_repaired => { "$(y)" };
}


body classes u_if_else(yes,no)
{
      promise_repaired => { "$(yes)" };
      repair_failed    => { "$(no)" };
      repair_denied    => { "$(no)" };
      repair_timeout   => { "$(no)" };
}


body contain u_in_shell
{
      useshell => "true";
}


body contain u_in_shell_and_silent
{
      useshell => "true";
      no_output => "true";
}


body contain u_postgres
{
  useshell   => "useshell";
  exec_owner => "cfpostgres";
  chdir      => "/tmp";
  no_output  => "true";
}


body action u_ifwin_bg
{
    windows::
      background => "true";
}


body service_method u_bootstart
{
      service_autostart_policy => "boot_time";
}


body contain u_silent_in_dir(s)
{
      chdir => "$(s)";
      no_output => "true";
}


body link_from u_ln_s(x)
{
      link_type => "symlink";
      source => "$(x)";
      when_no_source => "force";
}


body delete u_tidy
{
      dirlinks => "delete";
      rmdirs   => "true";
}
cfe_internal_update_processes

This step manages the running processes, ensuring cf-execd and cf-serverd and cf-monitord are running and doing some other tasks.

cfe_internal_update_bins

This step does a self-update of CFEngine. See the Enterprise documentation for details; this functionality is unsupported in CFEngine Community.

update.cf configuration

input_name_patterns

Change this variable to add more file extensions to the list copied from the policy server. By default this is a pretty sparse list.

masterfiles_perms_mode

Usually you want to leave this at 0600 meaning the inputs will be readable only by their owner.

cfengine_internal_masterfiles_update

Off by default.

Turn this on (set to any) to auto-deploy policies on the policy server, it has no effect on clients. See Version Control and Configuration Policy for details on how to use it.

This may result in DATA LOSS.

cfengine_internal_encrypt_transfers

Off by default.

Turn this on (set to any) to encrypt your policy transfers.

Note it has a duplicate in def.cf, see below. If they are not synchronized, you will get unexpected behavior.

cfengine_internal_purge_policies

Off by default.

Turn this on (set to any) to delete any files in your $(sys.inputdir) that are not in the policy server's masterfiles.

This may result in DATA LOSS.

Note it has a duplicate in def.cf, see below. If they are not synchronized, you will get unexpected behavior.

cfengine_internal_preserve_permissions

Off by default.

Turn this on (set to any) to preserve the permissions of the policy server's masterfiles when they are copied.

This may result in FUNCTIONALITY LOSS if your scripts lose their exec bits unexpectedly

Note it has a duplicate in def.cf, see below. If they are not synchronized, you will get unexpected behavior.

def.cf

After update.cf is configured, you can configure the main def.cf policy.

This file is included by the main promises.cf and you can run that with cf-agent -KI -f ./promises.cf but as before, make sure you understand what this command does before using it.

Keep referring to def.cf as you read this.

Implementation (warning: advanced usage):

bundle common def

{

  vars:

    any::

      # Begin change

      # Your domain name, for use in access control

      "domain"  string => "$(sys.domain)", # this default may be inaccurate!
      comment => "Define a global domain for all hosts",
      handle => "common_def_vars_domain";

      # Mail settings used by body executor control found in controls/cf_execd.cf
      "mailto" string => "root@$(def.domain)";
      "mailfrom" string => "root@$(sys.uqhost).$(def.domain)";
      "smtpserver" string => "localhost";

      # List here the IP masks that we grant access to on the server

      "acl"     slist => {
                           # Allow everything in my own domain.

                           # Note that this:
                           # 1. requires def.domain to be correctly set
                           # 2. will cause a DNS lookup for every access
                           ".*$(def.domain)",

                           # Assume /16 LAN clients to start with
                           "$(sys.policy_hub)/16",

                           #  "2001:700:700:3.*",
                           #  "217.77.34.18",
                           #  "217.77.34.19",
      },
      comment => "Define an acl for the machines to be granted accesses",
      handle => "common_def_vars_acl";

      # Out of the hosts in allowconnects, trust new keys only from the
      # following ones.  This is open by default for bootstrapping.

      "trustkeysfrom" slist => {
                                 # COMMENT THE NEXT LINE OUT AFTER ALL MACHINES HAVE BEEN BOOTSTRAPPED.
                                 "0.0.0.0/0", # allow any IP
      },
      comment => "Define from which machines keys can be trusted";

      # End change #

  cfengine_3_4|cfengine_3_5::
      "dir_masterfiles" string => translatepath("$(sys.workdir)/masterfiles"),
      comment => "Define masterfiles path",
      handle => "common_def_vars_dir_masterfiles_backport";

  !cfengine_3_4.!cfengine_3_5::
      "dir_masterfiles" string => translatepath("$(sys.masterdir)"),
      comment => "Define masterfiles path",
      handle => "common_def_vars_dir_masterfiles";

      "dir_reports"     string => translatepath("$(sys.workdir)/reports"),
      comment => "Define reports path",
      handle => "common_def_vars_dir_reports";

      "dir_software"    string => translatepath("$(sys.workdir)/master_software_updates"),
      comment => "Define software path",
      handle => "common_def_vars_dir_software";

      "dir_bin"         string => translatepath("$(sys.bindir)"),
      comment => "Define binary path",
      handle => "common_def_vars_dir_bin";

      "dir_modules"     string => translatepath("$(sys.workdir)/modules"),
      comment => "Define modules path",
      handle => "common_def_vars_dir_modules";

      "dir_plugins"     string => translatepath("$(sys.workdir)/plugins"),
      comment => "Define plugins path",
      handle => "common_def_vars_dir_plugins";

    cfengine_3_4|cfengine_3_5::
      "cf_apache_user" string => "apache",
      comment => "User that CFEngine Enterprise webserver runs as",
      handle => "common_def_vars_cf_apache_user";

      "cf_apache_group" string => "apache",
      comment => "Group that CFEngine Enterprise webserver runs as",
      handle => "common_def_vars_cf_apache_group";

    !cfengine_3_4.!cfengine_3_5::
      "cf_apache_user" string => "cfapache",
      comment => "User that CFEngine Enterprise webserver runs as",
      handle => "common_def_vars_cf_cfapache_user";

      "cf_apache_group" string => "cfapache",
      comment => "Group that CFEngine Enterprise webserver runs as",
      handle => "common_def_vars_cf_cfapache_group";

      solaris::
      "cf_runagent_shell"
        string  => "/usr/bin/sh",
        comment => "Define path to shell used by cf-runagent",
        handle  => "common_def_vars_solaris_cf_runagent_shell";

      !(windows|solaris)::
      "cf_runagent_shell"
        string  => "/bin/sh",
        comment => "Define path to shell used by cf-runagent",
        handle  => "common_def_vars_cf_runagent_shell";

    any::
      "base_log_files" slist =>
      {
        "$(sys.workdir)/cf3.$(sys.uqhost).runlog",
        "$(sys.workdir)/promise_summary.log",
      };

      "enterprise_log_files" slist =>
      {
        "$(sys.workdir)/cf_notkept.log",
        "$(sys.workdir)/cf_repair.log",
        "$(sys.workdir)/state/cf_value.log",
        "$(sys.workdir)/outputs/dc-scripts.log",
      };

      "hub_log_files" slist =>
      {
        "$(sys.workdir)/httpd/logs/access_log", # Mission Portal
        "$(sys.workdir)/httpd/logs/error_log", # Mission Portal
      };

      "max_client_history_size" -> { "cf-hub", "CFEngine Enterprise" }
        int => "50M",
        comment => "The threshold of report diffs which will trigger purging of
                    diff files.";

    enterprise.!am_policy_hub::
      # CFEngine's own log files
      "cfe_log_files" slist => { @(base_log_files), @(enterprise_log_files) };

    enterprise.am_policy_hub::
      # CFEngine's own log files
      "cfe_log_files" slist => { @(base_log_files), @(enterprise_log_files), @(hub_log_files) };

      # Number of days to keep scheduled reports before purging
      "purge_scheduled_reports_older_than_days" ->  { "Mission Portal", "CFEngine Enterprise" }
        int => "30";

    !enterprise::
      # CFEngine's own log files
      "cfe_log_files" slist => { @(base_log_files) };

    any::
      "cfe_log_dirs" slist =>
      {
        "$(sys.workdir)/outputs",
        "$(sys.workdir)/reports",
      };

    # enable_cfengine_enterprise_hub_ha is defined below
    # Disabled by default

    enable_cfengine_enterprise_hub_ha::
      "policy_servers" slist => {"$(sys.policy_hub)", @(ha_def.ips)};

    !enable_cfengine_enterprise_hub_ha::
      "policy_servers" slist => {"$(sys.policy_hub)"};


  classes:

      ### Enable special features policies. Set to "any" to enable.

      # Auto-load files in "services/autorun" and run bundles tagged "autorun".
      # Disabled by default!
      "services_autorun" expression => "!any";

      # Internal CFEngine log files rotation
      "cfengine_internal_rotate_logs" expression => "any";

      # Disable agent email output
      "cfengine_internal_agent_email" expression => "any";

      # Transfer policies and binaries with encryption
      # you can also request it from the command line with
      # -Dcfengine_internal_encrypt_transfers

      # NOTE THAT THIS CLASS ALSO NEEDS TO BE SET IN update.cf

      "cfengine_internal_encrypt_transfers" expression => "!any";

      # Purge policies that don't exist on the server side.
      # you can also request it from the command line with
      # -Dcfengine_internal_purge_policies

      # NOTE THAT THIS CLASS ALSO NEEDS TO BE SET IN update.cf

      "cfengine_internal_purge_policies" expression => "!any";

      # Class defining which versions of cfengine are (not) supported
      # by this policy version.
      # Also note that this policy will only be run on enterprise policy_server
      "postgresql_maintenance_supported" expression => "policy_server.enterprise.!(cfengine_3_4|cfengine_3_5)";

      # Allow the hub to edit sudoers in order for the Apache user to
      # run passwordless sudo cf-runagent. Enable this if you want the
      # Mission Portal to be able to troubleshoot failed Design Center
      # sketch activations on a host.
      "cfengine_internal_sudoers_editing_enable" expression => "!any";

      # Class defining which versions of cfengine are (not) supported
      # by this policy version.
      # Also note that this policy will only be run on enterprise policy_server
      "postgresql_maintenance_supported"
        expression => "(policy_server.enterprise.!cfengine_3_5.!enable_cfengine_enterprise_hub_ha)|(policy_server.enterprise.enable_cfengine_enterprise_hub_ha.hub_active)";

      # This class is for PosgreSQL maintenance
      # pre-defined to every Sunday at 2 a.m.
      # This can be changed later on.

      "postgresql_full_maintenance" expression => "postgresql_maintenance_supported.Sunday.Hr02.Min00_05";

      # Vacuum monitoring_mg table every day (except Sunday, when vacuum is run on entire db)
      # Required only by CFEngine Enterprise Hub 3.6.0 and 3.6.1
      "postgresql_monitoring_maintenance" expression => "postgresql_maintenance_supported.!Sunday.Hr02.Min00_05.(cfengine_3_6_0|cfengine_3_6_1)";

      # Run vacuum job on database
      # pre-defined to every night except Sunday when full cleanup is executed.
      "postgresql_vacuum" expression => "postgresql_maintenance_supported.!Sunday.Hr02.Min00_05";

      # Enable CFEngine Enterprise HA Policy
      "enable_cfengine_enterprise_hub_ha" expression => "!any";
      #"enable_cfengine_enterprise_hub_ha" expression => "enterprise_edition";

      # Enable cleanup of agent report diffs when they exceed
      # `def.max_client_history_size`
      "enable_cfe_internal_cleanup_agent_reports" -> { "cf-hub", "CFEngine Enterprise" }
        expression => "enterprise_edition",
        comment => "If reports are not collected for an extended period of time
                    the disk may fill up or cause additional collection
                    issues.";

}

bundle common inventory_control
{
  vars:
      "dmidecoder" string => "/usr/sbin/dmidecode";
      "lldpctl_exec" string => "/usr/bin/lldpctl";
      "lsb_exec" string => "/usr/bin/lsb_release";
      "mtab" string => "/etc/mtab";
      "proc" string => "/proc";

  classes:
      # setting this disables all the inventory modules except package_refresh
      "disable_inventory" expression => "!any";

      # disable specific inventory modules below

      # by default disable the LSB inventory if the general inventory
      # is disabled or the binary is missing.  Note that the LSB
      # binary is typically not very fast.
      "disable_inventory_lsb" expression => "disable_inventory";
      "disable_inventory_lsb" not => fileexists($(lsb_exec));

      # by default disable the dmidecode inventory if the general
      # inventory is disabled or the binary does not exist.  Note that
      # typically this is a very fast binary.
      "disable_inventory_dmidecode" expression => "disable_inventory";
      "disable_inventory_dmidecode" not => fileexists($(dmidecoder));

      # by default disable the LLDP inventory if the general inventory
      # is disabled or the binary does not exist.  Note that typically
      # this is a reasonably fast binary but still may require network
      # I/O.
      "disable_inventory_LLDP" expression => "disable_inventory";
      "disable_inventory_LLDP" not => fileexists($(lldpctl_exec));

      # by default run the package inventory refresh every time, even
      # if disable_inventory is set
      "disable_inventory_package_refresh" expression => "!any";

      # by default disable the mtab inventory if the general inventory
      # is disabled or $(mtab) is missing.  Note that this is very
      # fast.
      "disable_inventory_mtab" expression => "disable_inventory";
      "disable_inventory_mtab" not => fileexists($(mtab));

      # by default disable the fstab inventory if the general
      # inventory is disabled or $(sys.fstab) is missing.  Note that
      # this is very fast.
      "disable_inventory_fstab" expression => "disable_inventory";
      "disable_inventory_fstab" not => fileexists($(sys.fstab));

      # by default disable the proc inventory if the general
      # inventory is disabled or /proc is missing.  Note that
      # this is typically fast.
      "disable_inventory_proc" expression => "disable_inventory";
      "disable_inventory_proc" not => isdir($(proc));

      # by default don't run the CMDB integration every time, even if
      # disable_inventory is not set
      "disable_inventory_cmdb" expression => "any";

  reports:
    verbose_mode.disable_inventory::
      "$(this.bundle): All inventory modules disabled";
    verbose_mode.!disable_inventory_lsb::
      "$(this.bundle): LSB module enabled";
    verbose_mode.!disable_inventory_dmidecode::
      "$(this.bundle): dmidecode module enabled";
    verbose_mode.!disable_inventory_LLDP::
      "$(this.bundle): LLDP module enabled";
    verbose_mode.!disable_inventory_mtab::
      "$(this.bundle): mtab module enabled";
    verbose_mode.!disable_inventory_fstab::
      "$(this.bundle): fstab module enabled";
    verbose_mode.!disable_inventory_proc::
      "$(this.bundle): proc module enabled";
    verbose_mode.!disable_inventory_package_refresh::
      "$(this.bundle): package_refresh module enabled";
    verbose_mode.!disable_inventory_cmdb::
      "$(this.bundle): CMDB module enabled";
}

How it works

def.cf has some crucial settings used by the rest of CFEngine. It's expected that users will edit it but won't normally change the rest of the masterfiles except in services or if they know it's necessary.

This is a simple CFEngine policy, so read on for configuring it.

def.cf configuration

domain

Set your domain to the right value. By default it's used for mail and to deduce your file access ACLs.

acl

The acl is crucial. This is used by every host, not just the policy server. Make sure you only allow hosts you want to allow.

trustkeysfrom

trustkeysfrom tells the policy server from which IPs it should accept connections even if the host's key is unknown, trusting it at connect time. This is only useful to be open during for bootstrapping these hosts. As the comments say, empty it after your hosts have been bootstrapped to avoid unpleasant surprises.

services_autorun

Off by default.

Turn this on (set to any) to auto-load files in services/autorun and run bundles found that are tagged autorun. Here's a simple example of such a bundle in services/autorun/hello.cf:

bundle agent hello_world_autorun
{
  meta:
      "tags" slist => { "autorun" };

  reports:
    verbose_mode::
      "$(this.bundle): Hello, this is an automatically loaded bundle";
}
cfengine_internal_rotate_logs

On by default. Rotates CFEngine's own logs. Here is the cfe_internal_log_rotation bundle implementation:

bundle agent cfe_internal_log_rotation
{

  methods:

    cfengine_internal_rotate_logs::
      # CFEngine generates internal log files that need to be rotated.
      # Have a look at def.cf to enable rotation of these files
      "rotate_promise_summary" usebundle => logrotate("@(def.cfe_log_files)", "1m", "10"),
                               comment   => "Rotate log files once their size reach 1MB, keep 10 versions";

      "rotate_outputs"         usebundle => prunedir("@(def.cfe_log_dirs)", "30"),
                               comment   => "Delete outputs/* files older than 30 days";
}
cfengine_internal_agent_email

On by default. Enables agent email output from cf-execd.

cfengine_internal_encrypt_transfers

Duplicate of the one in update.cf. They should be set in unison or you will get unexpected behavior.

cfengine_internal_purge_policies

Duplicate of the one in update.cf. They should be set in unison or you will get unexpected behavior.

cfengine_internal_preserve_permissions

Duplicate of the one in update.cf. They should be set in unison or you will get unexpected behavior.

cfengine_internal_sudoers_editing_enable

Off by default. Only used on the CFEngine Enterprise hub.

Turn this on (set to any) to allow the hub to edit sudoers in order for the Apache user to run passwordless sudo cf-runagent (part of Mission Portal troubleshooting).

def.cf inventory control

The inventory is a cool new feature in 3.6. You can disable pieces of it (inventory modules) or the whole thing if you wish.

disable_inventory

This class is off by default (meaning the inventory is on by default). Here's the master switch to disable all inventory modules.

disable_inventory_lsb

LSB is the Linux Standard Base, see https://wiki.linuxfoundation.org/en/LSB

By default, this class is turned off (and the module is on) if the LSB executable /usr/bin/lsb_release can be found. This inventory module will populate inventory reports and variables for you with LSB details. For details, see LSB

disable_inventory_dmidecode

By default, this class is turned off (and the module is on) if the executable /usr/sbin/dmidecode can be found. This inventory module will populate inventory reports and variables for you. For details, see DMI decoding

disable_inventory_LLDP

LLDP is a protocol for Link Layer Discovery. See http://en.wikipedia.org/wiki/Link_Layer_Discovery_Protocol

By default, this class is turned off (and the module is on) if the executable /usr/bin/lldpctl can be found. This inventory module will populate variables for you. For details, see LLDP

disable_inventory_package_refresh

By default, this class is turned off (and the module is on). This inventory module will populate the installed packages for you. On CFEngine Enterprise, the available packages will also be populated.

disable_inventory_mtab

By default, this class is turned off (and the module is on) if /etc/mtab exists. This inventory module will populate variables for you based on the mounted filesystems. For details, see mtab

disable_inventory_fstab

By default, this class is turned off (and the module is on) if $(sys.fstab) (usually /etc/fstab or /etc/vfstab) exists. This inventory module will populate variables for you based on the defined filesystems. For details, see fstab

disable_inventory_proc

By default, this class is turned off (and the module is on) if /proc is a directory. This inventory module will populate variables for you from some of the contents of /proc. For details, see procfs

disable_inventory_cmdb

By default, this class is turned on (and the module is off).

Turn this on (set to any) to allow each client to load a me.json file from the server and load its contents. For details, see CMDB

promises.cf

How it works

promises.cf is your main run file. Keep referring to your installation's promises.cf as you read this.

promises.cf is the first file that cf-agent with no arguments will try to look for. So whenever you see cf-agent with no flile parameter, read it as "run my promises.cf".

It should contain all of the basic configuration settings, including a list of other files to include. In normal operation, it must also have a bundlesequence.

promises.cf configuration

bundlesequence

The bundlesequence acts like the 'genetic makeup' of the configuration. Edit the bundlesequence to add any bundles you have defined, or are pre-defined. Consider using the services_autorun facility so you don't have to edit this setting at all.

BEWARE THAT ONLY VALID (KNOWN) BUNDLES CAN BE ADDED.

By default, the inventory modules, then internal hub modules, then Design Center sketches, then the autorun services, and finally internal management bundles are in the bundlesequence.

In a large configuration, you might want to have a different bundlesequence for different classes of host, so that you can build a complete system like a check-list from different combinations of building blocks. You can construct different lists by composing them from other lists, or you can use methods promises as an alternative for composing bundles for different classes. This is an advanced topic and a risky area (if you get it wrong, your policies will not validate) so make sure you test your changes carefully!

inputs

In order to find bundles, CFEngine needs to know where to look. This list defines what files are needed. Note there are several dynamic entries here, coming from other bundles. CFEngine will keep evaluating the inputs and bundlesequence until all the bundles are found and resolved.

Make sure to add any of your own services files here if you don't use the services_autorun facility, to ensure the bundles in them are found.

failsafe.cf

The failsafe.cf file ensures that your system can survive errors and can upgrade gracefully to new versions even when mistakes are made. It's literally a failsafe if promises.cf and update.cf should fail.

This file is generated during the bootstrapping process, and should normally never be changed. The only job of failsafe.cf is to execute the update bundle in a “standalone” context should there be a syntax error somewhere in the main set of promises. In this way, if a client machine's policies are ever corrupted after downloading erroneous policy from a server, that client will have a failsafe method for downloading a corrected policy once it becomes available on the server. Note that by “corrupted” and “erroneous” we typically mean “broken via administrator error” - mistakes happen, and the failsafe.cf file is CFEngine's way of being prepared for that eventuality.

If you ever change failsafe.cf (or when you upgrade CFEngine), make sure the old and the new CFEngine can successfully parse and execute this file. If not, you risk losing control of your system (that is, if CFEngine cannot successfully execute this policy file, it has no failsafe/fallback mechanism for distributing new policy files).

Some general rules (but again, note you can completely break your CFEngine installation by editing failsafe.cf):

  • Upgrade the software first, then add new features to the configuration.
  • Never use advanced features in the failsafe or update file.
  • Avoid using library code (including any bodies from stdlib.cf or the files it includes). Copy/paste any bodies you need using a unique name that does not collide with a name in library (we recommend simply adding the prefix “u_”). This may mean that you create duplicate functionality, but that is okay in this case to ensure a 100% functioning standalone update process). The promises which manage the update process should not have any dependencies on any other files.

CFEngine will fail-over to the failsafe.cf configuration if it is unable to read or parse the contents successfully. That means that any syntax errors you introduce (or any new features you utilize in a configuration) will cause a fail-over, because the parser will not be able to interpret the policy. If the failover is due to the use of new features, they will not parse until the software itself has been updated (so we recommend that you always update CFEngine before updating policy to use new features). If you accidentally cause a bad (i.e., unparseable) policy to be distributed to client machines, the failsafe.cf policy on those machines will run (and will eventually download a working policy, once you fix it on the policy host).

Further structure

  • cfe_internal: internal CFEngine policies you shouldn't modify or you will get unexpected behavior
  • controls: configuration of components, e.g. the cf-agent or cf-serverd, beyond what def.cf can offer
  • def.cf: defaults you can and should configure, see above
  • inventory: inventory modules (loaded before anything else to discover facts about the system) live here; see above
  • lib: main library directory. You'll see 3.5 and 3.6 and 3.7 under it. These are the supported versions for masterfiles backwards compatibility.
  • promises.cf: main policy, you will need to configure this, see above
  • services: your site's policies go here
  • services_autorun: see above
  • sketches: Design Center installations use this; do not touch or you will get unexpected behavior
  • update and update.cf: functionality for updating inputs and CFEngine itself, see above. You shouldn't modify files under update or you will get unexpected behavior.

cf_promises_validated

Several CFEngine components that read policy (e.g. cf-agent, cf-execd, cf-serverd) run cf-promises to validate the syntax of their input files before actually running the policy. To illustrate this, if cf-promises runs every 5 minutes then there will be 12 checks occurring every hour, 24 hours a day, 7 days a week -- a total of 2016 possible validation checks. Each of those individual validation sessions can take some number of seconds to perform depending on the system, scale, circumstances and configuration.

Starting with CFEngine 3.1.2, the outcome of every run of cf-promises was cached, which lets agents skip the validation of input files that have not changed since the previous run.

Starting with CFEngine 3.6, outcome on both hosts and hubs is stored in the file $(sys.workdir)/masterfiles/cf_promises_validated (usually sys.workdir is /var/cfengine). The file can be created by cf-agent after it has successfully verified the policy with cf-promises. The file can also be created by a user with cf-promises -T DIRECTORY which is useful for validating an entire directory.

When the hash content of any file under WORKDIR/inputs changes, and validates to be syntactically correct, then a timestamp in cf_promises_validated is updated. If not, the run of cf-promises is skipped and, at the same time, the cf-execd, cf-serverd and cf-monitord daemons will not reload the policy unless cf_promises_validated has an updated timestamp, which cf-agent will normally take care of.

In the default installation, the masterfiles are populated automatically on the policy server and you can even auto-deploy them from a version control system.

You should configure the masterfiles as described above. Leaving them at their default settings may expose your masterfiles or worse, especially the cf-serverd ACL settings. If you are not sure of the terms used below or what it all means, come back to this page after you've learned about writing policy and the CFEngine syntax.

CFEngine 3 Inventory Modules

The CFEngine 3 inventory modules are pieces of CFEngine policy that are loaded and used by the promises.cf mechanism in order to inventory the system.

CFEngine Enterprise has specific functionality to show and use inventory data, but users of the Community Version can use them as well locally on each host.

How It Works

The inventory modules are called in promises.cf:

body common control
{
      bundlesequence => {
                        # Common bundle first (Best Practice)
                          inventory_control,
                          @(inventory.bundles),
                          ...

As you see, this calls the inventory_control bundle, and then each bundle in the list inventory.bundles. That list is built in the top-level common inventory bundle, which will load the right things for some common cases. The any.cf inventory module is always loaded; the rest are loaded if they are appropriate for the platform. For instance, Debian systems will load debian.cf and linux.cf and lsb.cf but may load others as needed.

The effect for users is that the right inventory modules will be loaded and evaluated.

The inventory_control bundle lives in def.cf and defines what inventory modules should be disabled. You can simply set disable_inventory to avoid the whole system, or you can look for the disable_inventory_xyz class to disable module xyz.

Any inventory module works the same way, by doing some discovery work and then tagging its classes and variables with the report or inventory tags. For example:

  vars:
      "ports" slist => { @(mon.listening_ports) },
      meta => { "inventory", "attribute_name=Ports listening" };

This defines a reported attribute "Ports listening" which contains a list of strings representing the listening ports. More on this in a second.

Your Very Own Inventory Module

The good news is, writing an inventory module is incredibly easy.

They are just CFEngine bundles. You can see a simple one that collects the listening ports in any.cf:

bundle agent cfe_autorun_inventory_listening_ports
# @brief Inventory the listening ports
#
# This bundle uses `mon.listening_ports` and is always enabled by
# default, as it runs instantly and has no side effects.
{
  vars:
      "ports" slist => { @(mon.listening_ports) },
      meta => { "inventory", "attribute_name=Ports listening" };
}

Well, the slist copy is a CFEngine detail (we get the listening ports from the monitoring daemon), so just assume that the data is correct. What's important is the second line that starts with meta. That defines metadata for the promise that CFEngine will use to determine that this data is indeed inventory data and should be reported to the CFEngine Enterprise Hub.

That's it. Really. The comments are optional but nice to have. You don't have to put your new bundle in a file under the inventory directory, either. The variables and classes can be declared anywhere as long as they have the right tags. So you can use the services directory or whatever else makes sense to you.

CFEngine Enterprise vs. Community

In CFEngine Enterprise, the reported data is aggregated in the hub and reported across the whole host population.

In CFEngine Community, users can use the classesmatching() and variablesmatching() functions to collect all the inventory variables and classes and report them in other ways.

Implementation Best Practice for CFEngine Enterprise

It is important that inventory variables and classes are continually defined. Only inventory variables and classes defined during the last reported run are available for use by the inventory reporting interface.

Inventory items that change frequently can create a burden on the Enterprise reporting infrastructure. Generally, inventory attributes should change infrequently.

If you wish to inventory attributes that frequently change or are expensive to discover consider implementing a sample interval and caching mechanism.

What Modules Are Available?

As soon as you use the promises.cf provided in the parent directory, quite a few inventory modules will be enabled (if appropriate for your system). Here's the list of modules and what they provide. Note they are all enabled by code in def.cf as explained above.

LSB

  • lives in: lsb.cf
  • applies to: LSB systems (most Linux distributions, basically)
  • runs: lsb_release -a
  • sample data:
Distributor ID: Ubuntu
Description:    Ubuntu 14.04 LTS
Release:    14.04
Codename:   trusty
  • provides:
    • classes lsb_$(os), lsb_$(os)_$(release), lsb_$(os)_$(codename)
    • variables: inventory_lsb.os (Distributor ID), inventory_lsb.codename, inventory_lsb.release, inventory_lsb.flavor, inventory_lsb.description
  • implementation:
bundle agent inventory_lsb
{
  classes:
      "have_lsb" expression => fileexists($(lsb_exec));

      "_inventory_lsb_found" expression => regcmp("^[1-9][0-9]*$", $(dim)),
                                  scope => "namespace";

    _inventory_lsb_found::
      "lsb_$(os)" expression => "any",
      comment => "LSB Distributor ID",
      depends_on => { "inventory_lsb_os" },
      scope => "namespace",
      meta => { "inventory", "attribute_name=none" };

      "lsb_$(os)_$(release)" expression => "any",
      comment => "LSB Distributor ID and Release",
      depends_on => { "inventory_lsb_os", "inventory_lsb_release" },
      scope => "namespace",
      meta => { "inventory", "attribute_name=none" };

      "lsb_$(os)_$(codename)" expression => "any",
      comment => "LSB Distributor ID and Codename",
      depends_on => { "inventory_lsb_os", "inventory_lsb_codename" },
      scope => "namespace",
      meta => { "inventory", "attribute_name=none" };

  vars:
      "lsb_exec" string => "$(inventory_control.lsb_exec)";

    have_lsb::
      "data" string => execresult("$(lsb_exec) -a", "noshell");
      "dim" int => parsestringarray(
                                     "lsb",
                                     $(data),
                                     "\s*#[^\n]*",
                                     "\s*:\s+",
                                     "15",
                                     "4095"
      );

    _inventory_lsb_found::
      "lsb_keys" slist => getindices("lsb");

      "os" string => canonify("$(lsb[Distributor ID][1])"),
      handle => "inventory_lsb_os",
      comment => "LSB-provided OS name",
      meta => { "inventory", "attribute_name=none" };

      "codename" string => canonify("$(lsb[Codename][1])"),
      handle => "inventory_lsb_codename",
      comment => "LSB-provided OS code name",
      meta => { "inventory", "attribute_name=none" };

      "release" string => "$(lsb[Release][1])",
      handle => "inventory_lsb_release",
      comment => "LSB-provided OS release",
      meta => { "inventory", "attribute_name=none" };

      "flavor" string => canonify("$(lsb[Distributor ID][1])_$(lsb[Release][1])"),
      handle => "inventory_lsb_flavor",
      comment => "LSB-provided OS flavor",
      meta => { "inventory", "attribute_name=none" };

      "description" string => "$(lsb[Description][1])",
      handle => "inventory_lsb_description",
      comment => "LSB-provided OS description",
      meta => { "inventory", "attribute_name=none" };

  reports:
    inform_mode._inventory_lsb_found::
      "$(this.bundle): OS = $(os), codename = $(codename), release = $(release), flavor = $(flavor), description = $(description)";
    verbose_mode._inventory_lsb_found::
      "$(this.bundle): got $(dim) LSB keys";
      "$(this.bundle): prepared LSB key $(lsb_keys) = '$(lsb[$(lsb_keys)][1])'";
}
  • sample output:
% cf-agent -KI -binventory_control,inventory_lsb

R: inventory_lsb: OS = Ubuntu, codename = trusty, release = 14.04, flavor = Ubuntu_14_04, description = Ubuntu 14.04 LTS

SUSE

  • lives in: suse.cf
  • applies to: SUSE Linux
  • provides classes: suse_pure and suse_derived
  • implementation:
bundle common inventory_suse
{
  classes:
      "suse_pure" expression => "(sles|sled).!opensuse",
      comment => "pure SUSE",
      meta => { "inventory", "attribute_name=none" };

      "suse_derived" expression => "opensuse.!suse_pure",
      comment => "derived from SUSE",
      meta => { "inventory", "attribute_name=none" };
}

Debian

  • lives in: debian.cf
  • applies to: Debian and its derivatives
  • provides:
    • variables: inventory_debian.mint_release and inventory_debian.mint_codename
    • classes: debian_pure, debian_derived, linuxmint, lmde, linuxmint_$(mint_release), linuxmint_$(mint_codename), $(mint_codename)
  • implementation:
bundle common inventory_debian
{
  vars:
    has_lsb_release::
      "lsb_release_info" string => readfile("/etc/lsb-release","256"),
      comment => "Read more OS info" ;

    has_etc_linuxmint_info::
      "linuxmint_info"  string => readfile("/etc/linuxmint/info","1024"),
      comment => "Read Linux Mint specific info" ;

      "lm_info_count"
      int => parsestringarray("mint_info", # array to populate
                              "$(linuxmint_info)", # data to parse
                              "\s*#[^\n]*",        # comments
                              "=",                 # split
                              100,                 # maxentries
                              2048) ;              # maxbytes

      "mint_release" string  => "$(mint_info[RELEASE][1])" ;
      "mint_codename" string => "$(mint_info[CODENAME][1])" ;

  classes:
    any::
      "debian_derived_evaluated"
      scope => "bundle",
      or => { "has_os_release", "has_lsb_release", "has_etc_linuxmint_info" } ;

      "linuxmint"
      expression => "has_etc_linuxmint_info",
      comment => "this is a Linux Mint system, of some sort",
      meta => { "inventory", "attribute_name=none" } ;

    has_lsb_release::
      "linuxmint"
      expression => regcmp("(?ms).*^DISTRIB_ID=LinuxMint$.*", "$(lsb_release_info)"),
      comment => "this is a Linux Mint system, of some sort",
      meta => { "inventory", "attribute_name=none" } ;

    linuxmint.has_os_release::
      "lmde"
      expression => regcmp('(?ms).*^NAME="Linux Mint LMDE"$.*', "$(inventory_linux.os_release_info)"),
      comment => "this is a Linux Mint Debian Edition",
      meta => { "inventory", "attribute_name=none", "derived-from=inventory_linux.os_release_info" } ;

    linuxmint.has_lsb_release::
      "lmde"
      expression => regcmp('(?ms).*^DISTRIB_DESCRIPTION="LMDE.*', "$(lsb_release_info)"),
      comment => "this is a Linux Mint Debian Edition",
      meta => { "inventory", "attribute_name=none", "derived-from=inventory_debian.lsb_release_info" } ;

    has_etc_linuxmint_info::
      "lmde"
      expression => regcmp('(?ms).*^DESCRIPTION="LMDE.*',"$(linuxmint_info)"),
      comment => "this is a Linux Mint Debian Edition",
      meta => { "inventory", "attribute_name=none", "derived-from=inventory_debian.linuxmint_info" } ;

    debian_derived_evaluated.has_etc_linuxmint_info.!lmde::
      # These need to be evaluated only after debian_derived_evaluated is defined
      # to ensure that the mint_info array has been evaluated as well.
      # Failing to do that will create meaningless classes
      # On non-LMDE Mint systems, this will create classes like, e.g.:
      # linuxmint_14, nadia, linuxmint_nadia
      "linuxmint_$(mint_release)"  expression => "any",
      meta => { "inventory", "attribute_name=none" } ;

      "$(mint_codename)"           expression => "any",
      meta => { "inventory", "attribute_name=none" } ;

      "linuxmint_$(mint_codename)" expression => "any",
      meta => { "inventory", "attribute_name=none" } ;

    debian_derived_evaluated::
      "debian_pure" expression => "debian.!(ubuntu|linuxmint)",
      comment => "pure Debian",
      meta => { "inventory", "attribute_name=none" };

      "debian_derived" expression => "debian.!debian_pure",
      comment => "derived from Debian",
      meta => { "inventory", "attribute_name=none" };

    any::
      "has_lsb_release" expression => fileexists("/etc/lsb-release"),
      comment => "Check if we can get more info from /etc/lsb-release";

      "has_etc_linuxmint_info" expression => fileexists("/etc/linuxmint/info"),
      comment => "If this is a Linux Mint system, this *could* be available";

}

Red Hat

  • lives in: redhat.cf
  • applies to: Red Hat and its derivatives
  • provides classes: redhat_pure, redhat_derived
  • implementation:
bundle common inventory_redhat
{
  classes:
      "redhat_pure" expression => "redhat.!centos.!oracle",
      comment => "pure Red Hat",
      meta => { "inventory", "attribute_name=none" };

      "redhat_derived" expression => "redhat.!redhat_pure",
      comment => "derived from Red Hat",
      meta => { "inventory", "attribute_name=none" };
}

Windows

  • lives in: windows.cf

Mac OS X

  • lives in: macos.cf

Generic (unknown OS)

  • lives in: generic.cf (see any.cf for generally applicable inventory modules)

LLDP

  • lives in: any.cf
  • runs inventory_control.lldpctl_exec through a Perl filter
  • provides variables: cfe_autorun_inventory_LLDP.K for each K returned by the LLDB executable
  • implementation:
bundle agent cfe_autorun_inventory_LLDP
{
  classes:
      "disable_inventory_LLDP" not => fileexists($(inventory_control.lldpctl_exec));

  commands:
    !disable_inventory_LLDP::
      "$(inventory_control.lldpctl_exec) | perl -n -e 'my ($k, $v) = m/([^=]+)=(.*)/; $k =~ s/\W/_/g; print \"=$k=$v\";"
      classes => kept_successful_command,
      module => "true";
}

mtab

  • lives in: any.cf
  • parses: /etc/mtab
  • provides classes: have_mount_FSTYPE and have_mount_FSTYPE_MOUNTPOINT
  • implementation:
bundle agent cfe_autorun_inventory_mtab
{
  vars:
    have_mtab::
      "mount_count" int =>  readstringarrayidx("mounts",
                                               $(inventory_control.mtab),
                                               "\s*#[^\n]*",
                                               "\s+",
                                               500,
                                               50000);

      "idx" slist => getindices("mounts");

  classes:
      "have_mtab" expression => fileexists($(inventory_control.mtab));

      # define classes like have_mount_ext4__var for a ext4 /var mount
      "have_mount_$(mounts[$(idx)][2])_$(mounts[$(idx)][1])"
      expression => "any",
      scope => "namespace";

      # define classes like have_mount_ext4 if there is a ext4 mount
      "have_mount_$(mounts[$(idx)][2])"
      expression => "any",
      scope => "namespace";

  reports:
    verbose_mode::
      "$(this.bundle): we have a $(mounts[$(idx)][2]) mount under $(mounts[$(idx)][1])";
}
  • sample output (note this is verbose mode with -v because there's a lot of output):
% cf-agent -Kv -binventory_control,cfe_autorun_inventory_mtab|grep 'cfe_autorun_inventory_mtab: we have'

R: cfe_autorun_inventory_mtab: we have a ext4 mount under /
...
R: cfe_autorun_inventory_mtab: we have a cgroup mount under /sys/fs/cgroup/systemd
R: cfe_autorun_inventory_mtab: we have a tmpfs mount under /run/shm

fstab

  • lives in: any.cf
  • parses: sys.fstab
  • provides classes: have_fs_FSTYPE have_fs_MOUNTPOINT and have_fs_FSTYPE_MOUNTPOINT
  • implementation:
bundle agent cfe_autorun_inventory_fstab
{
  vars:
    have_fstab::
      "mount_count" int =>  readstringarrayidx("mounts",
                                               $(sys.fstab),
                                               "\s*#[^\n]*",
                                               "\s+",
                                               500,
                                               50000);

      "idx" slist => getindices("mounts");

  classes:
      "have_fstab" expression => fileexists($(sys.fstab));

      # define classes like have_fs_ext4__var for a ext4 /var entry
      "have_fs_$(mounts[$(idx)][2])_$(mounts[$(idx)][1])"
      expression => "any",
      scope => "namespace";

      # define classes like have__var for a /var entry
      "have_fs_$(mounts[$(idx)][1])"
      expression => "any",
      scope => "namespace";

      # define classes like have_fs_ext4 if there is a ext4 entry
      "have_fs_$(mounts[$(idx)][2])"
      expression => "any",
      scope => "namespace";

  reports:
    verbose_mode::
      "$(this.bundle): we have a $(mounts[$(idx)][2]) fstab entry under $(mounts[$(idx)][1])";
}
  • sample output (note this is verbose mode with -v because there's a LOT of output):
% cf-agent -Kv -binventory_control,cfe_autorun_inventory_fstab|grep 'cfe_autorun_inventory_fstab: we have'

R: cfe_autorun_inventory_fstab: we have a ext4 fstab entry under /
R: cfe_autorun_inventory_fstab: we have a cifs fstab entry under /backups/load
R: cfe_autorun_inventory_fstab: we have a auto fstab entry under /mnt/cdrom

CMDB

  • lives in: any.cf
  • parses: me.json (which is copied from the policy server; see implementation)
  • provides classes: CLASS for each CLASS found under the classes key in the JSON data
  • provides variables: inventory_cmdb_load.VARNAME for each VARNAME found under the vars key in the JSON data
  • implementation:
bundle agent inventory_cmdb_load(file)
{
  classes:
      "have_cmdb_data" expression => isvariable("cmdb");

      "$(ckeys)" expression => "any", scope => "namespace";

  vars:
      "cmdb" data => readjson($(file), "999999");
      "cmdb_string" string => format("%S", cmdb);

      "bkeys" slist => getindices("cmdb[vars]");
      "vkeys_$(bkeys)" slist => getindices("cmdb[vars][$(bkeys)]");
      "$(vkeys_$(bkeys))" string => nth("cmdb[vars][$(bkeys)]", $(vkeys));

      "ckeys" slist => getindices("cmdb[classes]");

  reports:
    inform_mode.have_cmdb_data::
      "$(this.bundle): Got CMDB data from $(file): $(cmdb_string)";
    verbose_mode.have_cmdb_data::
      "$(this.bundle): Got CMDB key = $(vkeys_$(bkeys)), CMDB value = $((vkeys_$(bkeys)))";
      "$(this.bundle): Got CMDB class = $(ckeys)";
    inform_mode.!have_cmdb_data::
      "$(this.bundle): Could not read the CMDB data from $(file)";
}

DMI decoding

  • lives in: any.cf
  • runs: dmidecode
  • provides variables: cfe_autorun_inventory_dmidecode.dmi[K] for each key K in the dmidecode output
  • implementation:
bundle agent cfe_autorun_inventory_dmidecode
{
  vars:
      "dmidefs" data => parsejson('
{
  "bios-vendor": "BIOS vendor",
  "bios-version": "BIOS version",
  "system-serial-number": "System serial number",
  "system-manufacturer": "System manufacturer",
  "system-version": "System version",
  "processor-version": "CPU model"
}');
  • sample output (sudo is needed to access the DMI):
% sudo /var/cfengine/bin/cf-agent -KI -binventory_control,cfe_autorun_inventory_dmidecode

R: cfe_autorun_inventory_dmidecode: Obtained BIOS vendor = 'Intel Corp.'
R: cfe_autorun_inventory_dmidecode: Obtained BIOS version = 'BLH6710H.86A.0146.2013.1555.1888'
R: cfe_autorun_inventory_dmidecode: Obtained System serial number = ''
R: cfe_autorun_inventory_dmidecode: Obtained System manufacturer = ''
R: cfe_autorun_inventory_dmidecode: Obtained System version = ''
R: cfe_autorun_inventory_dmidecode: Obtained CPU model = 'Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz'

Listening ports

  • lives in: any.cf
  • provides variables: cfe_autorun_inventory_listening_ports.ports as a copy of mon.listening_ports
  • implementation:
bundle agent cfe_autorun_inventory_listening_ports
{
  vars:
      "ports" slist => sort( "mon.listening_ports", "int"),
      meta => { "inventory", "attribute_name=Ports listening" };
}

Disk space

  • lives in: any.cf
  • provides variables: cfe_autorun_inventory_disk.free as a copy of mon.value_diskfree
  • implementation:
bundle agent cfe_autorun_inventory_disk
{
  vars:
    enterprise::
      "free" string => "$(mon.value_diskfree)",
               meta => { "inventory", "attribute_name=Disk free (%)" };
}

Available memory

  • lives in: any.cf
  • provides variables: cfe_autorun_inventory_memory.free as a copy of mon.value_mem_free and cfe_autorun_inventory_memory.total as a copy of mon.value_mem_total
  • implementation:
bundle agent cfe_autorun_inventory_memory
{
  vars:
    enterprise::
      # due to a Windows issue this is set to 0 there for now
      "total" string => ifelse("windows", "0",
                               $(mon.value_mem_total)),
      meta => { "inventory", "attribute_name=Memory size (MB)" };

      "free" string => ifelse("windows", "0",
                              $(mon.value_mem_free)),
      meta => { "report" };
}

Load average

  • lives in: any.cf
  • provides variables: cfe_autorun_inventory_loadaverage.value as a copy of mon.value_loadavg
  • implementation:
bundle agent cfe_autorun_inventory_loadaverage
{
  vars:
    enterprise::
      "value" string => "$(mon.value_loadavg)",
      meta => { "report" };
}

procfs

  • lives in: any.cf
  • parses: consoles, cpuinfo, modules, partitions, version
  • provides variables: cfe_autorun_inventory_proc.console_count, cfe_autorun_inventory_proc.cpuinfo[K] for each CPU info key, cfe_autorun_inventory_proc.paritions[K] for each partition key
  • provides classes: _have_console_CONSOLENAME, have_module_MODULENAME
  • implementation:
bundle agent cfe_autorun_inventory_proc
{
  vars:
      "basefiles" slist => { "consoles", "cpuinfo", "modules", "partitions", "version" };
      "files[$(basefiles)]" string => "$(inventory_control.proc)/$(basefiles)";

    _have_proc_consoles::
      "console_count" int =>  readstringarrayidx("consoles",
                                                 "$(files[consoles])",
                                                 "\s*#[^\n]*",
                                                 "\s+",
                                                 500,
                                                 50000);

      "console_idx" slist => getindices("consoles");

    _have_proc_modules::
      "module_count" int =>  readstringarrayidx("modules",
                                                "$(files[modules])",
                                                "\s*#[^\n]*",
                                                "\s+",
                                                2500,
                                                250000);

      "module_idx" slist => getindices("modules");

    _have_proc_cpuinfo::
      # this will extract all the keys in one bunch, so you won't get
      # detailed info for processor 0 for example
      "cpuinfo_count" int =>  readstringarrayidx("cpuinfo_array",
                                                 "$(files[cpuinfo])",
                                                 "\s*#[^\n]*",
                                                 "\s*:\s*",
                                                 500,
                                                 50000);

      "cpuinfo_idx" slist => getindices("cpuinfo_array");
      "cpuinfo[$(cpuinfo_array[$(cpuinfo_idx)][0])]" string => "$(cpuinfo_array[$(cpuinfo_idx)][1])";
      "cpuinfo_keys" slist => getindices("cpuinfo");

    _have_proc_partitions::
      "partitions_count" int =>  readstringarrayidx("partitions_array",
                                                    "$(files[partitions])",
                                                    "major[^\n]*",
                                                    "\s+",
                                                    500,
                                                    50000);

      "partitions_idx" slist => getindices("partitions_array");
      "partitions[$(partitions_array[$(partitions_idx)][4])]" string => "$(partitions_array[$(partitions_idx)][3])";
      "partitions_keys" slist => getindices("partitions");

    _have_proc_version::
      "version" string => readfile("$(files[version])", 2048);

  classes:
      "have_proc" expression => isdir($(inventory_control.proc));

    have_proc::
      "_have_proc_$(basefiles)"
      expression => fileexists("$(files[$(basefiles)])");

    _have_proc_consoles::
      "have_console_$(consoles[$(console_idx)][0])"
      expression => "any",
      scope => "namespace";

    _have_proc_modules::
      "have_module_$(modules[$(module_idx)][0])"
      expression => "any",
      scope => "namespace";

  reports:
    _have_proc_consoles.verbose_mode::
      "$(this.bundle): we have console $(consoles[$(console_idx)][0])";
    _have_proc_modules.verbose_mode::
      "$(this.bundle): we have module $(modules[$(module_idx)][0])";
    _have_proc_cpuinfo.verbose_mode::
      "$(this.bundle): we have cpuinfo $(cpuinfo_keys) = $(cpuinfo[$(cpuinfo_keys)])";
    _have_proc_partitions.verbose_mode::
      "$(this.bundle): we have partitions $(partitions_keys) with $(partitions[$(partitions_keys)]) blocks";
    _have_proc_version.verbose_mode::
      "$(this.bundle): we have kernel version '$(version)'";
}
  • sample output (note this is verbose mode with -v because there's a LOT of output):
% cf-agent -Kv -binventory_control,cfe_autorun_inventory_proc|grep 'cfe_autorun_inventory_proc: we have'

R: cfe_autorun_inventory_proc: we have console tty0

R: cfe_autorun_inventory_proc: we have module snd_seq_midi
...
R: cfe_autorun_inventory_proc: we have module ghash_clmulni_intel

R: cfe_autorun_inventory_proc: we have cpuinfo flags = fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx lahf_lm ida arat epb xsaveopt pln pts dtherm tpr_shadow vnmi flexpriority ept vpid
...
R: cfe_autorun_inventory_proc: we have cpuinfo model name = Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz

R: cfe_autorun_inventory_proc: we have partitions sr0 with 1048575 blocks
...
R: cfe_autorun_inventory_proc: we have partitions sda with 468851544 blocks

R: cfe_autorun_inventory_proc: we have kernel version 'Linux version 3.11.0-15-generic (buildd@roseapple) (gcc version 4.8.1 (Ubuntu/Linaro 4.8.1-10ubuntu8) ) #25-Ubuntu SMP Thu Jan 30 17:22:01 UTC 2014'