Actually, I was looking to get the EC2 instance name,
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?
CodePudding user response:
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:
CodePudding user response:
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);
}
}