Tuesday, May 18, 2021

Python script get vm and errors azure.core.exceptions.ServiceRequestError: [SSL: CERTIFICATE_VERIFY_FAILED]

 

 Script is pretty simple:

from azure.identity import ClientSecretCredential
from azure.mgmt.compute import ComputeManagementClient


print("Starting script")
SUBSCRIPTION_ID = "mysubscriptionid"
credential = ClientSecretCredential(
    tenant_id='mytenantid,
    client_id='myapplicationid,
    client_secret='myapplicationsecret'
)

compute_client = ComputeManagementClient(
    credential=credential,
    subscription_id=SUBSCRIPTION_ID,
    
)

print("Getting vms")
# List all Virtual Machines in the specified subscription
def list_virtual_machines():
    for vm in compute_client.virtual_machines.list_all():
        print(vm.name)

list_virtual_machines()
 
Errors encountered and fixes.
 
  •  Packages not found 
   Solution :    
                   Install the packages using 
                   pip install packagename
  • pip error while installing packages.
        pip install azure-storage
        Defaulting to user installation because normal site-packages is not writeable
        WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None,    
        status=None))            after connection broken by 'SSLError(SSLCertVerificationError(1,   
        '[SSL:                                                CERTIFICATE_VERIFY_FAILED] certificate verify   
        failed: self signed certificate in certificate             chain (_ssl.c:1091)'))': /simple/azure-
        storage/
 

    Solution :   

                    Use the following command to install packages

                    pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --upgrade pip

                    pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org Django==3.2

 
  • azure.core.exceptions.ServiceRequestError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain
   Solution :    Link to solution is below. Same solution can be used for the above problem

                        https://stackoverflow.com/questions/27835619/urllib-and-ssl-certificate-verify-                           failed-error.
Credit to user : Bruno Gabuzomeu
 

        On Windows, Python does not look at the system certificate, it uses its own located at                 ?\lib\site-packages\certifi\cacert.pem.

  1. download the certificate chain from portal.azure.com as *.crt or *pem file
  2. open the file in editor and copy it's content to clipboard. contents will be like below. Copy all of it.
      -----BEGIN CERTIFICATE-----
     bunch of gibbereshin between.
      -----END CERTIFICATE-----
  1. Find your cacert.pem location: from requests.utils import DEFAULT_CA_BUNDLE_PATH; print(DEFAULT_CA_BUNDLE_PATH)
  2. edit the cacert.pem file and paste your domain validation certificate at the end of the file.
  3. Save the file.