Home Generate Active AWS EC2 Instance Report
Post
Cancel

Generate Active AWS EC2 Instance Report

When sing AWS for running instance it’s important that we keep an eye on the running instances in-order to manage your cost. In most cases you will forget that you have started an instance to run your tests and It will run unnecessarily till you notice it. So in this pose I will explain how we can generate a simple Email everyday with the instances that are running. I will be using AWS SDK for this.

Prerequisits : aws cli configured in your machine.

Lets get started, So the final outcome will be something like below,

I will be generating an html report As you can see I have highlighted the instances that are running more than 2 hours. Also it captures information like Intance Name, ID, State, Instance Type, Started time, Associated stack and uptime. So following is the simple code segment that I have used.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package org.ycr.aws;

import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.Tag;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) {

        StringBuilder tempalte = new StringBuilder();
        // Excludes any permanently running instances from the report
        List<String> excludeIdList = new ArrayList<>();
        excludeIdList.add("i-0e637e411a26a3cd4");
        excludeIdList.add("i-0f978eabef81c5b20");
        
        tempalte.append("<!DOCTYPE html>\n" +
                        "<html>\n" +
                        "<head>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "\n" +
                        "<table id=\"customers\" border=\"1\" style=\"font-family: \"Trebuchet MS\", Arial, Helvetica, sans-serif; width: 100%;\">\n" +
                        "  <tr>\n" +
                        "    <th>Instance Name</th>\n" +
                        "    <th>Instance ID</th>\n" +
                        "    <th>State</th>\n" +
                        "    <th>Instance Type</th>\n" +
                        "    <th>Started Time Stamp</th>\n" +
                        "    <th>Associated Stack</th>\n" +
                        "    <th>Uptime(Hours)</th>\n" +
                        "  </tr>\n");
        final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();
        boolean done = false;
        boolean runningInstancesAvailable = false;

        DescribeInstancesRequest request = new DescribeInstancesRequest();
        while (!done) {
            DescribeInstancesResult response = ec2.describeInstances(request);

            for (Reservation reservation : response.getReservations()) {
                boolean exclude = false;
                for (Instance instance : reservation.getInstances()) {
                    for (String id : excludeIdList) {
                        if (id.equals(instance.getInstanceId())) {
                            exclude = true;
                            break;
                        }
                    }
                    if (!exclude) {
                        // Here I'm excluding instances that are t2.micro since they are included in the free tier.
                        if (instance.getState().getName().equals("running") && !instance.getInstanceType().equals
                                ("t2.micro")) {
                            runningInstancesAvailable = true;
                            // Get the insatance name
                            String instanceName = "Unknown";
                            String stackName = "No Stack!";
                            
                            // Iterating over the tags to find information ike stack name and instance name
                            if (instance.getTags() != null) {
                                for (Tag tag : instance.getTags()) {
                                    if (tag.getKey().equals("Name")) {
                                        instanceName = tag.getValue();
                                        System.out.println("Instance Name : " + instanceName);
                                    }
                                    if (tag.getKey().equals("aws:cloudformation:stack-name")){
                                        stackName = tag.getValue();
                                    }
                                }
                            }
                            // Calculating the uptime
                            long uptime = getDateDiff(instance.getLaunchTime(), new Date(), TimeUnit.HOURS);
                            // If the uptime is more than 2 hours highlighting the text.
                            if (uptime > 2) {
                                tempalte.append("  <tr style=\"color: #f71313; font-weight:bold\">\n" +
                                                "    <td>" + instanceName + "</td>\n" +
                                                "    <td>" + instance.getInstanceId() + "</td>\n" +
                                                "    <td>" + instance.getState().getName() + "</td>\n" +
                                                "    <td>" + instance.getInstanceType() + "</td>\n" +
                                                "    <td>" + instance.getLaunchTime().toString() + "</td>\n" +
                                                "    <td>" + stackName + "</td>\n" +
                                                "    <td style=\"text-align:center\">" + uptime + "</td>\n" +
                                                "  </tr>\n");

                            } else {
                                tempalte.append("  <tr>\n" +
                                                "    <td>" + instanceName + "</td>\n" +
                                                "    <td>" + instance.getInstanceId() + "</td>\n" +
                                                "    <td>" + instance.getState().getName() + "</td>\n" +
                                                "    <td>" + instance.getInstanceType() + "</td>\n" +
                                                "    <td>" + instance.getLaunchTime().toString() + "</td>\n" +
                                                "    <td>" + stackName + "</td>\n" +
                                                "    <td style=\"text-align:center\">" + uptime + "</td>\n" +
                                                "  </tr>\n");
                            }

                            System.out.printf(
                                    "Found instance with id %s, " +
                                    "AMI %s, " +
                                    "type %s, " +
                                    "state %s " +
                                    "and monitoring state %s",
                                    instance.getInstanceId(),
                                    instance.getImageId(),
                                    instance.getInstanceType(),
                                    instance.getState().getName(),
                                    instance.getMonitoring().getState());
                        }
                        instance.getKeyName();
                    }
                }
            }
            request.setNextToken(response.getNextToken());
            if (response.getNextToken() == null) {
                done = true;
            }
        }
        tempalte.append("</table>\n" +
                        "</body>\n" +
                        "</html>");
        System.out.println(tempalte);
        if (runningInstancesAvailable){
            File file = new File("./mail.html");
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                writer.write(tempalte.toString());
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Get a diff between two dates
     * @param date1 the oldest date
     * @param date2 the newest date
     * @param timeUnit the unit in which you want the diff
     * @return the diff value, in the provided unit
     */
    public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
        long diffInMillies = date2.getTime() - date1.getTime();
        return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
    }
}

You can find the full project from here (https://github.com/yasassri/aws-observer). You can simply do an mvn clean install to generate the html content. Please drop a comment if you have any queries.

This post is licensed under CC BY 4.0 by the author.

Create A Jenkins Job with a Groovy Script

Parsing data between Jenkins Jobs