this is just an extension of @qrtt1 code to support multiple tags :
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;
}