How to Check File Existence in Puppet: File Resource Testing Methods


2 views

In Puppet, unlike Chef's File.exists? method, checking for file existence requires different approaches since Puppet operates on a declarative model rather than procedural execution. Here are the most effective ways to test file existence without creating files.

The find_file function searches for files in Puppet's module path:

$file_path = find_file('/path/to/your/file.txt')
if $file_path {
  notify { 'File exists': }
} else {
  notify { 'File not found': }
}

For more control, use an exec resource with the test command:

exec { 'check_file_existence':
  command => '/bin/true',
  onlyif  => 'test -f /path/to/file',
  returns => [0]
}

Leverage Puppet's native file resource with conditional attributes:

file { '/path/to/file':
  ensure  => present,
  replace => false,
  audit   => all
}

Here's how to check multiple files in a manifest:

$files_to_check = ['/etc/hosts', '/etc/resolv.conf']
$files_to_check.each |$file| {
  if find_file($file) {
    notify { "${file} exists": }
  } else {
    notify { "${file} missing": }
  }
}
  • Agent vs Master: File paths must be accessible from the Puppet agent's perspective
  • Performance: Frequent file checks may impact catalog compilation time
  • Security: Always validate paths to prevent directory traversal

When managing infrastructure with Puppet, there are scenarios where you need to verify whether a specific file exists on a client node before taking any action. Unlike Chef's straightforward File.exists? method, Puppet requires a different approach.

The most reliable way to check file existence in Puppet is by using the file resource with the onlyif or unless metaparameters. Here's a basic example:


exec { 'check_file_existence':
  command => '/bin/true',
  onlyif  => 'test -f /path/to/your/file',
}

For more complex scenarios, you can create a custom fact:


# In module/lib/facter/file_exists.rb
Facter.add(:file_exists) do
  setcode do
    File.exist?('/path/to/your/file').to_s
  end
end

Then use it in your manifest:


if $facts['file_exists'] == 'true' {
  notify { 'File exists': }
}

For one-time checks, you can use an exec resource with a test command:


exec { 'verify_file':
  command => 'echo "File exists"',
  onlyif  => 'test -e /etc/yourfile.conf',
  path    => ['/bin', '/usr/bin'],
}

Remember to consider:

  • File permissions that might affect visibility
  • Symbolic links and their resolution
  • Different operating system path conventions

For frequent checks, custom facts are more efficient as they're evaluated once during fact collection rather than on every Puppet run.