How to Zombie EC2 Cost Optimisation with Slack?

Yusuf Tayman
Devops Türkiye☁️ 🐧 🐳 ☸️
3 min readNov 11, 2020

As you know, there are times when we use EC2 machines for development, production, and test environments. Sometimes there are situations where we leave these machines open. If you are working with too many EC2 machines, it can get difficult to track over time. According to the EC2 type and as long as it remains open, it may have a greater effect on your cost. So how can we handle this? There may be many ways, but I’ll tell you how you can overcome this with slack.

Firstly, we need to open a custom app via slack. You can examine in detail how to do it through the documentation. → https://api.slack.com/start/building

Now that our Slack app is ready, we can start writing code. We will use Boto3 to view and list your machines that are open on AWS.

What is Boto3?

Boto is the Amazon Web Services (AWS) SDK for Python. It enables Python developers to create, configure, and manage AWS services, such as EC2 and S3.

To use Boto3, you must first import it and tell it what service you are going to use. Then we need to filter our EC2. I just want to list those with running status. But if you want, you can add more different filters.

Now we get the tags we created on the instances for the message we will send via slack. And to calculate how many hours the instance has been running, you can first take instance.launchtime and then use a simple function as below.

def running_hours_calculator(date_time):
launch_time = datetime.strptime(date_time, '%Y-%m-%d %H:%M:%S')
datetime_now = datetime.now()
diff = datetime_now - launch_time
days, seconds = diff.days, diff.seconds
hours = days * 24 + seconds // 3600
return hours

Now the message content we will send via slack is ready, now all we have to do is send a message using the Slack API. We will use the slack block kit while sending a message.

You can get more information about the block kit from the link here. → https://api.slack.com/block-kit

With Block kit, you can customize your messages and add more remarkable things such as buttons and gifs.

After adding the block kit you customized on the site to your code, all we have to do is send a message via slack with the chat_postMessage command.

client = WebClient(token='your_app_token')
client.chat_postMessage(
channel="C01E968NS69",
blocks=blocks,
user="D01EC8SQTT4"
)

And that’s all, now you can send annoying messages when your machines are turned on. 🎉🎉🎉

As you can see above, I added a terminate button and you can also use boto3 to give the instance id and write an automatically terminate function.

If you have any questions or suggestions, please share them with me. 👌

--

--