API Examples

2 minute readReferenceDeveloper productivity

To use the CloudBees CD/RO Groovy API, you must first create an instance of ElectricFlow class. All CloudBees CD/RO APIs for ec-groovy can be invoked through that instance. Here is a basic script for invoking a CloudBees CD/RO API.

// All the {PRODUCT} APIs are accessible through the // ElectricFlow groovy class so you start by importing the class. import com.electriccloud.client.groovy.ElectricFlow // Instantiate ElectricFlow instance ElectricFlow ef = new ElectricFlow() // Invoke API def result = ef.getVersions() // Handle response println result.serverVersion.version

Specifying arguments

Most APIs expect one or more arguments. Arguments are specified as named parameters to the API.

// All the {PRODUCT} APIs are accessible through the // ElectricFlow groovy class so you can start by importing the class. import com.electriccloud.client.groovy.ElectricFlow // Instantiate ElectricFlow instance ElectricFlow ef = new ElectricFlow() // Invoke API with applicable arguments def result = ef.getApplication(applicationName: 'Test Application', projectName: 'Default') // Handle response println result.application

Using argument models

// All the {PRODUCT} APIs are accessible through the // ElectricFlow groovy class so you can start by importing the class. import com.electriccloud.client.groovy.ElectricFlow // Import the models for the API arguments from the client models package. import com.electriccloud.client.groovy.models.ActualParameter import com.electriccloud.client.groovy.models.Credential // Instantiate ElectricFlow instance ElectricFlow ef = new ElectricFlow() // In order to invoke runProcedure, first, build the list of actual parameters def params = [ new ActualParameter('param1', 'test12'), new ActualParameter(value: 'test12', actualParameterName: 'param1'), new ActualParameter(actualParameterName: 'param2', value: 'test24'), new ActualParameter(actualParameterName: 'testCred', value: 'testCred')] def creds = [new Credential(credentialName: 'testCred', userName: 'zzzxxx', password: 'pwd')] // Invoke API ef.runProcedure(projectName: 'Groovy Demo', procedureName: 'testProc', actualParameters: params, credentials: creds)

Running Groovy Scripts using Third-Party Libraries

In addition to the CloudBees CD/RO Groovy APIs, ec-groovy can be used to run any Groovy script using third-party libraries. Consider the following Groovy script:

import groovyx.net.http.RESTClient def client = new RESTClient('\https://www.google.com') client.get( path : '/search', query : [q:'Groovy'] ) { response, data -> println "Response Status: ${response.statusLine}" println data }

Example: Groovy GET Script 1

import groovyx.net.http.HTTPBuilder def http = new HTTPBuilder('\https://www.google.com') def html = http.get( path : '/search', query : [q:'Groovy'] )

Example: Groovy GET Script 2

import groovyx.net.http.HTTPBuilder def http = new HTTPBuilder('\https://www.google.com') http.get( path : '/search', contentType : 'TEXT', query : [q:'Groovy'] ) { resp, reader -> println "response status: ${resp.statusLine}" println 'Headers: -----------' resp.headers.each { h -> println " ${h.name} : ${h.value}" } println 'Response data: -----' System.out << reader println '\n--------------------' }

Example: Groovy POST Script

import groovyx.net.http.HTTPBuilder import static groovyx.net.http.ContentType.URLENC def http = new HTTPBuilder( '\https://restmirror.appspot.com/' ) def postBody = [name: 'bob', title: 'construction worker'] // will be url-encoded http.post( path: '/', body: postBody, requestContentType: URLENC ) { resp -> println "POST Success: ${resp.statusLine}" assert resp.statusLine.statusCode == 201

Example: Creating a deny list

Groovy also allows runtime resolution of artifacts that can download themselves across the internet. To disable this ability or to denylist only trusted repositories to download, write a grapeConfig.xml file and put it in the $COMMANDER_DATA/grape directory. This is an example of a grapeConfig.xml file without internet repositories:

<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at \https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <ivysettings> <settings defaultResolver="downloadGrapes"/> <resolvers> <chain name="downloadGrapes" returnFirst="true"> <filesystem name="cachedGrapes"> <ivy pattern="${user.home}/.groovy/grapes /[organisation]/[module]/ivy-[revision].xml"/> <artifact pattern="${user.home}/.groovy/grapes/[organisation] /[module]/[type]s/[artifact]-[revision](-[classifier]).[ext]"/> </filesystem> <ibiblio name="localm2" root="file:${user.home}/.m2/repository/" checkmodified="true" changingPattern=".*" changingMatcher="regexp" m2compatible="true"/> </chain> </resolvers> </ivysettings>

Error handling

If the API call to the CloudBees CD/RO server fails, by default, it causes the groovy script to fail. If you want to handle the error and continue processing, you can register custom success and failure handlers with the API invocation.

import com.electriccloud.client.groovy.ElectricFlow ElectricFlow ef = new ElectricFlow() def result ef.getPipeline(pipelineName: 'Test Pipeline', projectName: 'Default', /*success handler*/ { response, data -> println('Found pipeline!') result = data }, /*failure handler*/ { response, data -> //assuming pipeline does not exist hence the failure println('Creating pipeline...') result = ef.createPipeline(pipelineName: 'Test Pipeline', projectName: 'Default') }) println('Pipeline retrieved or created: ' + result?.pipeline?.pipelineName)