Automatically add role to group via script

ejaram
Kilo Expert

Hello,

I am working on a script to create a group, add users to the group, set the manager, and add a role to the group.

I have the group creation, user add, and manager set working fine however I cannot get the role portion to work. I am not sure how to manipulate the 'sys_user_group' table to add the role to the group (since the 'Roles' is a related list on the table).

Anyone have any experience with this or how to go about it?

Thanks in advance,
Evan

1 ACCEPTED SOLUTION

TJW2
Mega Guru

The 'sys_group_has_role' table is where this information is stored. You will need to store the reference to the Group and the reference to the Role in this table.


View solution in original post

5 REPLIES 5

kevinanderson
Giga Guru

This worked for me (transaction cancelled for very long lists, may require multiple runs):



var groups=[


'<group 1 name >',


'<group 2 name >',


'<group 2 name >',


'<group 4 name >',


...


];






// 1. get sys id of item role




var gr = new GlideRecord('sys_user_role')


gr.addQuery('name' , 'itil');


gr.query();


if (gr.next()){


      // 2.   loop over list of groups


      for (var i=0; i < groups.length; i++){


           


              var gr2 = new GlideRecord('sys_user_group');


              gr2.addQuery('name' , groups[i]);


              gr2.query();


              while (gr2.next()){


                        // 3. get group sys id


                       


                        // update group roles table swith group sys id and role sys id


                     


                      var gr3 = new GlideRecord('sys_group_has_role');


                      gr3.addQuery('group', gr2.sys_id);


                      gr3.addQuery('role', gr.sys_id);


                      gr3.query();


                      if (gr3.getRowCount() == 0){


                              var gr4 = new GlideRecord('sys_group_has_role');


                              gr4.initialize();


                              gr4.group = gr2.sys_id;


                              gr4.role = gr.sys_id;


                              gr4.inherits = true;


                              gr4.insert();


                              gs.print('added record for '+gr2.name)


                      }


                      else{


                            gs.print('existing record found for '+gr2.name)    


                      }


                   


              }


           


      }


     


}