For instances which use version 2 of instance metadata, IMDSv2, run the following 2 commands:

[ec2-user@ip-172-31-45-35 ~]$ TOKEN=`curl -X PUT "" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
[ec2-user@ip-172-31-45-35 ~]$ curl -w "\n" -H "X-aws-ec2-metadata-token: $TOKEN"

If you use IMDsv1, then there is no need generate the TOKEN value first, just query the instance-id directly:

[ec2-user@ip-172-31-45-35 ~]$ curl -w "\n"

In my case, it returned nothing as my EC2 instances uses IMDsV2. Oh, by the way, are you aware of -w or --write-out flag for curl? It’s pretty cool, you can use it to inject a newline character e.g. "\n" to the end of output from the curl command.