Groovy script to create masked password in Jenkins - jenkins

I am looking for a Groovy script that can create a masked password pair in Jenkins.
I've tried the following but it doesn't work.
import java.util.logging.Logger
import jenkins.model.*
import hudson.logging.*
//import com.michelin.cio.hudson.plugins.maskpasswords.*
import com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsConfig
import com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsBuildWrapper.VarPasswordPair
maskPasswordsConfig = MaskPasswordsConfig.getInstance()
varPasswordPairs = maskPasswordsConfig.getGlobalVarPasswordPairs()
MaskPasswordsConfig plugin = new MaskPasswordsConfig()
VarPasswordPair pwdPair = new VarPasswordPair("PWD", "myPassword")
plugin.addGlobalVarPasswordPair(pwdPair)
plugin.save()
I'm getting no results in the script console. Any help is appreciated.

#mweish, Just come across your post as I was trying to setup something similar, this should do what you are looking for:
import java.util.logging.Logger
import com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsConfig
import com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsBuildWrapper.VarPasswordPair
import jenkins.model.*
import hudson.logging.*
Logger logger = Logger.getLogger("")
Jenkins jenkins = Jenkins.getInstance()
MaskPasswordsConfig plugin = new MaskPasswordsConfig()
MASKED_PARAMETER_CLASSES = [
'com.michelin.cio.hudson.plugins.passwordparam.PasswordParameterDefinition',
'hudson.model.PasswordParameterDefinition'
]
def NAME_PASSWORD_PAIRS = [
[NAME:'PWD', PASSWORD:'myPassword']
]
// Add classes that should automatically be masked
MASKED_PARAMETER_CLASSES.each { maskedClass ->
plugin.addMaskedPasswordParameterDefinition(maskedClass)
}
// Add Global name/password pairs
NAME_PASSWORD_PAIRS.each { namePassPair ->
VarPasswordPair passwordPair = new VarPasswordPair(namePassPair.NAME, namePassPair.PASSWORD)
plugin.addGlobalVarPasswordPair(passwordPair)
}
plugin.save(plugin)
logger.info('Successfully Configured the Mask Passwords plugin')

Related

Jira REST endpoint redirected to error page

I am using a REST endpoint and here is my code: and here are some screenshots. The first screenshot shows the declaration of the condition and the denclaration of the Link: /rest/scriptrunner/latest/custom/callSubTaskCreator?issueId=${issue.id}. The second screenshot shows the declaration of the REST endpoint. I am specifying the link of a file in the script editor. Finally, the last screenshot shows the error page where I am redirected after clicking on the link.
as you can see I am redirected to an error page after I click on the button. Anyone knows what is wrong?
package CreateMultipleSubtasks
import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.JsonBuilder
import groovy.transform.BaseScript
import com.atlassian.jira.issue.Issue;
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response
import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.scriptrunner.runner.ScriptRunnerImpl
import com.atlassian.sal.api.ApplicationProperties
import com.atlassian.sal.api.UrlMode
import org.apache.log4j.Logger
import com.atlassian.jira.project.Project
import com.atlassian.jira.bc.project.component.ProjectComponent
import com.atlassian.jira.project.ProjectManager
#BaseScript CustomEndpointDelegate delegate
callSubTaskCreator(httpMethod: "GET", groups: ["jira-users"]) {
MultivaluedMap queryParams, String body ->
def log = Logger.getLogger("atlassian-jira.log")
log.warn("I AM HERE MOUNA 1");
ConfigurationCreateMultipleSubtasks conf = new ConfigurationCreateMultipleSubtasks()
def subTaskCreatorHashMap= conf.getSubTaskCreatorHashMap()
String itracCreatemultiplesubtasksProjectCategoriesURL = subTaskCreatorHashMap["itracCreatemultiplesubtasksProjectCategoriesURL"];
def user = ComponentAccessor.jiraAuthenticationContext?.loggedInUser
Issue issue = ComponentAccessor.getIssueManager().getIssueObject(queryParams.getFirst("issueId") as Long)
def itracCreatemultiplesubtasksProjectCategoriesURL2 = itracCreatemultiplesubtasksProjectCategoriesURL.replaceAll(":1:", issue.getKey())
def itracCreatemultiplesubtasksProjectCategoriesURL3 = itracCreatemultiplesubtasksProjectCategoriesURL2.replaceAll(":2:", user.getUsername())
Response.temporaryRedirect(URI.create(itracCreatemultiplesubtasksProjectCategoriesURL3)).build()
 
}

