Assign a custom role to all users
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-10-2024 01:15 AM
Hi All,
I have a requirement that I wanted to add a custom role to all active users in system. I am aware how can we assign role to one user, but need to know how can we assign for all users which is active in system. Also wanted to know how can we add this role if new user record is created in system he/she needs to get this role by default. I guess this can be achieved through some scheduled jobs, but not aware what is the condition needs to be applied here.
Anyone implemented this, please help me with the steps.
Thanks in Advance,
Regards,
Ajith Pillai.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-10-2024 01:34 AM - edited 06-10-2024 01:37 AM
The below script will do the job of adding the role to existing active users:
var gr = new GlideRecord("sys_user");
gr.addActiveQuery();
gr.query();
while(gr.next()) {
var grrole = new GlideRecord("sys_user_has_role");
grrole.initialize();
grrole.user = gr.sys_id ;
grrole.role = '1d6b7b83971131102ab77d100153af97'; //sys id of your custom role here
grrole.insert();
}
For adding to new users, create an After Insert Business Rule on 'sys_user' to add the role to 'sys_user_has_role' for each new user as they are created.
Regards
Paul

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-10-2024 01:37 AM
@Ajith A Pillai You need to use two types of script here.
1. A fix script, which will assign the role to all active users.
var glideUser = new GlideRecord('sys_user');
glideUser.addActiveQuery();
glideUser.query();
while(glideUser.next()){
var glideUserRole = new GlideRecord('sys_user_has_role');
glideUserRole.initialize();
glideUserRole.setValue('user',glideUser.getValue('sys_id'));
glideUserRole.setValue('role','<sys_id_of_role>');//Todo: provide sys_id of your role here
glideUserRole.insert();
}
2. A business rule which will trigger as and when a record is inserted in sys_user table
Here is the script
(function executeRule(current, previous /*null when async*/ ) {
// Add your code here
var glideUserRole = new GlideRecord('sys_user_has_role');
glideUserRole.initialize();
glideUserRole.setValue('user', current.getValue('sys_id'));
glideUserRole.setValue('role', '<sys_id_of_role>'); //Todo: provide sys_id of your role here
glideUserRole.insert();
})(current, previous);