Change Chef node environments

This little snippet is useful for two reasons. First, if you want to progress all (or a subset) of your Chef nodes to a different environment, this is the secret sauce.

More importantly, if you want to convert the output of `knife node list` to a space-delimited array (instead of the \n-delimited list), the sed command is your weapon.

First, let’s get all of the nodes into an array:


nodes=($(knife node list | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g'))

*Humbly shagged from this Stack Overflow post.

Before moving forward, let’s make sure the nodes are ACTUALLY in an array (and not a string).


echo ${nodes[2]}
echo ${nodes[3]}

Yep. They are in an array! Now, let’s do our magic on that array. In this case, we want to move all Chef nodes in this Chef Server to the production environment:


for node in ${nodes[@]}; do
knife node environment_set $node production
done

Simple as that.

Now, let’s step it up a notch. What if you wanted to operate on a subset of your nodes? Well, just throw an if statement in there…


for node in ${nodes[@]}; do
if [[ $node =~ .*this.* ]] || [[ $node =~ .*This.* ]] ; then
knife node environment_set $node production
fi
done

Hope this helps! Post your variants and additions in the comments. I’d love to see what you do with this.

Tags: , , ,