LoginSignup
6
2

More than 5 years have passed since last update.

ElasticBeanstalk の EC2 内で、environment-name を取得する方法

Last updated at Posted at 2018-02-24

ElasticBeanstalk の EC2 内で、environment-name を取得するコマンド

aws ec2 describe-instances \
   --region `curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e 's/.$//'` \
   --instance-id `/usr/bin/curl -s http://169.254.169.254/latest/meta-data/instance-id` \
   --query 'Reservations[0].Instances[0].Tags[?Key==`elasticbeanstalk:environment-name`].Value' \
| ruby -r json -e 'puts JSON.parse(STDIN.read)[0]' 

前提条件

ElasticBeanstalk が生成する EC2 の IAM role で、ec2:DescribeInstances の実行が許可されていること
具体的にはこんなポリシーを書けばOK

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeInstances"
            ],
            "Resource": "*"
        }
    ]
}

コマンド解説

--region `curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e 's/.$//`'
  • region で絞り込む option
  • curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e 's/.$// で、自身の region を取得
    • インスタンスのメタデータplacement/availability-zoneavailability-zone を取得       - availability-zone の末尾の英語を取れば、region が取れる
--instance-ids `/usr/bin/curl -s http://169.254.169.254/latest/meta-data/instance-id`
--query 'Reservations[0].Instances[0].Tags[?Key==`elasticbeanstalk:environment-name`].Value'
  • describe-instances に渡す検索クエリ
  • 今回必要なのは、Tagの elasticbeanstalk:environment-name の値だけなので、それだけ返すように絞り込んでいる
ruby -r json -e 'puts JSON.parse(STDIN.read)[0]' 
  • クエリの戻り値が以下のような配列なので、バースして値だけ取得している
[
    "elasticbeanstalk:environment-name-value"
]

参考

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