Created
July 9, 2013 16:14
-
-
Save chrisroberts/5958726 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'chef' | |
require 'chef/knife' | |
require 'getoptlong' | |
def print_help | |
puts "#{File.basename(__FILE__)} OPTS" | |
puts ' --> Help is on a help yourself basis.' | |
end | |
args = Mash.new( | |
:kind => 'default' | |
) | |
opts = GetoptLong.new( | |
['--default', '-d', GetoptLong::NO_ARGUMENT], | |
['--override', '-o', GetoptLong::NO_ARGUMENT], | |
['--role-name', '-r', GetoptLong::REQUIRED_ARGUMENT], | |
['--attribute', '-a', GetoptLong::REQUIRED_ARGUMENT], | |
['--value', '-v', GetoptLong::REQUIRED_ARGUMENT], | |
['--cast', '-c', GetoptLong::REQUIRED_ARGUMENT], | |
['--help', '-h', GetoptLong::NO_ARGUMENT] | |
) | |
opts.each do |opt,arg| | |
case opt | |
when '--default' | |
args[:kind] = 'default' | |
when '--override' | |
args[:kind] = 'override' | |
when '--role-name' | |
args[:role_name] = arg | |
when '--attribute' | |
args[:attribute] = arg | |
when '--value' | |
args[:value] = arg | |
when '--cast' | |
args[:cast] = arg | |
else | |
print_help | |
exit 1 | |
end | |
end | |
%w(kind role_name attribute value).each do |req| | |
next if args[req] | |
puts "Missing required data for update: #{req}" | |
exit 2 | |
end | |
Chef::Knife.new.configure_chef | |
if(args[:cast]) | |
case args[:cast] | |
when 'integer' | |
args[:value] = args[:value].to_i | |
when 'float' | |
args[:value] = args[:value].to_f | |
when 'bool' | |
args[:value] = args[:value] == 'true' | |
else | |
puts "Unsupported cast type provided: #{args[:cast]}" | |
end | |
end | |
begin | |
role = Chef::Role.load(args[:role_name]) | |
attributes = role.send("#{args[:kind]}_attributes") | |
attribute_path = args[:attribute].split('.') | |
dest = attribute_path.slice(0, attribute_path.size - 1).inject(attributes) do |memo, key| | |
if(memo[key].nil? || !memo[key].is_a?(Hash)) | |
memo[key] = {} | |
end | |
memo[key] | |
end | |
dest[attribute_path.last] = args[:value] | |
role.save | |
puts "Role successfully updated!" | |
rescue => e | |
$stderr.puts "Failed to update role. Reason: #{e}" | |
exit 3 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment