Check the public address from EC2 metadata

TOC

Check the public address from EC2 metadata

Access to instance metadata provides access to a variety of information about the instance.

Instance metadata is data about your instance that you can use to configure or manage the running instance. Instance metadata is divided into categories, for example, host name, events, and security groups.

Instance metadata and user data

There are also two ways to retrieve instance metadata. IMDSv1 and IMDSv2.

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

This time we will use both to check the metadata, especially the IPv4 public address values.

Environment

Diagram of checking the public address from EC2 metadata

Create an EC2 instance within the public address. The OS of the instance is Amazon Linux 2.

This instance is assigned a public address.

SSM Session Manager is used to access the instance.

CloudFormation template files

The above configuration is built with CloudFormation. The CloudFormation templates are placed at the following URL

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

Explanation of key points of template files

EC2 Instance

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)

The key setting for the instance is the AssociatePublicIpAddress property. Enabling this property will automatically assign a public address when the instance is started.

The IAM role for the instance attaches the AWS management policy AmazonSSMMManagedInstanceCore. This grants access to the instance using SSM Session Manager.

Architecting

Use CloudFormation to build this environment and check its actual behavior.

Create CloudFormation stacks and check the resources in the stacks

Create CloudFormation stacks. For information on how to create stacks and check each stack, please see the following page.

あわせて読みたい
CloudFormation’s nested stack 【How to build an environment with a nested CloudFormation stack】 Examine nested stacks in CloudFormation. CloudFormation allows you to nest stacks. Nested ...

After reviewing the resources in each stack, information on the main resources created in this case is as follows

  • EC2 instance: i-0d820a868682a89cc

Operation Check

Now that you are ready, access the EC2 instance.

SSM Session Manager is used to access EC2 instances.

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

For more information on SSM Session Manager, please refer to the following page.

あわせて読みたい
Accessing Linux instance via SSM Session Manager 【Configure Linux instances to be accessed via SSM Session Manager】 We will check a configuration in which an EC2 instance is accessed via SSM Session Manag...

IMDSv1

Use IMDSv1 to retrieve metadata. With IMDSv1, you can retrieve metadata simply by accessing the URL shown below.

https://docs.aws.amazon.com/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)

A list of information that can be retrieved as metadata is now displayed.

This time we will check the public address.

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

We did indeed get a public address.

IMDSv2

For IMDSv2, obtain a session token and use it to retrieve metadata.

https://docs.aws.amazon.com/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)

Even with IMDSv2, we were able to obtain a public address.

(Reference) ec2-metadata command

For Amazon Linux, metadata can also be obtained by using the ec2-metadata command.

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)

This command will, by default, display all information.

Check the help for the command.

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)

The -v/–public-ipv4 option indicates that only IPv4 public addresses can be obtained.

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

We did indeed get a public address.

Summary

We have identified how to check the metadata (IPv4 public address).

TOC