Send vRA Deployment Lease Expiration Mails [CB10109]

In this post, we will see how to send Aria Automation Deployments Lease Expiry Custom mails using vRO JavaScript code.

Send vRA Deployment Lease Expiration Mails [CB10109]

A simple use-case where we want to notify the vRA users about the deployments lease expiration over the email via vRO script. Use this script and modify accordingly. Let me quickly explain what I am doing here.

Steps

  • Get all the deployments by hitting the vRA Deployments API (/deployment/api/deployments) available at https://{{vRA_FQDN}}/automation-ui/api-docs
// typeof(host) == vRA:Host
var restClient = host.createRestClient();
//Assuming there are less than 10000 deployments in your environment
var request = restClient.createRequest("GET", "/deployment/api/deployments?$limit=10000", null);
request.setHeader("Content-Type", "application/json");
var response = restClient.execute(request);

System.log("****Status Code****");
var statusCode = response.statusCode;
System.log("Status code: " + statusCode);

System.log("****Content As String****");
var contentAsString = response.contentAsString;
System.log("Content as string: " + contentAsString);
JavaScript

Note Make sure to deal with pagination in REST API if you have a large number of deployments. Find the pagination code in final script.

We will get response something like,

{
   "content":[
      {
         "id":"xyz123-abcd-efgh-9ijk-lmnop123rst",
         "name":"new_deploy01-2023-03-1T21:13:55.799Z",
         "orgId":"xyz123-abcd-efgh-9ijk-lmnop123rst",
         "catalogItemId":"xyz123-abcd-efgh-9ijk-lmnop123rst",
         "catalogItemVersion":"1",
         "blueprintId":"xyz123-abcd-efgh-9ijk-lmnop123rst",
         "blueprintVersion":"1",
         "iconId":"xyz123-abcd-efgh-9ijk-lmnop123rst",
         "createdAt":"2023-03-1T21:14:11.773990Z",
         "createdBy":"mayank.goyal",
         "ownedBy":"mayank.goyal",
         "lastUpdatedAt":"2023-03-1T21:23:42.518212Z",
         "lastUpdatedBy":"new_deploy01",
         "leaseExpireAt":"2023-05-19T21:23:00Z",
         "inputs":{
            "name":"vm_sql01",
            "vm-size":"Small (1vCPU|2Gb)",
            "os-image":"Win2016",
            "leaseDays":60,
            "textField_b8ad97ef":"2023-03-1T21:13:55.799Z"
         },
         "projectId":"xyz123-abcd-efgh-9ijk-lmnop123rst",
         "status":"CREATE_SUCCESSFUL"
      },
.
.
.
.
  ]
}
JSON
  • Parse the response JSON to get properties like lease expiration date, deployment owner & deployment name.
