Skip to main content

Command Palette

Search for a command to run...

Basics of Python for DevOps Engineers

#90daysofDevOps Day-15

Published
6 min read
Basics of Python for DevOps Engineers

Today, let’s start with Python - one of the most essential languages for DevOps engineers. Knowing Python opens the door to automating tasks, building applications, managing infrastructure, and much more. Let's dive into the basics of Python, from installation to understanding data types.

Why Python?

Python is a high-level, open-source, and general-purpose language created by Guido van Rossum. It’s known for being versatile and easy to read, which is one reason it’s widely used in DevOps. Python comes with a vast set of libraries and frameworks, making it suitable for everything from web development with Flask and Django to machine learning with TensorFlow and Keras.

Whether you're automating deployments or analyzing data, Python’s simplicity makes it accessible, while its power makes it indispensable.

Installing Python

Python can be installed on various platforms, including Windows, macOS, Ubuntu, and CentOS. Here’s how to get started with installation:

1. Install Python on Windows

Visit the official Python website and download the installer. During installation, make sure to check the box that says "Add Python to PATH" - this is crucial for running Python from the command line.

2. Install Python on Ubuntu

On Ubuntu, you can install Python directly from the terminal. Open the terminal and type:

sudo apt-get update
sudo apt-get install python3.6

To verify the installation and check the version, run:

python3.6 --version

This should display the installed Python version, confirming everything is set up correctly.

Exploring Python Basics: Data Types

Python has a variety of data types that make it easy to handle different kinds of data. Let’s go over the essentials:

1. Numeric Types

  • Integer (int): Whole numbers, positive or negative.

      age = 30
    
  • Float: Numbers with decimals.

      pi = 3.14
    
  • Complex: Numbers with a real and imaginary part.

      complex_num = 3 + 4j
    

2. Strings

Strings are used to represent text. They are created by enclosing text in single (' ') or double (" ") quotes.

greeting = "Hello, DevOps!"

3. Boolean (bool)

Booleans represent True or False values, useful in conditional statements.

is_ready = True

4. Lists

Lists are ordered, mutable collections. They can hold items of different data types, and elements can be modified after creation.

tools = ["Python", "Git", "Docker"]

5. Tuples

Tuples are similar to lists but are immutable, meaning they cannot be changed after creation.

credentials = ("admin", "password123")

6. Dictionaries

Dictionaries store data as key-value pairs, allowing quick data lookup based on the key.

user_info = {"username": "devops_guru", "role": "admin"}

7. Sets

Sets are unordered collections with no duplicate elements, used mainly for testing membership and eliminating duplicate entries.

unique_tools = {"Python", "Git", "Docker"}

Python Variables and Comments

Variables

Variables store data and can be updated. They’re essential for assigning values in scripts.

tool_name = "Docker"
tool_version = 20.10

Comments

Comments are used to explain code and make it more readable.

  • Single-line comment: # This is a single-line comment

  • Multi-line comment: """ This is a multi-line comment """

User Input and Basic Output

Using input() and print() for interaction is essential in scripting.

# Get user input
username = input("Enter your username: ")

# Display output
print("Hello, " + username)

Python Conditionals: If-Else Statements

Conditional statements allow decision-making in scripts.

if tool_name == "Docker":
    print("Using Docker!")
else:
    print("Not using Docker.")

Loops: For and While

Loops repeat code blocks, which is useful for automating tasks.

For Loop

tools = ["Git", "Docker", "Kubernetes"]
for tool in tools:
    print(f"Using tool: {tool}")

While Loop

count = 0
while count < 3:
    print("Counting:", count)
    count += 1

Functions: Reusable Code Blocks

Functions help organize code, making it reusable and more manageable.

def greet_user(username):
    print(f"Hello, {username}!")

# Call the function
greet_user("DevOps_Guru")

File Handling: Reading and Writing Files

Reading and writing files are critical for logging and configuration.

Writing to a File

with open("output.txt", "w") as file:
    file.write("DevOps logs saved here.")

Reading from a File

with open("output.txt", "r") as file:
    content = file.read()
    print(content)

Tasks

Task 1: Install Python and Check the Version

Follow the installation instructions and verify the installation:

python3 --version

Task 2: Explore Different Data Types

Create a Python script (data_types.py) that defines variables with different data types and prints them.

integer_example = 42
string_example = "Hello DevOps"
float_example = 3.14
boolean_example = True

print(integer_example, type(integer_example))
print(string_example, type(string_example))
print(float_example, type(float_example))
print(boolean_example, type(boolean_example))

Task 3: Try Conditionals and Loops

Practice writing if-else statements and loops to simulate basic decision-making and repetitive tasks. For example, write a script to print each tool name from a list of tools.

tools = ["Git", "Docker", "Kubernetes"]

for tool in tools:
    if tool == "Docker":
        print(f"{tool} is installed and ready!")
    else:
        print(f"{tool} is not yet installed.")

Task 4: Write Functions

Write a function that takes a tool name as input and returns a message saying "Working with [tool name]." This will help solidify your understanding of reusable functions.

def tool_info(tool_name):
    return f"Working with {tool_name}"

print(tool_info("Docker"))

Task 5: Experiment with File Handling

Create a script to write some text into a file and then read it back. Try creating a “DevOps-Tools.txt” file and list the tools you’re using for practice.

# Write to a file
tools = ["Git", "Docker", "Kubernetes"]
with open("DevOps-Tools.txt", "w") as file:
    for tool in tools:
        file.write(tool + "\n")

# Read from the file
with open("DevOps-Tools.txt", "r") as file:
    print("Tools in file:")
    print(file.read())

Additional Topics for DevOps Engineers

Here are a few additional Python topics helpful for automation and scripting in DevOps:

  1. Error Handling: Learn try-except blocks to handle unexpected errors.

     try:
         with open("config.txt", "r") as file:
             content = file.read()
     except FileNotFoundError:
         print("File not found. Please check the file path.")
    
  2. Modules and Libraries: Explore Python libraries like os for system commands, sys for system-specific parameters, and subprocess for executing shell commands directly in Python.

     import os
    
     # List files in the current directory
     print(os.listdir("."))
    
  3. Automation with subprocess: Execute shell commands from within Python scripts.

     import subprocess
    
     # Execute a simple shell command
     subprocess.run(["echo", "Hello from Python!"])
    
  4. Environment Variables: Learn to manage configuration with environment variables using os.environ.

     import os
    
     # Set an environment variable
     os.environ["ENV_MODE"] = "Production"
     print("Environment Mode:", os.environ["ENV_MODE"])
    

Conclusion

Python’s versatility makes it an essential tool for DevOps engineers, especially for automating tasks and managing systems. By understanding the basics, from data types to file handling, you’re now equipped to tackle fundamental scripting needs and build a strong foundation for more advanced DevOps tasks. Keep practicing, and soon Python will be your go-to language for efficient and effective automation!