Rest API call from Script runner

Bibin Mohan_K June 28, 2021

Hi All,

 

I'm trying to PUT a simple REST API call to create deployment  project creation  in Bamboo  via Script Runner. Unfortunately it's not working in script runner but same script I able executed successfully in Linux environment .


curl -X PUT -H "Content-Type: application/json" https://bamboo.abc.com/rest/api/latest/deploy/project -d '{"name":"test deployment", "planKey":{"key":"TP-MS"},"description":"some project description"}' -u abc -p

 

 

 

 

2 answers

1 accepted

0 votes
Answer accepted
Charlie Misonne
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
June 28, 2021

How does your script look in scriptrunner? And do you get an error in your logs?

Are you aware that you can't use curl in scriptrunner?
Scriptrunner expects scripts in the Groovy languages. So if you want to make an HTTP request you will need to user the proper functions for that.

0 votes
Bibin Mohan_K June 28, 2021

Thank you for connecting . 

 

I managed to create a script in groovy to run script runner but it's not working .

import groovy.json.StreamingJsonBuilder
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import java.text.SimpleDateFormat
import java.text.DateFormat
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.comments.CommentManager

def baseURL = " https://bamboo.abc.com/rest/api/latest/deploy/project";

def body_req = [
"""
{ "fields":
{
"name":"Creating deployment project",
"planKey":{"key":"TP-MS"},
"description":"Creating deployment project rest api"
}
}
"""
]

URL url = new URL(baseURL);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setRequestProperty( "Authorization", "abc" );
connection.requestMethod = "PUT";
connection.doOutput = true;
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.outputStream.withWriter("UTF-8") { new StreamingJsonBuilder(it, body_req) }
connection.connect();

Charlie Misonne
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
June 28, 2021

Doy you get a syntax validation error or any particular error when running the scripts?

Make sure to check your log files if it's not in the user interface.

Bibin Mohan_K June 29, 2021

I am not getting any syntax error while running the script  . But functionality also not working. It's not creating the  deployment project.

Bibin Mohan_K June 29, 2021

Scriptrunner.PNG

Bibin Mohan_K June 29, 2021

I tried new script . Now I am getting error but don't how to resolve .

 

import groovy.json.JsonSlurper
import groovy.json.JsonParserType
import com.atlassian.jira.issue.customfields.option.Option
import com.atlassian.jira.issue.customfields.option.Options
import com.atlassian.jira.component.ComponentAccessor

