Linux – Create a file only if the directory exists

linuxpuppetredhatunix

I am trying to write the module where it creates the file if directory exists or else it shouldn't do anything.

class puppetmodule{
  exec { 'chk_dir_exists':
    command => 'test -d /usr/dir1',
    path    =>  ["/usr/bin","/usr/sbin", "/bin"],
  } ->

  file {'usr/dir1/test.txt':
    ensure => 'file',
    owner  => 'root',
    group  => 'root',
    mode   => '0750',
  }
}

Below is the error it is throwing. Please advice me on this.

Error: test -d /usr/dir1 returned 1 instead of one of [0]

Best Answer

Something like this will work:

  $dir = "/usr/dir1"

  exec { "chk_${dir}_exist":
    command => "true",
    path    =>  ["/usr/bin","/usr/sbin", "/bin"],
    onlyif  => "test -d ${dir}"
  }

  file {"${dir}/test.txt":
    ensure => file,
    owner  => 'root',
    group  => 'root',
    mode   => '0750',
    require => Exec["chk_${dir}_exist"],
  }

Explanation:

onlyif => "test -d ${dir}"

means that the Exec resource is only created if the output of test -d is true.

require => Exec["chk_${dir}_exist"]

means the File resource is created only if the Exec resource exists.

If the directory does not exist, the puppet run will generate an error indicating that it cannot create File resource because the Exec resource does not exist. This is expected and can be safely ignored as the rest of the puppet catalog still gets applied.

If the directory exists, the File resource is created and applied.