Chef Recipe How To Check If File Exists
Solution 1
As mentioned in the comments, for a deletion action, the if
statement is unnecessary, as mentioned, because if chef doesn't find the file to be deleted, it will assume it was already deleted.
Otherwise, you generally want to use guard properties in the resource (available for all resources), rather than wrapping a resource in an if-then.
file '/var/www/html/login.php' do
only_if { ::File.exist?('/var/www/html/login.php') }
action :touch
end
And you probably also want to familiarize yourself with the Ruby File
class methods.
Solution 2
The basic idea of Chef is that you state the desired state of the system, and then Chef compares that to the actual state, and makes any changes needed to bring the system into the desired state. You do not need to have an if statement to check if the file exists before deleting it; Chef itself should check if the file exists if I'm not mistaken.
Corey
Updated on July 10, 2022Comments
-
Corey over 1 year
I just started using Chef and I'm trying to figure out how to first check if a file exists before doing anything.
I have the file part down for my current use case, where I'm removing a login file for the production server, ex:
file '/var/www/html/login.php' do action :delete end
However, I'd like the abilty to first check if the file exists, ex.
if (file_exists === true) file '/var/www/html/login.php' do action :delete end end
-
Corey over 7 yearsThanks Karen, this is very helpful.
-
Corey over 7 yearsThank you for the clarification. It seems I need to continue shifting my mindset towards the fact that Chef is a declarative description for the state you want your infrastructure to be in, so this is a great reminder.
-
opricnik over 7 yearsThis is redundant, as mentioned below. The
file
resource already does nothing for the:delete
action if the file does not exist.