Skip to content

Instantly share code, notes, and snippets.

@jpterry
Created September 26, 2014 23:02
Show Gist options
  • Save jpterry/41d149c374407904851a to your computer and use it in GitHub Desktop.
Save jpterry/41d149c374407904851a to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby#
# encoding: utf-8
require 'thor'
require 'octokit'
require 'etc'
class GithubKeyGenerator < Thor
include Thor::Actions
GITHUB_KEY_NAME = 'github_key'
SSH_KEYGEN_COMMAND = "ssh-keygen -t rsa -b 4096 -f #{GITHUB_KEY_NAME} -q -N ''"
desc 'generate_and_add', 'generates a new ssh key and adds it to your github account'
def generate_and_add
pub_key = generate_ssh_key
github_username = ask("What is your github username?")
github_password = ask("What is your github password?", echo: false)
puts
otp_key = nil
begin
client = Octokit::Client.new(login: github_username, password: github_password)
client.user # make a request
rescue Octokit::OneTimePasswordRequired
otp_key = ask("Two factor auth code:")
end
say "Adding public key to github account"
if otp_key
client.add_key("chef_kitchen key for #{Socket.gethostname}", pub_key, title: ssh_key_title, headers: { "X-GitHub-OTP" => otp_key })
else
client.add_key("chef_kitchen key for #{Socket.gethostname}", pub_key, title: ssh_key_title)
end
say "All done! Check out https://github.com/settings/ssh to see the added key"
end
desc 'copy_to_cookbooks', "copies github_key to all cloned cookbooks"
def copy_to_cookbooks
GithubKeyGenerator.source_root(File.expand_path("../..", __FILE__ ))
msg = set_color("Didn't find #{GITHUB_KEY_NAME}. Generate one first.", :red, :bold)
raise Thor::Error, msg unless File.exist?(GITHUB_KEY_NAME)
priv_key_content = File.read(GITHUB_KEY_NAME)
Dir['cookbooks/*'].each do |rel_dir_name|
if File.directory?(rel_dir_name)
create_file("#{rel_dir_name}/#{GITHUB_KEY_NAME}", priv_key_content)
end
end
end
no_tasks do
def oauth_token_note
"OpenGovDevStack github key. Generated on #{Socket.gethostname} by user #{Etc.getlogin} at #{Time.now}"
end
def ssh_key_title
"github_key for chef_kitchen on #{Socket.gethostname} generated by #{Etc.getlogin} at #{Time.now}"
end
def generate_ssh_key
if File.exist?(GITHUB_KEY_NAME)
if yes?("#{GITHUB_KEY_NAME} already exists. Do you want to remove it?")
remove_file(GITHUB_KEY_NAME)
remove_file("#{GITHUB_KEY_NAME}.pub")
else
say "Okay. Stopping."
exit(2)
end
end
say "Generating a new github_key keypair. This may take a minute"
run(SSH_KEYGEN_COMMAND)
raise "Failed to generate ssh keypair." unless $?.to_i == 0
File.read("#{GITHUB_KEY_NAME}.pub")
end
end
end
GithubKeyGenerator.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment