-
Notifications
You must be signed in to change notification settings - Fork 0
/
hosts.rb
executable file
·65 lines (50 loc) · 1.4 KB
/
hosts.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env ruby
require 'dotenv/load'
require 'net/http'
require 'uri'
require 'json'
require 'optparse'
class DigitalOcean
class << self
def list
request = Net::HTTP::Get.new('/v2/droplets')
request.add_field('Content-Type', 'application/json')
request.add_field('Authorization', authorization)
response = with_http do |http|
http.request request
end
JSON.parse(response.body)
end
private
def with_http(&block)
Net::HTTP.start(uri.host, uri.port, use_ssl: use_ssl, &block)
end
def use_ssl
uri.scheme = 'https'
end
def uri
URI('https://api.digitalocean.com')
end
def authorization
"Bearer #{ENV['DIGITALOCEAN_OAUTH_TOKEN']}"
end
end
end
OptionParser.new do |opts|
opts.banner = 'Usage: hosts.rb [options]'
opts.on('--list') do
hosts = DigitalOcean.list['droplets'].map { |d| d['name'] }
puts JSON.dump('digitalocean' => hosts)
end
opts.on('--host HOSTNAME') do |hostname|
droplet = DigitalOcean.list['droplets'].find { |d| d['name'] == hostname }
puts JSON.dump(
'digitalocean' => droplet,
'ansible_host' => droplet['networks']['v4'].first['ip_address']
)
end
opts.on('--ip HOSTNAME') do |hostname|
droplet = DigitalOcean.list['droplets'].find { |d| d['name'] == hostname }
puts droplet['networks']['v4'].first['ip_address']
end
end.parse!