LoginSignup
2
0

More than 5 years have passed since last update.

AWS EC2のNameタグをインスタンスのホスト名として設定する方法

Last updated at Posted at 2018-09-19

前提条件

  • curlとawscliが当該インスタンスにインストールされていること
  • 当該インスタンスにec2 describe-instances可能なIAMロールが設定されていること
#!/bin/sh
TMPDIR=/tmp

# 自分自身(インスタンス)のIDを取得する
curl 'http://169.254.169.254/latest/meta-data/instance-id' > ${TMPDIR}/instance-id.txt

# 自分自身(インスタンス)のホスト名を取得する
aws ec2 describe-instances \
--query 'Reservations[].Instances[].{Name:Tags[?Key==`Name`].Value}' \
--filter "Name=instance-id,Values=`cat ${TMPDIR}/instance-id.txt`" \
| jq -r .[0].Name[0] > ${TMPDIR}/hostname.txt

# ホスト名をセットする
hostname `cat ${TMPDIR}/hostname.txt`
2
0
1

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
2
0