AWSで踏み台の先にあるEC2にタグでsshする
AWS で踏み台の先にある EC2 にタグで ssh ログインするスクリプトを書いたので紹介します。
これまで踏み台の先にある EC2 インスタンスにログインするには、多段 ssh の設定を ~/.ssh/config に書いていましたが、AWS はインスタンスを作り直すとプライベート IP が変わるので ~/.ssh/config のメンテナンスが大変でした。
EC2 のタグでログインできるようにしたかったのでツールを探してみたところ、ec2-ssh が見つかりましたが、踏み台に対応していなかったので自分でスクリプトを書きました。同じようなことを考えている方の参考になれば幸いです。
目次
踏み台インスタンスの先にある EC2 インスタンスに ssh するスクリプト
やっていることは単純で、aws-cli を使って踏み台インスタンスの public ip を取得し、引数で渡されたタグ名を使ってログインしたいインスタンスの private ip を取得して ssh のコマンドに渡しているだけです。
#!/usr/bin/env bash set -e progname=$(basename $0) # check parameters if [ "$1" == "" ] || [ "$1" == "-h" ]; then echo "Usage: ${progname} <tag:Name>" echo "Ex: ${progname} web01" exit fi bastion_tag_name=bastion bastion_user=ec2-user bastion_port=22 bastion_ssh_key=~/.ssh/id_rsa remote_tag_name=$1 remote_user=ec2-user remote_port=22 remote_ssh_key=~/.ssh/id_rsa # find bastion's public ip bastion_public_ip=`aws ec2 describe-instances --query "Reservations[0].Instances[0].PublicIpAddress" --filters "Name=tag:Name,Values=${bastion_tag_name}" "Name=instance-state-name,Values=running" --output=text` if [ "${bastion_public_ip}" == "None" ]; then echo "The bastion instance's public_ip is not found" exit 1 fi # find remote host's private ip remote_private_ip=`aws ec2 describe-instances --query "Reservations[0].Instances[0].PrivateIpAddress" --filters "Name=tag:Name,Values=${remote_tag_name}" "Name=instance-state-name,Values=running" --output=text` if [ "${remote_private_ip}" == "None" ]; then echo "The ${remote_tag_name} instance is not available" exit 1 fi # connect remote host through bastion ssh -p ${remote_port} -i ${remote_ssh_key} \ -o ProxyCommand="ssh -p ${bastion_port} -i ${bastion_ssh_key} -W %h:%p ${bastion_user}@${bastion_public_ip}" \ ${remote_user}@${remote_private_ip}
使い方
AWS CLI の設定を済ませておき、aws ec2 describe-instances
コマンドを実行できるようにしておきます。
上記スクリプトを適当な名前で保存して実行権限を与えます。今回は ssh-tag とします。
$ chmod +x ssh-tag
上記スクリプトの 14 行目から 21 行目の remote_tag_name 以外の変数を自身の環境のものに書き換えます。
bastion_tag_name=bastion bastion_user=ec2-user bastion_port=22 bastion_ssh_key=~/.ssh/id_rsa remote_tag_name=$1 remote_user=ec2-user remote_port=22 remote_ssh_key=~/.ssh/id_rsa
設定は以上です。ログインしたいインスタンスのタグ名を引数に指定すればログインできます。
$ ssh-tag ec2-tag-name