Creating groovy script to configure slave node properties >> "Restrict jobs execution at node"

3,545 views
Skip to first unread message

Amit Ghatwal

unread,
Oct 4, 2016, 1:19:56 AM10/4/16
to Jenkins Users

Hi All,

I am trying to automate the process of creating a slave node on jenkins server , creating users and then and also allow certain users to access only certain slave nodes. The automation is to be achieved via a groovy script.

Here's my script thus far
import jenkins.model.*
import hudson.security.*
import hudson.slaves.*
import hudson.plugins.sshslaves.*
import hudson.model.*


SLAVE_IP_ADDR
="172.17.1.55"
SLAVE_LOGIN
="root"
SLAVE_PWD
="root"

SLAVE_NODE_LABEL
="My_Slave_Node_Autogenerated-Label"


println
"create a slave node.. \n\r"
Slave slave_node = new DumbSlave(
"My_Slave_Node_Autogenerated",
"This slave node is generated using a jenkins job via groovy script",
"/home/jenkins",
"1",
Node.Mode.NORMAL,
SLAVE_NODE_LABEL
,
new SSHLauncher(SLAVE_IP_ADDR,22,SLAVE_LOGIN,SLAVE_PWD,"","","","",""),
new RetentionStrategy.Always(),
new LinkedList()
)
Jenkins.instance.addNode(slave_node)



So doing above , i am able to achieve creation of slave nodes, now what i want to do is to restrict the users created ( done by a groovy script too ) to have restricted access to the slave nodes created above. For this we need "job-restriction" plugin installed. I have version 0.5 installed on my server. Post installation of the plugin ,i have " Restrict jobs execution at node " option seen under " Node properties " for any slave node configure setting.

Now i can manually on the jenkins UI , i am able to achieve restriction of users created for any slave node , however do i get this automated using a groovy script.

Any thought how "Restrict jobs execution at node " can be achieved using a groovy script ? Any pointers will be helpful

Thanks and regards,
Amit

I

Victor Martinez

unread,
Oct 4, 2016, 12:54:47 PM10/4/16
to Jenkins Users
You might need to look at the job resctriciton plugin to find its jobs properties and create that property:

https://github.com/jenkinsci/job-restrictions-plugin/blob/master/src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/nodes/JobRestrictionProperty.java

The above url might help you to understand what that plugin does

Cheers

Amit Ghatwal

unread,
Oct 5, 2016, 12:25:27 AM10/5/16
to Jenkins Users
Hi Victor,

Thanks for quick comment.
I had already looked at the below repo of "job-restriction plugin" - https://github.com/jenkinsci/job-restrictions-plugin/tree/master/src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions

However i am unable to figure how do i change the slave node >>  configure >> Node Properties >> Restrict jobs execution at node via a groovy script ?
Any pointers on how can i bring out the above change might be helpful.

Thanks and regards,
Amit

Indra Gunawan (ingunawa)

unread,
Oct 5, 2016, 1:42:23 AM10/5/16
to jenkins...@googlegroups.com
Hi Amit,

1. You need to instantiate a new JobRestrictionProperty class giving to it a new instance of jobRestriction class.

2. You are saying you want to Restrict jobs execution at node just for User?   Do you want to configure “Started by User”?
This class extends AbstractUserCauseRestriction which extends jobRestriction so this class is a subclass of JobRestriction.
You need to instantiate a new StartedByUserRestriction class giving it :  (list of UserSelector, false, false, false).  <==  I presume you just want the list of users able to run job on the node, with no Upstream Job started by user or AutoRun or started by Anonymous User.

3. You pass in “StartedByUserRestriction" class created when you instantiate the new “JobRestrictionProperty" class.

4. Then you create a new LinkList and you add the JobRestrictionProperty class instance to the List.

5. You pass in the LinkList as the last parameter to the creation of the new DumbSlave class to create new node/Agent (see nodeProperties below):

public DumbSlave(String name,
         String nodeDescription,
         String remoteFS,
         String numExecutors,
         Node.Mode mode,
         String labelString,
         ComputerLauncher launcher,
         RetentionStrategy retentionStrategy,
         List<? extends NodeProperty<?>> nodeProperties)
          throws IOException,
                 Descriptor.FormException



--
You received this message because you are subscribed to the Google Groups "Jenkins Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jenkinsci-use...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/jenkinsci-users/3d03feac-510c-4ba2-987c-76e50b7a1f38%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Amit Ghatwal

unread,
Oct 5, 2016, 2:34:11 AM10/5/16
to Jenkins Users, ingu...@cisco.com
Hi Indra ,

You've have hit the nail on its head , you have perfectly summarized my requirements and precisely what i intent to achieve via a groovy script.

import jenkins.model.*
import hudson.model.*
import hudson.slaves.*
import hudson.plugins.sshslaves.*
import java.util.ArrayList;
import hudson.slaves.EnvironmentVariablesNodeProperty.Entry;


import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.nodes.JobRestrictionProperty;

import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionBlockageCause;
import hudson.Extension;
import hudson.model.Node;
import hudson.model.Queue;
import hudson.model.queue.CauseOfBlockage;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import org.kohsuke.stapler.DataBoundConstructor;

 
List<Entry> env = new ArrayList<Entry>();
  env
