0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

IMDSv2メモ

0
Posted at

EC2 の IMDSv2 (Instance Metadata Service v2) を使えば、EC2インスタンス内部から色々なサーバ情報(インスタンスID、AMI、ホスト名、セキュリティグループ、IAMロールなど)が取得できます。


基本ステップ(IMDSv2)

  1. トークンを取得

    TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" \
      -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
    
  2. トークンを使ってメタデータを取得

    # インスタンスID
    curl -H "X-aws-ec2-metadata-token: $TOKEN" \
      http://169.254.169.254/latest/meta-data/instance-id
    
    # AMI ID
    curl -H "X-aws-ec2-metadata-token: $TOKEN" \
      http://169.254.169.254/latest/meta-data/ami-id
    
    # インスタンスタイプ
    curl -H "X-aws-ec2-metadata-token: $TOKEN" \
      http://169.254.169.254/latest/meta-data/instance-type
    
    # VPC ID(NIC単位の情報)
    curl -H "X-aws-ec2-metadata-token: $TOKEN" \
      http://169.254.169.254/latest/meta-data/network/interfaces/macs/
    
  3. 全一覧を取得する

    curl -H "X-aws-ec2-metadata-token: $TOKEN" \
      http://169.254.169.254/latest/meta-data/
    

Windows (PowerShell) の場合

# トークン取得
$TOKEN = curl.exe -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"

# インスタンスIDを取得
curl.exe -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id

取得できる代表的な情報

  • instance-id: インスタンスのID
  • ami-id: 使用中のAMI
  • instance-type: t3.micro, m6i.large などのタイプ
  • local-ipv4 / public-ipv4: IPアドレス
  • security-groups: アタッチされているセキュリティグループ名
  • iam/info, iam/security-credentials/: IAMロール情報
  • placement/availability-zone: AZ情報

スクリーンショット 2025-09-23 14.30.23のコピー.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?