Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to run a cookbook_file resource only if the current environment is "dev". How can this be expressed?

The documentation suggests this:

In a recipe, a code block like this would be useful:

qa_nodes = search(:node,"chef_environment:QA")      
qa_nodes.each do |qa_node|                          
    # Do useful specific to qa nodes only

But I'm not sure that's what I want - the fact it's a loop seems wrong.

share|improve this question
up vote 36 down vote accepted

Look in the chef_environment Ruby attribute (not a regular Chef attribute) on the node:

if node.chef_environment == "dev"
  # stuff
share|improve this answer
Specifically, chef_environment is a method on the Chef::Node object that returns the value of the node's environment. It is not a node attribute and should not be confused as such. – jtimberman Aug 15 '12 at 21:50
Thanks @jtimberman. I had always thought of an environment being an attribute of a node but it does make sense that it's not. – Tim Potter Aug 15 '12 at 22:56
Great, this works. So the answer to my original question is to add only_if { node.chef_environment == "dev" }. Confirmed. – Steve Bennett Aug 16 '12 at 0:39
Couldn't get this answer to work. This syntax does work for me: if "#{node.chef_environment}" == "dev" – spuder Aug 20 '15 at 16:31

Your Answer


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.