.add(new Entry("key1","value1"))
  env
.add(new Entry("key2","value2"))
 
EnvironmentVariablesNodeProperty envPro = new EnvironmentVariablesNodeProperty(env);
 
Slave slave = new DumbSlave(
                   
"agent-node","Agent node description",

                   
"/home/jenkins",
                   
"1",
                   
Node.Mode.NORMAL,

                   
"agent-node-label",
                   
new SSHLauncher("agenNode",22,"user","password","","","","",""),
                   
new RetentionStrategy.Always(),
                   
new LinkedList())
  slave
.getNodeProperties().add(envPro)
 
Jenkins.instance.addNode(slave)

I am actually kind of new to "groovy" , if u don't mind , as referred by you in above points : 1,2,3,4,5 is perfectly what i need , but if you could help in editing above groovy code to incorporate the points 1-5 as mentioned by you would be helpful.

Appreciate your time and help.
Thanks and regards,
Amit

Amit Ghatwal

unread,
Oct 5, 2016, 8:08:44 AM10/5/16
to Jenkins Users, ingu...@cisco.com
Hi Indra,

Got it working with the below changes to my groovy script . Copying the updated script for benefit of others

import jenkins.model.*
import hudson.model.*
import hudson.slaves.*
import hudson.plugins.sshslaves.*

import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.nodes.JobRestrictionProperty;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.job.StartedByUserRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.util.UserSelector;
import java.util.List;

List<UserSelector> usersList;

UserSelector  u1 = new UserSelector ("user1");
List userlist = new LinkedList();
userlist
.add(u1);

StartedByUserRestriction startuserrect = new StartedByUserRestriction(userlist, false, false,false );

JobRestrictionProperty jobrestrict = new JobRestrictionProperty(startuserrect);

List restrictlist = new LinkedList();
restrictlist
.add(jobrestrict);



 
Slave slave = new DumbSlave(
                   
"agent-node",
                   
"Agent node description",
                   
"/home/jenkins",
                   
"1",
                   
Node.Mode.NORMAL,
                   
"agent-node-label",

                   
new SSHLauncher("172.17.1.55",22,"root","root","","","","",""),
                   
new RetentionStrategy.Always(),
                    restrictlist
)
 
Jenkins.instance.addNode(slave)


Thanks for all the guidance and pointing out the detailed steps.

Thanks and regards,
Amit

chowh...@gmail.com

unread,
Nov 16, 2016, 6:02:24 AM11/16/16
to Jenkins Users, ingu...@cisco.com
Hi All 
i am also trying to achieve the similar thing where will be passing the parameters as string in Jenkins so  In the above solution tried to modify to my requirement as i wanted to add "new SSHLauncher("172.17.1.55",22,"root","root","","","","",""),"
but it fails to find the class could some share your thoughts

Thanks in advance 
Aditya

/**
 * This script is meant to be executed by a parameterized job in Jenkins and will then create new agents (slaves) as per the parameters
 *
 * SUGGESTED PAIRED PARAMETERS IN JENKINS (type, name, default values, description):
 *
 * Text - AgentList - "TestAutoAgent" - Name of agents to create, optionally more than one (each line makes one agent)
 * String - AgentDescription - "Auto-created Jenkins agent" - Description that'll be set for _every_ created agent
 * String - AgentHome - "D:\JenkinsAgent" - Remote filesystem root for the agent
 * String - AgentExecutors - 2 - Number of executors for the agent
 */

import hudson.model.Node.Mode
import hudson.slaves.*
import jenkins.model.Jenkins
import hudson.plugins.sshslaves.*
import java.util.List;
/*
//Handy debug logging
Jenkins.instance.nodes.each {
    println "BEFORE - Agent: $it"
}
*/

// The "build" object is added by the Jenkins Groovy plugin and can resolve parameters and such
String agentList = build.buildVariableResolver.resolve('AgentList')
String agentDescription = build.buildVariableResolver.resolve('AgentDescription')
String agentHome = build.buildVariableResolver.resolve('AgentHome')
String agentExecutors = build.buildVariableResolver.resolve('AgentExecutors')

agentList.eachLine {

    // There is a constructor that also takes a list of properties (env vars) at the end, but haven't needed that yet
    DumbSlave dumb = new DumbSlave(it,  // Agent name, usually matches the host computer's machine name
            agentDescription,           // Agent description
            agentHome,                  // Workspace on the agent's computer
            agentExecutors,             // Number of executors
            Mode.NORMAL,                // "Usage" field, EXCLUSIVE is "only tied to node", NORMAL is "any"
            "",                         // Labels
            new SSHLauncher(),
            RetentionStrategy.INSTANCE) // Is the "Availability" field and INSTANCE means "Always"

    Jenkins.instance.addNode(dumb)
    println "Agent '$it' created with $agentExecutors executors and home '$agentHome'"
}

/*
Jenkins.instance.nodes.each {
    println "AFTER - Agent: $it"
}
*/
Reply all
Reply to author
Forward
0 new messages