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.
但是,我希望abilty首先检查文件是否存在。
if (file_exists === true)
file '/var/www/html/login.php' do
action :delete
end
end
2 个解决方案
#1
8
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.
否则,您通常希望在资源中使用保护属性(对所有资源都可用),而不是将资源包装在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文件类方法。
#2
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.
Chef的基本思想是您声明系统的期望状态,然后Chef将其与实际状态进行比较,并进行所需的任何更改以使系统进入所需的状态。在删除文件之前,不需要使用if语句检查文件是否存在;如果我没有弄错的话,厨师本身应该检查文件是否存在。
#1
8
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.
否则,您通常希望在资源中使用保护属性(对所有资源都可用),而不是将资源包装在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文件类方法。
#2
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.
Chef的基本思想是您声明系统的期望状态,然后Chef将其与实际状态进行比较,并进行所需的任何更改以使系统进入所需的状态。在删除文件之前,不需要使用if语句检查文件是否存在;如果我没有弄错的话,厨师本身应该检查文件是否存在。