Static type checking The variable jiraHelper/issue is undeclared

I am using a condition in my script in the REST endpoint and I am receiving the following errors:
Anyone knows what the problem is and what needs to be fixed?
Here is the code:
package CreateMultipleSubtasks
import org.apache.log4j.Logger
import com.atlassian.jira.plugin.webfragment.model.JiraHelper
import com.atlassian.jira.component.ComponentAccessor
def log1 = Logger.getLogger("atlassian-jira.log")
log1.warn("MOUNA BEFORE")
Configuration_CreateMultipleSubtasks conf = new Configuration_CreateMultipleSubtasks()
def subTaskCreatorHashMap= conf.getSubTaskCreatorHashMap()
String projectKey = subTaskCreatorHashMap["projectKey"];
String issueTypeName = subTaskCreatorHashMap["issueTypeName"];
log.warn("MOUNA PROJECT KEY "+ projectKey+" issuetypename "+issueTypeName)
def val=jiraHelper.project?.key==projectKey && issue.issueType.name==issueTypeName
return val

Install Snyk in Jenkins "Global Tool Configuration" using groovy

I'm trying to add a Snyk installation to Jenkins using groovy. The plugin is installed and I can see the installation option in Global Tool Configuration:
The problem is the Descriptor is not available until I manually add the installer and click Save. If I don't do this task manually, which I want to prevent, it causes my code to fail with the following error message "Cannot invoke method setInstallations() on null object"
My code:
import hudson.model.*
import jenkins.model.*
import hudson.tools.*
import hudson.tasks.*
import io.snyk.jenkins.tools.SnykInstaller
import io.snyk.jenkins.tools.SnykInstallation
def snyk_name = "Snyk"
def snyk_home = ""
def snyk_installer = new SnykInstaller("", "latest", 24)
def snyk_properties = new InstallSourceProperty([snyk_installer])
def instance = Jenkins.getInstance()
println("[init.groovy.d] START Configuring Snyk Installation...")
// Get the GlobalConfiguration descriptor of Snyk plugin.
def snyk_conf = instance.getDescriptor("io.snyk.jenkins.SnykStepBuilder.SnykStepBuilderDescriptor")
def snyk_inst = new SnykInstallation(
snyk_name,
snyk_home,
[snyk_properties]
)
// Only add the new Snyk setting if it does not exist - do not overwrite existing config
def snyk_installations = snyk_conf.getInstallations()
def snyk_inst_exists = false
snyk_installations.each {
installation = (SnykInstallation) it
if (snyk_inst.getName() == installation.getName()) {
snyk_inst_exists = true
println("Found existing installation: " + installation.getName())
}
}
if (!snyk_inst_exists) {
snyk_installations += snyk_inst
snyk_conf.setInstallations((SnykInstallation[]) snyk_installations)
snyk_conf.save()
}
// Save the state
instance.save()
println("[init.groovy.d] END")
Is there any way to do what I want programmatically?
After testing your groovy on my local Jenkins (v 2.263.1) I came up with the below which then worked for me:
import hudson.model.*
import jenkins.model.*
import hudson.tools.*
import hudson.tasks.*
import io.snyk.jenkins.tools.*
def instance = Jenkins.getInstance()
def snyk_name = "SnykLatest"
def snyk_home = ""
def snyk_installer = new SnykInstaller("", "latest", 24L, null)
def snyk_properties = new InstallSourceProperty([snyk_installer])
println("[init.groovy.d] START Configuring Snyk Installation...")
// Get the GlobalConfiguration descriptor of Snyk plugin.
def snyk_conf = instance.getDescriptor("io.snyk.jenkins.tools.SnykInstallation")
def snyk_inst = new SnykInstallation(
snyk_name,
snyk_home,
[snyk_properties]
)
// Only add the new Snyk setting if it does not exist - do not overwrite existing config
def snyk_installations = snyk_conf.getInstallations()
def snyk_inst_exists = false
snyk_installations.each {
installation = (SnykInstallation) it
if (snyk_inst.getName() == installation.getName()) {
snyk_inst_exists = true
println("Found existing installation: " + installation.getName())
}
}
if (!snyk_inst_exists) {
snyk_installations += snyk_inst
snyk_conf.setInstallations((SnykInstallation[]) snyk_installations)
snyk_conf.save()
}
// Save the state
instance.save()
println("[init.groovy.d] END")
In basic Terms the SnykInstaller was expecting 4 values not 3. Groovy also took the 3rd value as an Integer when it was expecting a Long Value.
References:
https://javadoc.jenkins.io/plugin/snyk-security-scanner/io/snyk/jenkins/tools/SnykInstaller.html
https://github.com/jenkinsci/snyk-security-scanner-plugin/blob/master/src/main/java/io/snyk/jenkins/tools/SnykInstaller.java
https://github.com/jenkinsci/snyk-security-scanner-plugin/blob/master/src/main/java/io/snyk/jenkins/tools/PlatformItem.java

Zeppelin Twitter Streaming Example Not Working

I am trying to run Twitter Streaming Example in Zeppelin. After I searched around, I added "org.apache.bahir:spark-streaming-twitter_2.11:2.0.0" into Spark Interpreter. So I can make the first part work, as in:
Apache Zeppelin 0.6.1: Run Spark 2.0 Twitter Stream App
Now I am trying to add the second half as:
case class Tweet(createdAt:Long, text:String, screenName:String)
twt.map(status=>
Tweet(status.getCreatedAt().getTime()/1000, status.getText(), status.getUser().getScreenName())
).foreachRDD(rdd=>
rdd.toDF().registerTempTable("tweets")
)
Now I got the error:
<console>:56: error: not found: type StreamingContext
val ssc = new StreamingContext(sc, Seconds(2))
^
<console>:56: error: not found: value Seconds
val ssc = new StreamingContext(sc, Seconds(2))
^
<console>:61: error: not found: value Seconds
val twt = tweets.window(Seconds(60))
Actually I added the case line, I got the above error. I really had no idea what happened here.
Any one has any clue here?
Here are details
Spark: 2.0.0
Zeppelin: 0.6.2
Thanks a lot.
=====================================================================
// All codes for your reference:
import org.apache.spark.streaming.twitter
import org.apache.spark.streaming._
import org.apache.spark.storage.StorageLevel
import scala.io.Source
import scala.collection.mutable.HashMap
import java.io.File
import org.apache.log4j.Logger
import org.apache.log4j.Level
import sys.process.stringSeqToProcess
import org.apache.spark.SparkConf
// ********************************* Configures the Oauth Credentials for accessing Twitter ****************************
def configureTwitterCredentials(apiKey: String, apiSecret: String, accessToken: String, accessTokenSecret: String) {...}
// ***************************************** Configure Twitter credentials ********************************************
val apiKey = ...
val apiSecret = ...
val accessToken = ...
val accessTokenSecret = ...
configureTwitterCredentials(apiKey, apiSecret, accessToken, accessTokenSecret)
// ************************************************* The logic itself *************************************************
val ssc = new StreamingContext(sc, Seconds(2))
val tweets = TwitterUtils.createStream(ssc, None)
val twt = tweets.window(Seconds(60))
twt.print
// above codes work correctly
// If added the following line, it failed with the above error
case class Tweet(createdAt:Long, text:String, screenName:String)
I had the same problem, and I have no idea why moving the import statements from the top to right before the new StreamingContext fixed it, but it did.
import org.apache.spark.streaming._ //moved here from top
import org.apache.spark.streaming.twitter._ //moved here from top
val ssc = new StreamingContext(sc, Seconds(2)) //existing
I had a similar issue. Using the FQCNs worked ok, so I ended up using that as a workaround.

