If the Configuration Item (CI) record does not exist in the cmdb_ci_computer table, and you need to create it before updating the alm_hardware record, you'll need to adjust your script accordingly. Below is how you can do this in both a Business Rule and a Background Script context.
Business Rule
The Business Rule script can be modified to check for the existence of the CI in the cmdb_ci_computer table, and create one if it does not exist. Here's the updated script for the Business Rule:
-
Navigate to Business Rules:
- Go to System Definition > Business Rules.
-
Create a New Business Rule:
- Name:
Update CI with Asset Tag
- Table:
alm_hardware
- When: Before (or After) - depending on when you want this to trigger
- Insert, Update: Check these options
-
Advanced Configuration:
- Check the "Advanced" checkbox to bring up the script editor.
-
Script:
(function executeRule(current, previous /*null when async*/) {
if (current.asset_tag) {
var ciGr = new GlideRecord('cmdb_ci_computer');
ciGr.addQuery('name', current.asset_tag); // Assuming 'name' field is unique
ciGr.query();
if (!ciGr.next()) { // CI record not found
var newCI = new GlideRecord('cmdb_ci_computer');
newCI.initialize();
newCI.name = current.asset_tag;
newCI.insert();
current.ci = newCI.sys_id;
} else {
current.ci = ciGr.sys_id;
}
} else {
gs.log("Asset Tag is empty for record: " + current.sys_id);
}
})(current, previous);
-
Save and Activate:
Save the Business Rule and make sure it is active.
Background Script
To update existing records in a similar manner, you can use the following Background Script:
-
Navigate to Scripts - Background:
- Go to System Definition > Scripts - Background.
-
Script:
var hardwareGr = new GlideRecord('alm_hardware');
hardwareGr.query();
while (hardwareGr.next()) {
if (hardwareGr.asset_tag) {
var ciGr = new GlideRecord('cmdb_ci_computer');
ciGr.addQuery('name', hardwareGr.asset_tag); // Assuming `name` field is unique
ciGr.query();
if (!ciGr.next()) { // CI record not found
var newCI = new GlideRecord('cmdb_ci_computer');
newCI.initialize();
newCI.name = hardwareGr.asset_tag;
var newSysId = newCI.insert();
hardwareGr.ci = newSysId;
} else {
hardwareGr.ci = ciGr.sys_id;
}
hardwareGr.update();
} else {
gs.log("Asset Tag is empty for record: " + hardwareGr.sys_id);
}
}
-
Execute:
Run the script to update all existing records in the alm_hardware table.
Notes:
- Ensure you're testing in a development or staging environment first to verify the script works as intended.
- Additional fields can be added to the new CI record if necessary (besides just the
name field).
- Be mindful of performance when running scripts that iterate through large datasets.
These scripts will handle records where the CI does not exist by creating a new record in the cmdb_ci_computer table and then updating the reference in the alm_hardware table.