Aria Automation Cloud(aka vRA)- How to add Custom Attributes to vSphere VM

One of the used came which i came across recently is How we can utilise Aria Automation Cloud to specify the value of Custom Attribute via Cloud template.
This was possible in by defining custom property in vRA7 Blueprint. But unfortunately Currently it is there is no Out of box way.

So i have decided to capture this using Python and Powercli ABX Flow .
Those who do not know what is Custom Attribute , here is good Article by William Lam.

Prerequisite:

Create secret for below things

  1. vCenter IP/FQDN
  2. vCenter Username
  3. vCenter Password
  4. vRA Cloud url
  5. CSP Token

Those are from my lab, You may create variable name as per your convenient , We need to use same variable in code which we create in secret , so if you are giving different name do not forget to replace in code.

List of All Custom Attribute which we want to update

In my case I have 3 Custom attributes by name Application, Owner, Backup

Implementation

  1. Create Cloud template and release the version
  2. Create Python ABX action
  3. Create PowerCli ABX action
  4. Create ABX FLOW
  5. Create subscription
  6. Sync the cloud template in content source
  7. Submit catalog Item

Create Cloud template and release the version

formatVersion: 1
inputs:
  chooseOS:
    type: string
    title: Choose OS for VM
    enum:
      - Linux
      - Windows
  CPU:
    type: integer
    title: 'Enter CPU Count '
  Memory:
    type: integer
    title: Enter Memory in MB
  application:
    type: string
    title: Choose Application
    enum:
      - PHP
      - SAP
  backup:
    type: boolean
    title: Backup
    default: true
resources:
  Cloud_vSphere_Machine_1:
    type: Cloud.vSphere.Machine
    properties:
      cpuCount: ${input.CPU}
      totalMemoryMB: ${input.Memory}
      application: ${input.application}
      owner: ${env.requestedBy}
      image: ${input.chooseOS}
      backup: ${input.backup}
      networks:
        - network: ${resource.Cloud_vSphere_Network_1.id}
          assignment: static
  Cloud_vSphere_Network_1:
    type: Cloud.vSphere.Network
    properties:
      networkType: existing

Line 31,32 and 34 are the custom properties which will be used to update the Custom Attributes.

Create Python ABX Action

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


def handler(context,inputs):
    Outputs = {}
    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}')
    start = time.time()
    
    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
            }
            deployment_url = f'{cloudurl}/deployment/api/deployments/{deploymentid}' \
                             f'/resources?resourceTypes=Cloud.vSphere.Machine&apiVersion={apiversion}'
            print(deployment_url)
            deployment_output = requests.get(deployment_url, headers=headers, verify=False)
            if deployment_output.status_code == 200:
                print('Deploymnet details API response is success, starting the payload reading ....')
                data = deployment_output.json()['content']
                data_dict = {}
                data_list = []
                for i in data:
                    data_dict['id'] = i['id']
                    data_dict['name'] = i['name']
                    data_dict['VMIP'] = i['properties']['networks'][0]['address']
                    data_dict['resourceName'] = i['properties']['resourceName']
                    data_dict['EndPoint'] = i['properties']['accounts']
                    data_dict['zone'] = i['properties']['zone']
                    data_dict['region'] = i['properties']['region']
                    data_list.append(data_dict.copy())
                Outputs['deployment_details']= data_list
                end = time.time()
                timetaken = end - start
                print(f'Time taken to collect the data: {timetaken}')
                return Outputs
            else:
                print(f'Deployment API result is : {deployment_output.status_code}')
                if deployment_output.json():
                    print(deployment_output.json())
                    raise Exception("Check the API result")

        else:
            print(f'Authentication API result is: {iaasApiOutput.status_code}')
            if iaasApiOutput.json():
                return iaasApiOutput.json()
                raise Exception("Check the API result")
    else:
        print(output.status_code)

Line 11 and 27 where we are using secret which we created as prerequisite.

PowerCLI ABX Action

function handler($context, $inputs) {
    #_______________________Debug and Verbose Mode Off____________________________________
    Set-PSDebug -Off
    $DebugPreference="SilentlyContinue"
    $VerbosePreference="SilentlyContinue"
    #_______________________Debug and Verbose Mode Off____________________________________
    
    #_______________________Get Secrets and Inputs____________________________________'
    $vc = $context.getSecret($inputs.vc_155_name)
    $username = $context.getSecret($inputs.vC_155_username)
    $password = $context.getSecret($inputs.vc_155_password)
    $application_name = $inputs.customProperties.application
    $owner_name = $inputs.customProperties.owner
    $backup = $inputs.customProperties.backup
    $data = $inputs['deployment_details']
    #_______________________Get Secrets and Inputs____________________________________'
    
    $connection = Connect-VIServer -Server $vc -User $username -Password $password  -force
    $application_ca = Get-CustomAttribute -TargetType VirtualMachine -Name 'Application'
    $owner_ca = Get-CustomAttribute -TargetType VirtualMachine -Name 'owner'
    $backup_ca = Get-CustomAttribute -TargetType VirtualMachine -Name 'backup'
    foreach($item in $data){
        Write-Host "Setting Custom Attribute to Application :"  -NoNewline
        $result = get-vm $item.resourceName|Set-Annotation -CustomAttribute $application_ca -Value $application_name
        if ($result.value -match $application_name )
        {
        Write-Host "Done"    
        }
        Write-Host "Setting Custom Attribute to Owner :"  -NoNewline
        $result1 = get-vm $item.resourceName|Set-Annotation -CustomAttribute $owner_ca -Value $owner_name
        if($result1.value -match $owner_name){
            Write-Host "Done"
        }
        Write-Host "Setting CUstom Attribute to Backp: " -NoNewline
        $result3 = get-vm $item.resourceName|Set-Annotation -CustomAttribute $backup_ca -Value $backup
        if($result3.value -match $backup){
            Write-Host "Done"
        }    
    }
}

Line 19,20,21 are the one where we are looking for custom attributes of vCenter .

Create ABX FLOW

---
version: 1
flow:
  flow_start:
    next: action1
  action1:
    action: Get_Deployment_Details_vCenter
    next: action2
  action2:
    action: Add vSphere Custom Attribute
    next: flow_end

Create subscription

Subscription: compute initial Power on

Sync the cloud template in Content Source

If you are followed the steps , we should be able to submit the catalog

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: