Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.