def response = ["curl", "-k", "-D", "-X", "PUT", "-H", "Content-Type: application/json", "--data" ,'{"name":"test deployment", "planKey":{"key":"TP-MS"},"description":"some project description"}', https://bamboo.abc.com/rest/api/latest/deploy/project/all?token=MT].execute().text

 

 

Error : The script could not be compiled: <pre>org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script109.groovy: 8: unexpected token: @ line 8, column 2. ^ 1 error </pre>.

Charlie Misonne
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
June 29, 2021

I've never used curl in a grooy scrupt but I believe you should put that URL between quotes too.

I don't have a Bamboo instance to test with myself. But here is your script with a "dummy" REST endpoint that does give a result.
I also included some logging so you can view the output on the "logs" tab. It will show you the curl error if any.
So: replace that test url in my script with yours and see what happens.

import groovy.json.JsonSlurper
import groovy.json.JsonParserType
import com.atlassian.jira.issue.customfields.option.Option
import com.atlassian.jira.issue.customfields.option.Options
import com.atlassian.jira.component.ComponentAccessor
import org.apache.log4j.Level
import org.apache.log4j.Logger

Logger logger = Logger.getLogger("myscript")
logger.setLevel(Level.DEBUG)

def response = ["curl", "-k", "-D", "-X", "PUT", "-H", "Content-Type: application/json", "--data" ,'{"name":"test deployment", "planKey":{"key":"TP-MS"},"description":"some project description"}', "https://jsonplaceholder.typicode.com/posts"].execute()
logger.info response.text
logger.debug response.errorStream.text
Like Bibin Mohan_K likes this
Bibin Mohan_K June 30, 2021

Hello Charli ,

Thank you for the code . I tried but got below error.

 

2021-06-30 14:04:56,314 INFO [myscript]: 2021-06-30 14:04:56,328 ERROR [common.UserScriptEndpoint]: ************************************************************************************* 2021-06-30 14:04:56,328 ERROR [common.UserScriptEndpoint]: Script console script failed: java.io.IOException: Stream closed at Script239.run(Script239.groovy:14)

 

One query ,how I able to pass my token key or user credentials for authorization .

 

Thanks & Regards

Bibin Mohan. K

Charlie Misonne
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
June 30, 2021

Bamboo needs basic authentication. This can be passed with -u username:password

Try to have a working curl command on your Linux machine first without a password prompt.

And perhaps you need to provide the full path to curl in the groovy scipt. Something like /bin/curl or wherever curl is installed on you machine.

Bibin Mohan_K June 30, 2021

Hi Charlie,

Yes, I passed the -u username -p while running curl command in Linux environment and it's working . But while trying groovy script in script runner it will throw syntax error on special character used in password. 

 

Thanks & Regards

Bibin Mohan. K

Charlie Misonne
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
June 30, 2021

Hi @Bibin Mohan_K 

In that case it might be better to skip to -u parameter and use the Basic Authentication header:

curl -H Authorization: Basic <your-base64-string>

Where <your-base64-string> is the base64 string for: username:password.
Don't forget to include the colon character in between.

You can find tools online to generate the base64 string or use this in Linux:

echo -n 'username:password' | base64

Note: base64 is not encryption. So if you paste this online or on this community post anybode can decode the string and see your actual credentials.

Bibin Mohan_K June 30, 2021

Still facing same error :


import groovy.json.JsonSlurper
import groovy.json.JsonParserType
import com.atlassian.jira.issue.customfields.option.Option
import com.atlassian.jira.issue.customfields.option.Options
import com.atlassian.jira.component.ComponentAccessor
import org.apache.log4j.Level
import org.apache.log4j.Logger

Logger logger = Logger.getLogger("myscript")
logger.setLevel(Level.DEBUG)

def response = ["curl", "-k", "-D", "-X","Authorization: Basic abc","PUT", "-H", "Content-Type: application/json", "--data" ,'{"name":"Create test deployment", "planKey":{"key":"TP-MS"},"description":"some project description"}', "https://bamboo-abc.com/rest/api/latest/deploy/project"].execute()
logger.info response.text
logger.debug response.errorStream.text

Charlie Misonne
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
June 30, 2021

Make sure you get the right order with those curl parameters.

"Authorization: Basic abc" is a header so you need to have -H in front of it.

PUT is a value of the -X parameter.

Try this:

def response = ["curl", "-k", "-D", "-X","PUT", "-H", "Authorization: Basic abc", "-H", "Content-Type: application/json", "--data" ,'{"name":"Create test deployment", "planKey":{"key":"TP-MS"},"description":"some project description"}', "https://bamboo-abc.com/rest/api/latest/deploy/project"].execute()

 I'm also getting the stream closed error but that's because the hostname bamboo-abc.com does not exist. When I put something real there I get an authorization exception which is fine because I'm not providing an existing password.

Charlie Misonne
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
July 8, 2021

Hi @Bibin Mohan_K 

Out of curiosity: were you able to solve your issue with the information I provided in my last comment?

Bibin Mohan_K July 14, 2021

Hi @Charlie Misonne 

 

Thank you for asking . I am still facing the below error. But same hostname URL is working using curl command in Linux environment.  


2021-07-14 13:02:17,480 INFO [myscript]: 2021-07-14 13:02:17,513 ERROR [common.UserScriptEndpoint]: ************************************************************************************* 2021-07-14 13:02:17,513 ERROR [common.UserScriptEndpoint]: Script console script failed: java.io.IOException: Stream closed at Script290.run(Script290.groovy:12) 

 

If I comment the line logger.debug response.errorStream.text ,then no runtime error but then also after excuting it will not create a new deployment project in bamboo.

 

 

Thanks & Regards

Bibin Mohan. K

 

Bibin Mohan_K July 15, 2021

Hi @Charlie Misonne 

 

I tried below script . But now I am facing syntax issue .

import java.text.DateFormat
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.comments.CommentManager
import groovyx.net.http.HTTPBuilder

def baseurl = ComponentAccessor.getApplicationProperties().getString("https://bamboo-example/rest/api/latest/deploy/project")
def authString = "eXXXXXXXXX=".bytes.encodeBase64().toString()
def remote = new HTTPBuilder(baseurl+"/rest/configuration-manager/api/1.3/snapshots")
def issueJson = remote.request(Method.POST, ContentType.JSON) { req ->
headers."Authorization" = "Basic ${authString}"
body = [ name :"Auto deployment",
"planKey": {key: "TP-MS"} ,
"description": "Test"
]
response.success = { resp, json ->
log.warn("Successful = " + json.messages)
}
response.failure = { resp, json ->
log.warn("Failed = " + json.messages)
}
}

Like Georgi Hadzhi-Manev likes this
Bibin Mohan_K July 19, 2021

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events