.
.
.
for (var i = 0; i < contentAsString.content.length; i++){
    System.log("//------ Deployment "+contentAsString.content[i].inputs.name+" ------//");
    System.log("Lease expiring at "+contentAsString.content[i].leaseExpireAt);
.
.
var toAddress = contentAsString.content[i].ownedBy + "@email.domain";
var emailBody = "Deployment "+ contentAsString.content[i].inputs.name +" is about to expire";
.
.
.
JavaScript
  • Find out how many days remaining for the deployment lease to expire. Using some date and time operations, we are doing the calculation of days difference between today and leaseDate.
//2023-05-19T21:23:00Z -> vRO doesn't understand this format. So, we are converting it.
var dateString = contentAsString.content[i].leaseExpireAt;
var dateFromUI = dateString.split("Z")[0].split("T")[0];
var timeFromUI = dateString.split("Z")[0].split("T")[1];
var dateParts = dateFromUI.split("-");
var timeParts = timeFromUI.split(":");
var date = new Date(dateParts[0], dateParts[1]-1, dateParts[2], timeParts[0], timeParts[1], timeParts[2]);
System.warn("Expiration Date: "+date);
var todayDate = new Date();
System.warn("Present Date: "+todayDate);
System.log("How many days remaining for lease to expire? "+ getDaysDiffBetweenDates(todayDate, date));
if((getDaysDiffBetweenDates(todayDate, date) == 14 || (getDaysDiffBetweenDates(todayDate, date) == 7 || (getDaysDiffBetweenDates(todayDate, date) == 1)){
var toAddress = contentAsString.content[i].ownedBy + "@email.domain";
var emailBody = "Deployment "+ contentAsString.content[i].inputs.name +" is about to expire in "+getDaysDiffBetweenDates(todayDate, date)+" days. Take action now!";

function getDaysDiffBetweenDates(initialDate, finalDate){
    return Math.floor((finalDate - initialDate) / (1000 * 3600 * 24));
}
JavaScript
  • And then we have to send notification mails to the users at different time interval, lets say at 14 days , 7 days and 1 day before expiration.
if((getDaysDiffBetweenDates(todayDate, date) == 14) || (getDaysDiffBetweenDates(todayDate, date) == 7) || (getDaysDiffBetweenDates(todayDate, date) == 1)){
        var toAddress = contentAsString.content[i].ownedBy + "@email.domain";
        var emailBody = "Deployment "+ contentAsString.content[i].inputs.name +" is about to expire in "+getDaysDiffBetweenDates(todayDate, date)+" days. Take action now!";
        sendMail(toAddress,emailBody);

function sendMail(toAddress,emailBody){
    var message = new EmailMessage();
    var smtpHost = "[INPUT]your SMTP server fqdn/relay address</mark>";
    message.smtpHost = smtpHost;
    message.subject = "Take Action now! Deployment Expiring Soon";
    message.toAddress = toAddress;
    message.fromAddress = "[INPUT]from address";
    message.addMimePart(emailBody, "text/html; charset=UTF-8");
    message.sendMessage();    
    System.log("Mail sent to user "+toAddress);
}
JavaScript

Final Script

Create vRO Action with an input host of type vRA:Host and edit values like smtp server address, email domain, fromAddress.

// Input typeof(host) == vRA:Host
var restClient = host.createRestClient();
var items = [];
var path = "/deployment/api/deployments"; 
var page = 0; 
var page_size = 200; 
var base_path = path + "?$top=" + page_size; 
while (true) {    
    var skipFilter = page * page_size; 
    System.log(base_path + "&$skip=" + skipFilter);
    var request = restClient.createRequest("GET", base_path + "&$skip=" + skipFilter, null);
    request.setHeader("Content-Type", "application/json");
    var response = restClient.execute(request);
    var statusCode = response.statusCode;
    System.log("Status code: " + statusCode);
    var contentAsString = response.contentAsString;
    contentAsString = JSON.parse(contentAsString);

    for (var i = 0; i< contentAsString.content.length; i++)
        items.push(contentAsString.content[i]); 
    page++; 
    if (page >= contentAsString.totalPages) break  
};

var completedDeploymentCount = 0;
System.log("Total number of records fetched: "+ items.length);

for (var i = 0; i < items.length; i++) {
    //** Note: In some cases, items[i].name & items[i].status contain the data. Please check the JSON response from the first call.
    if (items[i].inputs.name &&items[i].status != "CREATE_INPROGRESS" && items[i].status != "CREATE_FAILED"  && items[i].status != "UPDATE_FAILED" && items[i].status != "UPDATE_INPROGRESS") {
        completedDeploymentCount++; 
        System.log("*** Deployment #" + completedDeploymentCount + " " + items[i].inputs.name + " ***");
        if (items[i].leaseExpireAt) { 
            var dateString = items[i].leaseExpireAt; 
            var dateFromUI = dateString.split("Z")[0].split("T")[0];
            var timeFromUI = dateString.split("Z")[0].split("T")[1];
            var dateParts = dateFromUI.split("-");
            var timeParts = timeFromUI.split(":");
            var date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2], timeParts[0], timeParts[1], timeParts[2]);
            System.log("Lease expiring on " + date);
            var todayDate = new Date();
            System.log("How many days remaining for the lease to expire? " + getDaysDiffBetweenDates(todayDate, date));  
            if ((getDaysDiffBetweenDates(todayDate, date) == 30) || (getDaysDiffBetweenDates(todayDate, date) == 14) || (getDaysDiffBetweenDates(todayDate, date) == 7) || (getDaysDiffBetweenDates(todayDate, date) == 1)) {
              if(items[i].ownedBy){  
                var toAddress =items[i].ownedBy + "@domain.com";
                var emailBody = "Deployment " + items[i].inputs.name + "'s lease is about to expire in " + getDaysDiffBetweenDates(todayDate, date) + " days.";
                sendMail(toAddress, emailBody);
              } else {
                 System.error("\"ownedBy\" attribute not found in response JSON for deployment: " + items[i].inputs.name + ". Cannot send mail!"); 
              }
            }
        } else {
            System.error("\"leaseExpireAt\" attribute not found in response JSON for deployment: " + items[i].inputs.name +". Skipping...");
        }
    }
}

function sendMail(toAddress, emailBody) {
    var message = new EmailMessage();
    var smtpHost = "x";
    message.smtpHost = smtpHost;
    message.subject = "Take Action Now!";
    message.toAddress = toAddress;
    message.fromAddress = "fromAddress@domain.com";
    message.addMimePart(emailBody, "text/html; charset=UTF-8");
    message.sendMessage();
    System.log("Mail sent to user " + toAddress);
}

function getDaysDiffBetweenDates(initialDate, finalDate) {
    return Math.ceil((finalDate - initialDate) / (1000 * 3600 * 24));
}
JavaScript

That’s all in this post for now. I hope you will find it useful. In case, you are facing any issue, feel free to reach out.

Leave a Reply

Related Posts

%d bloggers like this: