groovy,jenkins,jenkins-scriptler , create email list of all users


create email list of all users

Question:

Tag: groovy,jenkins,jenkins-scriptler

On occasion I need to email all Jenkins users, for example warning them Jenkins will be offline for maintenance. The script below gives me email addresses for all people that Jenkins knows about, but it includes people that don’t have accounts, these are people that have committed changes that triggered builds. I’d like to remove them from the email list, that is the list should only include the users that you’d see on the securityRealm page. I’m looking for help modifying the script. Thanks.

import hudson.model.User
import hudson.tasks.Mailer

def users = User.getAll()
for (User u : users) {
    def mailAddress = u.getProperty(Mailer.UserProperty.class).getAddress()
    print(mailAddress + "; ")
}

Answer:

First of all you should know that Jenkins will not always be able to tell you whether the user exists or not. From Jenkins' javadoc:

This happens, for example, when the security realm is on top of the servlet implementation, there's no way of even knowing if an user of a given name exists or not.

I found two solutions.

Solution 1

HudsonPrivateSecurityRealm.html#getAllUsers() returns all users who can login to the system. And this works for me:

import hudson.model.User
import hudson.tasks.Mailer
import jenkins.model.Jenkins

def realm = Jenkins.getInstance().getSecurityRealm()
def users = realm.getAllUsers()
for (User u : users) {
    def mailAddress = u.getProperty(Mailer.UserProperty.class).getAddress()
    print(mailAddress + "; ")
}

Note: this depends on the Jenkins config and may not work on the system where used another (not a HudsonPrivateSecurityRealm) security realm.

Solution 2

SecurityRealm#loadUserByUsername returns user details if user exists and throws UsernameNotFoundException otherwise:

import hudson.model.User
import hudson.tasks.Mailer
import jenkins.model.Jenkins
import org.acegisecurity.userdetails.UsernameNotFoundException

def realm = Jenkins.getInstance().getSecurityRealm()
def users = User.getAll()
for (User u : users) {
    try {
        realm.loadUserByUsername(u.getId()) // throws UsernameNotFoundException
        def mailAddress = u.getProperty(Mailer.UserProperty.class).getAddress()
        print(mailAddress + "; ")
    } catch (UsernameNotFoundException e) { }
 }

This is tricky one, but should work with all security realms as we use the method that exists in top level abstract class (SecurityRealm).


Related:


Build failure due to Sonar plugin


service,jenkins,sonarqube,sonarqube5.1
My build keeps failing on Jenkins because of this error: ERROR: Error during Sonar runner execution org.sonar.runner.impl.RunnerException: Unable to execute Sonar at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:91) at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75) at java.security.AccessController.doPrivileged(Native Method) at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69) at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50) at...

Groovy: run SQL SELECT LIKE from file with params


