Created
August 30, 2017 16:04
-
-
Save th3james/d343a2386ff121325db27901a6ecd0a0 to your computer and use it in GitHub Desktop.
This file contains 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 | |
# Executes a given command on a given ecs cluster | |
# Usage: | |
# ./ecs_cluster_exec.rb cluster-name docker ps | |
def command_pipe(*commands) | |
commands.join(' | ') | |
end | |
def get_cluster_host_arns(cluster_name) | |
command_pipe( | |
"aws ecs list-container-instances --cluster #{cluster_name} --output text", | |
"awk '{split($2,a,\"/\"); print a[2]}'" | |
) | |
end | |
def get_cluster_host_ids(cluster_name) | |
command_pipe( | |
"aws ecs describe-container-instances --output text --cluster #{cluster_name} --container-instances $(#{get_cluster_host_arns(cluster_name)})", | |
"grep CONTAINERINSTANCES", | |
"awk '{print $4}'" | |
) | |
end | |
def get_instance_address(id) | |
command_pipe( | |
"aws ec2 describe-instances --instance-ids=#{id}", | |
"grep ASSOCIATION", | |
"head -n1", | |
"awk '{print $3}'" | |
) | |
end | |
def ec2_run_command(server_address, command) | |
"ssh ec2-user@#{server_address} \"#{command}\"" | |
end | |
def run(cmd) | |
`#{cmd}`.split("\n") | |
end | |
cluster_name = ARGV[0] || (raise "Missing first argument cluster_name") | |
raise "Missing command to execute on cluster" if ARGV.length < 2 | |
command = ARGV[1..-1].join(' ') | |
cluster_host_ids = run(get_cluster_host_ids(cluster_name)) | |
puts cluster_host_ids.map { |id| | |
run(get_instance_address(id))[0] | |
}.map { |ec2_address| | |
run(ec2_run_command(ec2_address, command)).map { |ps_row| | |
"#{ec2_address}\t#{ps_row}" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment