LoginSignup
1
0

More than 3 years have passed since last update.

【誰得?】AWS EC2 autoscaling でスケールアウト時にインスタンスの Tag:Name 値がユニークな値になるようにしたいぞ!!

Last updated at Posted at 2020-07-17

作った背景

ハピタスでは負荷に応じて EC2 インスタンスが自動でスケールアウト・インするように Autoscaling を導入しています。

導入前、システム上の課題で、EC2 インスタンスの Tag:Name がユニークであるという前提で稼働している監視サーバがあり、
単純にスケールアウトすると、Autoscaling Group で設定された Tag:Name が適用されてしまい、ユニークが崩壊するため、
監視サーバが正しく動作しなくなるという課題がありました。

そこでその課題を解決するために EC2 インスタンスの Tag:Name がユニークになるように今回の対応をしました。

まあ、誰得やねんって記事ですが、、
似たようなニッチな状況の人がいるかもしれません、そういう人に役に立てれば幸いですw

対応読者

  • AWS 触っている人
  • Autoscaling 導入しようとしている人
  • EC2 インスタンスの Tag:Name をユニークにしたいレアな方 もしくは、単に興味でこの記事を見ている方

 今回の対応

  • aws-cli をインスタンスに導入します (古い EC2 インスタンスでなければ、ほとんどはいってますね!)
  • User data なるものを使います

細かい手順は割愛します。

対応方法

一. AutoScaling を導入したい EC2 インスタンスに aws-cli が導入されているかを調べます

$ aws --version

これでバージョンが表示されなければ、インストールされていません。
AWS のドキュメント に従いインストールします。

二. インストール後 EC2 インスタンスの AMI を作ります
三. 起動設定を作ります。インスタンスタイプやSecurityGroup など、必要な設定をしてください。
  さらに [追加設定 - 省略可能(Additional configuration - optional)] の [高度な詳細(Advanced details)] の中の [ユーザーデータ(User data)] のテキスト箇所に以下のおまじないを記載します

Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

#cloud-config
cloud_final_modules:
- [scripts-user, always]

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

#!/bin/bash
instance_id=`curl -s 169.254.169.254/latest/meta-data/instance-id`
az=`curl -s 169.254.169.254/latest/meta-data/placement/availability-zone`
region=${az%[a-z]}
instance_name=`aws ec2 describe-instances --output text --region $region --instance-ids $instance_id \
  --query 'Reservations[].Instances[].Tags[?Key==\`Name\`].Value'`

if [[ $instance_name =~ $instance_id ]];
then
  exit 0;
fi

new_instance_name=${instance_name}-${instance_id}
aws ec2 create-tags --region $region --resources $instance_id --tags Key=Name,Value=${new_instance_name}

四. 作った起動設定を Autoscaling グループに適用します。そして、EC2 インスタンスに適用されるタグ名を以下のように設定しておきます

スクリーンショット 2020-07-17 16.28.27.png

あとは、スケールアウトされると勝手に EC2 インスタンスの Tag:Name が web-server-i-aabbccddee のように 設定した Name 値に ユニークな インスタンスID がひっつく形になります

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