lib/routes.rb in gaptool-server-0.6.4 vs lib/routes.rb in gaptool-server-0.6.6

- old
+ new

@@ -1,9 +1,10 @@ # encoding: utf-8 require 'securerandom' require 'set' require_relative 'exceptions' + class GaptoolServer < Sinatra::Application def require_parameters(required_keys, data) data = data.delete_if { |k,v| v.nil? } required_keys = [*required_keys].to_set unless required_keys.is_a? Set @@ -25,12 +26,12 @@ post '/init' do data = require_parameters(%w(role environment zone itype), JSON.parse(request.body.read)) secret = SecureRandom.hex(12) - security_group = data['security_group'] || Gaptool::Data::get_role_data(data['role'])["security_group"] - sgid = Gaptool::EC2::get_or_create_securitygroup(data['role'], data['environment'], data['zone'], security_group) + data['security_group'] = data['security_group'] || Gaptool::Data::get_sg_for_role(data['role'], data['environment']) + sgid = Gaptool::EC2::get_or_create_securitygroup(data['role'], data['environment'], data['zone'], data['security_group']) image_id = data['ami'] || Gaptool::Data::get_ami_for_role(data['role'], data['zone'].chop) data['terminable'] = data['terminable'].nil? ? true : !!data['terminable'] data['secret'] = secret instance = Gaptool::EC2::create_ec2_instance( @@ -45,12 +46,30 @@ role: data['role'], env: data['environment'], zone: data['zone'] } ) + + # Tag instance + role = data['role'] + env = data['environment'] + name = "#{role}-#{env}-#{instance[:id]}" + {'Name' => name, 'gaptool' => 'yes', 'role' => role, 'environment' => env}.each do |tag, value| + begin + Gaptool::EC2::tag_ec2_instance(instance[:instance], tag, value) + rescue => e + logger.error("Error while tagging: #{e}. Skipping tag") + Airbrake.notify_or_ignore( + e, + error_class: "EC2 Tag failed", + parameters: {instance: instance[:id], name: name, role: role, environment: env} + ) + end + end + # Add host tag - data.merge(instance.reject { |k, v| k == :id }) + data.merge(instance.reject { |k, v| [:id, :instance].include?(k) }) Gaptool::Data::addserver(instance[:id], data, secret) json({instance: instance[:id], ami: image_id, role: data['role'], hostname: instance[:hostname], @@ -137,10 +156,16 @@ end.select{ |s| !s['registered'] } json servers end get '/instance/:id' do - json Gaptool::Data::stringify_apps(Gaptool::Data::get_server_data(params[:id])) + rs = Gaptool::Data::get_server_data(params[:id]) + if rs.nil? + status 404 + error_response "instance with id '#{params[:id]}' not found" + else + json Gaptool::Data::stringify_apps(rs) + end end get '/hosts/:role/:environment' do if params[:role] == 'ALL' list = Gaptool::Data::servers_in_env params[:environment]