从终端输出替换Amazon EC2 SSH主机名(文本文件)

时间:2017-06-04 05:04:31

标签: linux amazon-web-services ssh amazon-ec2

我已部署了3台Ubuntu计算机的Amazon EC2集群(其中2台构成了集群,最后一台只是提交作业和管理存储的客户端)。我通过无密码SSH连接到所有这些。

每次重新启动这些计算机时,他们都会从Amazon获取新的公共主机名,我想在~/.ssh/config

中的SSH配置文件中替换它

到目前为止,我找到了一种方法,可以使用Amazon CLI在我的本地计算机(CentOS 7)上使用以下命令获取其名称和主机名:

aws ec2 describe-instances --query "Reservations[*].Instances[*].[PublicDnsName,Tags]" --output=text | grep -vwE "None"

这会打印类似

的内容
ec2-XX-XX-XXX-XXX.us-east-2.compute.amazonaws.com
Name    datanode1
ec2-YY-YY-YYY-YYY.us-east-2.compute.amazonaws.com
Name    namenode
ec2-ZZ-ZZ-ZZZ-ZZZ.us-east-2.compute.amazonaws.com
Name    client

即。主机名,新行,相应的名称等。上面的IP字段如XX-XX-XXX-XXX等基本上是4个连字符分隔的2或3位数字。 grep命令我只删除了最后一条无用的行。现在我想找到一种方法将这些主机名替换为SSH配置文件,或者重新生成它,看起来像

Host namenode
  HostName ec2-YY-YY-YYY-YYY.us-east-2.compute.amazonaws.com
  User ubuntu
  IdentityFile ~/.ssh/mykey.pem

Host datanode1
  HostName ec2-XX-XX-XXX-XX.us-east-2.compute.amazonaws.com
  User ubuntu
  IdentityFile ~/.ssh/mykey.pem

Host client
  HostName ec2-ZZ-ZZ-ZZZ-ZZZ.us-east-2.compute.amazonaws.com
  User ubuntu
  IdentityFile ~/.ssh/mykey.pem

请注意,我不知道Amazon CLI命令如何对输出进行排序。但是,当然,我可以在SSH文件中更改机器的顺序,或者删除它并重新创建它是个好主意。

1 个答案:

答案 0 :(得分:0)

以下是我最终想出来的结果。这是Bash脚本,您可以将其保存为.sh文件,如script.sh并执行。如果无法运行,请执行chmod +x script.sh。我添加了评论以澄清我在做什么。

#Ask Amazon CLI for your hostnames, remove the last line, replace the "Name\t" with "", combine every 2 consecutive lines and save to a txt file
aws ec2 describe-instances --query "Reservations[*].Instances[*].[PublicDnsName,Tags]" --output=text | grep -vwE "None" | sed 's/Name\t//g' | sed 'N;s/\n/ /' > 'ec2instances.txt';

#Change the following variables based on your cluster
publicKey="mykey.pem";
username="ubuntu";

#Remove any preexisting SSH configuration file
rm config
touch config

while read line
do
    #Read the line, keep the 1st word and save it as the public DNS
    publicDns=$(echo "$line" | cut -d " " -f1);

    #Read the line, keep the 2nd word and save it as the hostname you will be using locally to connect to your Amazon EC2
    instanceHostname=$(echo "$line" | cut -d " " -f2);

    #OK, we are now ready to store to SSH known hosts
    sshEntry="Host $instanceHostname\n";
    sshEntry="$sshEntry HostName $publicDns\n";
    sshEntry="$sshEntry User $username\n";
    sshEntry="$sshEntry IdentityFile ~/.ssh/$publicKey\n";

    #Attach to the EOF, '-e' enables interpretation of backslash escapes
    echo -e "$sshEntry" >> config

#Below is the txt file you will be traversing in the loop
done < ec2instances.txt

#Done
rm ~/.ssh/config
mv config ~/.ssh/config
rm ec2instances.txt