yjaques
Tera Contributor

I recently had a big stack of applications, over 50, in which I was asked to create a user group for each one, assign a manager and email to each group and create a CI/Group relationship between each newly created group and its corresponding CI. Certainly I could have clicked through several hundred screens and a thousand input fields to do it, but scripting seemed like a lot more fun. Here's what I ran as a background script:

(one thing that might not be so obvious -- the cmdb_rel_group table that holds the relationship needs three values, the CI, the GROUP and the Relationship type. You can go into the tables and find the sys_id for the relationship type you want to add, which is what the rel.type = '27c52344d95d61004f9c9aac0acc15a3'; is all about)

//table can be any CI table -- this is one that holds our java apps

var gr = new GlideRecord('u_cmdb_ci_applications_web_jav'); //Indicate the table to query from

gr.query(); //Execute the query

while (gr.next()) { //While the recordset contains records, iterate through them

  gr.u_user_group = getGroupSysId(gr);

      gr.update();

      //now lets add a CI/group relationship too

      updateGroupRel(gr);

}

//this builds the relatioship between the created group and the existing CI

function updateGroupRel(gr) {

    var rel = new GlideRecord('cmdb_rel_group'); //Indicate the table to query from

  rel.addQuery('ci', gr.sys_id);

  rel.query();

  while (rel.next()) {

  //record exists so do nothing

  return rel.sys_id;

  }

    rel.initialize();

      rel.ci = gr.sys_id;

      rel.group = gr.u_user_group;

      //sys_id of the relationship type

      rel.type = '27c52344d95d61004f9c9aac0acc15a3';

      var user_group_rel_id = rel.insert();

  if (user_group_rel_id != null) {

  gs.log("Created new relationship.");

  }

  return user_group_rel_id;

}

//this creates the group, or gets it if it already exists

function getGroupSysId(gr) {

  //get the user

  var userRecord = new GlideRecord("sys_user");    

  userRecord.get(gr.supported_by);

  //create a group for the app

  var groupRecord = new GlideRecord("sys_user_group");    

  groupRecord.addQuery('name', gr.name);

  groupRecord.query();

  while (groupRecord.next()) {

  gs.log("Found group: " + groupRecord.getDisplayValue());

  if(groupRecord.email == '') {

        groupRecord.email = userRecord.email;

        groupRecord.update();

        gs.log("Added email: " + userRecord.email);

  }

  return groupRecord.sys_id;

  }

  groupRecord.initialize();

  groupRecord.name = gr.name;

  groupRecord.manager = gr.supported_by;

  groupRecord.group_email = userRecord.email;

  var group_sys_id = groupRecord.insert();

  if (group_sys_id != null) {

  gs.log("Created new group: " + group_sys_id);

  }

  return group_sys_id;

}