Add existing users to group through script

J_31
Kilo Sage

I want to add existing users to group and create a business rule to check if the user exist in the group if not add to the group

Please can someone help with script

17 REPLIES 17

1. Add existing users to group and add a role to the group

2. BR to check if the users exists incase of new record, if not add to the group. 

Role only have to be added once to the group so it's better to do it manually from the web page.

  1. From Application Navigator, to go "System Security" > "Groups".
  2. Select the group to add a role. If It's going to be a new role, click on the "New" button.
  3. Enter value to "Name".
  4. Right click on the header area and select "Save"
    find_real_file.png
  5. Several tabs will appear at the bottom of the page. Click on the "Edit" button.
    find_real_file.png
  6. Move the role to add to the group and click on the "Save" button
    find_real_file.png

Create a following business rule.

Name: Add owned_by user to group

Table: Configuration Item [cmdb_ci]

Check "Advanced"

When to run

  When: before

  Check "Insert" and "Update"

find_real_file.png

Click on "Advanced" tab and enter the following script.

(function executeRule(current, previous /*null when async*/ ) {
    if (current.owned_by == '') {
        return;
    }
    var groupName = 'Cmdb owner by group';  // Changed to name of group created above
    var grUserGroup = new GlideRecord('sys_user_grmember');
    grUserGroup.addQuery('group.name', groupName);
    grUserGroup.addQuery('user', current.owned_by);
    grUserGroup.query();
    if (!grUserGroup.hasNext()) {
        grUserGroup.initialize();
        grUserGroup.setDisplayValue('group', groupName);
        grUserGroup.user = current.owned_by;
        grUserGroup.insert();
    }
})(current, previous);

find_real_file.png

 

Many thanks Hitoshi for such a detailed step, it helps learners like us.

one more condition I wanted to have here, 

if (current.owned_by == '') 
{
 
if I am removing the user from the field, I need to check if he is associated with any other CIs if not remove him from the group
can this be added to script you created ?
 
}

Hi,

CI - User relationship is saved in cmdb_rel_person table. Add a check to see if there is a record in this table. If there is, there is a CI related to this user.

Insert the following script to check if there is a CI related to the user.

var grCIUser = new GlideRecord('cmdb_rel_person');
if (!grCIUser.get('user', current.owned_by)) {
  return;
}

thank you its good to learn about cmdb_rel_person table, but though many CI are related to one user, I don't find any record in this table, is there any alternate way to find user associated with more CI's if he is , ignore updating group.