CFEngine: new strftime() function
  2013-04-04

2013-06-11: Links to documentation updated

An implementation of strftime() has just been merged into the master branch

Full documentation is provided, as well as an example reproduced below:

body common control

{
bundlesequence => { "example" };
}

###########################################################

bundle agent example

{
  vars:
      "time" int => now();
      "now" string => strftime("localtime", "%F %T", now());
      "then" string => strftime("localtime", "%F %T", 0);

      "gmt_now" string => strftime("gmtime", "%F %T", now());
      "gmt_then" string => strftime("gmtime", "%F %T", 0);

  reports:
    cfengine::
      "time $(time); now $(now); then $(then)";
      "time $(time); GMT now $(now); GMT then $(then)";
}

Output:

R: time 1365106904; now 2013-04-04 22:21:44; then 1970-01-01 01:00:00
R: time 1365106904; GMT now 2013-04-04 22:21:44; GMT then 1970-01-01 01:00:00

I found this function very handy to replace ugly uses of “date” through execresult(), when a special formatted date is needed and hard date/time classes are not enough, so:

body common control {
  bundlesequence => { "foo" };
}

bundle agent foo {

  vars:
    "year"           string  =>  execresult("/bin/date +%Y", "noshell");
    "month"          string  =>  execresult("/bin/date +%m", "noshell");
    "year_month"     string  =>  "$(year)-$(month)";
    "month_year"     string  =>  "$(month)-$(year)";

  reports:
    cfengine::
      "Date as YYYY-MM: $(year_month)";
      "Date as MM-YYYY: $(month_year)";

}

Output:

R: Date as YYYY-MM: 2013-04
R: Date as MM-YYYY: 04-2013

May be shortened (with extra portability, flexibility and greater clarity) to:

body common control {
  bundlesequence => { "foo" };
}

bundle agent foo {

  vars:
    "year_month"     string  =>  strftime("localtime", "%Y-%m", now());
    "month_year"     string  =>  strftime("localtime", "%m-%Y", now());

  reports:
    cfengine::
      "Date as YYYY-MM: $(year_month)";
      "Date as MM-YYYY: $(month_year)";

}

Output:

R: Date as YYYY-MM: 2013-04
R: Date as MM-YYYY: 04-2013


Availability: master branch, upcoming 3.5