Devops scripting in Python

posted: November 10, 2018

tl;dr: Tips on how to use Python to write better devops scripts...

I’ve used bash for decades, and normally favor using ubiquitous tools, especially for devops tasks. Almost always a devops script is developed on one machine, perhaps a developer’s laptop, and run on potentially numerous other machines. Those other machines may have different OS flavors and versions, and different software packages installed, so choosing a ubiquitous, lowest common denominator script interpreter such as bash can avoid headaches when the script is run elsewhere.

A short, simple bash script that runs a few commands can be easy to write, but bash starts to suffer as script size and complexity grows. Bash syntax shows its age in comparison to other more modern languages, and is less readable. Fewer new programmers enter the workplace schooled in bash. The maintenance of non-trivial bash scripts can be a challenge.

Python is a great modern alternative to bash for devops scripts of moderate to high complexity, for these reasons:

Python is becoming more ubiquitous, although Apple needs to start pre-installing Python3 in MacOS. Aaron Christianson’s article Replacing Bash Scripting with Python goes into more technical depth about the shortcomings of bash. I won’t bash bash any further, but will instead offer my own advice on writing Python devops scripts.

I usually import these standard Python libraries into most of my devops scripts:

My best practices for writing Python devops scripts:

Related post: Devops script comparison: Python and NodeJS