skip to Main Content

Actually, I was looking to get the EC2 instance name,

enter image description here

I tried using EC2MetadataUtils class to get the metadata but in that response, the instance name is not there.
Could you please someone suggest any util class endpoint to get the name?

2

Answers


  1. As luk2302 correctly states, the Name field is just a tag. The EC2 documentation has an example for how you can retrieve tags from the instance metadata:

    https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html#instance-metadata-ex-7

    Login or Signup to reply.
  2. You can use this Java code piece. EC2MetadataUtils does not currently allow to read tags by SDK.

            Ec2Client ec2Client = Ec2Client.builder().build();
            String instanceId = "i-qqweqweqwe";
            DescribeInstancesRequest instanceRequest = DescribeInstancesRequest.builder()
                    .instanceIds(instanceId)
                    .build();
    
            DescribeInstancesResponse describeInstancesResponse = ec2Client.describeInstances(instanceRequest);
            if (describeInstancesResponse.reservations().size() > 0 && describeInstancesResponse.reservations().get(0).instances().size() > 0) {
                List<Tag> tags = describeInstancesResponse.reservations().get(0).instances().get(0).tags();
                Optional<String> name = tags.stream().filter(t -> t.key().equals("Name")).map(Tag::value).findFirst();
                if (name.isPresent()) {
                    System.out.println(instanceId + " name is " + name);
                }
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search