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

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)