Saturday, November 23, 2019

google cloud compute instance creation using python script



First steps to create dedicated service account for our python script with name libcloud( since we are going to use apache libcloud python framework )

And then map the necessary roles to the service account to create compute instances









After mapping above roles, i was not able to create instances in my python scripts, it was keep on throwing below exception


    response = responseCls(**kwargs)
  File "/home/sathish/miniconda3/lib/python3.7/site-packages/libcloud/common/base.py", line 154, in __init__
    self.object = self.parse_body()
  File "/home/sathish/miniconda3/lib/python3.7/site-packages/libcloud/common/google.py", line 267, in parse_body
    raise GoogleBaseError(message, self.status, code)
libcloud.common.google.GoogleBaseError: "The user does not have access to service account '123333333333-compute@developer.gserviceaccount.com'.  User: 'libcloud@xxxxxxxxx.iam.gserviceaccount.com'.  Ask a project owner to grant you the iam.serviceAccountUser role on the service account"


Then i granted additional below roles.








then try below python script to create instance

       
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

ComputeEngine = get_driver(Provider.GCE)
# Note that the 'PEM file' argument can either be the JSON format or
# the P12 format.
driver = ComputeEngine('libcloud@xxxxx.iam.gserviceaccount.com','/home/sathish/gcp_pem.json',
                       project='ferrous-weaver-xxxxx')

#(driver.list_images())

### Function to findout the gcp image name to provide arg in create instance function ###

def list_all_gcp_images(driver):
        images = driver.list_images()
        for image in images:
                print(image)

### use below function to create compute instance ##

def create_instance(driver):
        s = 'n1-standard-1'
        i = 'centos-7-v20191121'
        z = 'us-central1-a'

        sa_scopes = [{'email': 'default','scopes': ['storage-ro']}]
        node_1 = driver.create_node("n2", s, i, z, ex_service_accounts=sa_scopes)

create_instance(driver)
list_all_gcp_images(driver)