#Day15: Python Libraries for DevOps #90DaysofDevOps

#Day15: Python Libraries for DevOps #90DaysofDevOps

Tasks

Create a Dictionary in Python and write it to a json File.

Create a file dict.py

touch dict.py

Open vim and type following code

import json

my_dict = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

with open("my_dict.json", "w") as file:
    json.dump(my_dict, file)

Run the following .py file using:

python3 dict.py

Check using ls

Verify by opening it

vim my_dict.json

Task2: 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

Step 1:

Create a file services.json

[
  {
    "name": "aws",
    "services": "ec2"
  },
  {
    "name": "azure",
    "services": "VM"
  },
  {
    "name": "gcp",
    "services": "compute engine"
  }
]

Step 2:

Create a new file called clouds.py and write the code into it.

import json

# Read the JSON data from the file
with open('services.json') as f:
    data = json.load(f)

# Print the service names for each cloud service provider
for provider in data:
    print(provider['name'], ':', provider['services'])

Now run it with python, it will give us the content in json file

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

Step1

Create a file service.yaml

vim service.yaml

Add the following data in it:

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

Step 2:

Create a file conversion.py and type the following code:

import json
import yaml

with open('service.yaml', 'r') as f:
    data = yaml.load(f, Loader=yaml.Safeloader)
with open('provider.json', 'w') as f:
    json.dump(data, f, sort_keys=False)

Step 3:

run python3 conversion.py

File provider.json is created -

Congratulations! you are done with the tasks!