Day 15 Task: Python Libraries for DevOps

Day 15 Task: Python Libraries for DevOps

#Day15 of 90DaysofDevOps Challenge

Reading JSON and YAML in Python

  • As a DevOps Engineer, you should be able to parse files, be it txt, json, yaml, etc.

  • You should know what all libraries one should use in Python for DevOps.

  • Python has numerous libraries like os, sys, json, yaml etc that a DevOps Engineer uses in day-to-day tasks.

  • Ref

  • Tasks

    1. Read a json file services.json kept in this folder and print the service names of every cloud service provider.
    output

    aws : ec2
    azure : VM
    gcp : compute engine

2. Read YAML file using python, file services.yaml and read the contents to convert yaml to json

  • Ans 1 and 2

  •         import json
            import yaml
    
            json_file = r"path\services.json"
            yaml_file = r"path\services.yaml"
    
            # Load data from JSON file
            with open(json_file, 'r', encoding='utf-8') as f:
                json_data = json.load(f)
    
            print("JSON:\n", json_data)
    
            # Load data from YAML file
            with open(yaml_file, "r") as stream:
                try:
                    yaml_data = yaml.safe_load(stream)
                    print("YAML:\n", yaml_data)
                except yaml.YAMLError as exc:
                    print(exc)
    
{
    "Services":{
        "debug": "on",
        "aws":{
            "name": "EC2",
            "type": "pay-per hour",
            "instances": 500,
            "count": 500
        },
        "azure":{
            "name": "VM",
            "type": "pay-per hour",
            "instances": 500,
            "count": 500
        },
        "gcp":{
            "name": "Compute Engine",
            "type": "pay-per hour",
            "instances": 500,
            "count": 500
        }
    }
}
---
services:
  debug: 'on'
  aws:
    name: EC2
    type: pay per hour
    instances: 500
    count: 500
  azure:
    name: VM
    type: pay per hour
    instances: 500
    count: 500
  gcp:
    name: Compute Engine
    type: pay per hour
    instances: 500
    count: 500

ย