1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWSで、パブリックサブネットに作成したインスタンスのIPを取得する

Posted at

作業用に使えそうだったのでメモ
AWSで、パブリックサブネットに作成したインスタンスに、ElasticIPアドレスを割り当てていないと、
再起動の際に毎回違うパブリックIPが割り当てられるので、取得が面倒ですよね。。
ElasticIPアドレスを割り当てていない作業用のssh踏み台サーバーへ楽にssh出来る方法を考えてみました

インスタンスを起動したタイミングで以下のシェルを実行すると、
楽にsshできるようになります

実行方法
./getPublicIpAddress.sh
ssh test_server1
getPublicIpAddress.sh
# !/bin/bash
ip=$(aws ec2 describe-instances --filter "Name=tag:Name,Values=test_server1" | jq '.Reservations[].Instances[].PublicIpAddress' )
echo $ip
sed  -i -e  "/test_server1$/s/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/${ip//\"/}/" /etc/hosts

([0-9]{1,3}.){3}[0-9]{1,3}:IPアドレス変換用の正規表現
${ip//"/}:変数をパラメータ展開して、変数ipについている”を除外

/etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
0.0.0.0 test_server1

シェル実行によって「0.0.0.0 (ネームタグの名前)」の部分が置き換わります
停止時に実行するとnullが入ってしまうので、起動時に実行します

/etc/ssh/ssh_config
Host test_server1
 User ec2-user
 IdentityFile /(鍵の場所)/my-keypair.pem

ローカル環境:CentOS7

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?