How to manage VRA 8 & vRLCM using Google assistant (okGoogle)

This is one of the project which I had in my To Do list and recently I managed to complete it .


Here is the Backhand flow ,how the communication works in backhand .

While sending the traffic from OkGoogle to VRA.

While sending the traffic from OkGoogle to vRLCM.

Once operation is performed in VRA and send the traffic back to Google Assistant.

Once operation is performed in vRLCM and send the traffic back to Google Assistant.

Later I performed VRA upgrade also Here is the Demo video for that.



.Here is the Backhand code of web server , I have removed the IDs which are related to my environment.

from VRA import listcatalogItems, submitBuild
from vRLCM import lcmGetAllEnvironment, lcmTriggerInventorySyncProduct,upgradeProduct
from flask import Flask, request, make_response


app = Flask(__name__)


@app.route('/')
def test():
    return "Server belongs to Ankush"


def results():
    req = request.get_json(silent=True, force=True)
    if req.get("queryResult").get("action") == "Test":
        return listcatalogItems()

    elif req.get("queryResult").get("action") == "submit_build_request":
        selectedbp = req.get("queryResult").get("parameters").get("Blueprints")
        if selectedbp == 'demo' or selectedbp == 'Demo':
            ids = 'xxxx'
        elif selectedbp == 'Test' or selectedbp == 'test':
            ids = 'xxxxxx'
        print(ids)
        return submitBuild(ids)

    elif req.get("queryResult").get("action") == "list_lcm_product":
        return lcmGetAllEnvironment()
    elif req.get("queryResult").get("action") == "trigger_inven_sync":
        product = req.get("queryResult").get("parameters").get("ProductName")
        if product == 'idm' or product == 'IDM' or product == 'VIDM' or product == 'vidm' or product == "Idm":
            environmentid = 'globalenvironment'
            productid = 'vidm'
        elif product == 'Automation' or product == 'automation' or product == 'Vra' or product == 'vra':
            environmentid = 'xxxx'
            productid = 'vra'
        return lcmTriggerInventorySyncProduct(environmentid, productid)

    elif req.get("queryResult").get("action") == "upgrade":
        product = req.get("queryResult").get("parameters").get("productname")
        if product == 'idm' or product == 'IDM' or product == 'VIDM' or product == 'vidm' or product == "Idm":
            productid = 'vidm'
        elif product == 'Automation' or product == 'automation' or product == 'Vra' or product == 'vra':
            productid = 'vra'
        return upgradeProduct(productid)










@app.route('/webhook', methods=['POST'])
def test1():
    return make_response(results())

Here is my VRA code

import requests
import datetime
import json
import random
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)



vrafqdn = 'xxxx'
username = 'xxx'
password = 'xxxx'


def vratoken():

    refreshtokenurl = f"https://{vrafqdn}/csp/gateway/am/api/login?access_token"
    iaasUrl = f"https://{vrafqdn}/iaas/api/login"
    headers = {
        'accept': "application/json",
        'content-type': "application/json"
    }
    payload = f'{{"username":"{username}","password":"{password}"}}'
    apioutput = requests.post(refreshtokenurl, data=payload, verify=False, headers=headers)
    refreshtoken = apioutput.json()['refresh_token']
    iaasPayload = f'{{"refreshToken": "{refreshtoken}"}}'
    iaasApiOutput = requests.post(iaasUrl, data=iaasPayload, headers=headers, verify=False).json()['token']
    bearerToken = "Bearer " + iaasApiOutput
    return bearerToken

a=vratoken()




def listcatalogItems():
    url = f"https://{vrafqdn}/catalog/api/items"
    headers = {
            'accept': "application/json",
            'content-type': "application/json",
            'authorization': a
    }
    apioutput = requests.get(url, headers=headers, verify=False).json()['content']
    #print(apioutput)
    totalname = []
    for s in apioutput:
        totalname.append(s['name'])

    return {
        'fulfillmentText': f'We have total {len(totalname)} blueprint and here are the names {str(totalname)}'
    }

