8

What is the recommended approach for using an attribute in a resource, like a template, when there is no reasonable default for that attribute. The attribute value is expected to be provided at runtime. If it is not, the chef recipe execution should error.

The way I have things now the attribute value when applied to the template is empty string.

/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 %>"

The resulting /var/tmp/my_script.sh file would looks like this:

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

But I wish it would just error out. Any advice?

Sarah Haskins
  • 303
  • 3
  • 10

1 Answers1

5

One thing to point out - if node['environment'] hasn't been set at all, your example would fail as it is. Here's the output I got:

[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

But that's not very helpful, and it's not always enough. Perhaps you want to do some extra validation of the attribute. In that case, you can put something like this into your recipe:

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

Now, the Chef run will give you a more helpful message when it fails:

[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
zts
  • 945
  • 5
  • 8