简体   繁体   English

厨师食谱如何检查文件是否存在

[英]Chef Recipe How To Check If File Exists

I just started using Chef and I'm trying to figure out how to first check if a file exists before doing anything. 我刚刚开始使用Chef,我试图弄清楚在做任何事情之前如何首先检查文件是否存在。

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

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. 正如评论中所提到的,对于删除操作, if语句是不必要的,如上所述,因为如果chef没有找到要删除的文件,它将认为它已被删除。

Otherwise, you generally want to use guard properties in the resource (available for all resources), rather than wrapping a resource in an if-then. 否则,您通常希望在资源中使用guard属性 (可用于所有资源),而不是将资源包装在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 . 您可能还想熟悉Ruby File类方法

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. Chef的基本思想是说明系统所需的状态,然后Chef将其与实际状态进行比较,并进行所需的任何更改以使系统进入所需状态。 You do not need to have an if statement to check if the file exists before deleting it; 在删除文件之前,您不需要使用if语句来检查文件是否存在; Chef itself should check if the file exists if I'm not mistaken. 如果我没有弄错的话,厨师本身应该检查文件是否存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM