我目前正在开发一个简单的脚本来处理Chef部署期间的属性文件。我正在使用chef-apply script.rb
class_path = '/var/lib/tomcat/webapps/ROOT/WEB-INF/classes'
file '/home/corp/working/corp.properties' do
owner 'root'
group 'root'
mode 0644
p File.exist?("#{class_path}")
content File.open("#{class_path}/corp.properties").read
action :create_if_missing
only_if { File.exist?("#{class_path}/corp.properties") }
end
但它运行错误
false
[2017-12-20T11:37:40-05:00] FATAL: Stacktrace dumped to /home/corp/.chef/cache/chef-stacktrace.out
[2017-12-20T11:37:40-05:00] FATAL: Stacktrace dumped to /home/corp/.chef/cache/chef-stacktrace.out
[2017-12-20T11:37:40-05:00] FATAL: Please provide the contents of the stacktrace.out file if you file a bug report
[2017-12-20T11:37:40-05:00] FATAL: Please provide the contents of the stacktrace.out file if you file a bug report
[2017-12-20T11:37:40-05:00] FATAL: Errno::ENOENT: No such file or directory @ rb_sysopen - /var/lib/tomcat/webapps/ROOT/WEB-INF/classes/corp.properties
[2017-12-20T11:37:40-05:00] FATAL: Errno::ENOENT: No such file or directory @ rb_sysopen - /var/lib/tomcat/webapps/ROOT/WEB-INF/classes/corp.properties
正如您所看到的,即使File.exist?
调用返回false,也会执行File.open而不管后卫。
答案 0 :(得分:2)
资源块中的任何代码都默认在编译时运行。守卫在收敛时间运行。您可以通过使content lazy { File.open("#{class_path}/corp.properties").read }
强制文件读取在收敛时发生来解决此问题。有关详细信息,请参阅https://coderanger.net/two-pass/。