Is there an easy way to connect to EC2 instances u

2020-06-06 02:10发布

问题:

Our team is working on AWS, where we have lots of instances, which we keep adding and removing. Each instance has a logical name, which helps us know what it does as well as finding it. When we want to connect to one, though, we either need to update the ~/.ssh/config file all the time, or go to the web console, find the instance by its name, copying its IP and only then we can run it using:

ssh -i ~/.aws/my-pem-file.pem ubuntu@ec2-111-111-111-111.compute-1.amazonaws.com

I was wandering whether there is an easier way to do it, where you could specify the machine name, and EC2 would do the rest?

Something like

ssh-aws my-machine-name

回答1:

If you configure your instance/load balancer with an Elastic IP (which doesn't change), you can always use an SSH config file.

  • http://webadvent.org/2012/ssh-tips-by-lorna-mitchell
  • http://nerderati.com/2011/03/simplify-your-life-with-an-ssh-config-file/

Secondly, if you have the Unified AWS CLI Tools configured, you can add these functions to your Bash profile. Assuming every instance you have has a unique "Name" tag, this will return the IP address of that instance for SSH requests. (Otherwise, it will simply use the first "Name" match.)

function hostname_from_instance() {
    echo $(aws ec2 describe-instances --filters "{\"Name\":\"tag:Name\", \"Values\":[\"$1\"]}" --query='Reservations[0].Instances[0].PublicDnsName' | tr -d '"')
}

function ip_from_instance() {
    echo $(aws ec2 describe-instances --filters "{\"Name\":\"tag:Name\", \"Values\":[\"$1\"]}" --query='Reservations[0].Instances[0].PublicIpAddress' | tr -d '"')
}

function ssh-aws() {
    ssh -i ~/.ssh/your-keypair.pem ec2-user@$(ip_from_instance "$1")
}

Depending on whether you're running instances inside of VPC or not, sometimes you'll get back one or the other. All-public (classic) EC2 should always get back a hostname, and sometimes a public IP.

Feel free to tweak/adjust as necessary.



回答2:

I wrote a little bash script which uses aws-cli (thanks @Ryan Parman) to find the correct machine IP and PEM from the machine name:

http://sash.agassi.co.il/

To use it simply call

sash <machine-name>

I've also added more features to it like upload, download, and multiplex connect...



回答3:

The simple way would be enter this ssh -i ~/.aws/my-pem-file.pem ubuntu@ec2-111-111-111-111.compute-1.amazonaws.cominto a .sh file with a logical name as you specified. Now when u run $logical-name.sh, you are logged in to that instance. The file needs to be updated in case the instance address has changed. One option to overcome would be assign ip's to each instance but i'm not sure if that is feasible from your end.