Impersonate as admin in workflow run script

Feddy
Kilo Sage

Hi Team, 
I have below workflow run script activity which needs to be executed as system admin.
The purpose of the script is when the manager approves request,  the user would to be added to respective group.
Currently it is not happening as the manager required some additional role (w.r.t group) to add members.

Could you please let me know how can I impersonate as admin user,

addMultipleUsers();
function addMultipleUsers(){


var currentUser = gs.getUserID();

//1. first approch

var impUser = new GlideImpersonate();
impUser.impersonate(system user sys_id);//to impersonate as system user

//2 . second approach
gs.getSession().impersonate(system user sys_id);


var addUsersList = current.variables.u_user_add.toString().split(',');

for (var i = 0; i < addUsersList.length; i++) {
var grMembersGR = new GlideRecord('sys_user_grmember');
grMembersGR.initialize();
grMembersGR.group = current.variables.u_group_name;
grMembersGR.user = addUsersList[i];
grMembersGR.insert();
}
gs.getSession().impersonate(currentUser);//to impersonate as logged in user
}

Any help on this would be much appreciated

4 REPLIES 4

Kieran Anson
Kilo Patron

Hi,

If you add a wait timer at the start of your workflow, it'll set the workflow as a background transaction that'll run under the system account. GlideImpersonate isn't possible as the system account as the system account isn't a user.

Alternatively, you can trigger an event as part of the script, and then use a script action to complete the work. This has the same solution as the above, effectively putting the work in the background for the system to pickup and run in its own context.

Thank you for your inputs.

1. So I cannot impersonate as system admin in Glideimpersonate? Do I need to add the timer in the start of the workflow(before begin activity) or before runscript activity?

2. If I use the script action, no need to impersonate as the system admin user? just need use the same piece of code?


Thanks.

Looks like there is support for system user impersonating as below, to whether this allows a workflow in the context of a user (i.e what you have) elevate is another question....I doubt it. I think it's more around ending an impersonation.

new GlideImpersonate().impersonate("system");

A timer can go anywhere in the flow and just be a 1 second delay. It's a good way to ensure a workflow isn't running as a user unless you have a specific need for the flow to run under their user context.

For the script action, it'll run as the system user as it's in the background, ran once the system scheduler picks of the event. Same code can be used

Sushma R1
Tera Expert

Try to find your solution in AutoResolutionProcessor SI, ServiceNow is trying to do something similar

Hit helpful if it was 🙂