8

I want to list a directory content and use the result somewhere else:

bundle agent test
{

   commands:
      "ls /tmp/test/";

    reports:
    ubuntu::
       "print output here for example";  
# or add it to a variable which is how I really want to use it.
 }
awsiv
  • 166
  • 11

2 Answers2

12
bundle agent test
{

    vars:
        "my_result" string => execresult("/bin/ls /tmp/test/","noshell");

    reports:
        ubuntu::
            "Output is : $(my_result)";  
}

See https://cfengine.com/manuals/cf3-solutions#Execresult-example

faker
  • 17,326
  • 2
  • 60
  • 69
  • Beware! This command will be run several times per `cf-agent` run. See the docs on [normal ordering](https://docs.cfengine.com/docs/master/reference-language-concepts-normal-ordering.html#agent-pre-evaluation-step) and the note at the bottom of [the docs for `execresult()`](https://docs.cfengine.com/docs/master/reference-functions-execresult.html). For `ls` it may not be important, but for more expensive commands it certainly will be. – Wildcard Sep 15 '16 at 22:40
4

As of version 3.3.0, you can use the lsdir() function instead.

vars:
  "result" slist => lsdir("/tmp/test", ".*", "false");

read more : https://cfengine.com/manuals/cf3-Reference#Function-lsdir

Pledge
  • 81
  • 3
  • This is actually better for the `ls` use case as it makes use of CFEngine's internal function caching and doesn't call an external command multiple times per run. Of course, `execresult()` is more general. – Wildcard Sep 15 '16 at 22:42