A couple of simple DevOps tasks in Python

I have so far preached to you the virtues of DevOps and the virtues of Python but so far, I have shown you very little of how the two work together. Now, we get to that part. Here, I will demonstrate a couple of examples of how to use Python to automate some regular DevOps tasks that some engineers may have to perform on a daily basis. These two examples will be from AWS, though they are applicable in other big clouds as well and can be applied on most data center servers if you have the right APIs.

The code for this chapter and all future chapters are stored in this repository: https://github.com/PacktPublishing/Hands-On-Python-for-DevOps

Automated shutdown of a server

Oftentimes, there is the case of certain servers that only need to be up during working hours and then need to be switched off afterward. Now, this particular scenario has a lot of caveats, which include the platform used, the accounts where the servers are running, and how working hours are measured…but for this scenario, we are simply going to shut our EC2 servers down in an AWS account using an AWS Lambda function microservice that runs a Python script that leverages the boto3 library. That sounds like a lot? Let’s break it down.

In my AWS account, I have two EC2 instances running. Every second that they run costs me money. However, I need them during business hours. Here they are:

Figure 2.2 – Running instances

Creatively named, I know. But they are running, and there will come a point in time when I want them to not be running. So, to achieve that, I need to find some way to stop them. I could stop them one by one, but that’s tedious. And would I still do that if these 2 instances were 1,000 instances? No. So, we need to find another way.

We could try the command-line interface (CLI), but this is a coding book and not a CLI book, so we won’t. Though, keep it in mind if you want to try it. So, let’s look to our old friend Python, and also to a service that allows you to deploy a function that you can call at any time, called AWS Lambda. Here are the steps to create a Lambda function and use it to start and stop an EC2 instance:

  1. Let’s create a function called stopper with the latest available Python runtime (3.10 for this book):

Figure 2.3 – Creating a Lambda function