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 "http://169.254.169.254/latest/api/token" -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" http://169.254.169.254/latest/meta-data/instance-id
i-04bd6066612345678

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" http://169.254.169.254/latest/meta-data/instance-id

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.