Jenkins脚本创建一个组并添加用户?

时间:2017-07-10 16:16:59

标签: jenkins jenkins-plugins jenkins-cli

我写了一个DSL脚本来在Jenkins中创建一个文件夹,但现在我需要一个脚本来为该文件夹创建一个组,并将用户添加到同一个组中并为一个组分配一个角色。

{{1}}

1 个答案:

答案 0 :(得分:0)

import nectar.plugins.rbac.groups.*
import java.util.*
import com.cloudbees.opscenter.server.model.*
import com.cloudbees.opscenter.server.clusterops.steps.*
import com.cloudbees.hudson.plugins.folder.*
import com.cloudbees.hudson.plugins.foldersplus.*
import jenkins.model.Jenkins;
import nectar.plugins.rbac.strategy.*;
import hudson.security.*;
import nectar.plugins.rbac.groups.*;
import nectar.plugins.rbac.roles.*;
import hudson.model.*;


// Assign request values
def appName = "TestApp";
def devs = ['userid1','userid2','userid3'];


// Begin Script
def instance = Jenkins.getInstance()

// Folder Path ( root dir is 'Jenkins/')
def targetDirectory = 'Jenkins/FolderName_Level_1 » ' + appName;

println("target Directory= ${targetDirectory}");

// Folder's Group Name (which you want to create or update)
def groupName = 'developers';


// Group's Role list that you want to assign e.g['admin','developer']
def groupRole = ['developer'] ;

                      
// Group's Member list which you want to add (by ADID) e.g['xyz','abc']
def addUsers = devs;

//Booleans to detect if function found group or not
Boolean foundGrp = false;


// Container used to handle connected Client masters
class ExploredObject {
  GroupContainer groupContainer
  Boolean isMaster
  Item instance
}

Map containers = new TreeMap();

// Add the root container
def root = new ExploredObject()
root.groupContainer = GroupContainerLocator.locate(Jenkins.instance)
root.isMaster = false
containers.put(Jenkins.instance.displayName, root)

// Add all the items that are be containers
for (i in Jenkins.instance.allItems) {
  if (GroupContainerLocator.isGroupContainer(i.getClass())) {
    GroupContainer g = GroupContainerLocator.locate(i)

    if (g != null) {
      def exploredObject = new ExploredObject()
      exploredObject.groupContainer = g
      exploredObject.instance = i
      containers.put("${Jenkins.instance.displayName}/${i.fullDisplayName}", exploredObject)
    }
  }
}

// Parse throuch all folder in root
for (cont in containers) {
  def c = cont.value.groupContainer
 // println(cont.key)

  if (cont.key == targetDirectory) {
    //println(cont.key)
    //println("Target Directory found")
    if (c.groups.size()){
      // Parse through the groups of the folder
      for (g in c.groups) {
        //If the group exist the add members
        if (g.name == groupName){
          foundGrp = true;
          println("    + ${g.name}")
          def currentMembers = g.members
          println("      * Current Members : ${currentMembers}")
          println("      * Current Roles: ${g.roles.collect {it + (g.doesPropagateToChildren(it) ?' (propagates)':'(pinned)')}}")
          if(addUsers.size() > 0){
            println("    -- Starting Add(+) / Delete(-) users to ${g.name}")
            // adds user to group
            for (eachUser in addUsers){
               g.doAddMember(eachUser)
               println("      + ${eachUser} Added")
            }

            println("    -- Completed Add / Delete users to ${g.name}")

            for (role in groupRole){
              g.doGrantRole(role, 0, Boolean.TRUE)
              println("      * Role assigned : role")
            }
          }
        }
      } //end of for loop g in c.groups
    }// end of if loop c.groups.size()
    //if the group doesn't exist then Create a group,Add member and assign role
    else{  // else of if loop c.groups.size()
        if(foundGrp == false){
            println("Group '${groupName}' does not exist")
            Group group = new Group(c, groupName)
            println("    + Start Adding user to ${groupName}")
            for (eachUser in addUsers){
                 group.doAddMember(eachUser)
                 println("      + ${eachUser} Added")
            }
            
            for (role in groupRole){
                 group.doGrantRole(role, 0, Boolean.TRUE)
                 println("      * Role assigned : ${role}")
            }
            c.addGroup(group)
            println("Group '${groupName}' is Created Succefully")
        }
      }
  } 
  else{
  }
}
instance.save()