require 'aws-sdk' # Context module Contexto # ECS class class Contextualize attr_reader :display, :cluster, :service def initialize(params = {}) @cluster = params.fetch(:cluster) @service = params.fetch(:service) if params[:service] @container = params.fetch(:container) if params[:container] @display = Contexto::Display.new end def show cluster puts "\n" return unless @service service puts "\n" tasks end private def cluster resp = ecs_client.describe_clusters( clusters: [ @cluster ] ) title = "Cluster #{@cluster}" headings = %w(Name Status Instances Services RunningTasks PendingTasks) cluster = resp.clusters[0].to_h rows = [] rows << [cluster[:cluster_name], cluster[:status], cluster[:registered_container_instances_count], cluster[:active_services_count], cluster[:running_tasks_count], cluster[:pending_tasks_count]] @display.create_display(title, headings, rows) end def service resp = ecs_client.describe_services( cluster: @cluster, services: [ @service ] ) title = "Service #{@service}" headings = %w(Name Status Desired Running Pending) service = resp.services[0].to_h rows = [] rows << [service[:service_name], service[:status], service[:desired_count], service[:running_count], service[:pending_count]] @display.create_display(title, headings, rows) rescue Aws::ECS::Errors::ServiceNotFoundException puts 'Service not found' end def tasks resp = ecs_client.describe_tasks( cluster: @cluster, tasks: [task_arn] ) task = resp.tasks[0].to_h containers = task[:containers] ec2_instance_id = describe_container_instance(task[:container_instance_arn]) title = 'Containers' headings = %w(Container Status IP) rows = [] containers.each do |container| rows << [container[:name], container[:last_status], describe_instances(ec2_instance_id)] end @display.create_display(title, headings, rows) end def task_arn resp = ecs_client.list_tasks( cluster: @cluster, service_name: @service ) resp.task_arns[0] end def describe_container_instance(container_instance_arn) resp = ecs_client.describe_container_instances( cluster: @cluster, container_instances: [ container_instance_arn ] ) resp.container_instances[0].ec2_instance_id end def describe_instances(ec2_instance_id) resp = ec2_client.describe_instances( instance_ids: [ec2_instance_id] ) resp.reservations[0].instances[0].private_ip_address end def region_name ENV['AWS_REGION'] || 'us-east-1' end def ecs_client Aws::ECS::Client.new(region: region_name.to_s) end def ec2_client Aws::EC2::Client.new(region: region_name.to_s) end end end