Python for DevOps: What to Learn and Scripts to Practise

At some point every DevOps engineer hits a task that is too fiddly for Bash. Maybe you need to call a cloud API, read a JSON response, filter it and send a summary to Slack. In Bash that turns into a tangle of curl, jq and string quoting. In Python it is fifteen readable lines. That is the real reason Python shows up in so many DevOps job descriptions.

The short answer: you do not need to be a Python developer to work in DevOps, but you should be able to write small, reliable scripts. Learn the basics (variables, loops, functions, error handling), then the handful of libraries DevOps work uses most: subprocess, pathlib, json, requests and boto3. Start after you are comfortable with Linux and Bash. Two to three weeks of steady practice gets you writing useful scripts.

Scripting runs through every stage of our DevOps training in Pune, from server setup to pipelines. This guide focuses on the Python you will actually use.

Bash or Python: when to use which

You will use both, so the question is which fits the task. A rough rule that works well:

  • Use Bash for short glue: running a few commands in order, setting up a server, a simple cron job. If it is under about 20 lines and mostly calls other programs, Bash is fine.
  • Use Python when you need logic: parsing JSON or YAML, calling an API, handling errors properly, working with dates, or anything you will maintain for months.

If your Bash is still shaky, start there. Our guide to Linux for DevOps covers the command line and shell basics that Python scripts build on.

The Python basics you need

You can skip a lot of what a general Python course teaches, such as classes, decorators and web frameworks, at least at first. Focus on:

  • Variables, strings, lists and dictionaries (dictionaries matter most, because JSON maps straight onto them)
  • if, for and functions
  • Reading and writing files
  • try and except, so a failed API call does not crash a script silently
  • Running a script with arguments, using argparse
  • Virtual environments (python3 -m venv) and pip for installing libraries

Libraries DevOps engineers use most

LibraryWhat it is for
subprocessRunning shell commands from Python and checking their output
os, pathlib, shutilWorking with files, folders and environment variables
json, PyYAMLReading and writing config files and API responses
requestsCalling REST APIs and checking web endpoints
boto3Automating AWS: EC2, S3, IAM and more
kubernetesTalking to a Kubernetes cluster from code
pytestTesting your scripts before they touch anything real

Three scripts worth writing as practice

1. A health checker for your services

This checks a list of URLs and exits with an error if any are down, so it can run in a pipeline or a cron job:

import sys
import requests

URLS = ["https://example.com", "https://example.com/api/health"]
failed = []

for url in URLS:
    try:
        r = requests.get(url, timeout=5)
        if r.status_code != 200:
            failed.append(f"{url} returned {r.status_code}")
    except requests.RequestException as e:
        failed.append(f"{url} error: {e}")

if failed:
    print("\n".join(failed))
    sys.exit(1)
print("All services healthy")

2. Find EC2 instances someone forgot to tag

Untagged servers are a classic source of surprise cloud bills. With boto3, listing them takes a few lines:

import boto3

ec2 = boto3.client("ec2", region_name="ap-south-1")
for r in ec2.describe_instances()["Reservations"]:
    for i in r["Instances"]:
        tags = {t["Key"]: t["Value"] for t in i.get("Tags", [])}
        if "Owner" not in tags:
            print(i["InstanceId"], i["State"]["Name"], "has no Owner tag")

3. Clean up old log files

A script that deletes logs older than seven days from a folder, with a dry-run flag so you can check what it would remove first. This one teaches pathlib, dates and argparse, and it is a good habit to build safety switches into anything that deletes.

Where Python fits in the wider toolset

Python sits underneath a lot of DevOps tooling, which is another reason it is worth learning. Ansible is written in Python, and custom Ansible modules are Python scripts; our guide to Ansible for beginners covers the playbook side. Many CI pipelines run Python scripts as steps, whether in Jenkins or GitHub Actions. And most cloud providers offer Python SDKs alongside their command-line tools.

Mistakes beginners make

  • Hard-coding secrets. Never put access keys in a script. Read them from environment variables or use the cloud’s own credentials, such as an IAM role.
  • Ignoring errors. A script that fails silently is worse than no script. Check return codes and exit with a non-zero code on failure.
  • No dry-run for destructive actions. Anything that deletes or stops resources should print what it would do first.
  • Installing everything globally. Use a virtual environment per project to avoid version clashes.
  • Learning Python in isolation. Practise on real DevOps problems from day one rather than generic exercises.

A three-week plan

  • Week 1: Python basics with small file and text tasks: count lines in logs, rename files, read a JSON config.
  • Week 2: requests and subprocess. Write the health checker and a script that runs and checks shell commands.
  • Week 3: boto3 against a free-tier AWS account. List, tag and stop instances, with a dry-run option. Put all three scripts on GitHub with a README.

Where this fits in the bigger picture is covered in our DevOps roadmap for freshers, where scripting sits in month one alongside Linux and Git.

Frequently asked questions

Is Python required for DevOps jobs?

Not always, but it helps a lot. Many Pune job descriptions list Python or another scripting language, and interviewers often ask you to write or read a short script. Bash alone can get you a first role, but Python makes you noticeably more useful.

Python or Go for DevOps?

Python first. It is easier to learn, used more widely for scripting and automation, and has libraries for almost every tool. Go is worth learning later if you want to build CLI tools or contribute to projects like Kubernetes and Terraform, which are written in it.

How much Python do I need for a DevOps interview?

Enough to read a script and explain it, and to write something small, such as parsing a log file or calling an API, without help. You will rarely be asked about advanced topics like classes or async code for junior roles.

Can I learn Python and DevOps at the same time?

Yes, and it often works better that way. Use Python to solve the DevOps problems you meet while learning, such as automating a setup step or checking a pipeline result, rather than studying it separately.

Facebook
Twitter
LinkedIn
Email
Picture of Wandex
Wandex

DevOps Expert

ENroll Now

Fill up the form and we will contact you 

Get Free Course Syllabus & Counseling

Takes only 10 seconds to fill out!