Search code examples
javaamazon-web-servicesamazon-ec2tagscloud

Set a tag to EC2 instance using JAVA


This is the last code I tried:

System.out.println("Manager not exists. Going to create.");
            // Basic 32-bit Amazon Linux AMI 1.0 (AMI Id: ami-08728661)
            RunInstancesRequest request = new RunInstancesRequest("ami-acd005d5", 1, 1);
            request.setInstanceType(InstanceType.T2Micro.toString());
            List<Instance> instances = ec2.runInstances(request).getReservation().getInstances();
            System.out.println("Launch instances: " + instances);
            Instance instance = instances.get(0);

            Collection<String> resources = new ArrayList();
            resources.add(instance.getInstanceId());
            Collection<Tag> tags = new ArrayList();
            tags.add(new Tag("Name", "Manager"));
            CreateTagsRequest createTagsRequest = new CreateTagsRequest();  
            createTagsRequest.setResourceId(instance.getInstanceId());
            createTagsRequest.setTags(tags);
            CreateTagsResult tagsRsults = createTags(createTagsRequest);

It doesn't compile on line createTagsRequest.setTags(tags):

The method setTags(java.util.Collection<com.amazonaws.services.workspaces.model.Tag>) in the type CreateTagsRequest is not applicable for the arguments (java.util.Collection<com.amazonaws.services.ec2.model.Tag>)

It offers me to change 'setTags' to 'withTags' and the opposite (Circular situation) . Tried several methods, looked at the AWS documentation and Javadoc.

This is my imports:

    import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceStateName;
import com.amazonaws.services.ec2.model.InstanceType;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.Tag;

Edit: Current code not working:

Collection<Tag> tags = new ArrayList<Tag>();
Tag t = new Tag();
            t.setKey("Name");
            t.setValue("Manager");
            tags.add(t);
            CreateTagsRequest createTagsRequest = new CreateTagsRequest();  
            createTagsRequest.withTags(tags);
            createTagsRequest.withResourceId(instance.getInstanceId());
            ec2.createTags(createTagsRequest);

Solution

  • It seems like you imported CreateTagsRequest from com.amazonaws.services.workspaces.model instead of from com.amazonaws.services.ec2.model. Notice the difference there between wokspaces and ec2 in the middle.