Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Remove & add user roles via scripting

bcitil
Kilo Explorer

I've created a catalog item and corresponding workflow that allows certain users to modify the user role of another user. The user selects one of two radio boxes and completes the user's name within the field provided.

For example, elevation between the knowledgeII and knowledgeIII roles would require the removal of the knowledgeII role and addition of the knowledgeIII role for a user.

Within the workflow, I've created a scripting step, yet am struggling to implement a script that will actually make the change in user roles.

I've searched extensively and discovered a script that will allow adding user roles but does so via a string: https://wiki.servicenow.com/index.php?title=Add_Role_to_Every_User. However, this isn't quite what I'm looking for, as removing a user role would be rather difficult in this manner.

Does anyone have an easy solution for this?

2 REPLIES 2

Not applicable

Have a look at the ouf-of-the-box workflow activity "Grant role_delegator role to user in group".
Basically you query the "sys_user_has_role" table which combines the user with a particular role.

See https://demo017.service-now.com/nav_to.do?uri=wf_activity.do?sys_id=0709a9a50a0a0bad01c9f47c372be8d1

Similar you can also query for the role you would like to delete.



bcitil
Kilo Explorer


laurens.brand


Okay..to start, I've tailored the built-in workflow to simply add a user role to a user, both specified in the catalog item submission. I'm not yet seeing the role being added to the specified user..ideas?



grantKCSIIRole();
//removeKCSIIIRole();

function grantKCSIIRole() {
var role = current.variable_pool.kcs_role;
var user = current.variable_pool.kcs_user;
var gr = new GlideRecord("sys_user_has_role");
gr.addQuery("user",user);
gr.addQuery("role",role.sys_id);
gr.addQuery("granted_by",role);
gr.addQuery("inherited","false");
gr.query();
if (!gr.next()) {
gr.initialize();
gr.user = user;
gr.role = role.sys_id;
gr.granted_by = current.variable_pool.kcs_role;
gr.inherited = false;
gr.insert();
}
}