Skip to content

Instantly share code, notes, and snippets.

@sbotman
Forked from nstielau/set_environment.rb
Created October 18, 2012 09:55
Show Gist options
  • Save sbotman/3910813 to your computer and use it in GitHub Desktop.
Save sbotman/3910813 to your computer and use it in GitHub Desktop.
A Knife plugin to set node environment
## Knife plugin to set node environment
# See http://wiki.opscode.com/display/chef/Environments
#
## Install
# Place in .chef/plugins/knife/set_environment.rb
#
## Usage
# Nick-Stielaus-MacBook-Pro:chef-repo nstielau$ knife node set_environment mynode.net my_env
# Looking for mynode.net
# Setting environment to my_env
# 1 items found
#
# Node Name: mynode.net
# Environment: my_env
# FQDN: mynode.net
# IP: 66.111.39.46
# Run List: role[base], role[web_app]
# Roles: base, web_app
# Recipes timezone::default, hosts::default, sudo::default, web_app::default
# Platform: ubuntu 10.04
require 'chef/knife'
class Chef
class Knife
class NodeSetEnvironment < Chef::Knife
deps do
require 'chef/node'
require 'chef/environment'
end
banner "knife node set_environment NODE ENVIRONMENT"
def run
unless @node_name = name_args[0]
ui.error "You need to specify a node"
exit 1
end
unless @environment = name_args[1]
ui.error "You need to specify an environment"
exit 1
end
puts "Looking for #{@node_name}"
if Chef::Node.list.include?(@node_name)
node = Chef::Node.load(@node_name)
else
puts "Could not find a node named: #{@node_name}"
exit 1
end
if Chef::Environment.list.include?(@environment)
puts "Setting environment to #{@environment}"
node.chef_environment(@environment)
node.save
else
puts "Could not find a environment named: #{@environment}"
exit 1
end
end
end
end
end
@sbotman
Copy link
Author

sbotman commented Oct 18, 2012

Changed the plugin so that it doesn't use search. I know that search is a powerfull function of chef, but it's not 100% reliable and sometimes gives me the wrong result. Further more I included a check if the environment exists. Thank you nstielau for sharing the initial code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment