Skip to main content

Command Palette

Search for a command to run...

Python Libraries for DevOps - #day15 of #90DaysOfDevopsChallenge

Published
2 min read
Python Libraries for DevOps -
#day15 of #90DaysOfDevopsChallenge
S

I write blogs about DevOps current and emerging tools/technologies.

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

    Python

    Step 1: create a file in the directory

    Command : touch file_name.py

    Here I have written a file into it and will import it into JSON File :

    command : vim file_name.py to write into the file

    Step-2 Create a json file by running this python file and verify with the command "ls"

    command : python3 file_name.py

    Step-3 Verify it :

    command : vi file_name.json

  2. 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 and write the following code into it :

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

Step-2 Create a new file named task2.py and write the following 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'])

Step-3 Now run it with python, it will revert the content:

command : python3 filename.py

Output :

  1. Read YAML file using python, file service.yaml and read the contents to convert yaml to json

Step-1 Create a file service.yaml and add the following data into 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 task3.py and add the following code into it :

import yaml 
import json 
with open('provider.json', '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 the python file using the below command and verify it using ls

command : python3 file_name.py

ls file_name.json

Thank you for your time!