2017-06-04 25 views
0

我已經部署了一個由3臺Ubuntu機器組成的Amazon EC2集羣(其中2個組成集羣,最後一個只是提交作業並管理其存儲的客戶端) 。我通過無密碼SSH連接到所有人。從終端輸出中替換Amazon EC2 SSH主機名(文本文件)

什麼情況是,我每次重新啓動這些機器時,他們得到來自亞馬遜新的公共主機名,我想在位於~/.ssh/config

到目前爲止,我的SSH的配置文件來替換,我想出了一個辦法讓他們的名字在我的本地機器(CentOS的7)使用Amazon CLI使用以下命令主機名:

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等,基本上是由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 

請注意,我不知道該怎麼亞馬遜CLI命令排序輸出。但是,當然,我可以在我的SSH文件中更改機器的順序,或者刪除它並重新創建它是個好主意。

+0

爲什麼不使用彈性IP在重啓機器時不會改變? – helloV

+0

@helloV你確定嗎?因爲我在他們的文檔中發現了這一點:「爲確保有效使用彈性IP地址,如果彈性IP地址與正在運行的實例無關,或者它與已停止的實例或未連接的網絡相關聯,我們會收取小時費用接口。當您的實例正在運行時,您不需要爲與該實例關聯的一個彈性IP地址收費,但您需要爲與該實例相關的任何其他彈性IP地址收費。「在我的情況下,我停止(不重新啓動)集羣幾個小時每天。 – mgus

+0

是的,你收取$ .005 /小時。實例停止時,每個實例一個半小時。 – helloV

回答

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