I know how to stop an instance with its id, but its very difficult to give EC2 instance id every time. How can I stop the instance with Tag Name
AmazonEC2 ec2 = new Am开发者_运维知识库azonEC2Client(credentials);
List<String> instancesToStop = new ArrayList<String>();
instancesToStop.add("INSTANCE_ID");
StopInstancesRequest stoptr = new StopInstancesRequest();
stoptr.setInstanceIds(instancesToStop);
ec2.stopInstances(stoptr);
How can I stop an instance by Tag Name
?
You can create a help method to get running instance with matching tag:
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;
}
The method getRunningInstancesByTags just simply matches the only one tag, you can improve it to support more tag matching.
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;
}
精彩评论