没有必需属性的默认值


8

在没有合理默认值的情况下,建议在资源(如模板)中使用属性的方法是什么?该属性值应在运行时提供。如果不是,则厨师配方执行应出错。

我现在拥有东西的方式将属性值应用于模板时是空字符串。

/recipes/default.rb

template "/var/tmp/my_script.sh" do
    source "my_script.erb"
    mode "0755"
    variables({
        :url => node['environment']['url']
    })
end

/templates/default/my_script.erb

#!/bin/bash
echo "The url is: <%= @url %>"

生成的/var/tmp/my_script.sh文件如下所示:

#!/bin/bash
echo "The url is: "

但是我希望它会出错。有什么建议吗?

Answers:


5

要指出的一件事-如果node['environment']根本没有设置,您的示例将按原样失败。这是我得到的输出:

[Tue, 16 Oct 2012 02:40:31 +0000] INFO: Starting Chef Run for vagrant.int.housepub.org
[Tue, 16 Oct 2012 02:40:31 +0000] INFO: Running start handlers
[Tue, 16 Oct 2012 02:40:31 +0000] INFO: Start handlers complete.
[Tue, 16 Oct 2012 02:40:31 +0000] ERROR: Running exception handlers
[Tue, 16 Oct 2012 02:40:31 +0000] ERROR: Exception handlers complete
[Tue, 16 Oct 2012 02:40:31 +0000] FATAL: Stacktrace dumped to /tmp/vagrant-chef-1/chef-stacktrace.out
[Tue, 16 Oct 2012 02:10:38 +0000] FATAL: NoMethodError: undefined method `[]' for nil:NilClass

但这不是很有帮助,而且并不总是足够的。也许您想对属性做一些额外的验证。在这种情况下,您可以在食谱中添加以下内容:

unless node['environment']['url'] && node['environment']['url'].size > 5
  Chef::Application.fatal!("The URL attribute isn't long enough.")
end

现在,Chef运行会在失败时为您提供更多有用的信息:

[Tue, 16 Oct 2012 02:41:36 +0000] INFO: Starting Chef Run for vagrant.int.housepub.org
[Tue, 16 Oct 2012 02:41:36 +0000] INFO: Running start handlers
[Tue, 16 Oct 2012 02:41:36 +0000] INFO: Start handlers complete.
[Tue, 16 Oct 2012 02:41:36 +0000] FATAL: The URL attribute isn't long enough.
[Tue, 16 Oct 2012 02:41:36 +0000] ERROR: Running exception handlers
[Tue, 16 Oct 2012 02:41:36 +0000] ERROR: Exception handlers complete
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.