Created
November 21, 2014 17:47
-
-
Save xcsrz/dcc0a2359a76ed87336c to your computer and use it in GitHub Desktop.
A script to help abbreviate knife commands.
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/ruby | |
require 'optparse' | |
envs = [] | |
roles = [] | |
user = ENV['XKNIFE_SSH_USER'] || nil | |
debug = false | |
if ENV['XKNIFE_CHEF_REPO'] | |
Dir.chdir ENV['XKNIFE_CHEF_REPO'] | |
end | |
optparser = OptionParser.new do |opts| | |
opts.banner = "Usage: #{File.basename($0)} [options] COMMAND\nREQUIRED: at least one role and one environment." | |
opts.on("-e", "--env ENVIRONMENT", "Chef Environment") do |env| | |
envs << "chef_environment:#{env}" | |
end | |
opts.on("-r", "--role ROLE", "Chef Role") do |role| | |
roles << "roles:#{role}" | |
end | |
opts.on("-u", "--user USERNAME", "SSH User (Also settable via the XKNIFE_SSH_USER environment variable)") do |username| | |
user = username | |
end | |
opts.on_tail("-D", "--debug", "Print the knife command instead of executing it.") do | |
debug = true | |
end | |
opts.on_tail("-h", "--help", "Show this message") do | |
puts opts | |
puts "","ENVIRONMENT VARIABLES:","\tXKNIFE_SSH_USER: The useraccount to use for SSH commands","\t\tThis will prevent the use of the --user flag every time", | |
"\tXKNIFE_CHEF_REPO: The path on the local machine of your chef repo", | |
"\t\tThis enables you to run xknife from any directory.", | |
"" | |
exit | |
end | |
end | |
optparser.parse! | |
if envs.length == 0 || roles.length == 0 | |
puts optparser | |
exit | |
end | |
cmd = 'knife' | |
query = '"(' + envs.join(' OR ') + ') AND (' + roles.join(' OR ') + ')" ' | |
if ARGV.length == 0 | |
cmd += ' search ' + query | |
else | |
cmd += ' ssh ' + query | |
cmd += '"' + ARGV.join(' ') + '"' | |
unless user.nil? | |
cmd += ' -x ' + user | |
end | |
end | |
if debug | |
puts "Command:", "\t" + cmd | |
else | |
exec cmd | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment