Created
February 10, 2015 22:37
-
-
Save numericillustration/0dd0fb03652033c6a958 to your computer and use it in GitHub Desktop.
io redirection with knife ssh from gem
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
def knifeSSH( search_string, command, env, region, environment_config ) | |
Chef::Config.from_file( File.expand_path($chef_conf) ) | |
kssh = Chef::Knife::Ssh.new | |
kssh.name_args[0] = search_string | |
kssh.name_args.push( command ) | |
Chef::Config[:environment] = env | |
Chef::Config[:knife][:yes] = true | |
kssh.config[:region] = region | |
kssh.config[:attribute] = 'cloud.local_ipv4' | |
kssh.config[:identity_file] = "#{$keypath}/#{$key}" | |
kssh.config[:aws_access_key_id] = "#{$aws_info[:key]}" | |
kssh.config[:aws_secret_access_key] = "#{$aws_info[:secret]}" | |
kssh.config[:aws_ssh_key_id] = environment_config['deployment_key'] | |
kssh.config[:ssh_port] = '22' | |
kssh.config[:ssh_user] = 'ubuntu' | |
begin | |
$logger.debug( "Now running command: #{command} for servers matching: #{search_string}" ) | |
kssh.run | |
rescue => hosed | |
$logger.info( "running command: #{command} for servers matching #{search_string} was unsuccessful: #{hosed.message} with trace #{hosed.backtrace.join( "\n" )}" ) | |
return nil | |
end | |
$logger.info( "running command: #{command} for servers matching #{search_string} was successful." ) | |
return 'Everything Is Awesome, thats my jam' | |
end | |
def capture_io | |
require 'stringio' | |
# clone whats there currently | |
orig_stdout, orig_stderr = $stdout, $stderr | |
# open new io objects | |
captured_stdout, captured_stderr = StringIO.new, StringIO.new | |
# reassign stdout and stderr to new io streams | |
$stdout, $stderr = captured_stdout, captured_stderr | |
# yield back to caller so that block uses redirected streams | |
yield | |
# now return the captured stdout and stderr | |
return captured_stdout.string, captured_stderr.string | |
ensure | |
# put that thing back where you found it or so help me | |
$stdout = orig_stdout | |
$stderr = orig_stderr | |
end | |
s_output, e_output = capture_io { | |
ssh_status = knifeSSH( "chef_environment:#{env}", my_command, env, region, environment_config ) | |
if ssh_status.nil? | |
$logger.error( "There was trouble running: #{my_command} on #{env} servers" ) | |
else | |
$logger.info( "Running: #{my_command} on #{env} servers returned #{ssh_status}" ) | |
end | |
} | |
$logger.debug( "chef-client Standard Output: #{s_output}" ) | |
$logger.debug( "chef-client Standard error: #{e_output}" ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment