EC2のメタデータからパブリックアドレスを確認する

EC2のメタデータからパブリックアドレスを確認する

EC2のメタデータからパブリックアドレスを確認する

インスタンスメタデータにアクセスすると、インスタンスのさまざまな情報にアクセスすることができます。

インスタンスメタデータは、インスタンスに関するデータで、実行中のインスタンスを設定または管理するために使用します。インスタンスメタデータは、ホスト名、イベント、およびセキュリティグループなどでカテゴリ分けされます。

インスタンスメタデータとユーザーデータ

またインスタンスのメタデータを取得する方法は2つあります。
IMDSv1とIMDSv2です。

https://docs.aws.amazon.com/ja_jp/AWSEC2/latest/WindowsGuide/configuring-instance-metadata-service.html

今回は両者を使用して、メタデータ、特にIPv4のパブリックアドレスの値を確認します。

構築する環境

Diagram of checking the public address from EC2 metadata

パブリックアドレス内にEC2インスタンスを作成します。
インスタンスのOSはAmazon Linux 2です。

このインスタンスにはパブリックアドレスを付与します。

インスタンスへのアクセスはSSM Session Managerを使用します。

CloudFormationテンプレートファイル

上記の構成をCloudFormationで構築します。
以下のURLにCloudFormationテンプレートを配置しています。

https://github.com/awstut-an-r/awstut-dva/tree/main/03/009

テンプレートファイルのポイント解説

EC2インスタンス

Resources:
  Instance:
    Type: AWS::EC2::Instance
    Properties:
      IamInstanceProfile: !Ref InstanceProfile
      ImageId: !Ref ImageId
      InstanceType: !Ref InstanceType
      NetworkInterfaces:
        - AssociatePublicIpAddress: true
          DeviceIndex: 0
          SubnetId: !Ref PublicSubnet
          GroupSet:
            - !Ref InstanceSecurityGroup

  InstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: /
      Roles:
        - !Ref InstanceRole

  InstanceRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service:
                - ec2.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
Code language: YAML (yaml)

インスタンスのポイントとなる設定はAssociatePublicIpAddressプロパティです。
本プロパティを有効化することで、インスタンス起動時に、自動的にパブリックアドレスが付与されます。

インスタンス用のIAMロールでは、AWS管理ポリシーAmazonSSMManagedInstanceCoreをアタッチします。
これはSSM Session Managerを使用して、インスタンスにアクセスするための権限を与えるものです。

環境構築

CloudFormationを使用して、本環境を構築し、実際の挙動を確認します。

CloudFormationスタックを作成し、スタック内のリソースを確認する

CloudFormationスタックを作成します。
スタックの作成および各スタックの確認方法については、以下のページをご確認ください。

あわせて読みたい
CloudFormationのネストされたスタックで環境を構築する 【CloudFormationのネストされたスタックで環境を構築する方法】 CloudFormationにおけるネストされたスタックを検証します。 CloudFormationでは、スタックをネストす...

各スタックのリソースを確認した結果、今回作成された主要リソースの情報は以下の通りです。

  • EC2インスタンス:i-0d820a868682a89cc

動作確認

準備が整いましたので、EC2インスタンスにアクセスします。

EC2インスタンスへのアクセスはSSM Session Managerを使用します。

% aws ssm start-session --target i-0d820a868682a89cc
...
sh-4.2$
Code language: Bash (bash)

SSM Session Managerの詳細につきましては、以下のページをご確認ください。

あわせて読みたい
LinuxインスタンスにSSM Session Manager経由でアクセスする 【LinuxインスタンスにSSM Session Manager経由でアクセスする】 EC2インスタンスにSSM Session Manager経由でアクセスする構成を確認します。 Session Manager は完全...

IMDSv1

IMDSv1を使用して、メタデータを取得します。
IMDSv1の場合、以下で示されているURLにアクセスするだけで、メタデータを取得することができます。

https://docs.aws.amazon.com/ja_jp/AWSEC2/latest/WindowsGuide/instancedata-data-retrieval.html

sh-4.2$ curl http://169.254.169.254/latest/meta-data/
ami-id
ami-launch-index
ami-manifest-path
block-device-mapping/
events/
hostname
iam/
identity-credentials/
instance-action
instance-id
instance-life-cycle
instance-type
local-hostname
local-ipv4
mac
metrics/
network/
placement/
profile
public-hostname
public-ipv4
reservation-id
security-groups
services/
system
Code language: Bash (bash)

メタデータとして取得可能な情報の一覧が表示されました。

今回はパブリックアドレスを確認します。

sh-4.2$ curl http://169.254.169.254/latest/meta-data/public-ipv4
52.195.211.122
Code language: Bash (bash)

確かにパブリックアドレスを取得できました。

IMDSv2

IMDSv2の場合、セッショントークンを取得し、それを使用してメタデータを取得します。

https://docs.aws.amazon.com/ja_jp/AWSEC2/latest/WindowsGuide/instance-metadata-v2-how-it-works.html

sh-4.2$ TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    56  100    56    0     0  44515      0 --:--:-- --:--:-- --:--:-- 56000

sh-4.2$ echo $TOKEN
AQAEAMxZLlDDeFBV_400m11KwG4RzZ6U9o5MvRDSu65XENr1o7oF2w==

sh-4.2$ curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/public-ipv4
52.195.211.122
Code language: Bash (bash)

IMDSv2でも、パブリックアドレスを取得することができました。

(参考) ec2-metadataコマンド

Amazon Linuxの場合、ec2-metadataコマンドを使用することで、メタデータを取得することもできます。

sh-4.2$ ec2-metadata
ami-id: ami-03eb0c9af5e36050f
ami-launch-index: 0
ami-manifest-path: (unknown)
ancestor-ami-ids: not available
block-device-mapping:
         ami: xvda
         root: /dev/xvda
instance-id: i-0d820a868682a89cc
instance-type: t4g.nano
local-hostname: ip-10-0-1-92.ap-northeast-1.compute.internal
local-ipv4: 10.0.1.92
kernel-id: not available
placement: ap-northeast-1a
product-codes: not available
public-hostname: not available
public-ipv4: 52.195.211.122
public-keys:
not available
ramdisk-id: not available
reservation-id: r-07070372d1b5297a6
security-groups: dva-03-009-InstanceSecurityGroup
user-data: not available
Code language: Bash (bash)

このコマンドを実行すると、デフォルトですと、全ての情報が表示されます。

コマンドのヘルプを確認します。

sh-4.2$ ec2-metadata help
ec2-metadata v0.1.2
Use to retrieve EC2 instance metadata from within a running EC2 instance.
e.g. to retrieve instance id: ec2-metadata -i
                 to retrieve ami id: ec2-metadata -a
                 to get help: ec2-metadata --help
For more information on Amazon EC2 instance meta-data, refer to the documentation at
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html

Usage: ec2-metadata <option>
Options:
--all                     Show all metadata information for this host (also default).
-a/--ami-id               The AMI ID used to launch this instance
-l/--ami-launch-index     The index of this instance in the reservation (per AMI).
-m/--ami-manifest-path    The manifest path of the AMI with which the instance was launched.
-n/--ancestor-ami-ids     The AMI IDs of any instances that were rebundled to create this AMI.
-b/--block-device-mapping Defines native device names to use when exposing virtual devices.
-i/--instance-id          The ID of this instance
-t/--instance-type        The type of instance to launch. For more information, see Instance Types.
-h/--local-hostname       The local hostname of the instance.
-o/--local-ipv4           Public IP address if launched with direct addressing; private IP address if launched with public addressing.
-k/--kernel-id            The ID of the kernel launched with this instance, if applicable.
-z/--availability-zone    The availability zone in which the instance launched. Same as placement
-c/--product-codes        Product codes associated with this instance.
-p/--public-hostname      The public hostname of the instance.
-v/--public-ipv4          NATted public IP Address
-u/--public-keys          Public keys. Only available if supplied at instance launch time
-r/--ramdisk-id           The ID of the RAM disk launched with this instance, if applicable.
-e/--reservation-id       ID of the reservation.
-s/--security-groups      Names of the security groups the instance is launched in. Only available if supplied at instance launch time
-d/--user-data            User-supplied data.Only available if supplied at instance launch time.
Code language: Bash (bash)

-v/–public-ipv4オプションを指定すると、IPv4のパブリックアドレスのみを取得できることがわかります。

sh-4.2$ ec2-metadata --public-ipv4
public-ipv4: 52.195.211.122
Code language: Bash (bash)

確かにパブリックアドレスを取得できました。

まとめ

メタデータ(IPv4パブリックアドレス)を確認する方法を確認しました。