Skip to content

Instantly share code, notes, and snippets.

@rgranadino
Last active February 16, 2018 18:12
Show Gist options
  • Save rgranadino/cce210300a284fc4089f90434dde3b4b to your computer and use it in GitHub Desktop.
Save rgranadino/cce210300a284fc4089f90434dde3b4b to your computer and use it in GitHub Desktop.
AWS ECS ssh helper
#!/usr/bin/ruby
require 'json'
$sshUser = 'ec2user'
#NOTE all of our ecs clusters are prefixed with "ecs-"
#which we assume here to save the time & trouble of having to type that out
#all of our tasks are also suffixed with the "environment" name
def sshToEcsInstance(clusterName)
cmd = "aws ecs list-container-instances --cluster ecs-"+ clusterName
instances = JSON.parse(`#{cmd}`)["containerInstanceArns"]
ec2InstanceHostname = getInstanceInfo(clusterName, instances.sample)
system("ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -J bastion #{$sshUser}@#{ec2InstanceHostname}")
end
def sshToTask(clusterName, taskName, subcommand)
cmd = "aws ecs list-tasks --cluster ecs-"+ clusterName
taskArns = JSON.parse(`#{cmd}`)["taskArns"].join(' ')
tasks = JSON.parse(` aws ecs describe-tasks --cluster ecs-#{clusterName} --tasks #{taskArns}`)['tasks']
tasks = tasks.select {|task|task["group"] == "service:#{taskName}-#{clusterName}"}
containerArns = tasks.map{ |x| x["containerInstanceArn"]}.flatten
ec2InstanceHostname = getInstanceInfo(clusterName, containerArns.sample)
system("ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -J bastion -t #{$sshUser}@#{ec2InstanceHostname} run-task #{taskName} #{subcommand}")
end
def getInstanceInfo(clusterName, containerArn)
ecsInstanceInfo = JSON.parse(`aws ecs describe-container-instances --cluster ecs-#{clusterName} --container-instances #{containerArn}`)["containerInstances"][0];
instanceId = ecsInstanceInfo["ec2InstanceId"];
ec2InstanceInfo = JSON.parse(`aws ec2 describe-instances --instance-ids #{instanceId}`)["Reservations"][0]["Instances"][0];
ec2InstanceIp = ec2InstanceInfo["PrivateIpAddress"];
#print ec2InstanceInfo["NetworkInterfaces"][0]
#PrivateIpAddress
#PrivateDnsName
ec2InstanceHostname = ec2InstanceInfo["NetworkInterfaces"][0]["PrivateIpAddress"];
end
clusterName = ARGV.shift
taskName = ARGV.shift
args = ARGV.join(' ')
subcommand = (args.empty?) ? 'bash' : args
#print taskName.inspect
#print clusterName.inspect
#print subcommand.inspect
if taskName.nil?
print "Finding instance in cluster: #{clusterName}"
sshToEcsInstance(clusterName)
else
print "Finding container running task: #{taskName}"
sshToTask(clusterName, taskName, subcommand)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment