Skip to content

Instantly share code, notes, and snippets.

@matheustardivo
Last active April 29, 2016 13:31
Show Gist options
  • Save matheustardivo/448478bda739060ddc13e07606172521 to your computer and use it in GitHub Desktop.
Save matheustardivo/448478bda739060ddc13e07606172521 to your computer and use it in GitHub Desktop.
Cluster ssh tool for Terminal.app

Cluster ssh tool for Terminal.app

O primeiro passo é instalar o Cluster ssh tool for Terminal.app ou csshX:

brew install csshx

Depois, incluir o script abaixo no seu .bashrc:

function server() {
    ruby -e '
    require "yaml"

    applications = YAML.load_file("#{Dir.home}/.servers.yml")
    app_name = ARGV.shift
    env_name = ARGV.shift

    def yellow(msg)
      "\033[33;33m#{msg}\033[0m"
    end

    def red(msg)
      "\033[33;31m#{msg}\033[0m"
    end

    def exit_with_message(msg)
      puts msg
      exit 1
    end

    exit_with_message "usage: server [application] [environment{index}]" if app_name.nil? or env_name.nil?

    application = applications[app_name]
    exit_with_message "#{red("application not found")}\navaliable applications are #{yellow(applications.keys)}" if application.nil?

    servers = application[env_name]
    if servers.nil?
      msg = "environment #{red(env_name)} not found for application #{yellow(app_name)}\navaliable environments are #{yellow(application.keys)}"

      server_and_index = env_name.match(/^(\D{1,})(\d{1,}$)/)
      exit_with_message msg if server_and_index.nil?

      servers = Array(application[server_and_index[1]][server_and_index[2].to_i.pred])
      exit_with_message msg if servers.nil?
    end

    cmd = servers.count == 1 ? :ssh : :csshX
    puts "accessing server(s) #{yellow(servers)}..."
    system "#{cmd} #{(servers + ARGV).join(" ")}"' $@
}

_server() {
    local cur="${COMP_WORDS[COMP_CWORD]}"
    local prev=${COMP_WORDS[COMP_CWORD-1]}

    if [[ "$prev" == "server" ]]; then
        local projects=$(ruby -e 'require "yaml"; puts YAML.load_file("#{Dir.home}/.servers.yml").keys.join(" ") rescue ""')
    else
        local projects=$(ruby -e "require 'yaml'; puts YAML.load_file(\"#{Dir.home}/.servers.yml\")['$prev'].keys.join(' ') rescue ''")
    fi

    COMPREPLY=()
    COMPREPLY=( $(compgen -W "${projects}" -- ${cur}) )
}
complete -F _server server

E, finalmente, criar o arquivo ~/.servers.yml com o seguinte formato:

appname1:
  qa:
    - host1
    - host2
  stg:
    - host1
    - host2
appname2:
  qa:
    - host1
    - host2

A utilização então fica:

server appname env[index]

Caso você queria acessar todos os servidores do ambiente de qa da aplicação appname1, seria:

server appname1 qa

Ou apenas o host2 da aplicação appname1 no ambiente de stg:

server appname1 stg1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment