简体   繁体   中英

In java, how can I get an Amazon EC2 Instance to see its own tags?

So I have a java program running within an Amazon EC2 instance. Is there a way to programatically get its own tags? I have tried instantiating a new AmazonEC2Client to us the describeTags() function but it only gives me null. Any help would be appreciated thank you.

Edit: To make things clearer, the instances are going to be unmanned worker machines spun up to solely do some computations

You should be able to get the current instance id by sending a request to: http://169.254.169.254/latest/meta-data/instance-id . This only works within ec2. With this you can access quite a bit of information about the instance. However, tags do not appear to be included.

You should be able to take the instance id along with the correct authentication to get the instance tags. If you are going to run this on an instance, you may want to provide an IAM user with limited access instead of a user which has access to everything in case the instance is compromised.

While using user-data may be the simplest solution, the OP was asking specifically about the tagging, and unfortunately amazon hasn't made this as easy as it could be. However, It can be done. You want to use a combination of 2 amazon services.

  1. First you need to retrieve the Instance ID. This can be achieved by hitting the URL from within your instance:

    http://169.254.169.254/latest/meta-data/instance-id

  2. Once you have the resource ID, you'll want to use Amazon's EC2 API to access the tags. Since you said you're using Java, I would suggest the Using the AWS SDK amazon makes available . Within this SDK you'll find a method called describeTags ( documentation ). You can use a Resource ID as one of the filters to get the specific tags to your instance. Supported filters are

     tag key resource-id resource-type 

I suggest doing this retrieval at boot using something like cloud-init and caching the tags on your server for use later if necessary.

This should help you get started...

String instanceId = EC2MetadataUtils.getInstanceId();
AmazonEC2 client = AmazonEC2ClientBuilder.standard()
    .withCredentials(new DefaultAWSCredentialsProviderChain())
    .build();
DescribeTagsRequest req = new DescribeTagsRequest()
    .withFilters(new Filter("resource-id", Collections.singletonList(instanceId)));
DescribeTagsResult describeTagsResult = client.describeTags(req);
List<TagDescription> tags = describeTagsResult.getTags()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM