Skip to content

Instantly share code, notes, and snippets.

@gionn
Last active December 18, 2018 17:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gionn/fabbd0f6d6ad897d0338 to your computer and use it in GitHub Desktop.
Save gionn/fabbd0f6d6ad897d0338 to your computer and use it in GitHub Desktop.
Quick script to generate an ssh_config after a terraform apply on OpenStack, GCE, DigitalOcean
#!/usr/bin/env ruby
# NOTICE: GCE and OpenStack providers only.
require 'json'
require 'erb'
def get_template()
%{
<% hosts.each do |key, entry| %>
Host <%= key %>
User <%= entry[:user] %>
Hostname <%= entry[:hostname] %>
<% end %>
}
end
class SshConfig
attr_accessor :hosts
def initialize(hosts)
@hosts = hosts
end
def get_binding
binding()
end
end
file = File.read('terraform.tfstate')
data_hash = JSON.parse(file)
hosts = {}
data_hash['modules'][0]['resources'].each do |key, resource|
if ['openstack_compute_instance_v2','google_compute_instance','digitalocean_droplet'].include?(resource['type'])
attributes = resource['primary']['attributes']
name = attributes['name']
hostname = attributes['access_ip_v4'] || attributes['network_interface.0.access_config.0.assigned_nat_ip'] || attributes['ipv4_address']
if resource['type'] == 'digitalocean_droplet'
user = 'root'
else
user = 'ubuntu'
end
hosts[name] = {
:hostname => hostname,
:user => user,
}
end
end
renderer = ERB.new(get_template)
puts renderer.result(SshConfig.new(hosts).get_binding)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment