0
0

More than 5 years have passed since last update.

EC2インスタンスのタグ情報を読み込んで振る舞いを変える

Last updated at Posted at 2016-06-19

目的

インスタンスの起動時、cloud-initで設定したスクリプトの中で
インスタンス自身のタグを読み取り、インスタンス自身が自分の役割を読み取り、振舞いを変える処理を行ってみます。

AWSで検証しましたが、『インスタンス自身が自分のメタデータを取得できる』
というクラウドベンダで『メタデータにRoleを設定する、という運用』
なら流用可能かもしれません( というより、個人的にはクラウドベンダに依存しない運用ができないか探してました )

このスクリプトは『ROLES変数にあるレシピ(role)を実行する』というだけなので、
例えばNIFTY cloudで先に export ROLES="hoge" してから、このセットアップ用スクリプトを流す、という方法にも使えます。

アイデア元

https://gist.github.com/na0AaooQ/440761480838103a5136
http://need4answer.blogspot.jp/2014/03/blog-post.html

メタデータ取得用URLに到達可能か確認してタグ取得

EC2インスタンスのRolesというタグの値を取得
if [ "x" = "x${ROLES}" ] && curl -s -m 1 http://169.254.169.254/ ; then
  # 環境変数 ROLESが空、かつ、AWSのAPIに到達可能であれば
  # タグ Nodesが設定されていないか確認する
  # インスタンス自身からのタグの取得の方法は、クラウドベンダによって異なると思われるが、
  # 現状、AWSのAPIに問い合わせを行っている。別クラウドベンダに対応する場合は別途処理を追加する必要がある
  REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e 's/.$//')
  INSTANCEID=$( curl -s http://169.254.169.254/latest/meta-data/instance-id)

  # インスタンス自身から自分のタグを取得するためにはインスタンスプロファイルを作成する必要があります
  ROLES=$(aws ec2 describe-instances --region=${REGION} --filters "Name=instance-id,Values=${INSTANCEID}" --query 'Reservations[].Instances[].Tags[?Key==`Roles`].Value' --output text)
fi

Rolesを実行

cloneしてRolesを実行
cd /usr/local
git clone ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/chef-repo
cd chef-repo
# 環境変数 ROLES、ないしAWS EC2のNodesタグに何もなければ、 roles/base.json を使ってchefレシピを流す
chef-client -z -r "role[${ROLES:-base}]" -L /var/log/chef.log
0
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
0
0