Create a file only if the directory exists?
Solution 1:
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.
Solution 2:
Puppet is about end state. You can ensure a file exists with the state you specify or is absent. If you need to do some branching (if) logic, Puppet supports that as well. See conditionals in the documentation - https://puppet.com/docs/puppet/latest/lang_conditional.html
$directory_exists = <insert logic here>
if $directory_exists {
file {'usr/dir1/test.txt':
ensure => 'file',
owner => 'root',
group => 'root',
mode => '0750',
}
}