如何在java中使用Tag名称停止EC2实例?

时间:2011-09-02 06:11:30

标签: java amazon-ec2

我知道如何使用其id停止实例,但每次都很难给出EC2实例ID。如何使用Tag Name

停止实例
AmazonEC2 ec2 = new AmazonEC2Client(credentials);

List<String> instancesToStop = new ArrayList<String>();
instancesToStop.add("INSTANCE_ID");
StopInstancesRequest stoptr = new StopInstancesRequest();       
stoptr.setInstanceIds(instancesToStop);
ec2.stopInstances(stoptr);

如何按Tag Name停止实例?

2 个答案:

答案 0 :(得分:3)

您可以创建一个帮助方法来获取具有匹配标记的运行实例:

public List<String> getRunningInstancesByTags(String tagName, String value) {
    List<String> instances = new ArrayList<String>();
    for (Reservation reservation : ec2client.describeInstances().getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            if (!instance.getState().getName().equals(InstanceStateName.Running.toString())) {
                continue;
            }
            for (Tag tag : instance.getTags()) {
                if (tag.getKey().equals(tagName) && tag.getValue().equals(value)) {
                    instances.add(instance.getInstanceId());
                }
            }
        }
    }
    return instances;
}

方法getRunningInstancesByTags只是简单匹配唯一的一个标记,您可以改进它以支持更多的标记匹配。

答案 1 :(得分:0)

这只是@ qrtt1代码的扩展,以支持多个标签:

private static final AWSCredentials AWS_CREDENTIALS = new BasicAWSCredentials("ABCDEF", "MNOPQRSTUVWXYZ");
private static final Map<String, String> ec2Tags = new LinkedHashMap<String, String>();
static {
    //ADD YOUR EC2 TAGS
    ec2Tags.put("stage", "test"); 
    ec2Tags.put("canBeStopped", "true");
}
public static List<Instance> getRunningInstancesByTags(Map<String, String> ec2Tags) {
    AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
                         .withCredentials(new AWSStaticCredentialsProvider(AWS_CREDENTIALS))
                         .withRegion(Regions.EU_CENTRAL_1).build();
    List<Instance> instances = new ArrayList<Instance>();
    Map<String, String> instanceTags = new LinkedHashMap<String, String>();
    for (Reservation reservation : ec2Client.describeInstances().getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            if (!instance.getState().getName().equals(InstanceStateName.Running.toString())) {
                continue;
            }
            instanceTags = instance.getTags().stream()
                       .collect(Collectors.toMap(Tag::getKey, Tag::getValue));
            if (instanceTags.entrySet().containsAll(ec2Tags.entrySet())) {
                logger.info("{}", instanceTags.entrySet().toString());
                instances.add(instance);
            }
        }
    }
    return instances;
}