How to assign role automatically for imported users?

swathigangadhar
Tera Expert

How to assign role automatically for imported users? I scheduling a job to run to import new users every week and i want to assign role 'end_user_new' to these users automatically, how to do that?

1 ACCEPTED SOLUTION

Hi,



I also suggest you tag the role to a group and add user in the group which is the best practice.



if(action =="insert"){


  var gr = new GlideRecord('sys_user_grmember');


  gr.initialize();


  gr.user = target.sys_id;   //After new user is inserted


  gr.group = 'sys_id_of_group';   // Tag the role to a group & add users in group


  gr.insert();


}





Thanks


PS: Hit like, Helpful or Correct depending on the impact of the response


View solution in original post

9 REPLIES 9

Okay,So now i need to do the following steps right?



1. I have to create a new group and tag the role to it.


2. I need to write 'Onafter' transform script .



It is right? What am following?


Yes you are.




Thanks


PS: Hit like, Helpful or Correct depending on the impact of the response


Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hello Swathi,



You can create a OnAfter transform script and assign role to the user. Please refer below script and adjust it accordingly.


(function runTransformScript(source, map, log, target /*undefined onStart*/ ) {


  // Add your code here


  var gr = new GlideRecord('sys_user_has_role');


  gr.initialize();


  gr.user = getUserSysId(source.u_email_id); //based on email Id


  gr.role = 'hardcode role sys_id'; //hardcode role sys_id for testing purpose. create a system property and fetch the value via gs.getProperty() method


  gr.insert();



  function getUserSysId(emailId)


  {


  var userGr = new GlideRecord('sys_user');


  userGr.addQuery('email', emailId);


  userGr.query();


  if(userGr.next())


  {


  return userGr.sys_id;



  }



  }



})(source, map, log, target);



Note: Untested code.


Hi

Any Ideas as to what you can do to get this to work, by adding a role to a group.

 

swathigangadhar
Tera Expert

Thanks a lot pradeep and alikutty, Very kind of you guys, it helped me a lot.