Creating automation script to stop instance of AMAZON EC2 provider

This topic describes how to create an automation script to stop an instance of AMAZON EC2 provider.

  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, AWS STOP INSTANCE.
    • Object: Search and select the SR object.
    • Object Event Condition: Fill below condition in this box:
      • :description='ManageIQ - AWS Stop Virtual Machine' and status='APPR'
        Note: The description above is the same as the description in the Offering Ticket Template that you created in Create Offering to stop amazon EC2 instance.
    • 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 of the script such as AWS STOP INSTANCE
    • 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.
    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,SqlFormat
    from psdi.mbo import MboSetEnumeration
    
    from psdi.security import UserInfo
    from psdi.server import MXServer
    
    from sys import *
    from org.python.core import PyTuple
    
    def getVmDetails(vmName):
        credential_to_use = "MANAGEIQ_AUTH"
        handler = Router.getHandler(credential_to_use)
        username = handler.getUserName();
        endPointInfo = EndPointCache.getInstance().getEndPointInfo(credential_to_use)
        password  = endPointInfo.getProperty("PASSWORD").getValue()
        url = handler.getUrl() + "/api/providers/2/vms"
    
        query = "filter[]=name=%27"+vmName+"%27&_format=json"
        System.out.println('Get Deatils of Amazon EC2 Instance:: ' +vmName+"\n Api invoked :"+ url)
        System.out.println('query'+query)
        paramMap = {"URL":url, "username":username, "password":password}
        result = String(handler.invoke(paramMap, query))
    
        jsnResp = JSONObject.parse(result)
        System.out.println(jsnResp)
        System.out.println("response:: "+str(jsnResp))
        resources = jsnResp.get("resources")
        System.out.println("resources:: "+ str(resources))
        return resources
        
    # method for creating the JSON string which is sent in http POST body
    def createJSONstring(resources):
        jsonStr = ""
        
        resource = resources.get(0)
        resource.put("enable_ipmi", "enabled")
        resource.put("initial_state","off")
        
        resourcesArr = JSONArray()
        resourcesArr.add(resource)
    
        obj = JSONObject()
        obj.put("action", "stop")
        obj.put("resources", resourcesArr)
        
        jsonStr = obj.serialize(True)
        return jsonStr
    
    # method for http POST using the path, JSON body and token with bearer authorization
    def httpPost(uri, jsonstring):
        System.out.println("\nManageIQ AMAZON EC2 STOP VM HttpPost Request invoked :\n ["+ uri+"] \n Json : \n"+jsonstring +" \n")
        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 http parameters
        params = BasicHttpParams()
        paramsBean = HttpProtocolParamBean(params)
       
        # 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( 'Request header 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())
        message = obj.get("results").get(0).get("message")
        postLog = postLog + "\n Http Response return sucessfully: " +  str(status)+ "\n"
        postLog = postLog + "\n Http Response Content: \n " +  str(obj)+ "\n"
        
        System.out.println("\n Http Response return sucessfully: " +  str(status)+ "\n")
        System.out.println("\n Http Response Content: \n " +  str(obj)+ "\n")
        if(status == 200):
            mbo.setValue("STATUS", "RESOLVED",MboConstants.NOACCESSCHECK)
            mbo.setValue("DESCRIPTION_LONGDESCRIPTION", message ,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 Changed to :'+ mbo.getString("STATUS"))
        return postLog
    
    # method for stop AWS instance using ManageIQ API 
    def stopVm(vmName):
        try:
            worklogDesc = "\n MANAGEIQ AMAZON EC2 STOP INSTANCE script \n"
    
            System.out.println( 'MANAGEIQ AMAZON EC2 STOP INSTANCE script')
         
            worklogDesc = worklogDesc + "\n Working on SR Description: [" +  mbo.getString("DESCRIPTION") + "]\n SR Status: [" + mbo.getString("STATUS") + "]\n \n"
            System.out.println("Working on SR Description: [" +  mbo.getString("DESCRIPTION") + "]\n SR Status: [" + mbo.getString("STATUS") + "]\n ")
    
            resources = getVmDetails(vmName)
            if  len(resources) == 0 :
                worklogDesc = worklogDesc + "\n Not found Instance with Name ::"+ vmName
                System.out.println("\n Not found Instance with Name ::"+ vmName)
                mbo.setValue("DESCRIPTION_LONGDESCRIPTION", "\n Not found Instance with Name ::"+ vmName ,MboConstants.NOACCESSCHECK)
                mbo.setValue("STATUS", "RESOLVED",MboConstants.NOACCESSCHECK)
                return worklogDesc
    
            jsonstr = createJSONstring(resources)
            credential_to_use = "MANAGEIQ_AUTH"
            handler = Router.getHandler(credential_to_use)
            manageiqApi = handler.getUrl() + "/api/vms"
    
            worklogDesc = worklogDesc + "\nManageIQ AMAZON EC2 STOP VM HttpPost Request invoked :\n ["+ manageiqApi+"] \n Json : \n"+jsonstr +" \n"
            log = httpPost(manageiqApi, jsonstr)
            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
    
    System.out.println('--------------------------------------------------------------------')
    
    ticketSpecSet = mbo.getMboSet("TICKETSPEC")
    vmName = None
    for i in range(0, ticketSpecSet.count()):
     ticketSpec = ticketSpecSet.getMbo(i)
     if ticketSpec.getString("ASSETATTRID") == "VM_NAME":
         vmName = ticketSpec.getString("ALNVALUE")
         System.out.println('VM NAME :'+vmName)
         break
    
    log = stopVm(vmName)
      # Record the output in a new worklog entry
      
    worklogSet = mbo.getMboSet("WORKLOG")
    
    worklogMbo = worklogSet.add()
    worklogMbo.setValue("description", "MANAGEIQ Amazon EC2 STOP Instance 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()
    System.out.println( '--------------------------------------------------------------')