Last active
December 18, 2018 17:34
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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