必需属性没有默认值

Sar*_*ins 8 chef chef-solo

当该属性没有合理的默认值时,在资源(如模板)中使用属性的推荐方法是什么。期望在运行时提供属性值。如果不是,厨师食谱执行应该出错。

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

/食谱/default.rb

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

/templates/default/my_script.erb

#!/bin/bash
echo "The url is: <%= @url %>"
Run Code Online (Sandbox Code Playgroud)

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

#!/bin/bash
echo "The url is: "
Run Code Online (Sandbox Code Playgroud)

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

zts*_*zts 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
Run Code Online (Sandbox Code Playgroud)

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

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

现在,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
Run Code Online (Sandbox Code Playgroud)