Day 15 Task: Python Libraries for DevOps

What is Python libraries?

A Python library is a collection of pre-written code that provides specific functionalities and can be imported and used in other Python programs. A library can contain functions, classes, and modules that can be used by other programs, saving time and effort in development.

Python libraries are often created to solve specific problems and make it easier for developers to write code by providing pre-built solutions. They can be open-source or proprietary, and can be installed via Python’s package manager, pip.

In DevOps, Python libraries can be used to automate tasks, interact with APIs and cloud services, and manipulate data, among other things. Common DevOps tasks that can be facilitated by Python libraries include server configuration and management, software deployment, testing, and monitoring.

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

In Python, you can create a dictionary using curly braces {} or by using the built-in dict() function. Once you have created a dictionary, you can write it to a JSON file using the json module.

Here’s an example of how to create a dictionary and write it to a JSON file in Python:

import json

# Create a dictionary
my_dict = {'name': 'Saurabh', 'age': 24, 'city': 'Pune'}

# Write the dictionary to a JSON file
with open('example.json', 'w') as file:
    json.dump(my_dict, file)

In this example, we first create a dictionary called my_dict with three key-value pairs. Next, we open a file called example.json in write mode using the open function and write the dictionary to the file using the json.dump function.

The json.dump function serializes the dictionary object to a JSON formatted string and writes it to the file object. The with statement is used to ensure that the file is properly closed after it's been written to.

After running this code, you should see a file called example.json in your working directory with the contents of the my_dict dictionary.

In summary, creating a dictionary in Python is easy and can be done using curly braces {}, the dict() function, or by creating an empty dictionary and adding key-value pairs to it later. You can write a dictionary to a JSON file using the json.dump function from the json module.

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

Output should be:


 aws : ec2
 azure : VM
 gcp : compute engine

JSON file called services.json and print the service names of every cloud service provider:

import json

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

# Iterate over the cloud service providers
for provider in data['cloud_services']:
    # Print the service names for each provider
    print(f"Services for {provider['provider_name']}:")
    for service in provider['services']:
        print(f"- {service['name']}")

In this example, we first open the services.json file and load its contents into a Python dictionary using the json.load() function.

Next, we iterate over the list of cloud service providers in the data dictionary and print the provider name. For each provider, we then iterate over the list of services and print the name of each service.

Assuming the services.json file contains a structure similar to this:

{
  "cloud_services": [
    {
      "provider_name": "AWS",
      "services": [
        {"name": "ec2"},
      ]
    },
    {
      "provider_name": "Azure",
      "services": [
        {"name": "VM"},
      ]
    },
    {
      "provider_name": "GCP",
      "services": [
        {"name": "compute engine"},
      ]
    }
  ]
}

The output of this code would be:

Services for Amazon Web Services:
- EC2
Services for Azure:
- VM
Services for GCP:
- Compute Engine

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

To read a YAML file in Python and convert it to JSON, you can use the yaml and json modules. Here's an example:

import yaml
import json

# Open the YAML file and load its contents
with open('services.yaml', 'r') as file:
    yaml_data = yaml.load(file, Loader=yaml.FullLoader)

# Convert the YAML data to JSON
json_data = json.dumps(yaml_data)

# Print the JSON data
print(json_data)

In this example, we first open the services.yaml file using the open function and load its contents into a Python dictionary using the yaml.load() function.

Next, we convert the YAML data to JSON format using the json.dumps() function, which converts a Python object to a JSON formatted string.

Finally, we print the JSON data using the print() function.

Assuming the services.yaml file contains a structure similar to this:

cloud_services:
  - provider_name: AWS
    services:
      - name: EC2
  - provider_name: Azure
    services:
      - name: Virtual Machines
  - provider_name: GCP
    services:
      - name: Compute Engine

The output of this code would be a JSON formatted string:

{
 "cloud_services": 
   [
    {
      "provider_name": "Amazon Web Services", 
      "services": [{"name": "EC2"}]
    }, 
    {
      "provider_name": "Microsoft Azure",
      "services": [{"name": "Virtual Machines"}]
    }, 
    {
      "provider_name": "Google Cloud Platform",
      "services": [{"name": "Compute Engine"}]
    }
  ]
}

Note: The yaml.load() function can be unsafe if loading untrusted YAML data, so you should only use it with trusted data. Alternatively, you can use the yaml.safe_load() function to load YAML data safely.