def submitBuild(id):
    if id == 'xxxxxx':
        deployname = 'okGoogle100'
    elif id == 'xxxx':
        deployname = 'okGoogle101'
    url = f'https://{vrafqdn}/catalog/api/items/{id}/request'
    headers = {
        'accept': "application/json",
        'content-type': "application/json",
        'authorization': a
    }
    inputs = {}
    data = json.dumps(inputs)


    payload = f'{{"bulkRequestCount":"1","deploymentName":"{deployname}","projectId":"xxx","reason": "Test","version":"1","inputs":{data}}}'
    apioutput = requests.post(url, headers=headers, data=payload, verify=False)
    print(apioutput)
    if apioutput.status_code == 200:
        return {
            'fulfillmentText': f'Deployment {deployname} has been submitted , You may check in VRA for same.'
        }

Here is my vRLCM Code snippet.

import requests
import base64
import re
from prettytable import PrettyTable
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

global vrlcmurl
global userName
global password

vrlcmurl = 'xxxx'
userName = 'xxxx'
password = 'xxxx'

def lcmlogin():
    UserCredential = f"{userName}:{password}"
    encode = base64.b64encode(UserCredential.encode())
    token = encode.decode("utf-8")
    return token

token = lcmlogin()
def lcmGetAllEnvironment():
    url = f"https://{vrlcmurl}/lcm/lcops/api/v2/environments"
    lcmheaders = {
            'accept': "application/json",
            'authorization': "Basic " + token,
            'content-type': "application/json"
        }
    apioutput = requests.get(url, headers= lcmheaders, verify=False)
    output = str(apioutput)
    validation = re.search("200", output)
    if validation:
        view = PrettyTable(['environmentId', 'environmentName', 'environmentStatus',
                                'ProductID', 'ProductVersion'])
        data = apioutput.json()
        totalproduct = []
        for env in data:
            for product in env['products']:
                ProductID = product['id']
                totalproduct.append(ProductID)
                ProductVersion = product['version']
                view.add_row(
                        (env['environmentId'], env['environmentName'],
                         env['environmentStatus'], ProductID, ProductVersion)
                    )

        print(view)
        return {
            'fulfillmentText': f'We have total {len(totalproduct)} products in LCM and here are the names {str(totalproduct)}'
        }
    else:
        print(apioutput)


def lcmTriggerInventorySyncProduct(environmentId , productId ):
    url = f"https://{vrlcmurl}/lcm/lcops/api/v2/environments/{environmentId}/products/{productId}/inventory-sync"
    lcmheaders = {
            'accept': "application/json",
            'authorization': "Basic " + token,
            'content-type': "application/json"
        }
    apioutput = requests.post(url, headers=lcmheaders, verify=False)
    output = str(apioutput)
    validation = re.search("200", output)
    if validation:
        return {
            'fulfillmentText': f'Inventory sync request has been triggered for {str(productId)}'
        }
    else:
        print(apioutput)



def upgradeProduct(productId):
    if productId == 'vra':
        url = f'https://{vrlcmurl}/lcm/lcops/api/v2/environments/xxx/products/vra/upgrade'
        payload = f'{{"productVersion":"8.4.2", "repositoryType":"lcmRepository","repositoryUrl":"xxxx"}}'
    elif productId == 'vidm':
        url = f'https://{vrlcmurl}/lcm/lcops/api/v2/environments/globalenvironment/products/vidm/upgrade'
        payload = f'{{"productVersion":"3.3.5", "repositoryType":"lcmRepository","repositoryUrl":"xxxx"}}'

    lcmheaders = {
            'accept': "application/json",
            'authorization': "Basic " + token,
            'content-type': "application/json"
        }

    apioutput = requests.post(url, data=payload, headers=lcmheaders, verify=False)
    output = str(apioutput)
    validation = re.search("200", output)
    if validation:
        return {
            'fulfillmentText': f'Upgrade request has been triggered for {str(productId)}'
        }
    else:
        print(apioutput)