How to perform automatic deletion of failed deployment in VRA 8 using Python ABX action

One of the most common scenario in VRA 8 is about testing and dealing with failed deployments. when we start provisioning the vms using VRA, there will be situation when we face multiple failures due to Configuration issues or Infra side issues .

In such scenario, Deleting the failed deployment one by one can become tedious task , here is the screenshot of similar situation .

I have submitted 4 builds and 4 went fail due to any reason and I need to come to Portal and perform the cleanup one by one which I do not prefer to do because these numbers can be large based on load and used case.

I have written Python ABX Action which will perform the deletion of the deployment if they are failed automatically .
So how we do set this up …..
Step 1 .

Click on Cloud Assembly => Secret and Create 3 secret by same name
VRAURL == VRA FQDN (Enter your FQND)
username == username (Enter your Username)
password == password (Enter your VRA password
Here is the example of my lab.

Step 2.

Once we have created the secrets , Click on Extensibility=>Action => New Action
Choose the any meaningful name , I have chosen Automatic-Deletion

Choose the language Python and Here is the below code which you can copy paste.

import requests
import time
import json


def handler(context, inputs):
    # Taking the value from secret into local Variable

    vrafqdn = context.getSecret(inputs['VRAURL'])
    username = context.getSecret(inputs['username'])
    password = context.getSecret(inputs['password'])
    deploymentid = inputs['deploymentId']


    # Taking the value from secret into local Variable

    # grabbing  the latest API API Version

    api_version_url = f'https://{vrafqdn}/iaas/api/about'
    headers = {
        'accept': "application/json",
        'content-type': "application/json"

    }
    output = requests.get(url=api_version_url, headers=headers, verify=False)
    # grabbing  the latest API API Version

    if output.status_code == 200:
        latest_api_version = output.json()['latestApiVersion']
        apiversion = latest_api_version
        # Grabbing the token for authentication
        refreshtokenurl = f"https://{vrafqdn}/csp/gateway/am/api/login?access_token"
        iaasUrl = f"https://{vrafqdn}/iaas/api/login?apiVersion={apiversion}"
        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
        # Grabbing the token for authentication

        url = f'https://{vrafqdn}/deployment/api/deployments/{deploymentid}/requests'
        dheaders = {
            'accept': "application/json",
            'content-type': "application/json",
            'authorization': bearerToken
        }
        
        data = {
            "actionId": "Deployment.Delete"
        }

        apioutput2 = requests.post(url, headers=dheaders, data = json.dumps(data),verify=False)
        if apioutput2.status_code == 200:
            print('Failed Deployment has been removed')
        else:
            print(f'Deployment deletion failed with error {apioutput2.status_code}, Here is the reason \n')
            print(apioutput2.json())
        




    else:
        print(output.status_code)




In the Right hand side add the secrets which we created initially and Under dependency put requests it will look like this.

Step 3 . Setup the Extensibility

Extensibility = > Subscription = > New Subscription
we will be adding Deployment completed event

Enter the Name and enable Filter in topics , It should look like below.

event.data.status == "FAILED" && event.data.eventType == "CREATE_DEPLOYMENT"

In the action/workflow Choose the Python action which we created in step 2.

And we are done here , Once any failure happens it will delete the deployment automatically

For cloud ,Please find the code

import json
import requests
import time
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


def handler(context, inputs):
    deploymentid = inputs['deploymentId']
    cloudurl = context.getSecret(inputs['VRAURL'])
    url = cloudurl
    api_version_url = f'{url}/iaas/api/about'
    print(f'Deployment ID from EBS fetched: {deploymentid}')
    headers = {
        'accept': "application/json",
        'content-type': "application/json"
    }
    output = requests.get(url=api_version_url, headers=headers, verify=False)
    if output.status_code == 200:
        latest_api_version = output.json()['latestApiVersion']
        apiversion = latest_api_version
        iaasUrl = f"{url}/iaas/api/login?apiVersion={apiversion}"
        print(iaasUrl)
        refreshtoken = context.getSecret(inputs['token'])
        iaasPayload = f'{{"refreshToken": "{refreshtoken}"}}'
        iaasApiOutput = requests.post(iaasUrl, data=iaasPayload, headers=headers, verify=False)
        if iaasApiOutput.status_code == 200:
            print('Authentication to CLoud instance Completed \n')
            jsondata = iaasApiOutput.json()['token']
            bearerToken = "Bearer " + jsondata
            bearertoken = bearerToken
            headers = {
                'accept': "application/json",
                'content-type': "application/json",
                'authorization': bearertoken
            }
            url = f'{url}/deployment/api/deployments/{deploymentid}/requests'
            data = {
                "actionId": "Deployment.Delete"
            }
            apioutput2 = requests.post(url, headers=headers, data=json.dumps(data), verify=False)
            if apioutput2.status_code == 200:
                print('Failed Deployment has been removed')
            else:
                print(f'Deployment deletion failed with error {apioutput2.status_code}, Here is the reason \n')
                print(apioutput2.content)
        else:
            print(output.status_code)
        # Grabbing the token for authentication

2 responses to “How to perform automatic deletion of failed deployment in VRA 8 using Python ABX action”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

%d bloggers like this: