Task 1 – ITSM: Automatically Assign analytics_admin Role Using Scheduled Job

YashwanthV18760
Tera Expert

REQUIREMENT : For every hour automatically assign analytics_admin role for users who don't have analytics_admin or analytics_viewer role.

 

SOLUTION: 

 

Step 1 — Navigate to Scheduled Jobs

All → System Definition → Scheduled Jobs

Screenshot 2026-02-23 153532.png

Step 2 — Create New Job

  1. Click New

  2. Select Automatically run a script of your choosing

Screenshot 2026-02-23 153858.pngScreenshot 2026-02-23 153919.png

Step 3 — Configure Job

Fill in the required fields:

  • Name: Assign Analytics Admin Role

  • Run: Hourly

  • Active: ✔ Enabled

 

Screenshot 2026-02-23 154812.png

Step 4 — Paste Script

Paste the following script inside the Run this script field:

 

 
 
(function() {

var ADMIN_ROLE = 'analytics_admin';
var VIEWER_ROLE = 'analytics_viewer';

function getRoleSysId(roleName){
var r = new GlideRecord('sys_user_role');
r.addQuery('name', roleName);
r.query();
if(r.next()) return r.sys_id.toString();
return null;
}

var adminRoleId = getRoleSysId(ADMIN_ROLE);
var viewerRoleId = getRoleSysId(VIEWER_ROLE);

if(!adminRoleId){
gs.error('analytics_admin role not found');
return;
}

var userGR = new GlideRecord('sys_user');
userGR.addActiveQuery();
userGR.query();

while(userGR.next()){

var hasRole = new GlideRecord('sys_user_has_role');
hasRole.addQuery('user', userGR.sys_id);
hasRole.addQuery('role', 'IN', adminRoleId + ',' + viewerRoleId);
hasRole.setLimit(1);
hasRole.query();

if(!hasRole.next()){
var insertRole = new GlideRecord('sys_user_has_role');
insertRole.initialize();
insertRole.user = userGR.sys_id;
insertRole.role = adminRoleId;
insertRole.insert();

gs.info('Assigned analytics_admin role to: ' + userGR.name);
}
}

})();
 

Step 5 — Save

Click Submit to activate the scheduled job.

2 REPLIES 2

GlideFather
Tera Patron

Hi @YashwanthV18760,

 

Why would you run this job every hour? Wouldn’t running it once a day be sufficient? 


And if it really is necessary, wouldn’t it be better to create a group with the required role and then add users to that group? Best practice is to assign roles to groups and manage access by adding users to those groups, rather than assigning roles directly to users.

 

What do you say?

_____
100 % GlideFather experience and 0 % generative AI

Hi, thanks for the suggestion!

You’re right — daily execution would usually be enough. I used hourly mainly for faster role compliance in cases where users are created or updated frequently. The schedule can definitely be adjusted based on requirements.

Also agree that assigning roles via groups is best practice. In real implementations, adding users to a role-mapped group would be the preferred approach. This example was mainly to demonstrate the automation logic.

Appreciate your input!