Search code examples
puppet

Puppet module that checks to see if a file exists


Since there is no easy way in Puppet to check whether a file exists on the agent, I am attempting to write a module that performs this check. However, it is not working as expected. I have done the following :

  1. In the modules folder, executed

puppet module generate root-mymodule

  1. In mymodule/manifests/file_check.pp
    ..
    ..
      if defined(File["/tmp/test_file"]) {
    ..
    ..

However, this does not achieve what I want it to. Apparently it only checks if the file is defined in the catalog. How do I get it to actually check if the file exists ?


Solution

  • Since there is no easy way in Puppet to check whether a file exists on the agent, I am attempting to write a module that performs this check.

    There is no way to test client-side existence of arbitrary files during catalog building when using a master / agent arrangement. Catalog building happens on the master; there is no way to obtain additional information from the agent during that process. If instead you are using puppet apply then you can use the generate function, but that's a trap waiting to bite someone who later tries to move your code to a master.

          if defined(File["/tmp/test_file"]) {
    

    [...] does not achieve what I want it to. Apparently it only checks if the file is defined in the catalog.

    Yes, that's what defined() does. And it's worse than that, actually: defined() can only test whether a declaration of that particular File resource has already been evaluated. It cannot tell you about declarations of that resource that may be evaluated later in the same catalog-building run. Since manifest evaluation order is difficult to predict, defined is worse than useless: it is dangerous. Do not use it.

    How do I get it to actually check if the file exists ?

    I presume you want to perform such a check in time to use the results to influence catalog building. This is what facts are for. Puppet offers multiple approaches to defining and distributing your own facts. For something as simple as testing whether a specific file exists, I'd suggest the "external fact" approach instead of the "custom fact" approach.

    But you should also reconsider your premise, which is apparently that a general-purpose mechanism for compile-time testing for the presence of arbitrary files on the agent would be a useful thing to have. In fact, such tests are rarely useful. Puppet has better ways of approaching most tasks for which you might otherwise use such a thing, and most of the remaining tasks are usually better not done at all. If you wanted this for something specific, then I invite you to pose a new question about that particular thing.