[英]How to stop EC2 instance using Tag name in java?
I know how to stop an instance with its id, but its very difficult to give EC2 instance id every time. 我知道如何使用其ID停止实例,但是每次都很难给EC2实例ID。 How can I stop the instance with
Tag Name
如何使用
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);
How can I stop an instance by Tag Name
? 如何通过
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. 方法getRunningInstancesByTags只匹配唯一一个标签,您可以对其进行改进以支持更多标签匹配。
this is just an extension of @qrtt1 code to support multiple tags : 这只是@ 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.