Press "Enter" to skip to content

Learning vCO Part 3 – bulk vm build via email

Hey Hey,

We are back with another learning vCO post, This one will be extending on a previous flow we made HERE which was uploading a csv file to provision VMs. Today lets take it a little further and extend it to emailing the file in, have the VMs be created and email the requester back saying it complete.

I will not be covering every little setting but hopefully give enough information for it to be recreated with easy. And I will be providing the workflow as a download.

1) first things first we are using the previous bulk vm creation workflow. you can make a copy of this or edit the existing one.
We will need to add 2 parts to it, to add all the VMs we create into an array and to output that array, I will use 2 scriptable tasks and inserted as per the below image.

Capture18

Adding VMs to array details
Capture14
Capture15

The code:

System.log(newVM);
clientsVMs.push(newVM);

The .push adds the VM object that was outputted from the VM creation workflow in this flow into an array.

var vmarrayout = new Array();

vmarrayout = clientsVMs;

This is taking the VM array and outputting it to an output array.

Outputting array of VM objects
Capture16
Capture17

Save the bulk creation workflow.

2) Now we will be using the built in mail flow called “Retrieve messages (via MailClient)” under the mail folder in the vCO workflow. make a copy of the workflow and save it under your folder.
Capture02

3) We will want to add all the required inputs as attributes and fill out the ones we know will be static as per the image below.
Capture04

These should be the login details for the mail account we want to send mail with attachments

4) We will be needing to add 2 more attributes one being a mimeattachment(FIle) and a sendersAddress attribute which we want to output from the check Emails script. as shown in the image below.
Capture21

5) Now the script, we will need to modify the script that comes with check emails section. To make this allot more simple and not have a 200 page post we will modify it to only check 1 email, pull out the attachment and grab the senders address and to delete emails that don’t match the template criteria.

Check Email code:

var myMailClient = new MailClient();

myMailClient.setProtocol(mailProtocol);
if(useSSL){
 myMailClient.enableSSL();
}

myMailClient.connect( mailServer, mailPort, mailUsername, mailPassword);
System.log("Successfully login!");

try {
	myMailClient.openFolder("Inbox");
	
	var messages = myMailClient.getMessages();
	System.log("Reading messages...!");
	if ( messages != null && messages.length > 0 ) {
	  System.log( "You have " + messages.length + " email(s) in your inbox" );
	var i = 0; 
	  System.log("");
	  System.log("-----MSG-------");
	  System.log("Headers: ");
	  var headerProp = messages[i].getHeaders();
	 for each(key in headerProp.keys){
	 System.log(key+": "+headerProp.get(key));
	  }
	  System.log("");  
	System.log("message number is: " + i);
	
	
	var tempemail =  messages[i].from;
	var stringToSearchIn = tempemail;
	var re = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/;
	var extractedEmail=re.exec(stringToSearchIn);
	var str = " " + extractedEmail + " ";
	var res = str.split(",",1);
	sendersAddress = " " + res  + " " ;
	
	System.log(sendersAddress); 
	
	  System.log( "Message["+ i +"] with subject: " + messages[i].subject);
	if (messages[i].subject != "vCAC Job Provision VM") {
	System.log("Email Message found in inbox does not meet the criteria .... Deleting");
	var messageid = i + 1;
	myMailClient.deleteMessage(messageid);
	}
	else{
	System.log("Email message is valid");
	  var content = messages[i].getContent();
	  if(messages[i].isContentMultiPart()){
   	   // get as multipart content
	   var multiPartContent = messages[i].getMultiPartContent();
	   System.log("==== Multipart msg detected ====");
	  for (p = 0; p < multiPartContent.getPartsCount(); p++){

	    System.log("== Body part " + p + " ==");
	    var bodyPart = multiPartContent.getBodyPart(p);

	    if(bodyPart.isAttachment()){
	     System.log("Getting as MimeAttachment:");

	     mimeAttachment = bodyPart.getAsMimeAttachment();
		 // could be saved to a file
	     System.log("Mime Name: " + mimeAttachment.name);
	     System.log("Mime Type: " + mimeAttachment.mimeType);
	System.log("Mime Content: " + mimeAttachment.content);

	    }
	   }
	  }
	var messageid = i + 1;
	myMailClient.deleteMessage(messageid);
	}
	// }
	} else {
	  System.warn( "No messages found" );
	}

} finally {
	myMailClient.closeFolder();
	myMailClient.close();
}

Important takeways from the above script is:

    Grabbing the Senders Email Address

	var tempemail =  messages[i].from;
	var stringToSearchIn = tempemail;
	var re = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/;
	var extractedEmail=re.exec(stringToSearchIn);
	var str = " " + extractedEmail + " ";
	var res = str.split(",",1);
	sendersAddress = " " + res  + " " ;

The email address that is retrieved will not work for my setup as it was (name, email address) format this may very well work for an exchange internal system but not in my mail setup so I needed to pull out the exact email address. You will notice the I have put quotes on either side when passing variables this is because the returned object is not a string but a mail object and this was a quick way to turn them into a string so we could output the value we want.

    getting the correct email

if (messages[i].subject != "vCAC Job Provision VM") {
	System.log("Email Message found in inbox does not meet the criteria .... Deleting");
	var messageid = i + 1;
	myMailClient.deleteMessage(messageid);

This section will check to see if the message has the correct subject. This was a quick test I put in, you can expand this and make it smarter but for this example we are leaving it simple. Because when grabbing the emails the number as in any array starts with 0, but the message ID is actually one higher than this so we are adding 1 to get the message ID and delete the email if the subject does not match.

    Getting the attachment

	     mimeAttachment = bodyPart.getAsMimeAttachment();
		 // could be saved to a file
	     System.log("Mime Name: " + mimeAttachment.name);
	     System.log("Mime Type: " + mimeAttachment.mimeType);
	System.log("Mime Content: " + mimeAttachment.content);

This is taking the attachment and assigning it to our mimeattachment attribute.

6) Ok that should be the modified email part. Now what we need to do is grab the bulk vm creation workflow that we created previously in Learning vCO part 1 and modified at the start of this post and drag and drop it into the mail flow as shown in the below image.

Capture07

7) now we need to link up the appropriate attributes going into and out of the flow. this is shown in the below image, we want to input the file attachment and output the array of VM objects.

Capture06

8) Next up we need to drag and drop a scriptable task after the bulk vm creation workflow, This will be where we generate the email to send back to the requester. This is shown in the below image.
Capture08

9)We now need to take the VM array that was outputted by the bulk creation workflow and input it into this task, then we need to out put the subject and content that we want in the email. create these attributes if you have not done so allready.

Capture09

10) now we need to create the script that will be run, this is shown in the image and below code.
Capture10

var emailbody = new String();
var emailsub = "Virtual Machine build Request";

emailbody += " Hi <BR />";
emailbody += "<BR />";
emailbody += "Thank you for the virtual machine buld request <BR />";
emailbody += "The following Virtual Machine were created and ready to access <BR />";
for each( item in newVM ) {
emailbody += item.name + "<BR />";
emailbody += "<BR />";
System.log(item.name);

}
System.log(emailsub);
System.log(emailbody);

clientContent = emailbody;
subject = emailsub;

The email is sent in HTML format so we use a single string with BR code to make the line breaks.

11) Ok so now it time to send the email, as you may have noticed I dont like re inventing the wheel and will reuse what I can. This is the great thing about vCO, if you create the flows try to do them in a modular fashion so they can be reused just like the bulk creation one.
So what we do now is search for the send notification email flow. This is located under the mail folder just like the receiving one we did. This is shown in the below image

Capture12

12) when we drag and drop the workflow we will get the setup button up on the top right, click this and we can setup the inputs into the send notification workflow. I have shown what I have done in the image below. I have reused the mail server and username and password bit added the rest.
Capture11
Capture13

13) There was no modification of the built in email script leave it as is.

Cool so now its time to test I am using the same csv file as used in part 1

First we send an email to the account we have setup.
emailsent

Then we will run a debug and have it pause so we can see the right details have been populated.
emailsent02

Now we continue on and we see if the VMs are being created.
emailsent03

Cool they are creating so lets see if we get our email back (this is a very ruff email) 🙂
emailsent04

woohooo it all worked well. What I then did is created a schedule and run the flow every minute. and just sent it emails all of which have worked perfectly.

This is only a base working flow and gives the opportunity to expand and make it allot more fancy.
What what would be the use case for a flow like this?
Well larger environments may very well use vCAC or other IaaS products. But not everyone out there has vCAC or vCD but anyone running vCenter has vCO or is licenced for vCO. Something like this could fit very well in a medium environment where you would like basic VM automation, and could even add smarts to send out approval emails before it actions etc.

Head over to Flowgrab to download the flow an all supporting actions etc located here

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Anti SPAM BOT Question * Time limit is exhausted. Please reload CAPTCHA.