Skip to content

Instantly share code, notes, and snippets.

@KonnorRogers
Last active April 12, 2019 05:52
Show Gist options
  • Save KonnorRogers/c835136c8e303a406d8addd78d9287fd to your computer and use it in GitHub Desktop.
Save KonnorRogers/c835136c8e303a406d8addd78d9287fd to your computer and use it in GitHub Desktop.
Adding an ssh key to github via Ruby with Net::HTTP or Rest-Client
require 'net/http'
require 'json'
uri = URI('https://api.github.com/user/keys')
token = "token #{ENV['MY_SUPER_SECRET_API_TOKEN']}"
ssh_key_content = File.read(File.join(Dir.home, '.ssh', 'id_rsa.pub'))
ssh_key_title = 'my_title'
ssh_content = { 'title' => ssh_key_title,
'key' => ssh_key_content }.to_json
headers = { 'Content-Type' => 'application/json',
'Authorization' => token,
'Accepts' => 'application/json' }
request = Net::HTTP::Post.new(uri, headers)
request.body = ssh_content
response = nil
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
response = http.request(request)
end
case response
when Net::HTTPSuccess, Net::HTTPRedirection
# OK
else
response.value
end
# To add an ssh key to github via the standard library Net:HTTP
require 'net/http'
require 'json'
uri = URI('https://api.github.com/user/keys')
token = "token #{ENV['MY_PERSONAL_API_TOKEN']}"
ssh_key_title = 'test_key'
ssh_key_content = File.read(File.join(Dir.home, '.ssh/id_rsa.pub'))
ssh_hash = { 'title' => ssh_key_title,
'key' => ssh_key_content }.to_json
headers = { 'Content-Type' => 'application/json',
'Authorization' => token,
'Accepts' => 'application/json' }
# This is where the actual request is made
response = Net::HTTP.post uri, ssh_hash, headers
# Checks that the request processed properly
case response
when Net::HTTPSuccess, Net::HTTPRedirection
# OK
p response
else
response.value
end
# Adding an ssh key to github via the rest-client gem
require 'rest-client'
require 'json'
uri = 'https://api.github.com/user/keys'
token = "token #{ENV['MY_SUPER_SECRET_API_TOKEN']}"
ssh_key_title = 'test_key'
ssh_key_content = File.read(File.join(Dir.home, '.ssh/id_rsa.pub'))
payload = { 'title' => ssh_key_title,
'key' => ssh_key_content }.to_json
# Actual request made here
response = RestClient.post uri, payload,
content_type: :json, accept: :json,
Authorization: 'token ' + token
p response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment