Creating automation script to create provision request for the AMAZON EC2 provider

This topic describes how to create an automation script to create provision requests for the AMAZON EC2 provider using ManageIQ.

  1. Open the Automation Scripts application.
  2. On the navigation panel, click Create and select Script with Object Launch Point.
  3. On the Create Script with Object Launch Point : Step 1 of 3 pop-up, fill the fields as follows:
    • Launch Point: Specify the launch point name, for example, ManageIQ AWS Provision VM Request.
    • Object: Search and select the SR object.
    • Object Event Condition: Fill below condition in this box:
    • Click the Save button, check the checkbox for the Update?, and click Before Save button.
    • Click the Next.
  4. On the Create Script with Object Launch Point : Step 2 of 3 pop-up, fill the fields as follows:
    • Script: Specify the name for the script such as ManageIQ AWS Provision VM Request
    • Script Language: Search and select jython
    • Log Level: Search and select Debug
    • Click Next
  5. On the Create Script with Object Launch Point : Step 3of 3 pop-up, fill the script box with the below script, and click Create.
    Note: The container path used in the following script is a sample and for reference only - //opt//ibm//wlp//usr//servers//defaultServer//apps. Enter an appropriate path as per the container in use.
    # LOGO REST Client - Maximo Company to Logo Tiger Current Account
    from com.ibm.json.java import JSONObject, JSONArray
    from psdi.iface.router import Router
    from psdi.iface.mic import EndPointCache
    from java.io import BufferedReader, IOException, InputStreamReader
    from java.lang import System, Class, String, StringBuffer
    from java.nio.charset import Charset
    from java.util import Date, Properties, List, ArrayList ,HashMap , Calendar
    from psdi.app.ticket import TicketRemote
    
    from org.apache.commons.codec.binary import Base64
    from org.apache.http import HttpEntity, HttpHeaders, HttpResponse, HttpVersion
    from org.apache.http.client import ClientProtocolException, HttpClient
    from org.apache.http.client.entity import UrlEncodedFormEntity
    from org.apache.http.client.methods import HttpPost
    from org.apache.http.entity import StringEntity
    from org.apache.http.impl.client import DefaultHttpClient
    from org.apache.http.message import BasicNameValuePair
    from org.apache.http.params import BasicHttpParams, HttpParams, HttpProtocolParamBean
    
    from psdi.mbo import Mbo, MboRemote, MboSet, MboSetRemote,MboConstants
    from psdi.security import UserInfo
    from psdi.server import MXServer
    from sys import *
    
    # method for creating the JSON string which is sent in http POST body
    def createJSONstring(vmName,template,memory,instance_type):
        jsonStr = ""
        
        templateFields = JSONObject()
        templateFields.put("guid", template)
        #templateFields.put("name", "amzn2-ami-hvm-2.0.20210326.0-x86_64-gp2")
        templateFields.put("request_type", "template")
        
        vmFields = JSONObject()
        vmFields.put("number_of_vms", 1)
        vmFields.put("vm_name", vmName)
        vmFields.put("vm_memory", memory)
        vmFields.put("instance_type", instance_type)
    	vmFields.put("guest_access_key_pair",5)
        vmFields.put("security_groups",12)
        
        obj = JSONObject()
        obj.put("version", "1.1")
        obj.put("template_fields", templateFields)
        obj.put("vm_fields", vmFields)
        
        jsonStr = obj.serialize(True)
        return jsonStr
    
    # method for http POST using the path, JSON body and token with bearer authorization
    def httpPost(path, jsonstring, vmName):
        postLog = ""
        System.out.println( 'httpPost invoked')
        
        # get connection properties from System Properties
        #properties = MXServer.getMXServer().getConfig()
        #host = properties.getProperty("logo.rest.host")
        uri = path
        ctx = HashMap()
        service.invokeScript("MANAGEIQ_AUTHTOKEN",ctx)
        service.log("the result is "+str(ctx.get("result")))
        postLog =  "\n Authentication Token Generated: \n " +  str(ctx.get("result"))+ "\n"
    
        # get authentication header
        System.out.println( 'authHeader set successfully')
        # get http parameters
        params = BasicHttpParams()
        paramsBean = HttpProtocolParamBean(params)
        
        System.out.println( 'BasicHttpParams set successfully')
        System.out.println( 'jsonstring created successfully')
        System.out.println( jsonstring)
    
        # get http body entities
        entity = StringEntity(jsonstring)
    
        # get client, http headers and request
        client = DefaultHttpClient()
        request = HttpPost(uri)
        request.setParams(params)
        request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
        request.addHeader('X-auth-token', ctx.get("token"))
        request.setEntity(entity)
        
        System.out.println( 'DefaultHttpClient set successfully')
    
        # get client response
        response = client.execute(request)
        System.out.println( 'client.executed invoked successfully')
        # return JSON response and reference number
        status = response.getStatusLine().getStatusCode()
        obj = JSONObject.parse(response.getEntity().getContent())
        id = obj.get("results").get(0).get("id")
        System.out.println( '--------------------------------------------------------------')
    
        System.out.println( 'SR Description :'+mbo.getString("DESCRIPTION"))
        System.out.println('Previous SR Status :'+ mbo.getString("STATUS"))
        
        System.out.println( 'HTTP Response :')
        System.out.println( response)
        System.out.println( 'HTTP Response Content:')
        System.out.println( obj)
        
        System.out.println( 'response status return successfully :')
        System.out.println( status)
        System.out.println( 'id :'+str(id))
        postLog = postLog + "\n Http Response return sucessfully: " +  str(status)+ "\n"
        postLog = postLog + "\n Http Response Content: \n " +  str(obj)+ "\n"
    
        if(status == 200):
            mbo.setValue("STATUS", "INPROG",MboConstants.NOACCESSCHECK)
            mbo.setValue("DESCRIPTION_LONGDESCRIPTION", "Provisioning Amazon EC2 Instance with name ::  "+vmName +" , id::"+str(id),MboConstants.NOACCESSCHECK)
            postLog = postLog + "\n Changed SR Staus  to :"+ mbo.getString("STATUS") +" and Details to :"+ mbo.getString("DESCRIPTION_LONGDESCRIPTION")+"\n"
            # Record the output in a new worklog entry
            mytext = mbo.getString("TICKETID")+":"+id
            my_file = open('//opt//ibm//wlp//usr//servers//defaultServer//apps','a')
            my_file.write(','+mytext)
            my_file.flush()
            my_file.close()
        else :
            mbo.setValue("STATUS", "INPROG",MboConstants.NOACCESSCHECK)
            mbo.setValue("DESCRIPTION_LONGDESCRIPTION", "Error While creating Provision Request,Please Check the details provided",MboConstants.NOACCESSCHECK)
            postLog = postLog + "\n Changed SR Staus  to :"+ mbo.getString("STATUS") +" and Details to :"+ mbo.getString("DESCRIPTION_LONGDESCRIPTION")+"\n"
            
      
        System.out.println(' SR Status :'+ mbo.getString("STATUS"))
    
        System.out.println( '--------------------------------------------------------------')
    
        return postLog
    
    # method for creating Maximo company record as a current account in Logo 
    def vmProvisionRequest(vmName,template,memory,instance_type):
        jsonstr = createJSONstring(vmName,template,memory,instance_type)
        worklogDesc = "\n MANAGEIQ AWS PROVISION VM REQUEST script \n"
        try:
            # format the start of the worklog entry
            System.out.println( 'ManageIQ AWS  VM Provision Request invoked')
            
            worklogDesc = worklogDesc + "\n Working on SR Description: [" +  mbo.getString("DESCRIPTION") + "]\n SR Status: [" + mbo.getString("STATUS") + "]\n \n"
            System.out.println("\n Working on SR Description: [" +  mbo.getString("DESCRIPTION") + "]\n SR Status: [" + mbo.getString("STATUS") + "]\n \n")
            credential_to_use = "MANAGEIQ_AUTH"
            handler = Router.getHandler(credential_to_use)
        
            manageiqApi = handler.getUrl() + "/api/provision_requests"
    
            worklogDesc = worklogDesc + "\n Request Invoked for VM NAME: "+vmName+" , AMI :"+template+"  ,memory : "+memory+" ,instance_type:"+str(instance_type)+"  \n"
            worklogDesc = worklogDesc + "\nManageIQ AWS  VM Provision HttpPost Request invoked :\n ["+ manageiqApi+"] \n Json : \n"+jsonstr +" \n"
            System.out.println("\nManageIQ AWS  VM Provision HttpPost Request invoked :\n ["+ manageiqApi+"] \n Json : \n"+jsonstr +" \n")
    
            log = httpPost(manageiqApi, jsonstr,vmName)
            worklogDesc = worklogDesc + "\n"+  str(log)+ "\n"
    
        except:
            System.out.println( 'Error:' + str(exc_info()[0]) + str(exc_info()[1]))
            worklogDesc =  worklogDesc + "\nError: " + str(exc_info()[0]) + str(exc_info()[1])+ "\n"
    
        finally:
            System.out.println( 'finally - all connections closed')
            worklogDesc = "\n" + worklogDesc + "\nfinally - all connections closed'\n"
        return worklogDesc
    
    
    # Main part
    
    try:
      System.out.println('--------------START------------')
      if(mbo.getString("STATUS") == 'APPR' ):
          id = str(System.currentTimeMillis())
          System.out.println('id:'+id)
        
          vmName = "aws-vm-" + id
          memory = ""
          template = ""
          instance_type = 0
          System.out.println('vmName ::'+vmName)
          
          ticketSpecSet = mbo.getMboSet("TICKETSPEC")
          for i in range(0, ticketSpecSet.count()):
            ticketSpec = ticketSpecSet.getMbo(i)
            if ticketSpec.getString("ASSETATTRID") == "VM_MEMORY":
                memory = str(ticketSpec.getInt("ALNVALUE"))
                System.out.println('memory :'+memory)
            if ticketSpec.getString("ASSETATTRID") == "AWS_AMI":
                template = ticketSpec.getString("ALNVALUE")
                System.out.println('AWS_AMI :'+template)
            if ticketSpec.getString("ASSETATTRID") == "FLAVOR":
                instance_type = int(ticketSpec.getString("ALNVALUE"))
                System.out.println('FLAVOR :'+str(instance_type))
                
          
          log = vmProvisionRequest(vmName,template,memory,instance_type)
                   
          worklogSet = mbo.getMboSet("WORKLOG")
        
          worklogMbo = worklogSet.add()
          worklogMbo.setValue("description", "MANAGEIQ AWS PROVISION VM REQUEST script",MboConstants.NOACCESSCHECK)
          worklogMbo.setValue("description_longdescription", log,MboConstants.NOACCESSCHECK)
          worklogMbo.setValue('CLIENTVIEWABLE', 1, MboConstants.NOACCESSCHECK)
        
          mboSet = mbo.getThisMboSet()
          mboSet = mbo.getMboSet("SR")
          mboSet.save() 
          worklogSet.save()
    
     
    except:
      System.out.println('Error in script ')