javaamazon-web-servicesamazon-ec2amazon-cloudwatchamazon-cloudwatch-metrics

Get current InstanceId in AWS Java SDK


I am using the AWS CloudWatch SDK to record metrics from a program running inside EC2 instance. I would like to report back the InstanceId as a dimension for these metrics. How do I find out the EC2 InstanceId from a Java program running inside the instance?


Solution

  • Use EC2MetadataUtils.

    import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils;
    
    String instanceId = EC2MetadataUtils.getInstanceId();