Chef Recipe How To Check If File Exists
Asked Answered
V

2

8

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
Vena answered 7/7, 2016 at 23:27 Comment(3)
Why do you need this ability? Doesn't Chef check to see if the system's desired state is equal to the state you described, and it only makes changes if the desired state is different? What actual problem or error message are you trying to solve right now?Megacycle
Hey @DavidGrayson thanks for responding. I'm new with Chef, so you may be right in your thinking. I'm not currently getting any errors or issues, however I'm so used to writing conditional statements that it seemed like the right thing to do - this could be a flaw in my thinking, as I'm still getting to know best practices how Chef operates. Do I not need to check if a file exists in this case? Meaning that I won't get any kind of error if the file doesn't exist and I'm still excuting a recipe that attempts to delete it?Vena
I don't usually delete files with Chef, but I know that when I create them I don't need to have "if" statements, so I don't see why you would need an "if" statement when deleting.Megacycle
M
19

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.

Mind answered 8/7, 2016 at 0:2 Comment(2)
Thanks Karen, this is very helpful.Vena
This is redundant, as mentioned below. The file resource already does nothing for the :delete action if the file does not exist.Cellulous
M
4

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.

Megacycle answered 8/7, 2016 at 0:2 Comment(1)
Thank 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.Vena

© 2022 - 2024 — McMap. All rights reserved.