sql,select,groovy
The groovy code is import groovy.sql.* dbUrl = 'jdbc:sqlserver://server' dbUser = 'username' dbPassword = 'password' dbDriver = 'com.microsoft.sqlserver.jdbc.SQLServerDriver' sql = Sql.newInstance(dbUrl, dbUser, dbPassword, dbDriver) def sqlfromfile = new SqlFromFile() sqlfromfile.sql_filename='select_query.sql' sqlfromfile.read() try{ def result = sql.rows(sqlfromfile.result,[id:'01']) println result }catch(e){ println e } class SqlFromFile { def sql_filename def read(){ result=...

Spock's @Narrative and @Title annotations


groovy,spock
Spock provides @Narrative and @Title annotations that you can use to provide a class-level description of your test, e.g. @Narrative('description of spec') @Title('title of spec') class ExampleSpec extends Specification { // tests omitted } What is the difference between these two? In other words, why do we need both of...

Why does DriverManager.getConnection() lookup fail in GroovyConsole?


mysql,jdbc,groovy,groovy-console
The following Groovy script works correctly from the command line. (I successfully get a Connection.) // ---- jdbc_test.groovy import java.sql.* Class.forName("com.mysql.jdbc.Driver") def con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", "password") println con > groovy -cp lib\mysql-connector-java-5.1.25-bin.jar script\jdbc_test.groovy [email protected] But if the same script is loaded into GroovyConsole (2.4.3) and run - after...

Get nth child node without knowing node name Groovy


xml,groovy
I have xml like this: <node1> <node2> <node3> <node4> <node5> <node6> </node6> <node7> </node7> </node5> </node4> </node3> </node2> </node1> How can I get the name of the 6th node - assuming I don't know the node's name is "node6"? I currently have: def text = <xml from above> def list...

set an annotation attribute from an environment variable?


spring,groovy,spring-boot
I'm trying to set an annotation value from an environment variable: @Configuration @ComponentScan @EnableAutoConfiguration @EnableScheduling class Application { @Scheduled(cron = "${DB_CRON}") def void schedule() { ... } public static void main(String... args) { SpringApplication.run(Application, args) } ... } However, I get the following compile time error: Attribute 'cron' should have...

Confused about the invokeMethod method in the Groovy MOP


groovy,mop
First look at the following Groovy code: class Car { def check() { System.out.println "check called..." } def start() { System.out.println "start called..." } } Car.metaClass.invokeMethod = { String name, args -> System.out.print("Call to $name intercepted... ") if (name != 'check') { System.out.print("running filter... ") Car.metaClass.getMetaMethod('check').invoke(delegate, null) } def validMethod...

Get just content of soap response in Groovy


xml,soap,groovy
I have following soap response: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetHTMLResponse xmlns="http://www.webserviceX.NET"> <GetHTMLResult> TEST </GetHTMLResult> </GetHTMLResponse> </soap:Body> </soap:Envelope> Now I want a method which deliverys me this xml: <root> <GetHTMLResponse...

How does the Groovy compiler work?


groovy
Can anyone explain the Groovy compiler works? Does it compile: Groovy code -> Java code -> Bytecode Groovy code -> Bytecode Some other method ...

sonar maven analysis only picks .java file


maven,groovy,sonarqube,sonarqube-5.0
I am trying to run a sonar maven analysis on my multilanguage project which contains many languages like *.java, *.groovy, *.js etc. I have installed all the languages plugin in my sonar and configured my pom sonar.sources parameter as src/main,src/test but still it picks up only java files. In the...

Display artifact in Jenkins Build description


plugins,jenkins
I would like to automatically display a artifact as part of the build description. Now I can do this by manually editing the build description but that would mean I have to do this for every build. Is there a way to automate this? This is what I would like...

How to get testStep responseAsXml in groovyScript


groovy,soapui
Concerning soapUI and groovy, I'm trying to get assertion (working) and response both in XML into a variable. I get the error groovy.lang.MissingMethodException: No signature of method: com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep.getResponseAsXml() is applicable for argument types: () values: [] error at line: 6 I have tried adding import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep but still cant figure...

Jenkins continuous deployment error


git,jenkins
I am learning Jenkins CI test & deploy as stated in the excellent tutorial http://code.tutsplus.com/tutorials/setting-up-continuous-integration-continuous-deployment-with-jenkins--cms-21511 at the end of the tutorial, it should handle the deployment of the app... as per the deploy script and the Jenkins project config w ./script/deploy #!/bin/sh ssh [email protected] <<EOF cd ~/hello-jenkins git pull npm...

Jenkins execute shell on job's executor during CONFIGURATION time (and access workspace)


java,shell,jenkins,jenkins-plugins
I would like to create a simple Jenkins plugin. Basically it is a custom build step (Builder extension) with a dropdown list. The trick is that I want to fill this dropdown list from the result of a shell script/command executed during configuration time. Here is my method stub. public...

How to access jenkins parent job build id in a MultiJob?


maven,jenkins
I have a requirement to trigger Automation Suite in multiple phases and summarize test results in a single test summary report. I configured a Jenkins Multi Job to trigger my automation suite, which is divided in to multiple chunks say suite#1, suite#2, suite#3, suite#4 (each suite is a maven job)...

Install gradle on Centos


jenkins,gradle
I'm trying to install gradle for building android app with the help of Jenkins. But I'm not able to find the link to download gradle for Centos. I tried to use binaries from https://gradle.org/downloads/, but when I unzipped I got gradle.bat file inside bin directory which tells me that this...

Jenkins (cloudbees): remotely trigger build (e.g.via instant message) w/o creating user account in Cloudbees


jenkins,cloudbees
We're using Jenkins (and precisely Cloudbees) for couple years. Well, it works. Not I have new use case when I would like to allow trigger build remotely (w/o user account in Cloudbees). Looks like it's impossible (standard token trigger mechanism requires an account in Cloudbees). The only one way that...

groovy/XML: Replace a node by another one


xml,groovy,xml-parsing,xmlslurper
I try to replace an XML node by another one by using XmlSlurper (or XmlParser). The original XML: <myXml> ... <myNode> <Name>name1</Name> <Name>name2</Name> <Name>name3</Name> </myNode> ... </myXml> The list that contains the items to build my new node def namelist = ['name4','name5','name6','name7'] What I want to have <myXml> ... <myNode>...

Grails JAX-RS Calling a class in src/groovy giving error - Message: No signature of method: is applicable for argument types


grails,groovy,jax-rs
While developing the rest api using jaxrs plugin I need to create some common class which I have created in "src/groovy". Below is the class class ValidateToken { String validate(String token){ println(token) return "test" } //... In resource file(jaxrs) this is what I am doing def instance=ValidateToken.validate("test") This throws error...

Saving docker container image


jenkins,docker
I created a new docker container using jenkings image This is the command I ran docker run -p 8080:8080 -v /var/jenkins_home jenkins I created a few jobs on the jenkins instance and commited the image docker commit 7b903d061654 test When I run the image I created using the command (below)...

Groovy - timestamp from minutes


oracle,grails,groovy,timestamp
I have an array or times/values coming back to be in an array like: [0, 60] Which are times in minutes, 0 = 12:00 a.m, 60 = 1:00 a.m. I am wanting to store these in an oracle database as timestamps. How do I convert minutes into timestamps in groovy?...

Jenkins does not find my git repository in Visual Studio Online


git,jenkins,visual-studio-online
I have a Visual Studio Online project working with Git. Everything works fine from inside Visual Studio. I'm trying then to configure a Jenkins job that gets the code from this project, but without success. Although the URL and the credentials are correct, Jenkins gives me this error on the...

Spock Framework: problems with spying


java,unit-testing,groovy,spock,spock-spy
I have an issue with using Spy in Spock, it either doesn't work as it should or my understanding is wrong so I'm trying to clarify this. Consider this code (Java): public class CallingClass { public String functionOne() { //does stuff return "one"; } public String functionTwo() { String one...

list of test step results in groovy script


groovy,automated-tests,soapui
I'm trying to figure out a way to get a list of (names) of just the failed test steps, currently the below code is giving me all the names def TestCase = testRunner.getTestCase() def StepList = TestCase.getTestStepList() StepList.each { log.info (it.name) } Now I'm not sure how to move on...

Why does `su` not work in Jenkins?


shell,jenkins,su
su doesn't seem to work as intended when run in Jenkins build job script. su username1234 whoami returns jenkins My initial guess is that each line of the Jenkins shell script is a new shell. But doing repeated echo $$ on separate lines shows that's not the case. ...

Model to LazyMap


dictionary,groovy,deserialization
How do I convert/deserialize these models public class AccessCredentials { String userName = '' String password = '' LoginOptions loginOptions = new LoginOptions() } public class LoginOptions { String partnerId = '' String applicationId = '' } into a LazyMap like : [ userName : userName, password : password, loginOptions...

Find view name from jenkins GUI given the job details


jenkins,jenkins-plugins
I have few hundreds of jenkins jobs all classified into different views based on different projects. So, I already have around 30+ views in Jenkins. My question is, Given a jenkins job name can I find out which View it is classified into.

Write Spock test cases for Spring boot application


java,spring,groovy,spock
I am working on spring boot application. I have to write test cases for it. I haven't written test cases before, so someone suggested using spock framework for it. I explored spock and i think it is more related to groovy language. Can i write spock test cases for my...

How to force team members to comment using eclipse plugin or something else


eclipse,jenkins,eclipse-plugin,coding-style,build-automation
Currently, I am working in a new project and it was difficult for me to understand since there is no comment. I wonder if it is possible to force team members(including me) to add more comments. I would like to automate this ject in jenkins later if possible.

Is it possible to save an adobe pdf file using selenium web driver and one click build Jenkins


java,pdf,selenium,jenkins
Here's my dilemma. I'm creating some automation tests using selenium web driver coding in Java. The main output of the software is to load a PDF in adobe acrobat. I'm also using Jenkins which is why my problem has come about as I wont be able to physically see the...

create email list of all users


groovy,jenkins,jenkins-scriptler
On occasion I need to email all Jenkins users, for example warning them Jenkins will be offline for maintenance. The script below gives me email addresses for all people that Jenkins knows about, but it includes people that don’t have accounts, these are people that have committed changes that triggered...

Decode base64 image in Grails [duplicate]


grails,groovy
This question already has an answer here: Convert base64 string to image 3 answers I have a post api where I am sending a json string which contain the base64 encoded image.Below is the json string { "imageData":"base64encoded string", "status":"1" } where base64encode string is iVBORw0KGgoAAAANSUhEUgAAAHgAAACgCAIAAABIaz/HAAAAAXNSR0IArs4c6QAA\r\nABxpRE9UAAAAAgAAAAAAAABQAAAAKAAAAFAAAABQAABWL3xrAqoAAEAASURBVHgB\r\nlL2Fe1t7mueZme6uewNGMUu2LNkyySSjDJKZmZkSO8zM7CTmmJnZYbxUVbdgsKp7\r\nqqdrdp I cant post...

Special Groovy magic re property access and collections / iterables?


groovy
I understand what is happening here with the spread operator *. in Groovy (2.4.3): [].class.methods*.name => [add, add, remove, remove, get, ... But why does the leaving the * out produce the same results? [].class.methods.name => [add, add, remove, remove, get, ... I'd have expected that to be interpreted as...

Downgrade Jenkins


jenkins,downgrade
I updated Jenkins some days ago. But in current Jenkins version, there are some annoying bugs. Is it possible, to downgrade the version of Jenkins and when it's possible, how is it possible?

Cron expression must consist of 6 fields (found 1 in “#{systemEnvironment['db_cron']}”)


spring,groovy,cron,spring-el
I'm trying to set a cron Scheduled annotation as follows: @Scheduled(cron = "#{systemEnvironment['db_cron']}") def void schedule() { } Next set the environment variable as: export db_cron="0 19 21 * * *" However, I get the runtime error: Cron expression must consist of 6 fields (found 1 in "#{systemEnvironment['db_cron']}") What can...

Triggering Jenkins to run application tests when GitHub PR is created


git,jenkins,continuous-integration,ansible,continuous-deployment
I am a noob to Jenkins, and I have a Jenkins server that runs an ansible playbook to deploy the app. I would like to be able to have Jenkins run an ansible playbook which runs application python tests when a GitHub pull request is opened. I would then like...

Class fields as method parameters


oop,groovy
My method needs to be strictly typed. If possible, I wanted to save some line of codes, setting the model properties from the parameter input by putting the model properties setter directly at the function definition. The current working code: class Connector { static def entityQuery( String httpMethod, String typeName,...

Fail Jenkins job when nosetests fail


python,shell,jenkins,continuous-integration
I am managing deployment / CI of a Flask app through Jenkins. I have a build step in the form of an executed shell which runs a shell script in the host that in turns runs nosetests. The Jenkins shell command looks like so: $WORKSPACE/ops/test_integration.sh integration.sh looks like so: SETTINGS_FILE="settings/integration.py"...

How to display all keep forever build number using Jenkins REST API for a specific job?


jenkins
I read the following post which does what I want for all jobs (and I made it works) List all keep-forever builds in Jenkins? here is what I have now : http://jenkinsmediaprocessor:7880/api/xml?depth=2&xpath=/hudson/job/build[keepLog=%22true%22]/url&wrapper=forever But I only want to display a specific task. However I don't know where to set the job...

Restrict allowed httpMethods using enum


rest,groovy,enums
I am creating connectors for REST API methods. Some methods has the same method name but performs different HTTP methods. For example, createEntity( HttpMethod httpMethod, CreateEntity model ) can perform POST and GET only. What I want is to have an error when httpMethod is supplied with PUT or DELETE....

How can I run the Jenkins jobs through terminal?


jenkins,terminal
I heard an version that webhooks could be used for this. Please help)

can't export a variable from execute shell in Jenkins to other project (with using properties file)


bash,shell,jenkins
I have a Jenkins project with one "Execute shell" that executes some bash commands and exports one variable to the env. variables: #!/bin/bash ... TARGET_FULLPATH="blablabla" export TARGET_FULLPATH In addition, I have configured to "Post-build Actions" with: "Trigger parameterized build on other projects" "Current build parameters" "Predefined parameters" -> FULLPATH=$TARGET_FULLPATH But,...

Jenkins Console Output Error


jenkins,jenkins-plugins
We've been using Jenkins for a while now, but recently we've added a couple plug-ins to the configuration and our Console Output is not showing in real-time anymore, we just get a big fat Java error! I've removed the offending plug-ins (emotional jenkins and Green Spot) in an attempt to...

Openshift - trigger Jenkins build on git push


jenkins,openshift
I work with Openshift now and I have a problem. I created an application server with Jenkins and when I push to the master branch of the git repository the Jenkins build is triggered automatically. The point is that the build isn't triggered when I push to another branch (not...

SBT is wasting lots of disk space for dependencies each build


jenkins,sbt,playframework-2.4
We have a Playframework 2.4 (with SBT 0.13.8) project which we build on a Jenkins. Today, the Jenkins stopped working because his $JENKINS_HOME run full. I analyzed which tool was wasting the disk space: SBT. There is a folder located at .sbt/0.13/dependency/module/dynamic that contains quadrillions of subfolders. Each of these...

How do I print the current classpath for a Jenkins plugin?


java,jenkins,classpath,classloader
I'm developing a Jenkins plugin but I'm having a few problems which I think might be due to a jar missing in the plugin's classpath even though its in the plugin's WEB-INF/lib directory. Normally I would use the following code in Java to print the classpath but this doesn't seem...

using classes in jenkins job dsl


groovy,jenkins,jenkins-job-dsl
Hi all I have a problem and I can't seem to figure it out. So I'm creating some helper classes for my dsl to use, but it just does not seem to execute any method within these classes. I have created a job with the following dsl in it: class...

Advantage of Jenkins Master/Slave architecture? [on hold]


jenkins
I am reading about the Jenkins Master/Slave architecture and how to configure it from here and as I am going down the page I am wondering why should I do it, what benefit I can achieve through it. I searched similar questions and reached here but still not convinced about...