Thursday, June 23, 2016

Replace a file in Puppet only if the file exists

Replace file in Puppet only if the file exists. So i have this question from my colleague. It sounds simple right? but it is not.

Some says that use exec with onlyif but it produces warning/errors logs if the file doesn't exist. In which functionality, it will suffice your needs, but you will have this warning logs.

This is the workaround that i've done:

file { '/tmp/file01.txt':    source => "puppet:///modules/common/custommodule/file01.txt",    owner => 'root',    group => 'root',    mode => '0640',  }

  exec {"copy_file01":    command => "/usr/bin/diff /tmp/file01.txt /var/tmp/file01.txt; if [ $? -ne 0 ]; then /bin/cp /tmp/file01.txt /var/tmp/file01.txt; fi",     require=> File['/tmp/file01.txt'],    onlyif => "/usr/bin/test -e /var/tmp/file01.txt",

two things that this will accomplish:

1. It will not replace or copy the file if the file doesn't exists. Where as if I use "file" type in puppet, it will create the file regardless if it exists or not.
2. If the file changes in puppet it will replace the existing file in the client. Test will be done by the diff command.

The only disadvantage of this, is that it will create a file under a directory.