๐Ÿ“œDay 15 - Python Libraries for DevOps

๐Ÿ“œDay 15 - Python Libraries for DevOps

ยท

2 min read

๐Ÿ“œ 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 Pythonfor DevOps.

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

๐Ÿ“œTasks

  1. Create a Dictionary in Python and write it to a json File.
#First step is make .json file named as a "service.json"
{
    "aws": "ec2",  
    "azure": "VM",
    "gcp": "compute engine"
}
  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
#Second Step is make "services_json.py" file
import json

with open('services.json', 'r') as f:
    services = json.load(f)

print("Service Names for Each Cloud Provider:")
for provider, service in services.items():
    print(f"{provider}: {service}")

# For Showing Output open terminal & write "python services_json.py"
  1. Read YAML file using python, file services.yaml and read the contents to convert yaml to json

To read a YAML file using Python and convert it to JSON, you can use the pyyaml library, which is commonly used for working with YAML data. First, you need to install the library using pip:

pip install pyyaml

Now, let's read a YAML file and convert it to JSON:

import yaml 
import json 

with open('services.yaml', 'r') as yaml_file: 
     yaml_data = yaml.safe_load(yaml_file)

# Convert YAML data to JSON 
json_data = json.dumps(yaml_data, indent=2) 
print(json_data)

In this code, we read a YAML file using yaml.safe_load and then use json.dumps to convert the YAML data to JSON format.

๐Ÿ˜ŠHappy Learning :)

ย