ruby Chef Recipe 如何检查文件是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38256803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:50:32  来源:igfitidea点击:

Chef Recipe How To Check If File Exists

rubyif-statementchefchef-recipe

提问by Corey

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

回答by Karen B

As mentioned in the comments, for a deletion action, the ifstatement is unnecessary, as mentioned, because if chef doesn't find the file to be deleted, it will assume it was already deleted.

正如评论中提到的,对于删除操作,该if语句是不必要的,如上所述,因为如果厨师没有找到要删除的文件,它会认为它已经被删除了。

Otherwise, you generally want to use guard propertiesin the resource (available for all resources), rather than wrapping a resource in an if-then.

否则,您通常希望在资源中使用保护属性(可用于所有资源),而不是将资源包装在 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 Fileclass methods.

您可能还想熟悉RubyFile类方法

回答by David Grayson

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.

Chef 的基本思想是,您声明系统的期望状态,然后 Chef 将其与实际状态进行比较,并进行使系统进入期望状态所需的任何更改。在删除文件之前,您不需要使用 if 语句来检查文件是否存在;如果我没记错的话,Chef 本身应该检查文件是否存在。