如何自动化EC2实例启动和ssh连接

时间:2017-02-06 05:33:51

标签: amazon-web-services amazon-ec2

目前我手动连接以下步骤:

  1. 打开EC2-Instance web
  2. 操作下 - > 实例状态点击开始
  3. 查看连接标签
  4. 手动复制ssh命令,例如:

    ssh -i "mykey.pem" ubuntu@ec2-13-112-241-333.ap-northeast-1.compute.amazonaws.com

  5. 最佳做法是什么,以便我可以通过本地计算机中的命令行简化这些词干?这样我就可以使用一个命令。

1 个答案:

答案 0 :(得分:3)

awscli的方法是

# Start the instance
aws ec2 start-instances --instance-ids i-xxxxxxxxxxx

status=0

# Wait for the instance until the 2/2 checks are passed
while [ $status -lt 2]
do
    status=`aws ec2 describe-instance-status --instance-ids  i-xxxxxxxxxxx --filters Name="instance-status.reachability,Values=passed" | grep  '"Status": "passed"' | wc -l`
    # add sleep time 
done

#  Associate an Elastic IP if already have one allocated (skip if not reqd)
aws ec2 associate-address --instance-id i-xxxxxxxxxxx --public-ip elastic_ip

#  Get the Public DNS, (If the instance has only PrivateIp, grep "PrivateIpAddress")
public_dns=`aws ec2 describe-instances --instance-ids i-xxxxxxxxxxx | grep "PublicDnsName" | head -1 | awk -F: '{print $2}' | sed 's/\ "//g;s/",//g'`

ssh -i key.pem username@public_dns