Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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
share|improve this answer
    
Just what I needed, thank you. –  Sarah Haskins Oct 16 '12 at 12:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.