Update JIRA subtask Fix Version when parent issue Fix Version updated

When an issue is created, the Fix Version field is set to a particular value (say 2.0). Then subtasks are created, and they inherit this value. So far so good. But if later, the issue's Fix Version value is modified (to say 1.0), the subtasks still keep the 2.0 fix version value.
Is there a plugin or technique I can use to keep these fields in sync?
Note: This has been requested as a JIRA feature, but Atlassian doesn't seem to want to do it.
https://jira.atlassian.com/browse/JRA-9016
I know its rather an old question. But here is my code I recently deployed. This is an event listener for issueUpdated event deployed on Script Listener from ScriptRunner plugin. A lot of the code is from Jamie Echlin's examples. It still needs to be tweaked for when a Fix Version field on the Parent is made "empty", it's sub tasks also need to be empty.
package com.custom.listeners
import org.apache.log4j.Category
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.event.issue.AbstractIssueEventListener
import com.atlassian.jira.event.issue.IssueEvent
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.project.version.Version
import com.opensymphony.workflow.InvalidInputException
import com.atlassian.jira.config.SubTaskManager
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.event.type.EventDispatchOption
import java.util.ArrayList
import java.util.Collection
class FixVersionPBI_To_SBI_1 extends AbstractIssueEventListener
{
Category log = Category.getInstance(FixVersionPBI_To_SBI_1.class)
#Override
void issueUpdated(IssueEvent event)
{
try
{
Issue fix_Issue = event.getIssue()
if (fix_Issue.issueTypeObject.name == "Parent issue type" )
{
List changeItems = event.getChangeLog().getRelated("ChildChangeItem")
if( fix_Issue.fixVersions?.name && changeItems.any {it.get('field')=='Fix Version'} )
{
Collection<Version> fixVersions = new ArrayList<Version>();
fixVersions = fix_Issue.getFixVersions()
Collection subTasks = fix_Issue.getSubTasks();
SubTaskManager subTaskManager = ComponentManager.getInstance().getSubTaskManager();
if (subTaskManager.subTasksEnabled && !subTasks.empty)
{
IssueManager issueManager = ComponentManager.getInstance().getIssueManager()
Collection _subTasks = fix_Issue.getSubTaskObjects()
_subTasks.each
{
it.setFixVersions(fixVersions)
issueManager.updateIssue(event.getUser(), it, EventDispatchOption.ISSUE_UPDATED, false)
}
}
}
}
}
catch (ex)
{
log.debug "Event: ${event.getEventTypeId()} fired for ${event.issue} and caught by FixVersionPBI_To_SBI_1"
log.debug (ex.getMessage())
}
}
}
For Jira 6.4
Your subtasks fixversion fields will be update automatically.
Install ScriptRunner plugin.
OPEN your-jira.host/secure/admin/ViewCustomFields.jspa
ADD the new custom field with (Advanced>Scripted field)
OPEN /plugins/servlet/scriptrunner/builtin?section=script_fields and find new field there.
ADD this script, test it and save.
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.config.SubTaskManager;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.event.type.EventDispatchOption;
def result = "";
def subTasks = issue.getSubTaskObjects()
Collection fixVersions = issue.getFixVersions();
if (!fixVersions.empty) {
SubTaskManager subTaskManager = ComponentAccessor.getSubTaskManager();
if(subTaskManager.subTasksEnabled && !subTasks.empty) {
def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser();
subTasks.each {
if (it.statusObject.name != "Closed") {
it.setFixVersions(fixVersions);
IssueManager issueManager = ComponentAccessor.getIssueManager()
result += it.getKey() + " ";
issueManager.updateIssue(user, it, EventDispatchOption.ISSUE_UPDATED, false);
}
}
if (count > 0) {
result += " versions updated";
}
}
}
return result;
To do it manually, you could do query such as "parent=TEST-123" and then a bulk edit. To do it automatically you would need to have a custom listener (e.g. Script Runner) to detect the Issue Updated event and only do something if the change was an issue update. Updating the subtask Fix Versions will also require that the subtasks are reindexed or your searches will not work as expected.
I don't know of a plugin to do this.

Resources