Skip to main content

Command Palette

Search for a command to run...

Day 15 - Task: Harnessing Python Libraries for DevOps - JSON and YAML (Dec 11, 2023)

Updated
2 min read
Day 15 - Task: Harnessing Python Libraries for DevOps - JSON and YAML (Dec 11, 2023)

As a DevOps Engineer, delving into the realms of Python libraries is crucial. Today, let's explore the power of Python libraries for handling JSON and YAML files, essential skills for parsing and managing configuration files.

Python Libraries for DevOps

As a DevOps Engineer, effective file parsing is a skill you'll use daily. Python offers a rich set of libraries for these tasks. Among them are:

  • os: For interacting with the operating system.

  • sys: For system-specific parameters and functions.

  • json: For working with JSON data.

  • yaml: For handling YAML files.

These libraries empower DevOps engineers to automate and streamline tasks seamlessly.

Tasks

Task 1: Creating and Writing to a JSON File

import json

# Create a Dictionary
cloud_services = {
    "aws": "ec2",
    "azure": "VM",
    "gcp": "compute engine"
}

# Write to a JSON File
with open("services.json", "w") as json_file:
    json.dump(cloud_services, json_file)

Task 2: Reading and Printing Service Names from JSON File

# Read from a JSON File
with open("services.json", "r") as json_file:
    services_data = json.load(json_file)

# Print Service Names
for provider, service in services_data.items():
    print(f"{provider} : {service}")

Output:

aws : ec2
azure : VM
gcp : compute engine

Task 3: Reading and Converting YAML to JSON

import yaml

# Read YAML and Convert to JSON
with open("services.yaml", "r") as yaml_file:
    yaml_data = yaml.safe_load(yaml_file)

# Print Converted JSON
json_data = json.dumps(yaml_data, indent=2)
print(json_data)

More from this blog

DevOps Journey with M Hassan

174 posts

I am writing these blogs because I recently completed a comprehensive DevOps course where I gained in-depth knowledge of the topics mentioned. As I progressed through the course, I realized the importance of having a concise and accessible resource to revise and reinforce my understanding of each topic. Therefore, I decided to create cheat sheets in the form of blog posts. These cheat sheets will not only serve as a handy reference for myself but also benefit others who are also interested in mastering DevOps concepts. By documenting each topic and providing concise explanations, I aim to create a valuable resource that simplifies complex concepts and facilitates hands-on practice. This way, I can solidify my own understanding while helping others on their DevOps journey.