使用JAVA将标记设置为EC2实例

时间:2017-11-03 16:44:47

标签: java amazon-web-services amazon-ec2 tags cloud

这是我尝试的最后一个代码:

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);

它不能在线编译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>)

它让我将'setTags'改为'withTags'而相反(循环情况)。 尝试了几种方法,查看了AWS文档和Javadoc。

这是我的导入:

    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;

编辑: 目前的代码不起作用:

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);

2 个答案:

答案 0 :(得分:2)

您好像是从CreateTagsRequest而不是com.amazonaws.services.workspaces.model导入了com.amazonaws.services.ec2.model。请注意中间wokspacesec2之间存在差异。

答案 1 :(得分:0)

使用CreateTagsRequest类中的 withResources (instanceId)方法代替 withResourceId (instanceId),并且有效。

以下代码供参考:

     Collection<Tag> tags = new ArrayList<Tag>();
     Tag t = new Tag();
     t.setKey("keyname");
     t.setValue("keyvalue");
     tags.add(t);
     
     CreateTagsRequest createTagsRequest = new CreateTagsRequest();  
     createTagsRequest.withTags(tags);
     createTagsRequest.withResources(instanceId);
     
     ec2Client.createTags(createTagsRequest);