fbpx

Python for Devops Engineer : Automate Everything!

INTRODUCTION

DevOps is all about automation, efficiency, and scalability. Python is one of the most powerful and versatile programming languages that helps DevOps engineers automate tasks, manage infrastructure, and enhance workflows. If you’re a DevOps engineer or aspiring to be one, mastering Python is a must.

Why Python for Devops ?

  • Simple syntax and easy to learn 
  • Support automation and scripting
  • Extensive libraries and frameworks
  • Great for  infrastructure as code (IAC) and cloud automation

     Let’s explore how Python fits into a DevOps workflow with some interactive tasks.

1. Automating Repetitive Tasks with Python

DevOps engineers handle several repetitive tasks, such as server monitoring, log analysis, and software deployments. Python simplifies these tasks with automation scripts.

Example : Automating Repetitive Tasks with Python

Here’s a simple script to delete log files older than 7 days:

import os
import time

log_directory = “/var/logs/myapp/”
seven_days_ago = time.time() – (7 * 86400)

for file in os.listdir(log_directory):
file_path = os.path.join(log_directory, file)
if os.path.isfile(file_path) and os.path.getmtime(file_path) < seven_days_ago:
os.remove(file_path)
print(f"Deleted: {file}")

Task for you🚀

Modify the script to back up the logs before deleting them.

2.Managing Infrastructure with Python

Python works well with Infrastructure as Code (IaC) tools like Ansible, Terraform, and AWS Boto3. It helps in provisioning, configuring, and managing cloud resources efficiently.

Example: Creating an AWS EC2 Instance with Boto3

  import boto3 

ec2 = boto3.resource(‘ec2’) 

instance = ec2.create_instances(

      ImageId=’ami-0abcdef1234567890′, 

      InstanceType=’t2.micro’,

      MinCount=1,

      MaxCount=1, 

)

 print(“Instance Created: “, instance[0].id)

Task for you🚀

Modify the script to launch an EC2 instance with a specific security group and key pair.

3.CI/CD Automation with Python

Continuous Integration and Continuous Deployment (CI/CD) are crucial for a DevOps engineer. Python helps automate CI/CD pipelines using tools like Jenkins, GitHub Actions, and GitLab CI.

Example: Triggering a Jenkins Build with Python

import requests

jenkins_url = “http://your-jenkins-url/job/my-job/build?token=mytoken”
response = requests.post(jenkins_url, auth=(“user”, “password”))

if response.status_code == 201:
print(“Build triggered successfully!”)
else:
print(“Failed to trigger build.”)

Task for you🚀

Modify the script to check the build status after triggering it.

4. Monitoring and Logging with Python

Monitoring and logging are essential to maintaining system health. Python can interact with monitoring tools like Prometheus, Grafana, and ELK Stack.

example: Fetching System Metrics with python

   import psutil

   print(“CPU Usage:”, psutil.cpu_percent(), “%”)
   print(“Memory Usage:”, psutil.virtual_memory().percent, “%”)

Task for you🚀

Extend the script to log system metrics every 10 seconds and store them in a file.

5. Containerization and Orchestration

Python can manage Docker containers and Kubernetes clusters efficiently.

Example: Managing Docker Containers with Python

import docker

client = docker.from_env()
container = client.containers.run(“nginx”, detach=True, ports={“80/tcp”: 8080})
print(“Container Started: “, container.id)

Task for you🚀

Modify the script to stop and remove the container after 30 seconds.

Conclusion :

Python is an indispensable tool for DevOps engineers. From automation to infrastructure management, CI/CD, monitoring, and containerization, it plays a vital role in modern DevOps workflows.

🔹 Next Steps:

  • Learn more about Python libraries for Devops (Fabric, Paramiko, etc.)
  • Integrate Python with Ansible, Terraform, and Kubernetes
  • Build a complete DevOps automation project using Python

Got a Python DevOps script? Share it in the comments! 🚀

DevOps with AWS Training

Take your DevOps skills to the next level with our AWS training! Gain hands-on experience, real-world project exposure, and industry-recognized expertise. Enroll today and step into a high-demand career

Leave a Comment

Your email address will not be published. Required fields are marked *

Open chat
Hello, Good day!!
How can we help you?