AWS EC2の情報をRuby/ERBを使ってHTMLとして出力する方法
AWS EC2の情報をERBを使ってHTMLを出力する方法をメモしておきます。
うまく表示してパラメータシートの代わりとして使えないかなーと思ってサンプルを作って見ました。
Javascript SDKで作るのがめんどくさかったので、慣れてるRubyで楽してしまいました。
出力した情報はDataTablesで表にして見やすくしています。
qiita.com
完成イメージ
AWS EC2の情報を表にして表示してます。各キーでソート、ページネーション、検索ができます。
ファイル作成
Gemfile, instance.rb, index.html.erbを用意します。
Gemfile
まずはGemfile
source :rubygems gem 'aws-sdk', '~> 2' gem 'aws_config'
instance.rb
ERBからHTMLを作成するrubyコードです。
EC2の情報を取得して、必要な情報を@arrayに格納してerbファイルに渡しています。
require 'erb' require 'aws-sdk' require 'aws_config' def name(instance) instance.tags.select do |tag| tag.key == "Name" end.first.value end def id(instance) instance.instance_id end def type(instance) instance.instance_type end def status(instance) instance.state.name end def az(instance) instance.placement.availability_zone end def subnet_id(instance) instance.subnet_id end def security_group(instance) res = [] instance.security_groups.each do |sg| res.push(sg.group_id) end res.join(", ") end def private_ip_address(instance) instance.private_ip_address end def public_ip_address(instance) instance.public_ip_address end Aws.config.update( :access_key_id => "XXXXXXXXXXX", :secret_access_key => "XXXXXXXXXXXXXXXXXXXXXX", :region => "us-east-1" ) ec2 = Aws::EC2::Client.new instances = [] reservations = ec2.describe_instances.reservations reservations.each do |reservation| instances.push(reservation.instances.first) end @array = [] instances.each do |instance| hash = { "Name" => name(instance), "ID" => id(instance), "Type" => type(instance), "Status" => status(instance), "AZ" => az(instance), "SubnetID" => subnet_id(instance), "SecurityGroup" => security_group(instance), "PrivateIP" => private_ip_address(instance), "PublicIP" => public_ip_address(instance), } @array.push(hash) end contents = ERB.new(File.read("index.html.erb")).result(binding) erb = ERB.new(contents) puts erb.result(binding)
index.html.erb
cdn.datables.netを読み込むだけで表が見やすくなるのが良いですね。
あとは@arrayで渡された値のkey, valueをeachで回して表示するだけ。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdn.datatables.net/t/bs-3.3.6/jqc-1.12.0,dt-1.10.11/datatables.min.css"/> <script src="https://cdn.datatables.net/t/bs-3.3.6/jqc-1.12.0,dt-1.10.11/datatables.min.js"></script> <script> jQuery(function($){ $("#foo-table").dataTable(); }); </script> <title></title> </head> <body> <table id="foo-table" class="table table-bordered"> <thead> <tr> <% @array.first.keys.each do |key| %> <th><%= key %></th> <% end %> </tr> </thead> <tbody> <% @array.each do |info| %> <tr> <% info.values.each do |item| %> <td><%= item %></td> <% end %> </tr> <% end %> </tbody> </table> </body> </html>
実行コマンド
$ bundle install --path=vendor/bundle $ bundle exec ruby instance.rb > index.html; open index.html
ちょっと雑に作ってますが、欲しい情報を整理してHTMLで表示させればパラメーターシートとして使えそうな気がしてきました。